org.el 806 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282
  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-2019 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: https://orgmode.org
  9. ;; Version: 9.3
  10. ;;
  11. ;; This file is part of GNU Emacs.
  12. ;;
  13. ;; GNU Emacs is free software: you can redistribute it and/or modify
  14. ;; it under the terms of the GNU General Public License as published by
  15. ;; the Free Software Foundation, either version 3 of the License, or
  16. ;; (at your option) any later version.
  17. ;; GNU Emacs is distributed in the hope that it will be useful,
  18. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. ;; GNU General Public License for more details.
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  23. ;;
  24. ;;; Commentary:
  25. ;;
  26. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  27. ;; project planning with a fast and effective plain-text system.
  28. ;;
  29. ;; Org mode develops organizational tasks around NOTES files that
  30. ;; contain information about projects as plain text. Org mode is
  31. ;; implemented on top of outline-mode, which makes it possible to keep
  32. ;; the content of large files well structured. Visibility cycling and
  33. ;; structure editing help to work with the tree. Tables are easily
  34. ;; created with a built-in table editor. Org mode supports ToDo
  35. ;; items, deadlines, time stamps, and scheduling. It dynamically
  36. ;; compiles entries into an agenda that utilizes and smoothly
  37. ;; integrates much of the Emacs calendar and diary. Plain text
  38. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  39. ;; entries, and any files related to the projects. For printing and
  40. ;; sharing of notes, an Org file can be exported as a structured ASCII
  41. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  42. ;; file. It can also serve as a publishing tool for a set of linked
  43. ;; webpages.
  44. ;;
  45. ;; Installation and Activation
  46. ;; ---------------------------
  47. ;; See the corresponding sections in the manual at
  48. ;;
  49. ;; https://orgmode.org/org.html#Installation
  50. ;;
  51. ;; Documentation
  52. ;; -------------
  53. ;; The documentation of Org mode can be found in the TeXInfo file. The
  54. ;; distribution also contains a PDF version of it. At the homepage of
  55. ;; Org mode, you can read the same text online as HTML. There is also an
  56. ;; excellent reference card made by Philip Rooke. This card can be found
  57. ;; in the doc/ directory.
  58. ;;
  59. ;; A list of recent changes can be found at
  60. ;; https://orgmode.org/Changes.html
  61. ;;
  62. ;;; Code:
  63. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  64. (defvar-local org-table-formula-constants-local nil
  65. "Local version of `org-table-formula-constants'.")
  66. (defvar org-inlinetask-min-level)
  67. ;;;; Require other packages
  68. (require 'cl-lib)
  69. (eval-when-compile (require 'gnus-sum))
  70. (require 'calendar)
  71. (require 'find-func)
  72. (require 'format-spec)
  73. (or (eq this-command 'eval-buffer)
  74. (condition-case nil
  75. (load (concat (file-name-directory load-file-name)
  76. "org-loaddefs.el")
  77. nil t t t)
  78. (error
  79. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  80. (sit-for 3)
  81. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  82. (sit-for 3))))
  83. (eval-and-compile (require 'org-macs))
  84. (require 'org-compat)
  85. (require 'org-keys)
  86. (require 'ol)
  87. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  88. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  89. (defvar org-outline-regexp "\\*+ "
  90. "Regexp to match Org headlines.")
  91. (defvar org-outline-regexp-bol "^\\*+ "
  92. "Regexp to match Org headlines.
  93. This is similar to `org-outline-regexp' but additionally makes
  94. sure that we are at the beginning of the line.")
  95. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  96. "Matches a headline, putting stars and text into groups.
  97. Stars are put in group 1 and the trimmed body in group 2.")
  98. (declare-function calendar-check-holidays "holidays" (date))
  99. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  100. (declare-function cdlatex-math-symbol "ext:cdlatex")
  101. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  102. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  103. (declare-function org-add-archive-files "org-archive" (files))
  104. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  105. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  106. (declare-function org-agenda-redo "org-agenda" (&optional all))
  107. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  108. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  109. (declare-function org-archive-subtree-default "org-archive" ())
  110. (declare-function org-archive-to-archive-sibling "org-archive" ())
  111. (declare-function org-attach "org-attach" ())
  112. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  113. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  114. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  115. (declare-function org-clock-cancel "org-clock" ())
  116. (declare-function org-clock-display "org-clock" (&optional arg))
  117. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  118. (declare-function org-clock-goto "org-clock" (&optional select))
  119. (declare-function org-clock-in "org-clock" (&optional select start-time))
  120. (declare-function org-clock-in-last "org-clock" (&optional arg))
  121. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  122. (declare-function org-clock-out-if-current "org-clock" ())
  123. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  124. (declare-function org-clock-report "org-clock" (&optional arg))
  125. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  126. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  127. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  128. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  129. (declare-function org-clock-update-time-maybe "org-clock" ())
  130. (declare-function org-clocking-buffer "org-clock" ())
  131. (declare-function org-clocktable-shift "org-clock" (dir n))
  132. (declare-function org-columns-insert-dblock "org-colview" ())
  133. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  134. (declare-function org-element-at-point "org-element" ())
  135. (declare-function org-element-cache-refresh "org-element" (pos))
  136. (declare-function org-element-cache-reset "org-element" (&optional all))
  137. (declare-function org-element-contents "org-element" (element))
  138. (declare-function org-element-context "org-element" (&optional element))
  139. (declare-function org-element-copy "org-element" (datum))
  140. (declare-function org-element-create "org-element" (type &optional props &rest children))
  141. (declare-function org-element-interpret-data "org-element" (data))
  142. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  143. (declare-function org-element-link-parser "org-element" ())
  144. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  145. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  146. (declare-function org-element-property "org-element" (property element))
  147. (declare-function org-element-put-property "org-element" (element property value))
  148. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  149. (declare-function org-element-timestamp-parser "org-element" ())
  150. (declare-function org-element-type "org-element" (element))
  151. (declare-function org-export-dispatch "ox" (&optional arg))
  152. (declare-function org-export-get-backend "ox" (name))
  153. (declare-function org-export-get-backend "ox" (name))
  154. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  155. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  156. (declare-function org-feed-goto-inbox "org-feed" (feed))
  157. (declare-function org-feed-update-all "org-feed" ())
  158. (declare-function org-goto "org-goto" (&optional alternative-interface))
  159. (declare-function org-goto "org-goto" (&optional alternative-interface))
  160. (declare-function org-id-find-id-file "org-id" (id))
  161. (declare-function org-id-get-create "org-id" (&optional force))
  162. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  163. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  164. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  165. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  166. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  167. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  168. (declare-function org-table--shrunk-field "org-table" ()) ;; For `org-table-with-shrunk-field'.
  169. (declare-function org-table-align "org-table" ())
  170. (declare-function org-table-begin "org-table" (&optional table-type))
  171. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  172. (declare-function org-table-blank-field "org-table" ())
  173. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  174. (declare-function org-table-copy-down "org-table" (N))
  175. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  176. (declare-function org-table-create-or-convert-from-region "org-table" (arg))
  177. (declare-function org-table-create-with-table.el "org-table" ())
  178. (declare-function org-table-cut-region "org-table" (beg end))
  179. (declare-function org-table-edit-field "org-table" (arg))
  180. (declare-function org-table-end "org-table" (&optional table-type))
  181. (declare-function org-table-end-of-field "org-table" (&optional n))
  182. (declare-function org-table-eval-formula "org-table" (&optional arg equation suppress-align suppress-const suppress-store suppress-analysis))
  183. (declare-function org-table-field-info "org-table" (arg))
  184. (declare-function org-table-insert-row "org-table" (&optional arg))
  185. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  186. (declare-function org-table-maybe-eval-formula "org-table" ())
  187. (declare-function org-table-maybe-recalculate-line "org-table" ())
  188. (declare-function org-table-move-cell-up "org-table" ())
  189. (declare-function org-table-move-cell-down "org-table" ())
  190. (declare-function org-table-move-cell-right "org-table" ())
  191. (declare-function org-table-move-cell-left "org-table" ())
  192. (declare-function org-table-next-row "org-table" ())
  193. (declare-function org-table-paste-rectangle "org-table" ())
  194. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  195. (declare-function org-table-rotate-recalc-marks "org-table" (&optional newchar))
  196. (declare-function org-table-shrink "org-table" (&optional begin end))
  197. (declare-function org-table-sort-lines "org-table" (&optional with-case sorting-type getkey-func compare-func interactive?))
  198. (declare-function org-table-sum "org-table" (&optional beg end nlast))
  199. (declare-function org-table-toggle-column-width "org-table" (&optional arg))
  200. (declare-function org-table-toggle-coordinate-overlays "org-table" ())
  201. (declare-function org-table-toggle-formula-debugger "org-table" ())
  202. (declare-function org-table-wrap-region "org-table" (arg))
  203. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  204. (declare-function org-timer "org-timer" (&optional restart no-insert))
  205. (declare-function org-timer-item "org-timer" (&optional arg))
  206. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  207. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  208. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  209. (declare-function org-timer-start "org-timer" (&optional offset))
  210. (declare-function org-timer-stop "org-timer" ())
  211. (declare-function org-timer-stop "org-timer" ())
  212. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  213. (declare-function org-update-radio-target-regexp "ol" ())
  214. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  215. (declare-function orgtbl-mode "org-table" (&optional arg))
  216. (defvar ffap-url-regexp)
  217. (defvar org-element-paragraph-separate)
  218. (defvar org-indent-indentation-per-level)
  219. (defvar org-radio-target-regexp)
  220. (defvar org-table-auto-blank-field)
  221. (defvar org-target-link-regexp)
  222. (defvar org-target-regexp)
  223. ;; load languages based on value of `org-babel-load-languages'
  224. (defvar org-babel-load-languages)
  225. ;;;###autoload
  226. (defun org-babel-do-load-languages (sym value)
  227. "Load the languages defined in `org-babel-load-languages'."
  228. (set-default sym value)
  229. (dolist (pair org-babel-load-languages)
  230. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  231. (if active
  232. (require (intern (concat "ob-" lang)))
  233. (fmakunbound
  234. (intern (concat "org-babel-execute:" lang)))
  235. (fmakunbound
  236. (intern (concat "org-babel-expand-body:" lang)))))))
  237. ;;;###autoload
  238. (defun org-babel-load-file (file &optional compile)
  239. "Load Emacs Lisp source code blocks in the Org FILE.
  240. This function exports the source code using `org-babel-tangle'
  241. and then loads the resulting file using `load-file'. With
  242. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  243. byte-compiled before it is loaded."
  244. (interactive "fFile to load: \nP")
  245. (let* ((tangled-file (concat (file-name-sans-extension file) ".el")))
  246. ;; Tangle only if the Org file is newer than the Elisp file.
  247. (unless (org-file-newer-than-p
  248. tangled-file
  249. (file-attribute-modification-time (file-attributes file)))
  250. (org-babel-tangle-file file tangled-file "emacs-lisp"))
  251. (if compile
  252. (progn
  253. (byte-compile-file tangled-file 'load)
  254. (message "Compiled and loaded %s" tangled-file))
  255. (load-file tangled-file)
  256. (message "Loaded %s" tangled-file))))
  257. (defcustom org-babel-load-languages '((emacs-lisp . t))
  258. "Languages which can be evaluated in Org buffers.
  259. \\<org-mode-map>
  260. This list can be used to load support for any of the languages
  261. below. Each language will depend on a different set of system
  262. executables and/or Emacs modes.
  263. When a language is \"loaded\", code blocks in that language can
  264. be evaluated with `org-babel-execute-src-block', which is bound
  265. by default to \\[org-ctrl-c-ctrl-c].
  266. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  267. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  268. default, only Emacs Lisp is loaded, since it has no specific
  269. requirement."
  270. :group 'org-babel
  271. :set 'org-babel-do-load-languages
  272. :version "24.1"
  273. :type '(alist :tag "Babel Languages"
  274. :key-type
  275. (choice
  276. (const :tag "Awk" awk)
  277. (const :tag "C" C)
  278. (const :tag "R" R)
  279. (const :tag "Asymptote" asymptote)
  280. (const :tag "Calc" calc)
  281. (const :tag "Clojure" clojure)
  282. (const :tag "CSS" css)
  283. (const :tag "Ditaa" ditaa)
  284. (const :tag "Dot" dot)
  285. (const :tag "Ebnf2ps" ebnf2ps)
  286. (const :tag "Emacs Lisp" emacs-lisp)
  287. (const :tag "Forth" forth)
  288. (const :tag "Fortran" fortran)
  289. (const :tag "Gnuplot" gnuplot)
  290. (const :tag "Haskell" haskell)
  291. (const :tag "hledger" hledger)
  292. (const :tag "IO" io)
  293. (const :tag "J" J)
  294. (const :tag "Java" java)
  295. (const :tag "Javascript" js)
  296. (const :tag "LaTeX" latex)
  297. (const :tag "Ledger" ledger)
  298. (const :tag "Lilypond" lilypond)
  299. (const :tag "Lisp" lisp)
  300. (const :tag "Makefile" makefile)
  301. (const :tag "Maxima" maxima)
  302. (const :tag "Matlab" matlab)
  303. (const :tag "Mscgen" mscgen)
  304. (const :tag "Ocaml" ocaml)
  305. (const :tag "Octave" octave)
  306. (const :tag "Org" org)
  307. (const :tag "Perl" perl)
  308. (const :tag "Pico Lisp" picolisp)
  309. (const :tag "PlantUML" plantuml)
  310. (const :tag "Python" python)
  311. (const :tag "Ruby" ruby)
  312. (const :tag "Sass" sass)
  313. (const :tag "Scala" scala)
  314. (const :tag "Scheme" scheme)
  315. (const :tag "Screen" screen)
  316. (const :tag "Shell Script" shell)
  317. (const :tag "Shen" shen)
  318. (const :tag "Sql" sql)
  319. (const :tag "Sqlite" sqlite)
  320. (const :tag "Stan" stan)
  321. (const :tag "Vala" vala))
  322. :value-type (boolean :tag "Activate" :value t)))
  323. ;;;; Customization variables
  324. (defcustom org-clone-delete-id nil
  325. "Remove ID property of clones of a subtree.
  326. When non-nil, clones of a subtree don't inherit the ID property.
  327. Otherwise they inherit the ID property with a new unique
  328. identifier."
  329. :type 'boolean
  330. :version "24.1"
  331. :group 'org-id)
  332. ;;; Version
  333. (org-check-version)
  334. ;;;###autoload
  335. (defun org-version (&optional here full message)
  336. "Show the Org version.
  337. Interactively, or when MESSAGE is non-nil, show it in echo area.
  338. With prefix argument, or when HERE is non-nil, insert it at point.
  339. In non-interactive uses, a reduced version string is output unless
  340. FULL is given."
  341. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  342. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  343. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  344. (load-suffixes (list ".el"))
  345. (org-install-dir
  346. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  347. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  348. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  349. (let* ((load-suffixes save-load-suffixes)
  350. (release (org-release))
  351. (git-version (org-git-version))
  352. (version (format "Org mode version %s (%s @ %s)"
  353. release
  354. git-version
  355. (if org-install-dir
  356. (if (string= org-dir org-install-dir)
  357. org-install-dir
  358. (concat "mixed installation! "
  359. org-install-dir
  360. " and "
  361. org-dir))
  362. "org-loaddefs.el can not be found!")))
  363. (version1 (if full version release)))
  364. (when here (insert version1))
  365. (when message (message "%s" version1))
  366. version1)))
  367. (defconst org-version (org-version))
  368. ;;; Syntax Constants
  369. ;;;; Block
  370. (defconst org-block-regexp
  371. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  372. "Regular expression for hiding blocks.")
  373. (defconst org-dblock-start-re
  374. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  375. "Matches the start line of a dynamic block, with parameters.")
  376. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  377. "Matches the end of a dynamic block.")
  378. ;;;; Clock and Planning
  379. (defconst org-clock-string "CLOCK:"
  380. "String used as prefix for timestamps clocking work hours on an item.")
  381. (defvar org-closed-string "CLOSED:"
  382. "String used as the prefix for timestamps logging closing a TODO entry.")
  383. (defvar org-deadline-string "DEADLINE:"
  384. "String to mark deadline entries.
  385. \\<org-mode-map>
  386. A deadline is this string, followed by a time stamp. It must be
  387. a word, terminated by a colon. You can insert a schedule keyword
  388. and a timestamp with `\\[org-deadline]'.")
  389. (defvar org-scheduled-string "SCHEDULED:"
  390. "String to mark scheduled TODO entries.
  391. \\<org-mode-map>
  392. A schedule is this string, followed by a time stamp. It must be
  393. a word, terminated by a colon. You can insert a schedule keyword
  394. and a timestamp with `\\[org-schedule]'.")
  395. (defconst org-ds-keyword-length
  396. (+ 2
  397. (apply #'max
  398. (mapcar #'length
  399. (list org-deadline-string org-scheduled-string
  400. org-clock-string org-closed-string))))
  401. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  402. (defconst org-planning-line-re
  403. (concat "^[ \t]*"
  404. (regexp-opt
  405. (list org-closed-string org-deadline-string org-scheduled-string)
  406. t))
  407. "Matches a line with planning info.
  408. Matched keyword is in group 1.")
  409. (defconst org-clock-line-re
  410. (concat "^[ \t]*" org-clock-string)
  411. "Matches a line with clock info.")
  412. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  413. "Matches the DEADLINE keyword.")
  414. (defconst org-deadline-time-regexp
  415. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  416. "Matches the DEADLINE keyword together with a time stamp.")
  417. (defconst org-deadline-time-hour-regexp
  418. (concat "\\<" org-deadline-string
  419. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  420. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  421. (defconst org-deadline-line-regexp
  422. (concat "\\<\\(" org-deadline-string "\\).*")
  423. "Matches the DEADLINE keyword and the rest of the line.")
  424. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  425. "Matches the SCHEDULED keyword.")
  426. (defconst org-scheduled-time-regexp
  427. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  428. "Matches the SCHEDULED keyword together with a time stamp.")
  429. (defconst org-scheduled-time-hour-regexp
  430. (concat "\\<" org-scheduled-string
  431. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  432. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  433. (defconst org-closed-time-regexp
  434. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  435. "Matches the CLOSED keyword together with a time stamp.")
  436. (defconst org-keyword-time-regexp
  437. (concat "\\<"
  438. (regexp-opt
  439. (list org-scheduled-string org-deadline-string org-closed-string
  440. org-clock-string)
  441. t)
  442. " *[[<]\\([^]>]+\\)[]>]")
  443. "Matches any of the 4 keywords, together with the time stamp.")
  444. (defconst org-keyword-time-not-clock-regexp
  445. (concat
  446. "\\<"
  447. (regexp-opt
  448. (list org-scheduled-string org-deadline-string org-closed-string) t)
  449. " *[[<]\\([^]>]+\\)[]>]")
  450. "Matches any of the 3 keywords, together with the time stamp.")
  451. (defconst org-maybe-keyword-time-regexp
  452. (concat "\\(\\<"
  453. (regexp-opt
  454. (list org-scheduled-string org-deadline-string org-closed-string
  455. org-clock-string)
  456. t)
  457. "\\)?"
  458. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  459. "\\|"
  460. "<%%([^\r\n>]*>\\)")
  461. "Matches a timestamp, possibly preceded by a keyword.")
  462. (defconst org-all-time-keywords
  463. (mapcar (lambda (w) (substring w 0 -1))
  464. (list org-scheduled-string org-deadline-string
  465. org-clock-string org-closed-string))
  466. "List of time keywords.")
  467. ;;;; Drawer
  468. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  469. "Matches first or last line of a hidden block.
  470. Group 1 contains drawer's name or \"END\".")
  471. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  472. "Regular expression matching the first line of a property drawer.")
  473. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  474. "Regular expression matching the last line of a property drawer.")
  475. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  476. "Regular expression matching the first line of a clock drawer.")
  477. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  478. "Regular expression matching the last line of a clock drawer.")
  479. (defconst org-property-drawer-re
  480. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  481. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  482. "[ \t]*:END:[ \t]*$")
  483. "Matches an entire property drawer.")
  484. (defconst org-clock-drawer-re
  485. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  486. org-clock-drawer-end-re "\\)\n?")
  487. "Matches an entire clock drawer.")
  488. ;;;; Headline
  489. (defconst org-heading-keyword-regexp-format
  490. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  491. "Printf format for a regexp matching a headline with some keyword.
  492. This regexp will match the headline of any node which has the
  493. exact keyword that is put into the format. The keyword isn't in
  494. any group by default, but the stars and the body are.")
  495. (defconst org-heading-keyword-maybe-regexp-format
  496. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  497. "Printf format for a regexp matching a headline, possibly with some keyword.
  498. This regexp can match any headline with the specified keyword, or
  499. without a keyword. The keyword isn't in any group by default,
  500. but the stars and the body are.")
  501. (defconst org-archive-tag "ARCHIVE"
  502. "The tag that marks a subtree as archived.
  503. An archived subtree does not open during visibility cycling, and does
  504. not contribute to the agenda listings.")
  505. (defconst org-tag-re "[[:alnum:]_@#%]+"
  506. "Regexp matching a single tag.")
  507. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  508. "Regexp matching the tag group at the end of a line, with leading spaces.
  509. Tags are stored in match group 1. Match group 2 stores the tags
  510. without the enclosing colons.")
  511. (defconst org-tag-line-re
  512. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  513. "Regexp matching tags in a headline.
  514. Tags are stored in match group 1. Match group 2 stores the tags
  515. without the enclosing colons.")
  516. (eval-and-compile
  517. (defconst org-comment-string "COMMENT"
  518. "Entries starting with this keyword will never be exported.
  519. \\<org-mode-map>
  520. An entry can be toggled between COMMENT and normal with
  521. `\\[org-toggle-comment]'."))
  522. ;;;; LaTeX Environments and Fragments
  523. (defconst org-latex-regexps
  524. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  525. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  526. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  527. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  528. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  529. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  530. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  531. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  532. "Regular expressions for matching embedded LaTeX.")
  533. ;;;; Node Property
  534. (defconst org-effort-property "Effort"
  535. "The property that is being used to keep track of effort estimates.
  536. Effort estimates given in this property need to have the format H:MM.")
  537. ;;;; Table
  538. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  539. "Detect an org-type or table-type table.")
  540. (defconst org-table-line-regexp "^[ \t]*|"
  541. "Detect an org-type table line.")
  542. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  543. "Detect an org-type table line.")
  544. (defconst org-table-hline-regexp "^[ \t]*|-"
  545. "Detect an org-type table hline.")
  546. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  547. "Detect a table-type table hline.")
  548. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  549. "Detect the first line outside a table when searching from within it.
  550. This works for both table types.")
  551. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  552. "Detect a #+TBLFM line.")
  553. ;;;; Timestamp
  554. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  555. "Regular expression for fast time stamp matching.")
  556. (defconst org-ts-regexp-inactive
  557. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  558. "Regular expression for fast inactive time stamp matching.")
  559. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  560. "Regular expression for fast time stamp matching.")
  561. (defconst org-ts-regexp0
  562. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  563. "Regular expression matching time strings for analysis.
  564. This one does not require the space after the date, so it can be used
  565. on a string that terminates immediately after the date.")
  566. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  567. "Regular expression matching time strings for analysis.")
  568. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  569. "Regular expression matching time stamps, with groups.")
  570. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  571. "Regular expression matching time stamps (also [..]), with groups.")
  572. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  573. "Regular expression matching a time stamp range.")
  574. (defconst org-tr-regexp-both
  575. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  576. "Regular expression matching a time stamp range.")
  577. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  578. org-ts-regexp "\\)?")
  579. "Regular expression matching a time stamp or time stamp range.")
  580. (defconst org-tsr-regexp-both
  581. (concat org-ts-regexp-both "\\(--?-?"
  582. org-ts-regexp-both "\\)?")
  583. "Regular expression matching a time stamp or time stamp range.
  584. The time stamps may be either active or inactive.")
  585. (defconst org-repeat-re
  586. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  587. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  588. "Regular expression for specifying repeated events.
  589. After a match, group 1 contains the repeat expression.")
  590. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  591. "Formats for `format-time-string' which are used for time stamps.")
  592. ;;; The custom variables
  593. (defgroup org nil
  594. "Outline-based notes management and organizer."
  595. :tag "Org"
  596. :group 'outlines
  597. :group 'calendar)
  598. (defcustom org-mode-hook nil
  599. "Mode hook for Org mode, run after the mode was turned on."
  600. :group 'org
  601. :type 'hook)
  602. (defcustom org-load-hook nil
  603. "Hook that is run after org.el has been loaded."
  604. :group 'org
  605. :type 'hook)
  606. (defcustom org-log-buffer-setup-hook nil
  607. "Hook that is run after an Org log buffer is created."
  608. :group 'org
  609. :version "24.1"
  610. :type 'hook)
  611. (defvar org-modules) ; defined below
  612. (defvar org-modules-loaded nil
  613. "Have the modules been loaded already?")
  614. (defun org-load-modules-maybe (&optional force)
  615. "Load all extensions listed in `org-modules'."
  616. (when (or force (not org-modules-loaded))
  617. (dolist (ext org-modules)
  618. (condition-case nil (require ext)
  619. (error (message "Problems while trying to load feature `%s'" ext))))
  620. (setq org-modules-loaded t)))
  621. (defun org-set-modules (var value)
  622. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  623. (set var value)
  624. (when (featurep 'org)
  625. (org-load-modules-maybe 'force)
  626. (org-element-cache-reset 'all)))
  627. (defcustom org-modules '(ol-w3m ol-bbdb ol-bibtex ol-docview ol-gnus ol-info ol-irc ol-mhe ol-rmail ol-eww)
  628. "Modules that should always be loaded together with org.el.
  629. If a description starts with <C>, the file is not part of Emacs
  630. and loading it will require that you have downloaded and properly
  631. installed the Org mode distribution.
  632. You can also use this system to load external packages (i.e. neither Org
  633. core modules, nor modules from the CONTRIB directory). Just add symbols
  634. to the end of the list. If the package is called org-xyz.el, then you need
  635. to add the symbol `xyz', and the package must have a call to:
  636. (provide \\='org-xyz)
  637. For export specific modules, see also `org-export-backends'."
  638. :group 'org
  639. :set 'org-set-modules
  640. :version "26.1"
  641. :package-version '(Org . "9.2")
  642. :type
  643. '(set :greedy t
  644. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  645. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  646. (const :tag " crypt: Encryption of subtrees" org-crypt)
  647. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  648. (const :tag " docview: Links to Docview buffers" ol-docview)
  649. (const :tag " eww: Store link to URL of Eww" ol-eww)
  650. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  651. (const :tag " habit: Track your consistency with habits" org-habit)
  652. (const :tag " id: Global IDs for identifying entries" org-id)
  653. (const :tag " info: Links to Info nodes" ol-info)
  654. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  655. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  656. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  657. (const :tag " mouse: Additional mouse support" org-mouse)
  658. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  659. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  660. (const :tag " tempo: Fast completion for structures" org-tempo)
  661. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  662. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  663. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  664. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  665. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  666. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  667. (const :tag "C collector: Collect properties into tables" org-collector)
  668. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  669. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  670. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  671. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  672. (const :tag "C eval: Include command output as text" org-eval)
  673. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  674. (const :tag "C git-link: Links to specific file version" ol-git-link)
  675. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  676. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  677. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  678. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  679. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  680. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  681. (const :tag "C man: Links to man pages in Org mode" ol-man)
  682. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  683. (const :tag "C notify: Notifications for Org mode" org-notify)
  684. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  685. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  686. (const :tag "C registry: A registry for Org links" org-registry)
  687. (const :tag "C screen: Visit screen sessions through links" org-screen)
  688. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  689. (const :tag "C secretary: Team management with Org" org-secretary)
  690. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  691. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  692. (const :tag "C track: Keep up with Org mode development" org-track)
  693. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  694. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  695. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  696. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  697. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  698. (defvar org-export-registered-backends) ; From ox.el.
  699. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  700. (declare-function org-export-backend-name "ox" (backend) t)
  701. (defcustom org-export-backends '(ascii html icalendar latex odt)
  702. "List of export back-ends that should be always available.
  703. If a description starts with <C>, the file is not part of Emacs
  704. and loading it will require that you have downloaded and properly
  705. installed the Org mode distribution.
  706. Unlike to `org-modules', libraries in this list will not be
  707. loaded along with Org, but only once the export framework is
  708. needed.
  709. This variable needs to be set before org.el is loaded. If you
  710. need to make a change while Emacs is running, use the customize
  711. interface or run the following code, where VAL stands for the new
  712. value of the variable, after updating it:
  713. (progn
  714. (setq org-export-registered-backends
  715. (cl-remove-if-not
  716. (lambda (backend)
  717. (let ((name (org-export-backend-name backend)))
  718. (or (memq name val)
  719. (catch \\='parentp
  720. (dolist (b val)
  721. (and (org-export-derived-backend-p b name)
  722. (throw \\='parentp t)))))))
  723. org-export-registered-backends))
  724. (let ((new-list (mapcar #\\='org-export-backend-name
  725. org-export-registered-backends)))
  726. (dolist (backend val)
  727. (cond
  728. ((not (load (format \"ox-%s\" backend) t t))
  729. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  730. backend))
  731. ((not (memq backend new-list)) (push backend new-list))))
  732. (set-default \\='org-export-backends new-list)))
  733. Adding a back-end to this list will also pull the back-end it
  734. depends on, if any."
  735. :group 'org
  736. :group 'org-export
  737. :version "26.1"
  738. :package-version '(Org . "9.0")
  739. :initialize 'custom-initialize-set
  740. :set (lambda (var val)
  741. (if (not (featurep 'ox)) (set-default var val)
  742. ;; Any back-end not required anymore (not present in VAL and not
  743. ;; a parent of any back-end in the new value) is removed from the
  744. ;; list of registered back-ends.
  745. (setq org-export-registered-backends
  746. (cl-remove-if-not
  747. (lambda (backend)
  748. (let ((name (org-export-backend-name backend)))
  749. (or (memq name val)
  750. (catch 'parentp
  751. (dolist (b val)
  752. (and (org-export-derived-backend-p b name)
  753. (throw 'parentp t)))))))
  754. org-export-registered-backends))
  755. ;; Now build NEW-LIST of both new back-ends and required
  756. ;; parents.
  757. (let ((new-list (mapcar #'org-export-backend-name
  758. org-export-registered-backends)))
  759. (dolist (backend val)
  760. (cond
  761. ((not (load (format "ox-%s" backend) t t))
  762. (message "Problems while trying to load export back-end `%s'"
  763. backend))
  764. ((not (memq backend new-list)) (push backend new-list))))
  765. ;; Set VAR to that list with fixed dependencies.
  766. (set-default var new-list))))
  767. :type '(set :greedy t
  768. (const :tag " ascii Export buffer to ASCII format" ascii)
  769. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  770. (const :tag " html Export buffer to HTML format" html)
  771. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  772. (const :tag " latex Export buffer to LaTeX format" latex)
  773. (const :tag " man Export buffer to MAN format" man)
  774. (const :tag " md Export buffer to Markdown format" md)
  775. (const :tag " odt Export buffer to ODT format" odt)
  776. (const :tag " org Export buffer to Org format" org)
  777. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  778. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  779. (const :tag "C deck Export buffer to deck.js presentations" deck)
  780. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  781. (const :tag "C groff Export buffer to Groff format" groff)
  782. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  783. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  784. (const :tag "C s5 Export buffer to s5 presentations" s5)
  785. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  786. (eval-after-load 'ox
  787. '(dolist (backend org-export-backends)
  788. (condition-case nil (require (intern (format "ox-%s" backend)))
  789. (error (message "Problems while trying to load export back-end `%s'"
  790. backend)))))
  791. (defcustom org-support-shift-select nil
  792. "Non-nil means make shift-cursor commands select text when possible.
  793. \\<org-mode-map>\
  794. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  795. start selecting a region, or enlarge regions started in this way.
  796. In Org mode, in special contexts, these same keys are used for
  797. other purposes, important enough to compete with shift selection.
  798. Org tries to balance these needs by supporting `shift-select-mode'
  799. outside these special contexts, under control of this variable.
  800. The default of this variable is nil, to avoid confusing behavior. Shifted
  801. cursor keys will then execute Org commands in the following contexts:
  802. - on a headline, changing TODO state (left/right) and priority (up/down)
  803. - on a time stamp, changing the time
  804. - in a plain list item, changing the bullet type
  805. - in a property definition line, switching between allowed values
  806. - in the BEGIN line of a clock table (changing the time block).
  807. Outside these contexts, the commands will throw an error.
  808. When this variable is t and the cursor is not in a special
  809. context, Org mode will support shift-selection for making and
  810. enlarging regions. To make this more effective, the bullet
  811. cycling will no longer happen anywhere in an item line, but only
  812. if the cursor is exactly on the bullet.
  813. If you set this variable to the symbol `always', then the keys
  814. will not be special in headlines, property lines, and item lines,
  815. to make shift selection work there as well. If this is what you
  816. want, you can use the following alternative commands:
  817. `\\[org-todo]' and `\\[org-priority]' \
  818. to change TODO state and priority,
  819. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  820. can be used to switch TODO sets,
  821. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  822. and properties can be edited by hand or in column view.
  823. However, when the cursor is on a timestamp, shift-cursor commands
  824. will still edit the time stamp - this is just too good to give up."
  825. :group 'org
  826. :type '(choice
  827. (const :tag "Never" nil)
  828. (const :tag "When outside special context" t)
  829. (const :tag "Everywhere except timestamps" always)))
  830. (defcustom org-loop-over-headlines-in-active-region nil
  831. "Shall some commands act upon headlines in the active region?
  832. When set to t, some commands will be performed in all headlines
  833. within the active region.
  834. When set to `start-level', some commands will be performed in all
  835. headlines within the active region, provided that these headlines
  836. are of the same level than the first one.
  837. When set to a string, those commands will be performed on the
  838. matching headlines within the active region. Such string must be
  839. a tags/property/todo match as it is used in the agenda tags view.
  840. The list of commands is: `org-schedule', `org-deadline',
  841. `org-todo', `org-set-tags-command', `org-archive-subtree',
  842. `org-archive-set-tag', `org-toggle-archive-tag' and
  843. `org-archive-to-archive-sibling'. The archiving commands skip
  844. already archived entries."
  845. :type '(choice (const :tag "Don't loop" nil)
  846. (const :tag "All headlines in active region" t)
  847. (const :tag "In active region, headlines at the same level than the first one" start-level)
  848. (string :tag "Tags/Property/Todo matcher"))
  849. :version "24.1"
  850. :group 'org-todo
  851. :group 'org-archive)
  852. (defcustom org-startup-folded t
  853. "Non-nil means entering Org mode will switch to OVERVIEW.
  854. This can also be configured on a per-file basis by adding one of
  855. the following lines anywhere in the buffer:
  856. #+STARTUP: fold (or `overview', this is equivalent)
  857. #+STARTUP: nofold (or `showall', this is equivalent)
  858. #+STARTUP: content
  859. #+STARTUP: showeverything
  860. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  861. to ignore this option when Org opens agenda files for the first
  862. time."
  863. :group 'org-startup
  864. :type '(choice
  865. (const :tag "nofold: show all" nil)
  866. (const :tag "fold: overview" t)
  867. (const :tag "content: all headlines" content)
  868. (const :tag "show everything, even drawers" showeverything)))
  869. (defcustom org-startup-truncated t
  870. "Non-nil means entering Org mode will set `truncate-lines'.
  871. This is useful since some lines containing links can be very long and
  872. uninteresting. Also tables look terrible when wrapped.
  873. The variable `org-startup-truncated' allows to configure
  874. truncation for Org mode different to the other modes that use the
  875. variable `truncate-lines' and as a shortcut instead of putting
  876. the variable `truncate-lines' into the `org-mode-hook'. If one
  877. wants to configure truncation for Org mode not statically but
  878. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  879. the variable `truncate-lines' has to be used because in such a
  880. case it is too late to set the variable `org-startup-truncated'."
  881. :group 'org-startup
  882. :type 'boolean)
  883. (defcustom org-startup-indented nil
  884. "Non-nil means turn on `org-indent-mode' on startup.
  885. This can also be configured on a per-file basis by adding one of
  886. the following lines anywhere in the buffer:
  887. #+STARTUP: indent
  888. #+STARTUP: noindent"
  889. :group 'org-structure
  890. :type '(choice
  891. (const :tag "Not" nil)
  892. (const :tag "Globally (slow on startup in large files)" t)))
  893. (defcustom org-use-sub-superscripts t
  894. "Non-nil means interpret \"_\" and \"^\" for display.
  895. If you want to control how Org exports those characters, see
  896. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  897. used to be an alias for `org-export-with-sub-superscripts' in
  898. Org <8.0, it is not anymore.
  899. When this option is turned on, you can use TeX-like syntax for
  900. sub- and superscripts within the buffer. Several characters after
  901. \"_\" or \"^\" will be considered as a single item - so grouping
  902. with {} is normally not needed. For example, the following things
  903. will be parsed as single sub- or superscripts:
  904. 10^24 or 10^tau several digits will be considered 1 item.
  905. 10^-12 or 10^-tau a leading sign with digits or a word
  906. x^2-y^3 will be read as x^2 - y^3, because items are
  907. terminated by almost any nonword/nondigit char.
  908. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  909. Still, ambiguity is possible. So when in doubt, use {} to enclose
  910. the sub/superscript. If you set this variable to the symbol `{}',
  911. the braces are *required* in order to trigger interpretations as
  912. sub/superscript. This can be helpful in documents that need \"_\"
  913. frequently in plain text."
  914. :group 'org-startup
  915. :version "24.4"
  916. :package-version '(Org . "8.0")
  917. :type '(choice
  918. (const :tag "Always interpret" t)
  919. (const :tag "Only with braces" {})
  920. (const :tag "Never interpret" nil)))
  921. (defcustom org-startup-with-beamer-mode nil
  922. "Non-nil means turn on `org-beamer-mode' on startup.
  923. This can also be configured on a per-file basis by adding one of
  924. the following lines anywhere in the buffer:
  925. #+STARTUP: beamer"
  926. :group 'org-startup
  927. :version "24.1"
  928. :type 'boolean)
  929. (defcustom org-startup-align-all-tables nil
  930. "Non-nil means align all tables when visiting a file.
  931. This can also be configured on a per-file basis by adding one of
  932. the following lines anywhere in the buffer:
  933. #+STARTUP: align
  934. #+STARTUP: noalign"
  935. :group 'org-startup
  936. :type 'boolean)
  937. (defcustom org-startup-shrink-all-tables nil
  938. "Non-nil means shrink all table columns with a width cookie.
  939. This can also be configured on a per-file basis by adding one of
  940. the following lines anywhere in the buffer:
  941. #+STARTUP: shrink"
  942. :group 'org-startup
  943. :type 'boolean
  944. :version "27.1"
  945. :package-version '(Org . "9.2")
  946. :safe #'booleanp)
  947. (defcustom org-startup-with-inline-images nil
  948. "Non-nil means show inline images when loading a new Org file.
  949. This can also be configured on a per-file basis by adding one of
  950. the following lines anywhere in the buffer:
  951. #+STARTUP: inlineimages
  952. #+STARTUP: noinlineimages"
  953. :group 'org-startup
  954. :version "24.1"
  955. :type 'boolean)
  956. (defcustom org-startup-with-latex-preview nil
  957. "Non-nil means preview LaTeX fragments when loading a new Org file.
  958. This can also be configured on a per-file basis by adding one of
  959. the following lines anywhere in the buffer:
  960. #+STARTUP: latexpreview
  961. #+STARTUP: nolatexpreview"
  962. :group 'org-startup
  963. :version "24.4"
  964. :package-version '(Org . "8.0")
  965. :type 'boolean)
  966. (defcustom org-insert-mode-line-in-empty-file nil
  967. "Non-nil means insert the first line setting Org mode in empty files.
  968. When the function `org-mode' is called interactively in an empty file, this
  969. normally means that the file name does not automatically trigger Org mode.
  970. To ensure that the file will always be in Org mode in the future, a
  971. line enforcing Org mode will be inserted into the buffer, if this option
  972. has been set."
  973. :group 'org-startup
  974. :type 'boolean)
  975. (defcustom org-ellipsis nil
  976. "The ellipsis to use in the Org mode outline.
  977. When nil, just use the standard three dots. When a non-empty string,
  978. use that string instead.
  979. The change affects only Org mode (which will then use its own display table).
  980. Changing this requires executing `\\[org-mode]' in a buffer to become
  981. effective."
  982. :group 'org-startup
  983. :type '(choice (const :tag "Default" nil)
  984. (string :tag "String" :value "...#"))
  985. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  986. (defvar org-display-table nil
  987. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  988. (defgroup org-keywords nil
  989. "Keywords in Org mode."
  990. :tag "Org Keywords"
  991. :group 'org)
  992. (defcustom org-closed-keep-when-no-todo nil
  993. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  994. :group 'org-todo
  995. :group 'org-keywords
  996. :version "24.4"
  997. :package-version '(Org . "8.0")
  998. :type 'boolean)
  999. (defgroup org-structure nil
  1000. "Options concerning the general structure of Org files."
  1001. :tag "Org Structure"
  1002. :group 'org)
  1003. (defgroup org-reveal-location nil
  1004. "Options about how to make context of a location visible."
  1005. :tag "Org Reveal Location"
  1006. :group 'org-structure)
  1007. (defcustom org-show-context-detail '((agenda . local)
  1008. (bookmark-jump . lineage)
  1009. (isearch . lineage)
  1010. (default . ancestors))
  1011. "Alist between context and visibility span when revealing a location.
  1012. \\<org-mode-map>Some actions may move point into invisible
  1013. locations. As a consequence, Org always expose a neighborhood
  1014. around point. How much is shown depends on the initial action,
  1015. or context. Valid contexts are
  1016. agenda when exposing an entry from the agenda
  1017. org-goto when using the command `org-goto' (`\\[org-goto]')
  1018. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1019. tags-tree when constructing a sparse tree based on tags matches
  1020. link-search when exposing search matches associated with a link
  1021. mark-goto when exposing the jump goal of a mark
  1022. bookmark-jump when exposing a bookmark location
  1023. isearch when exiting from an incremental search
  1024. default default for all contexts not set explicitly
  1025. Allowed visibility spans are
  1026. minimal show current headline; if point is not on headline,
  1027. also show entry
  1028. local show current headline, entry and next headline
  1029. ancestors show current headline and its direct ancestors; if
  1030. point is not on headline, also show entry
  1031. lineage show current headline, its direct ancestors and all
  1032. their children; if point is not on headline, also show
  1033. entry and first child
  1034. tree show current headline, its direct ancestors and all
  1035. their children; if point is not on headline, also show
  1036. entry and all children
  1037. canonical show current headline, its direct ancestors along with
  1038. their entries and children; if point is not located on
  1039. the headline, also show current entry and all children
  1040. As special cases, a nil or t value means show all contexts in
  1041. `minimal' or `canonical' view, respectively.
  1042. Some views can make displayed information very compact, but also
  1043. make it harder to edit the location of the match. In such
  1044. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1045. more context."
  1046. :group 'org-reveal-location
  1047. :version "26.1"
  1048. :package-version '(Org . "9.0")
  1049. :type '(choice
  1050. (const :tag "Canonical" t)
  1051. (const :tag "Minimal" nil)
  1052. (repeat :greedy t :tag "Individual contexts"
  1053. (cons
  1054. (choice :tag "Context"
  1055. (const agenda)
  1056. (const org-goto)
  1057. (const occur-tree)
  1058. (const tags-tree)
  1059. (const link-search)
  1060. (const mark-goto)
  1061. (const bookmark-jump)
  1062. (const isearch)
  1063. (const default))
  1064. (choice :tag "Detail level"
  1065. (const minimal)
  1066. (const local)
  1067. (const ancestors)
  1068. (const lineage)
  1069. (const tree)
  1070. (const canonical))))))
  1071. (defcustom org-indirect-buffer-display 'other-window
  1072. "How should indirect tree buffers be displayed?
  1073. This applies to indirect buffers created with the commands
  1074. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1075. Valid values are:
  1076. current-window Display in the current window
  1077. other-window Just display in another window.
  1078. dedicated-frame Create one new frame, and re-use it each time.
  1079. new-frame Make a new frame each time. Note that in this case
  1080. previously-made indirect buffers are kept, and you need to
  1081. kill these buffers yourself."
  1082. :group 'org-structure
  1083. :group 'org-agenda-windows
  1084. :type '(choice
  1085. (const :tag "In current window" current-window)
  1086. (const :tag "In current frame, other window" other-window)
  1087. (const :tag "Each time a new frame" new-frame)
  1088. (const :tag "One dedicated frame" dedicated-frame)))
  1089. (defconst org-file-apps-gnu
  1090. '((remote . emacs)
  1091. (system . mailcap)
  1092. (t . mailcap))
  1093. "Default file applications on a UNIX or GNU/Linux system.
  1094. See `org-file-apps'.")
  1095. (defconst org-file-apps-macos
  1096. '((remote . emacs)
  1097. (system . "open %s")
  1098. ("ps.gz" . "gv %s")
  1099. ("eps.gz" . "gv %s")
  1100. ("dvi" . "xdvi %s")
  1101. ("fig" . "xfig %s")
  1102. (t . "open %s"))
  1103. "Default file applications on a macOS system.
  1104. The system \"open\" is known as a default, but we use X11 applications
  1105. for some files for which the OS does not have a good default.
  1106. See `org-file-apps'.")
  1107. (defconst org-file-apps-windowsnt
  1108. (list '(remote . emacs)
  1109. (cons 'system (lambda (file _path)
  1110. (with-no-warnings (w32-shell-execute "open" file))))
  1111. (cons t (lambda (file _path)
  1112. (with-no-warnings (w32-shell-execute "open" file)))))
  1113. "Default file applications on a Windows NT system.
  1114. The system \"open\" is used for most files.
  1115. See `org-file-apps'.")
  1116. (defcustom org-file-apps
  1117. '((auto-mode . emacs)
  1118. ("\\.mm\\'" . default)
  1119. ("\\.x?html?\\'" . default)
  1120. ("\\.pdf\\'" . default))
  1121. "External applications for opening `file:path' items in a document.
  1122. \\<org-mode-map>\
  1123. Org mode uses system defaults for different file types, but
  1124. you can use this variable to set the application for a given file
  1125. extension. The entries in this list are cons cells where the car identifies
  1126. files and the cdr the corresponding command.
  1127. Possible values for the file identifier are:
  1128. \"string\" A string as a file identifier can be interpreted in different
  1129. ways, depending on its contents:
  1130. - Alphanumeric characters only:
  1131. Match links with this file extension.
  1132. Example: (\"pdf\" . \"evince %s\")
  1133. to open PDFs with evince.
  1134. - Regular expression: Match links where the
  1135. filename matches the regexp. If you want to
  1136. use groups here, use shy groups.
  1137. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1138. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1139. to open *.html and *.xhtml with firefox.
  1140. - Regular expression which contains (non-shy) groups:
  1141. Match links where the whole link, including \"::\", and
  1142. anything after that, matches the regexp.
  1143. In a custom command string, %1, %2, etc. are replaced with
  1144. the parts of the link that were matched by the groups.
  1145. For backwards compatibility, if a command string is given
  1146. that does not use any of the group matches, this case is
  1147. handled identically to the second one (i.e. match against
  1148. file name only).
  1149. In a custom function, you can access the group matches with
  1150. (match-string n link).
  1151. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1152. \"evince -p %1 %s\")
  1153. to open [[file:document.pdf::5]] with evince at page 5.
  1154. `directory' Matches a directory
  1155. `remote' Matches a remote file, accessible through tramp or efs.
  1156. Remote files most likely should be visited through Emacs
  1157. because external applications cannot handle such paths.
  1158. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1159. so all files Emacs knows how to handle. Using this with
  1160. command `emacs' will open most files in Emacs. Beware that this
  1161. will also open html files inside Emacs, unless you add
  1162. (\"html\" . default) to the list as well.
  1163. `system' The system command to open files, like `open' on Windows
  1164. and macOS, and mailcap under GNU/Linux. This is the command
  1165. that will be selected if you call `org-open-at-point' with a
  1166. double prefix argument (`\\[universal-argument] \
  1167. \\[universal-argument] \\[org-open-at-point]').
  1168. t Default for files not matched by any of the other options.
  1169. Possible values for the command are:
  1170. `emacs' The file will be visited by the current Emacs process.
  1171. `default' Use the default application for this file type, which is the
  1172. association for t in the list, most likely in the system-specific
  1173. part. This can be used to overrule an unwanted setting in the
  1174. system-specific variable.
  1175. `system' Use the system command for opening files, like \"open\".
  1176. This command is specified by the entry whose car is `system'.
  1177. Most likely, the system-specific version of this variable
  1178. does define this command, but you can overrule/replace it
  1179. here.
  1180. `mailcap' Use command specified in the mailcaps.
  1181. string A command to be executed by a shell; %s will be replaced
  1182. by the path to the file.
  1183. function A Lisp function, which will be called with two arguments:
  1184. the file path and the original link string, without the
  1185. \"file:\" prefix.
  1186. For more examples, see the system specific constants
  1187. `org-file-apps-macos'
  1188. `org-file-apps-windowsnt'
  1189. `org-file-apps-gnu'."
  1190. :group 'org
  1191. :type '(repeat
  1192. (cons (choice :value ""
  1193. (string :tag "Extension")
  1194. (const :tag "System command to open files" system)
  1195. (const :tag "Default for unrecognized files" t)
  1196. (const :tag "Remote file" remote)
  1197. (const :tag "Links to a directory" directory)
  1198. (const :tag "Any files that have Emacs modes"
  1199. auto-mode))
  1200. (choice :value ""
  1201. (const :tag "Visit with Emacs" emacs)
  1202. (const :tag "Use default" default)
  1203. (const :tag "Use the system command" system)
  1204. (string :tag "Command")
  1205. (function :tag "Function")))))
  1206. (defcustom org-open-non-existing-files nil
  1207. "Non-nil means `org-open-file' opens non-existing files.
  1208. When nil, an error is thrown.
  1209. This variable applies only to external applications because they
  1210. might choke on non-existing files. If the link is to a file that
  1211. will be opened in Emacs, the variable is ignored."
  1212. :group 'org
  1213. :type 'boolean
  1214. :safe #'booleanp)
  1215. (defcustom org-open-directory-means-index-dot-org nil
  1216. "When non-nil a link to a directory really means to \"index.org\".
  1217. When nil, following a directory link runs Dired or opens
  1218. a finder/explorer window on that directory."
  1219. :group 'org
  1220. :type 'boolean
  1221. :safe #'booleanp)
  1222. (defcustom org-bookmark-names-plist
  1223. '(:last-capture "org-capture-last-stored"
  1224. :last-refile "org-refile-last-stored"
  1225. :last-capture-marker "org-capture-last-stored-marker")
  1226. "Names for bookmarks automatically set by some Org commands.
  1227. This can provide strings as names for a number of bookmarks Org sets
  1228. automatically. The following keys are currently implemented:
  1229. :last-capture
  1230. :last-capture-marker
  1231. :last-refile
  1232. When a key does not show up in the property list, the corresponding bookmark
  1233. is not set."
  1234. :group 'org-structure
  1235. :type 'plist)
  1236. (defgroup org-cycle nil
  1237. "Options concerning visibility cycling in Org mode."
  1238. :tag "Org Cycle"
  1239. :group 'org-structure)
  1240. (defcustom org-cycle-skip-children-state-if-no-children t
  1241. "Non-nil means skip CHILDREN state in entries that don't have any."
  1242. :group 'org-cycle
  1243. :type 'boolean)
  1244. (defcustom org-cycle-max-level nil
  1245. "Maximum level which should still be subject to visibility cycling.
  1246. Levels higher than this will, for cycling, be treated as text, not a headline.
  1247. When `org-odd-levels-only' is set, a value of N in this variable actually
  1248. means 2N-1 stars as the limiting headline.
  1249. When nil, cycle all levels.
  1250. Note that the limiting level of cycling is also influenced by
  1251. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1252. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1253. than its value."
  1254. :group 'org-cycle
  1255. :type '(choice
  1256. (const :tag "No limit" nil)
  1257. (integer :tag "Maximum level")))
  1258. (defcustom org-hide-block-startup nil
  1259. "Non-nil means entering Org mode will fold all blocks.
  1260. This can also be set in on a per-file basis with
  1261. #+STARTUP: hideblocks
  1262. #+STARTUP: showblocks"
  1263. :group 'org-startup
  1264. :group 'org-cycle
  1265. :type 'boolean)
  1266. (defcustom org-cycle-global-at-bob nil
  1267. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1268. This makes it possible to do global cycling without having to use `S-TAB'
  1269. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1270. line of the buffer
  1271. must not be a headline -- it may be empty or some other text.
  1272. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1273. sure the cursor stays at the beginning of the buffer.
  1274. When this option is nil, don't do anything special at the beginning of
  1275. the buffer."
  1276. :group 'org-cycle
  1277. :type 'boolean)
  1278. (defcustom org-cycle-level-after-item/entry-creation t
  1279. "Non-nil means cycle entry level or item indentation in new empty entries.
  1280. When the cursor is at the end of an empty headline, i.e., with only stars
  1281. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1282. and then all possible ancestor states, before returning to the original state.
  1283. This makes data entry extremely fast: M-RET to create a new headline,
  1284. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1285. When the cursor is at the end of an empty plain list item, one TAB will
  1286. make it a subitem, two or more tabs will back up to make this an item
  1287. higher up in the item hierarchy."
  1288. :group 'org-cycle
  1289. :type 'boolean)
  1290. (defcustom org-cycle-emulate-tab t
  1291. "Where should `org-cycle' emulate TAB.
  1292. nil Never
  1293. white Only in completely white lines
  1294. whitestart Only at the beginning of lines, before the first non-white char
  1295. t Everywhere except in headlines
  1296. exc-hl-bol Everywhere except at the start of a headline
  1297. If TAB is used in a place where it does not emulate TAB, the current subtree
  1298. visibility is cycled."
  1299. :group 'org-cycle
  1300. :type '(choice (const :tag "Never" nil)
  1301. (const :tag "Only in completely white lines" white)
  1302. (const :tag "Before first char in a line" whitestart)
  1303. (const :tag "Everywhere except in headlines" t)
  1304. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1305. (defcustom org-cycle-separator-lines 2
  1306. "Number of empty lines needed to keep an empty line between collapsed trees.
  1307. If you leave an empty line between the end of a subtree and the following
  1308. headline, this empty line is hidden when the subtree is folded.
  1309. Org mode will leave (exactly) one empty line visible if the number of
  1310. empty lines is equal or larger to the number given in this variable.
  1311. So the default 2 means at least 2 empty lines after the end of a subtree
  1312. are needed to produce free space between a collapsed subtree and the
  1313. following headline.
  1314. If the number is negative, and the number of empty lines is at least -N,
  1315. all empty lines are shown.
  1316. Special case: when 0, never leave empty lines in collapsed view."
  1317. :group 'org-cycle
  1318. :type 'integer)
  1319. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1320. (defcustom org-pre-cycle-hook nil
  1321. "Hook that is run before visibility cycling is happening.
  1322. The function(s) in this hook must accept a single argument which indicates
  1323. the new state that will be set right after running this hook. The
  1324. argument is a symbol. Before a global state change, it can have the values
  1325. `overview', `content', or `all'. Before a local state change, it can have
  1326. the values `folded', `children', or `subtree'."
  1327. :group 'org-cycle
  1328. :type 'hook)
  1329. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1330. org-cycle-show-empty-lines
  1331. org-optimize-window-after-visibility-change)
  1332. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1333. The function(s) in this hook must accept a single argument which indicates
  1334. the new state that was set by the most recent `org-cycle' command. The
  1335. argument is a symbol. After a global state change, it can have the values
  1336. `overview', `contents', or `all'. After a local state change, it can have
  1337. the values `folded', `children', or `subtree'."
  1338. :group 'org-cycle
  1339. :type 'hook
  1340. :version "26.1"
  1341. :package-version '(Org . "8.3"))
  1342. (defgroup org-edit-structure nil
  1343. "Options concerning structure editing in Org mode."
  1344. :tag "Org Edit Structure"
  1345. :group 'org-structure)
  1346. (defcustom org-odd-levels-only nil
  1347. "Non-nil means skip even levels and only use odd levels for the outline.
  1348. This has the effect that two stars are being added/taken away in
  1349. promotion/demotion commands. It also influences how levels are
  1350. handled by the exporters.
  1351. Changing it requires restart of `font-lock-mode' to become effective
  1352. for fontification also in regions already fontified.
  1353. You may also set this on a per-file basis by adding one of the following
  1354. lines to the buffer:
  1355. #+STARTUP: odd
  1356. #+STARTUP: oddeven"
  1357. :group 'org-edit-structure
  1358. :group 'org-appearance
  1359. :type 'boolean)
  1360. (defcustom org-adapt-indentation t
  1361. "Non-nil means adapt indentation to outline node level.
  1362. When this variable is set, Org assumes that you write outlines by
  1363. indenting text in each node to align with the headline (after the
  1364. stars). The following issues are influenced by this variable:
  1365. - The indentation is increased by one space in a demotion
  1366. command, and decreased by one in a promotion command. However,
  1367. in the latter case, if shifting some line in the entry body
  1368. would alter document structure (e.g., insert a new headline),
  1369. indentation is not changed at all.
  1370. - Property drawers and planning information is inserted indented
  1371. when this variable is set. When nil, they will not be indented.
  1372. - TAB indents a line relative to current level. The lines below
  1373. a headline will be indented when this variable is set.
  1374. Note that this is all about true indentation, by adding and
  1375. removing space characters. See also \"org-indent.el\" which does
  1376. level-dependent indentation in a virtual way, i.e. at display
  1377. time in Emacs."
  1378. :group 'org-edit-structure
  1379. :type 'boolean
  1380. :safe #'booleanp)
  1381. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1382. (defcustom org-special-ctrl-a/e nil
  1383. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1384. When t, `C-a' will bring back the cursor to the beginning of the
  1385. headline text, i.e. after the stars and after a possible TODO
  1386. keyword. In an item, this will be the position after bullet and
  1387. check-box, if any. When the cursor is already at that position,
  1388. another `C-a' will bring it to the beginning of the line.
  1389. `C-e' will jump to the end of the headline, ignoring the presence
  1390. of tags in the headline. A second `C-e' will then jump to the
  1391. true end of the line, after any tags. This also means that, when
  1392. this variable is non-nil, `C-e' also will never jump beyond the
  1393. end of the heading of a folded section, i.e. not after the
  1394. ellipses.
  1395. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1396. normally, going to the true line boundary first. Only a directly
  1397. following, identical keypress will bring the cursor to the
  1398. special positions.
  1399. This may also be a cons cell where the behavior for `C-a' and
  1400. `C-e' is set separately."
  1401. :group 'org-edit-structure
  1402. :type '(choice
  1403. (const :tag "off" nil)
  1404. (const :tag "on: after stars/bullet and before tags first" t)
  1405. (const :tag "reversed: true line boundary first" reversed)
  1406. (cons :tag "Set C-a and C-e separately"
  1407. (choice :tag "Special C-a"
  1408. (const :tag "off" nil)
  1409. (const :tag "on: after stars/bullet first" t)
  1410. (const :tag "reversed: before stars/bullet first" reversed))
  1411. (choice :tag "Special C-e"
  1412. (const :tag "off" nil)
  1413. (const :tag "on: before tags first" t)
  1414. (const :tag "reversed: after tags first" reversed)))))
  1415. (defcustom org-special-ctrl-k nil
  1416. "Non-nil means `C-k' will behave specially in headlines.
  1417. When nil, `C-k' will call the default `kill-line' command.
  1418. When t, the following will happen while the cursor is in the headline:
  1419. - When the cursor is at the beginning of a headline, kill the entire
  1420. line and possible the folded subtree below the line.
  1421. - When in the middle of the headline text, kill the headline up to the tags.
  1422. - When after the headline text, kill the tags."
  1423. :group 'org-edit-structure
  1424. :type 'boolean)
  1425. (defcustom org-ctrl-k-protect-subtree nil
  1426. "Non-nil means, do not delete a hidden subtree with C-k.
  1427. When set to the symbol `error', simply throw an error when C-k is
  1428. used to kill (part-of) a headline that has hidden text behind it.
  1429. Any other non-nil value will result in a query to the user, if it is
  1430. OK to kill that hidden subtree. When nil, kill without remorse."
  1431. :group 'org-edit-structure
  1432. :version "24.1"
  1433. :type '(choice
  1434. (const :tag "Do not protect hidden subtrees" nil)
  1435. (const :tag "Protect hidden subtrees with a security query" t)
  1436. (const :tag "Never kill a hidden subtree with C-k" error)))
  1437. (defcustom org-special-ctrl-o t
  1438. "Non-nil means, make `C-o' insert a row in tables."
  1439. :group 'org-edit-structure
  1440. :type 'boolean)
  1441. (defcustom org-catch-invisible-edits nil
  1442. "Check if in invisible region before inserting or deleting a character.
  1443. Valid values are:
  1444. nil Do not check, so just do invisible edits.
  1445. error Throw an error and do nothing.
  1446. show Make point visible, and do the requested edit.
  1447. show-and-error Make point visible, then throw an error and abort the edit.
  1448. smart Make point visible, and do insertion/deletion if it is
  1449. adjacent to visible text and the change feels predictable.
  1450. Never delete a previously invisible character or add in the
  1451. middle or right after an invisible region. Basically, this
  1452. allows insertion and backward-delete right before ellipses.
  1453. FIXME: maybe in this case we should not even show?"
  1454. :group 'org-edit-structure
  1455. :version "24.1"
  1456. :type '(choice
  1457. (const :tag "Do not check" nil)
  1458. (const :tag "Throw error when trying to edit" error)
  1459. (const :tag "Unhide, but do not do the edit" show-and-error)
  1460. (const :tag "Show invisible part and do the edit" show)
  1461. (const :tag "Be smart and do the right thing" smart)))
  1462. (defcustom org-yank-folded-subtrees t
  1463. "Non-nil means when yanking subtrees, fold them.
  1464. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1465. it starts with a heading and all other headings in it are either children
  1466. or siblings, then fold all the subtrees. However, do this only if no
  1467. text after the yank would be swallowed into a folded tree by this action."
  1468. :group 'org-edit-structure
  1469. :type 'boolean)
  1470. (defcustom org-yank-adjusted-subtrees nil
  1471. "Non-nil means when yanking subtrees, adjust the level.
  1472. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1473. this function for details."
  1474. :group 'org-edit-structure
  1475. :type 'boolean)
  1476. (defcustom org-M-RET-may-split-line '((default . t))
  1477. "Non-nil means M-RET will split the line at the cursor position.
  1478. When nil, it will go to the end of the line before making a
  1479. new line.
  1480. You may also set this option in a different way for different
  1481. contexts. Valid contexts are:
  1482. headline when creating a new headline
  1483. item when creating a new item
  1484. table in a table field
  1485. default the value to be used for all contexts not explicitly
  1486. customized"
  1487. :group 'org-structure
  1488. :group 'org-table
  1489. :type '(choice
  1490. (const :tag "Always" t)
  1491. (const :tag "Never" nil)
  1492. (repeat :greedy t :tag "Individual contexts"
  1493. (cons
  1494. (choice :tag "Context"
  1495. (const headline)
  1496. (const item)
  1497. (const table)
  1498. (const default))
  1499. (boolean)))))
  1500. (defcustom org-insert-heading-respect-content nil
  1501. "Non-nil means insert new headings after the current subtree.
  1502. \\<org-mode-map>
  1503. When nil, the new heading is created directly after the current line.
  1504. The commands `\\[org-insert-heading-respect-content]' and \
  1505. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1506. for the duration of the command."
  1507. :group 'org-structure
  1508. :type 'boolean)
  1509. (defcustom org-blank-before-new-entry '((heading . auto)
  1510. (plain-list-item . auto))
  1511. "Should `org-insert-heading' leave a blank line before new heading/item?
  1512. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1513. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1514. which case Org will look at the surrounding headings/items and try to
  1515. make an intelligent decision whether to insert a blank line or not."
  1516. :group 'org-edit-structure
  1517. :type '(list
  1518. (cons (const heading)
  1519. (choice (const :tag "Never" nil)
  1520. (const :tag "Always" t)
  1521. (const :tag "Auto" auto)))
  1522. (cons (const plain-list-item)
  1523. (choice (const :tag "Never" nil)
  1524. (const :tag "Always" t)
  1525. (const :tag "Auto" auto)))))
  1526. (defcustom org-insert-heading-hook nil
  1527. "Hook being run after inserting a new heading."
  1528. :group 'org-edit-structure
  1529. :type 'hook)
  1530. (defcustom org-enable-fixed-width-editor t
  1531. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1532. This currently only means they are never auto-wrapped.
  1533. When nil, such lines will be treated like ordinary lines."
  1534. :group 'org-edit-structure
  1535. :type 'boolean)
  1536. (defgroup org-sparse-trees nil
  1537. "Options concerning sparse trees in Org mode."
  1538. :tag "Org Sparse Trees"
  1539. :group 'org-structure)
  1540. (defcustom org-highlight-sparse-tree-matches t
  1541. "Non-nil means highlight all matches that define a sparse tree.
  1542. The highlights will automatically disappear the next time the buffer is
  1543. changed by an edit command."
  1544. :group 'org-sparse-trees
  1545. :type 'boolean)
  1546. (defcustom org-remove-highlights-with-change t
  1547. "Non-nil means any change to the buffer will remove temporary highlights.
  1548. \\<org-mode-map>\
  1549. Such highlights are created by `org-occur' and `org-clock-display'.
  1550. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1551. to get rid of the highlights.
  1552. The highlights created by `org-latex-preview' always need
  1553. `\\[org-latex-preview]' to be removed."
  1554. :group 'org-sparse-trees
  1555. :group 'org-time
  1556. :type 'boolean)
  1557. (defcustom org-occur-case-fold-search t
  1558. "Non-nil means `org-occur' should be case-insensitive.
  1559. If set to `smart' the search will be case-insensitive only if it
  1560. doesn't specify any upper case character."
  1561. :group 'org-sparse-trees
  1562. :version "26.1"
  1563. :type '(choice
  1564. (const :tag "Case-sensitive" nil)
  1565. (const :tag "Case-insensitive" t)
  1566. (const :tag "Case-insensitive for lower case searches only" smart)))
  1567. (defcustom org-occur-hook '(org-first-headline-recenter)
  1568. "Hook that is run after `org-occur' has constructed a sparse tree.
  1569. This can be used to recenter the window to show as much of the structure
  1570. as possible."
  1571. :group 'org-sparse-trees
  1572. :type 'hook)
  1573. (defgroup org-table nil
  1574. "Options concerning tables in Org mode."
  1575. :tag "Org Table"
  1576. :group 'org)
  1577. (defcustom org-self-insert-cluster-for-undo nil
  1578. "Non-nil means cluster self-insert commands for undo when possible.
  1579. If this is set, then, like in the Emacs command loop, 20 consecutive
  1580. characters will be undone together.
  1581. This is configurable, because there is some impact on typing performance."
  1582. :group 'org-table
  1583. :type 'boolean)
  1584. (defcustom org-table-tab-recognizes-table.el t
  1585. "Non-nil means TAB will automatically notice a table.el table.
  1586. When it sees such a table, it moves point into it and - if necessary -
  1587. calls `table-recognize-table'."
  1588. :group 'org-table-editing
  1589. :type 'boolean)
  1590. (defvaralias 'org-activate-links 'org-highlight-links)
  1591. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1592. "Types of links that should be highlighted in Org files.
  1593. This is a list of symbols, each one of them leading to the
  1594. highlighting of a certain link type.
  1595. You can still open links that are not highlighted.
  1596. In principle, it does not hurt to turn on highlighting for all
  1597. link types. There may be a small gain when turning off unused
  1598. link types. The types are:
  1599. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1600. angle Links in angular brackets that may contain whitespace like
  1601. <bbdb:Carsten Dominik>.
  1602. plain Plain links in normal text, no whitespace, like http://google.com.
  1603. radio Text that is matched by a radio target, see manual for details.
  1604. tag Tag settings in a headline (link to tag search).
  1605. date Time stamps (link to calendar).
  1606. footnote Footnote labels.
  1607. If you set this variable during an Emacs session, use `org-mode-restart'
  1608. in the Org buffer so that the change takes effect."
  1609. :group 'org-appearance
  1610. :type '(set :greedy t
  1611. (const :tag "Double bracket links" bracket)
  1612. (const :tag "Angular bracket links" angle)
  1613. (const :tag "Plain text links" plain)
  1614. (const :tag "Radio target matches" radio)
  1615. (const :tag "Tags" tag)
  1616. (const :tag "Timestamps" date)
  1617. (const :tag "Footnotes" footnote)))
  1618. (defcustom org-mark-ring-length 4
  1619. "Number of different positions to be recorded in the ring.
  1620. Changing this requires a restart of Emacs to work correctly."
  1621. :group 'org-link-follow
  1622. :type 'integer)
  1623. (defgroup org-refile nil
  1624. "Options concerning refiling entries in Org mode."
  1625. :tag "Org Refile"
  1626. :group 'org)
  1627. (defcustom org-directory "~/org"
  1628. "Directory with Org files.
  1629. This is just a default location to look for Org files. There is no need
  1630. at all to put your files into this directory. It is used in the
  1631. following situations:
  1632. 1. When a capture template specifies a target file that is not an
  1633. absolute path. The path will then be interpreted relative to
  1634. `org-directory'
  1635. 2. When the value of variable `org-agenda-files' is a single file, any
  1636. relative paths in this file will be taken as relative to
  1637. `org-directory'."
  1638. :group 'org-refile
  1639. :group 'org-capture
  1640. :type 'directory)
  1641. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  1642. "Default target for storing notes.
  1643. Used as a fall back file for org-capture.el, for templates that
  1644. do not specify a target file."
  1645. :group 'org-refile
  1646. :group 'org-capture
  1647. :type 'file)
  1648. (defcustom org-reverse-note-order nil
  1649. "Non-nil means store new notes at the beginning of a file or entry.
  1650. When nil, new notes will be filed to the end of a file or entry.
  1651. This can also be a list with cons cells of regular expressions that
  1652. are matched against file names, and values."
  1653. :group 'org-capture
  1654. :group 'org-refile
  1655. :type '(choice
  1656. (const :tag "Reverse always" t)
  1657. (const :tag "Reverse never" nil)
  1658. (repeat :tag "By file name regexp"
  1659. (cons regexp boolean))))
  1660. (defcustom org-log-refile nil
  1661. "Information to record when a task is refiled.
  1662. Possible values are:
  1663. nil Don't add anything
  1664. time Add a time stamp to the task
  1665. note Prompt for a note and add it with template `org-log-note-headings'
  1666. This option can also be set with on a per-file-basis with
  1667. #+STARTUP: nologrefile
  1668. #+STARTUP: logrefile
  1669. #+STARTUP: lognoterefile
  1670. You can have local logging settings for a subtree by setting the LOGGING
  1671. property to one or more of these keywords.
  1672. When bulk-refiling, e.g., from the agenda, the value `note' is
  1673. forbidden and will temporarily be changed to `time'."
  1674. :group 'org-refile
  1675. :group 'org-progress
  1676. :version "24.1"
  1677. :type '(choice
  1678. (const :tag "No logging" nil)
  1679. (const :tag "Record timestamp" time)
  1680. (const :tag "Record timestamp with note." note)))
  1681. (defcustom org-refile-targets nil
  1682. "Targets for refiling entries with `\\[org-refile]'.
  1683. This is a list of cons cells. Each cell contains:
  1684. - a specification of the files to be considered, either a list of files,
  1685. or a symbol whose function or variable value will be used to retrieve
  1686. a file name or a list of file names. If you use `org-agenda-files' for
  1687. that, all agenda files will be scanned for targets. Nil means consider
  1688. headings in the current buffer.
  1689. - A specification of how to find candidate refile targets. This may be
  1690. any of:
  1691. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  1692. This tag has to be present in all target headlines, inheritance will
  1693. not be considered.
  1694. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  1695. todo keyword.
  1696. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  1697. headlines that are refiling targets.
  1698. - a cons cell (:level . N). Any headline of level N is considered a target.
  1699. Note that, when `org-odd-levels-only' is set, level corresponds to
  1700. order in hierarchy, not to the number of stars.
  1701. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  1702. Note that, when `org-odd-levels-only' is set, level corresponds to
  1703. order in hierarchy, not to the number of stars.
  1704. Each element of this list generates a set of possible targets.
  1705. The union of these sets is presented (with completion) to
  1706. the user by `org-refile'.
  1707. You can set the variable `org-refile-target-verify-function' to a function
  1708. to verify each headline found by the simple criteria above.
  1709. When this variable is nil, all top-level headlines in the current buffer
  1710. are used, equivalent to the value `((nil . (:level . 1))'."
  1711. :group 'org-refile
  1712. :type '(repeat
  1713. (cons
  1714. (choice :value org-agenda-files
  1715. (const :tag "All agenda files" org-agenda-files)
  1716. (const :tag "Current buffer" nil)
  1717. (function) (variable) (file))
  1718. (choice :tag "Identify target headline by"
  1719. (cons :tag "Specific tag" (const :value :tag) (string))
  1720. (cons :tag "TODO keyword" (const :value :todo) (string))
  1721. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  1722. (cons :tag "Level number" (const :value :level) (integer))
  1723. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  1724. (defcustom org-refile-target-verify-function nil
  1725. "Function to verify if the headline at point should be a refile target.
  1726. The function will be called without arguments, with point at the
  1727. beginning of the headline. It should return t and leave point
  1728. where it is if the headline is a valid target for refiling.
  1729. If the target should not be selected, the function must return nil.
  1730. In addition to this, it may move point to a place from where the search
  1731. should be continued. For example, the function may decide that the entire
  1732. subtree of the current entry should be excluded and move point to the end
  1733. of the subtree."
  1734. :group 'org-refile
  1735. :type '(choice
  1736. (const nil)
  1737. (function)))
  1738. (defcustom org-refile-use-cache nil
  1739. "Non-nil means cache refile targets to speed up the process.
  1740. \\<org-mode-map>\
  1741. The cache for a particular file will be updated automatically when
  1742. the buffer has been killed, or when any of the marker used for flagging
  1743. refile targets no longer points at a live buffer.
  1744. If you have added new entries to a buffer that might themselves be targets,
  1745. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  1746. if you find that easier, \
  1747. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  1748. \\[org-refile]'."
  1749. :group 'org-refile
  1750. :version "24.1"
  1751. :type 'boolean)
  1752. (defcustom org-refile-use-outline-path nil
  1753. "Non-nil means provide refile targets as paths.
  1754. So a level 3 headline will be available as level1/level2/level3.
  1755. When the value is `file', also include the file name (without directory)
  1756. into the path. In this case, you can also stop the completion after
  1757. the file name, to get entries inserted as top level in the file.
  1758. When `full-file-path', include the full file path.
  1759. When `buffer-name', use the buffer name."
  1760. :group 'org-refile
  1761. :type '(choice
  1762. (const :tag "Not" nil)
  1763. (const :tag "Yes" t)
  1764. (const :tag "Start with file name" file)
  1765. (const :tag "Start with full file path" full-file-path)
  1766. (const :tag "Start with buffer name" buffer-name)))
  1767. (defcustom org-outline-path-complete-in-steps t
  1768. "Non-nil means complete the outline path in hierarchical steps.
  1769. When Org uses the refile interface to select an outline path (see
  1770. `org-refile-use-outline-path'), the completion of the path can be
  1771. done in a single go, or it can be done in steps down the headline
  1772. hierarchy. Going in steps is probably the best if you do not use
  1773. a special completion package like `ido' or `icicles'. However,
  1774. when using these packages, going in one step can be very fast,
  1775. while still showing the whole path to the entry."
  1776. :group 'org-refile
  1777. :type 'boolean)
  1778. (defcustom org-refile-allow-creating-parent-nodes nil
  1779. "Non-nil means allow the creation of new nodes as refile targets.
  1780. New nodes are then created by adding \"/new node name\" to the completion
  1781. of an existing node. When the value of this variable is `confirm',
  1782. new node creation must be confirmed by the user (recommended).
  1783. When nil, the completion must match an existing entry.
  1784. Note that, if the new heading is not seen by the criteria
  1785. listed in `org-refile-targets', multiple instances of the same
  1786. heading would be created by trying again to file under the new
  1787. heading."
  1788. :group 'org-refile
  1789. :type '(choice
  1790. (const :tag "Never" nil)
  1791. (const :tag "Always" t)
  1792. (const :tag "Prompt for confirmation" confirm)))
  1793. (defcustom org-refile-active-region-within-subtree nil
  1794. "Non-nil means also refile active region within a subtree.
  1795. By default `org-refile' doesn't allow refiling regions if they
  1796. don't contain a set of subtrees, but it might be convenient to
  1797. do so sometimes: in that case, the first line of the region is
  1798. converted to a headline before refiling."
  1799. :group 'org-refile
  1800. :version "24.1"
  1801. :type 'boolean)
  1802. (defgroup org-todo nil
  1803. "Options concerning TODO items in Org mode."
  1804. :tag "Org TODO"
  1805. :group 'org)
  1806. (defgroup org-progress nil
  1807. "Options concerning Progress logging in Org mode."
  1808. :tag "Org Progress"
  1809. :group 'org-time)
  1810. (defvar org-todo-interpretation-widgets
  1811. '((:tag "Sequence (cycling hits every state)" sequence)
  1812. (:tag "Type (cycling directly to DONE)" type))
  1813. "The available interpretation symbols for customizing `org-todo-keywords'.
  1814. Interested libraries should add to this list.")
  1815. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1816. "List of TODO entry keyword sequences and their interpretation.
  1817. \\<org-mode-map>This is a list of sequences.
  1818. Each sequence starts with a symbol, either `sequence' or `type',
  1819. indicating if the keywords should be interpreted as a sequence of
  1820. action steps, or as different types of TODO items. The first
  1821. keywords are states requiring action - these states will select a headline
  1822. for inclusion into the global TODO list Org produces. If one of the
  1823. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1824. signify that no further action is necessary. If \"|\" is not found,
  1825. the last keyword is treated as the only DONE state of the sequence.
  1826. The command `\\[org-todo]' cycles an entry through these states, and one
  1827. additional state where no keyword is present. For details about this
  1828. cycling, see the manual.
  1829. TODO keywords and interpretation can also be set on a per-file basis with
  1830. the special #+SEQ_TODO and #+TYP_TODO lines.
  1831. Each keyword can optionally specify a character for fast state selection
  1832. \(in combination with the variable `org-use-fast-todo-selection')
  1833. and specifiers for state change logging, using the same syntax that
  1834. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1835. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1836. indicates to record a time stamp each time this state is selected.
  1837. Each keyword may also specify if a timestamp or a note should be
  1838. recorded when entering or leaving the state, by adding additional
  1839. characters in the parenthesis after the keyword. This looks like this:
  1840. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1841. record only the time of the state change. With X and Y being either
  1842. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1843. Y when leaving the state if and only if the *target* state does not
  1844. define X. You may omit any of the fast-selection key or X or /Y,
  1845. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1846. For backward compatibility, this variable may also be just a list
  1847. of keywords. In this case the interpretation (sequence or type) will be
  1848. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1849. :group 'org-todo
  1850. :group 'org-keywords
  1851. :type '(choice
  1852. (repeat :tag "Old syntax, just keywords"
  1853. (string :tag "Keyword"))
  1854. (repeat :tag "New syntax"
  1855. (cons
  1856. (choice
  1857. :tag "Interpretation"
  1858. ;;Quick and dirty way to see
  1859. ;;`org-todo-interpretations'. This takes the
  1860. ;;place of item arguments
  1861. :convert-widget
  1862. (lambda (widget)
  1863. (widget-put widget
  1864. :args (mapcar
  1865. (lambda (x)
  1866. (widget-convert
  1867. (cons 'const x)))
  1868. org-todo-interpretation-widgets))
  1869. widget))
  1870. (repeat
  1871. (string :tag "Keyword"))))))
  1872. (defvar-local org-todo-keywords-1 nil
  1873. "All TODO and DONE keywords active in a buffer.")
  1874. (defvar org-todo-keywords-for-agenda nil)
  1875. (defvar org-done-keywords-for-agenda nil)
  1876. (defvar org-todo-keyword-alist-for-agenda nil)
  1877. (defvar org-tag-alist-for-agenda nil
  1878. "Alist of all tags from all agenda files.")
  1879. (defvar org-tag-groups-alist-for-agenda nil
  1880. "Alist of all groups tags from all current agenda files.")
  1881. (defvar-local org-tag-groups-alist nil)
  1882. (defvar org-agenda-contributing-files nil)
  1883. (defvar-local org-current-tag-alist nil
  1884. "Alist of all tag groups in current buffer.
  1885. This variable takes into consideration `org-tag-alist',
  1886. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1887. (defvar-local org-not-done-keywords nil)
  1888. (defvar-local org-done-keywords nil)
  1889. (defvar-local org-todo-heads nil)
  1890. (defvar-local org-todo-sets nil)
  1891. (defvar-local org-todo-log-states nil)
  1892. (defvar-local org-todo-kwd-alist nil)
  1893. (defvar-local org-todo-key-alist nil)
  1894. (defvar-local org-todo-key-trigger nil)
  1895. (defcustom org-todo-interpretation 'sequence
  1896. "Controls how TODO keywords are interpreted.
  1897. This variable is in principle obsolete and is only used for
  1898. backward compatibility, if the interpretation of todo keywords is
  1899. not given already in `org-todo-keywords'. See that variable for
  1900. more information."
  1901. :group 'org-todo
  1902. :group 'org-keywords
  1903. :type '(choice (const sequence)
  1904. (const type)))
  1905. (defcustom org-use-fast-todo-selection t
  1906. "\\<org-mode-map>\
  1907. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1908. This variable describes if and under what circumstances the cycling
  1909. mechanism for TODO keywords will be replaced by a single-key, direct
  1910. selection scheme.
  1911. When nil, fast selection is never used.
  1912. When the symbol `prefix', it will be used when `org-todo' is called
  1913. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  1914. in an Org buffer, and
  1915. `\\[universal-argument] t' in an agenda buffer.
  1916. When t, fast selection is used by default. In this case, the prefix
  1917. argument forces cycling instead.
  1918. In all cases, the special interface is only used if access keys have
  1919. actually been assigned by the user, i.e. if keywords in the configuration
  1920. are followed by a letter in parenthesis, like TODO(t)."
  1921. :group 'org-todo
  1922. :type '(choice
  1923. (const :tag "Never" nil)
  1924. (const :tag "By default" t)
  1925. (const :tag "Only with C-u C-c C-t" prefix)))
  1926. (defcustom org-provide-todo-statistics t
  1927. "Non-nil means update todo statistics after insert and toggle.
  1928. ALL-HEADLINES means update todo statistics by including headlines
  1929. with no TODO keyword as well, counting them as not done.
  1930. A list of TODO keywords means the same, but skip keywords that are
  1931. not in this list.
  1932. When set to a list of two lists, the first list contains keywords
  1933. to consider as TODO keywords, the second list contains keywords
  1934. to consider as DONE keywords.
  1935. When this is set, todo statistics is updated in the parent of the
  1936. current entry each time a todo state is changed."
  1937. :group 'org-todo
  1938. :type '(choice
  1939. (const :tag "Yes, only for TODO entries" t)
  1940. (const :tag "Yes, including all entries" all-headlines)
  1941. (repeat :tag "Yes, for TODOs in this list"
  1942. (string :tag "TODO keyword"))
  1943. (list :tag "Yes, for TODOs and DONEs in these lists"
  1944. (repeat (string :tag "TODO keyword"))
  1945. (repeat (string :tag "DONE keyword")))
  1946. (other :tag "No TODO statistics" nil)))
  1947. (defcustom org-hierarchical-todo-statistics t
  1948. "Non-nil means TODO statistics covers just direct children.
  1949. When nil, all entries in the subtree are considered.
  1950. This has only an effect if `org-provide-todo-statistics' is set.
  1951. To set this to nil for only a single subtree, use a COOKIE_DATA
  1952. property and include the word \"recursive\" into the value."
  1953. :group 'org-todo
  1954. :type 'boolean)
  1955. (defcustom org-after-todo-state-change-hook nil
  1956. "Hook which is run after the state of a TODO item was changed.
  1957. The new state (a string with a TODO keyword, or nil) is available in the
  1958. Lisp variable `org-state'."
  1959. :group 'org-todo
  1960. :type 'hook)
  1961. (defvar org-blocker-hook nil
  1962. "Hook for functions that are allowed to block a state change.
  1963. Functions in this hook should not modify the buffer.
  1964. Each function gets as its single argument a property list,
  1965. see `org-trigger-hook' for more information about this list.
  1966. If any of the functions in this hook returns nil, the state change
  1967. is blocked.")
  1968. (defvar org-trigger-hook nil
  1969. "Hook for functions that are triggered by a state change.
  1970. Each function gets as its single argument a property list with at
  1971. least the following elements:
  1972. (:type type-of-change :position pos-at-entry-start
  1973. :from old-state :to new-state)
  1974. Depending on the type, more properties may be present.
  1975. This mechanism is currently implemented for:
  1976. TODO state changes
  1977. ------------------
  1978. :type todo-state-change
  1979. :from previous state (keyword as a string), or nil, or a symbol
  1980. `todo' or `done', to indicate the general type of state.
  1981. :to new state, like in :from")
  1982. (defcustom org-enforce-todo-dependencies nil
  1983. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1984. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1985. be blocked if any prior sibling is not yet done.
  1986. Finally, if the parent is blocked because of ordered siblings of its own,
  1987. the child will also be blocked."
  1988. :set (lambda (var val)
  1989. (set var val)
  1990. (if val
  1991. (add-hook 'org-blocker-hook
  1992. 'org-block-todo-from-children-or-siblings-or-parent)
  1993. (remove-hook 'org-blocker-hook
  1994. 'org-block-todo-from-children-or-siblings-or-parent)))
  1995. :group 'org-todo
  1996. :type 'boolean)
  1997. (defcustom org-enforce-todo-checkbox-dependencies nil
  1998. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1999. When this is nil, checkboxes have no influence on switching TODO states.
  2000. When non-nil, you first need to check off all check boxes before the TODO
  2001. entry can be switched to DONE.
  2002. This variable needs to be set before org.el is loaded, and you need to
  2003. restart Emacs after a change to make the change effective. The only way
  2004. to change it while Emacs is running is through the customize interface."
  2005. :set (lambda (var val)
  2006. (set var val)
  2007. (if val
  2008. (add-hook 'org-blocker-hook
  2009. 'org-block-todo-from-checkboxes)
  2010. (remove-hook 'org-blocker-hook
  2011. 'org-block-todo-from-checkboxes)))
  2012. :group 'org-todo
  2013. :type 'boolean)
  2014. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2015. "Non-nil means inserting a TODO heading is treated as state change.
  2016. So when the command `\\[org-insert-todo-heading]' is used, state change
  2017. logging will apply if appropriate. When nil, the new TODO item will
  2018. be inserted directly, and no logging will take place."
  2019. :group 'org-todo
  2020. :type 'boolean)
  2021. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2022. "Non-nil means switching TODO states with S-cursor counts as state change.
  2023. This is the default behavior. However, setting this to nil allows a
  2024. convenient way to select a TODO state and bypass any logging associated
  2025. with that."
  2026. :group 'org-todo
  2027. :type 'boolean)
  2028. (defcustom org-todo-state-tags-triggers nil
  2029. "Tag changes that should be triggered by TODO state changes.
  2030. This is a list. Each entry is
  2031. (state-change (tag . flag) .......)
  2032. State-change can be a string with a state, and empty string to indicate the
  2033. state that has no TODO keyword, or it can be one of the symbols `todo'
  2034. or `done', meaning any not-done or done state, respectively."
  2035. :group 'org-todo
  2036. :group 'org-tags
  2037. :type '(repeat
  2038. (cons (choice :tag "When changing to"
  2039. (const :tag "Not-done state" todo)
  2040. (const :tag "Done state" done)
  2041. (string :tag "State"))
  2042. (repeat
  2043. (cons :tag "Tag action"
  2044. (string :tag "Tag")
  2045. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2046. (defcustom org-log-done nil
  2047. "Information to record when a task moves to the DONE state.
  2048. Possible values are:
  2049. nil Don't add anything, just change the keyword
  2050. time Add a time stamp to the task
  2051. note Prompt for a note and add it with template `org-log-note-headings'
  2052. This option can also be set with on a per-file-basis with
  2053. #+STARTUP: nologdone
  2054. #+STARTUP: logdone
  2055. #+STARTUP: lognotedone
  2056. You can have local logging settings for a subtree by setting the LOGGING
  2057. property to one or more of these keywords."
  2058. :group 'org-todo
  2059. :group 'org-progress
  2060. :type '(choice
  2061. (const :tag "No logging" nil)
  2062. (const :tag "Record CLOSED timestamp" time)
  2063. (const :tag "Record CLOSED timestamp with note." note)))
  2064. ;; Normalize old uses of org-log-done.
  2065. (cond
  2066. ((eq org-log-done t) (setq org-log-done 'time))
  2067. ((and (listp org-log-done) (memq 'done org-log-done))
  2068. (setq org-log-done 'note)))
  2069. (defcustom org-log-reschedule nil
  2070. "Information to record when the scheduling date of a task is modified.
  2071. Possible values are:
  2072. nil Don't add anything, just change the date
  2073. time Add a time stamp to the task
  2074. note Prompt for a note and add it with template `org-log-note-headings'
  2075. This option can also be set with on a per-file-basis with
  2076. #+STARTUP: nologreschedule
  2077. #+STARTUP: logreschedule
  2078. #+STARTUP: lognotereschedule
  2079. You can have local logging settings for a subtree by setting the LOGGING
  2080. property to one or more of these keywords.
  2081. This variable has an effect when calling `org-schedule' or
  2082. `org-agenda-schedule' only."
  2083. :group 'org-todo
  2084. :group 'org-progress
  2085. :type '(choice
  2086. (const :tag "No logging" nil)
  2087. (const :tag "Record timestamp" time)
  2088. (const :tag "Record timestamp with note" note)))
  2089. (defcustom org-log-redeadline nil
  2090. "Information to record when the deadline date of a task is modified.
  2091. Possible values are:
  2092. nil Don't add anything, just change the date
  2093. time Add a time stamp to the task
  2094. note Prompt for a note and add it with template `org-log-note-headings'
  2095. This option can also be set with on a per-file-basis with
  2096. #+STARTUP: nologredeadline
  2097. #+STARTUP: logredeadline
  2098. #+STARTUP: lognoteredeadline
  2099. You can have local logging settings for a subtree by setting the LOGGING
  2100. property to one or more of these keywords.
  2101. This variable has an effect when calling `org-deadline' or
  2102. `org-agenda-deadline' only."
  2103. :group 'org-todo
  2104. :group 'org-progress
  2105. :type '(choice
  2106. (const :tag "No logging" nil)
  2107. (const :tag "Record timestamp" time)
  2108. (const :tag "Record timestamp with note." note)))
  2109. (defcustom org-log-note-clock-out nil
  2110. "Non-nil means record a note when clocking out of an item.
  2111. This can also be configured on a per-file basis by adding one of
  2112. the following lines anywhere in the buffer:
  2113. #+STARTUP: lognoteclock-out
  2114. #+STARTUP: nolognoteclock-out"
  2115. :group 'org-todo
  2116. :group 'org-progress
  2117. :type 'boolean)
  2118. (defcustom org-log-done-with-time t
  2119. "Non-nil means the CLOSED time stamp will contain date and time.
  2120. When nil, only the date will be recorded."
  2121. :group 'org-progress
  2122. :type 'boolean)
  2123. (defcustom org-log-note-headings
  2124. '((done . "CLOSING NOTE %t")
  2125. (state . "State %-12s from %-12S %t")
  2126. (note . "Note taken on %t")
  2127. (reschedule . "Rescheduled from %S on %t")
  2128. (delschedule . "Not scheduled, was %S on %t")
  2129. (redeadline . "New deadline from %S on %t")
  2130. (deldeadline . "Removed deadline, was %S on %t")
  2131. (refile . "Refiled on %t")
  2132. (clock-out . ""))
  2133. "Headings for notes added to entries.
  2134. The value is an alist, with the car being a symbol indicating the
  2135. note context, and the cdr is the heading to be used. The heading
  2136. may also be the empty string. The following placeholders can be
  2137. used:
  2138. %t a time stamp.
  2139. %T an active time stamp instead the default inactive one
  2140. %d a short-format time stamp.
  2141. %D an active short-format time stamp.
  2142. %s the new TODO state or time stamp (inactive), in double quotes.
  2143. %S the old TODO state or time stamp (inactive), in double quotes.
  2144. %u the user name.
  2145. %U full user name.
  2146. In fact, it is not a good idea to change the `state' entry,
  2147. because Agenda Log mode depends on the format of these entries."
  2148. :group 'org-todo
  2149. :group 'org-progress
  2150. :type '(list :greedy t
  2151. (cons (const :tag "Heading when closing an item" done) string)
  2152. (cons (const :tag
  2153. "Heading when changing todo state (todo sequence only)"
  2154. state) string)
  2155. (cons (const :tag "Heading when just taking a note" note) string)
  2156. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2157. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2158. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2159. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2160. (cons (const :tag "Heading when refiling" refile) string)
  2161. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2162. (unless (assq 'note org-log-note-headings)
  2163. (push '(note . "%t") org-log-note-headings))
  2164. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2165. (defcustom org-log-into-drawer nil
  2166. "Non-nil means insert state change notes and time stamps into a drawer.
  2167. When nil, state changes notes will be inserted after the headline and
  2168. any scheduling and clock lines, but not inside a drawer.
  2169. The value of this variable should be the name of the drawer to use.
  2170. LOGBOOK is proposed as the default drawer for this purpose, you can
  2171. also set this to a string to define the drawer of your choice.
  2172. A value of t is also allowed, representing \"LOGBOOK\".
  2173. A value of t or nil can also be set with on a per-file-basis with
  2174. #+STARTUP: logdrawer
  2175. #+STARTUP: nologdrawer
  2176. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2177. will be ignored.
  2178. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2179. a subtree.
  2180. Do not check directly this variable in a Lisp program. Call
  2181. function `org-log-into-drawer' instead."
  2182. :group 'org-todo
  2183. :group 'org-progress
  2184. :type '(choice
  2185. (const :tag "Not into a drawer" nil)
  2186. (const :tag "LOGBOOK" t)
  2187. (string :tag "Other")))
  2188. (defun org-log-into-drawer ()
  2189. "Name of the log drawer, as a string, or nil.
  2190. This is the value of `org-log-into-drawer'. However, if the
  2191. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2192. be used instead of the default value."
  2193. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2194. (cond ((equal p "nil") nil)
  2195. ((equal p "t") "LOGBOOK")
  2196. ((stringp p) p)
  2197. (p "LOGBOOK")
  2198. ((stringp org-log-into-drawer) org-log-into-drawer)
  2199. (org-log-into-drawer "LOGBOOK"))))
  2200. (defcustom org-log-state-notes-insert-after-drawers nil
  2201. "Non-nil means insert state change notes after any drawers in entry.
  2202. Only the drawers that *immediately* follow the headline and the
  2203. deadline/scheduled line are skipped.
  2204. When nil, insert notes right after the heading and perhaps the line
  2205. with deadline/scheduling if present.
  2206. This variable will have no effect if `org-log-into-drawer' is
  2207. set."
  2208. :group 'org-todo
  2209. :group 'org-progress
  2210. :type 'boolean)
  2211. (defcustom org-log-states-order-reversed t
  2212. "Non-nil means the latest state note will be directly after heading.
  2213. When nil, the state change notes will be ordered according to time.
  2214. This option can also be set with on a per-file-basis with
  2215. #+STARTUP: logstatesreversed
  2216. #+STARTUP: nologstatesreversed"
  2217. :group 'org-todo
  2218. :group 'org-progress
  2219. :type 'boolean)
  2220. (defcustom org-todo-repeat-to-state nil
  2221. "The TODO state to which a repeater should return the repeating task.
  2222. By default this is the first task of a TODO sequence or the
  2223. previous state of a TYPE_TODO set. But you can specify to use
  2224. the previous state in a TODO sequence or a string.
  2225. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2226. entry, which has precedence over this option."
  2227. :group 'org-todo
  2228. :version "24.1"
  2229. :type '(choice (const :tag "Use the previous TODO state" t)
  2230. (const :tag "Use the head of the TODO sequence" nil)
  2231. (string :tag "Use a specific TODO state")))
  2232. (defcustom org-log-repeat 'time
  2233. "Non-nil means record moving through the DONE state when triggering repeat.
  2234. An auto-repeating task is immediately switched back to TODO when
  2235. marked DONE. If you are not logging state changes (by adding \"@\"
  2236. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2237. record a closing note, there will be no record of the task moving
  2238. through DONE. This variable forces taking a note anyway.
  2239. nil Don't force a record
  2240. time Record a time stamp
  2241. note Prompt for a note and add it with template `org-log-note-headings'
  2242. This option can also be set with on a per-file-basis with
  2243. #+STARTUP: nologrepeat
  2244. #+STARTUP: logrepeat
  2245. #+STARTUP: lognoterepeat
  2246. You can have local logging settings for a subtree by setting the LOGGING
  2247. property to one or more of these keywords."
  2248. :group 'org-todo
  2249. :group 'org-progress
  2250. :type '(choice
  2251. (const :tag "Don't force a record" nil)
  2252. (const :tag "Force recording the DONE state" time)
  2253. (const :tag "Force recording a note with the DONE state" note)))
  2254. (defcustom org-todo-repeat-hook nil
  2255. "Hook that is run after a task has been repeated."
  2256. :package-version '(Org . "9.2")
  2257. :group 'org-todo
  2258. :type 'hook)
  2259. (defgroup org-priorities nil
  2260. "Priorities in Org mode."
  2261. :tag "Org Priorities"
  2262. :group 'org-todo)
  2263. (defcustom org-enable-priority-commands t
  2264. "Non-nil means priority commands are active.
  2265. When nil, these commands will be disabled, so that you never accidentally
  2266. set a priority."
  2267. :group 'org-priorities
  2268. :type 'boolean)
  2269. (defcustom org-highest-priority ?A
  2270. "The highest priority of TODO items. A character like ?A, ?B etc.
  2271. Must have a smaller ASCII number than `org-lowest-priority'."
  2272. :group 'org-priorities
  2273. :type 'character)
  2274. (defcustom org-lowest-priority ?C
  2275. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2276. Must have a larger ASCII number than `org-highest-priority'."
  2277. :group 'org-priorities
  2278. :type 'character)
  2279. (defcustom org-default-priority ?B
  2280. "The default priority of TODO items.
  2281. This is the priority an item gets if no explicit priority is given.
  2282. When starting to cycle on an empty priority the first step in the cycle
  2283. depends on `org-priority-start-cycle-with-default'. The resulting first
  2284. step priority must not exceed the range from `org-highest-priority' to
  2285. `org-lowest-priority' which means that `org-default-priority' has to be
  2286. in this range exclusive or inclusive the range boundaries. Else the
  2287. first step refuses to set the default and the second will fall back
  2288. to (depending on the command used) the highest or lowest priority."
  2289. :group 'org-priorities
  2290. :type 'character)
  2291. (defcustom org-priority-start-cycle-with-default t
  2292. "Non-nil means start with default priority when starting to cycle.
  2293. When this is nil, the first step in the cycle will be (depending on the
  2294. command used) one higher or lower than the default priority.
  2295. See also `org-default-priority'."
  2296. :group 'org-priorities
  2297. :type 'boolean)
  2298. (defcustom org-get-priority-function nil
  2299. "Function to extract the priority from a string.
  2300. The string is normally the headline. If this is nil Org computes the
  2301. priority from the priority cookie like [#A] in the headline. It returns
  2302. an integer, increasing by 1000 for each priority level.
  2303. The user can set a different function here, which should take a string
  2304. as an argument and return the numeric priority."
  2305. :group 'org-priorities
  2306. :version "24.1"
  2307. :type '(choice
  2308. (const nil)
  2309. (function)))
  2310. (defgroup org-time nil
  2311. "Options concerning time stamps and deadlines in Org mode."
  2312. :tag "Org Time"
  2313. :group 'org)
  2314. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2315. "Number of minutes to round time stamps to.
  2316. \\<org-mode-map>\
  2317. These are two values, the first applies when first creating a time stamp.
  2318. The second applies when changing it with the commands `S-up' and `S-down'.
  2319. When changing the time stamp, this means that it will change in steps
  2320. of N minutes, as given by the second value.
  2321. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2322. numbers should be factors of 60, so for example 5, 10, 15.
  2323. When this is larger than 1, you can still force an exact time stamp by using
  2324. a double prefix argument to a time stamp command like \
  2325. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2326. and by using a prefix arg to `S-up/down' to specify the exact number
  2327. of minutes to shift."
  2328. :group 'org-time
  2329. :get (lambda (var) ; Make sure both elements are there
  2330. (if (integerp (default-value var))
  2331. (list (default-value var) 5)
  2332. (default-value var)))
  2333. :type '(list
  2334. (integer :tag "when inserting times")
  2335. (integer :tag "when modifying times")))
  2336. ;; Normalize old customizations of this variable.
  2337. (when (integerp org-time-stamp-rounding-minutes)
  2338. (setq org-time-stamp-rounding-minutes
  2339. (list org-time-stamp-rounding-minutes
  2340. org-time-stamp-rounding-minutes)))
  2341. (defcustom org-display-custom-times nil
  2342. "Non-nil means overlay custom formats over all time stamps.
  2343. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2344. To turn this on on a per-file basis, insert anywhere in the file:
  2345. #+STARTUP: customtime"
  2346. :group 'org-time
  2347. :set 'set-default
  2348. :type 'sexp)
  2349. (make-variable-buffer-local 'org-display-custom-times)
  2350. (defcustom org-time-stamp-custom-formats
  2351. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2352. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2353. These are overlaid over the default ISO format if the variable
  2354. `org-display-custom-times' is set. Time like %H:%M should be at the
  2355. end of the second format. The custom formats are also honored by export
  2356. commands, if custom time display is turned on at the time of export."
  2357. :group 'org-time
  2358. :type 'sexp)
  2359. (defun org-time-stamp-format (&optional long inactive)
  2360. "Get the right format for a time string."
  2361. (let ((f (if long (cdr org-time-stamp-formats)
  2362. (car org-time-stamp-formats))))
  2363. (if inactive
  2364. (concat "[" (substring f 1 -1) "]")
  2365. f)))
  2366. (defcustom org-deadline-warning-days 14
  2367. "Number of days before expiration during which a deadline becomes active.
  2368. This variable governs the display in sparse trees and in the agenda.
  2369. When 0 or negative, it means use this number (the absolute value of it)
  2370. even if a deadline has a different individual lead time specified.
  2371. Custom commands can set this variable in the options section."
  2372. :group 'org-time
  2373. :group 'org-agenda-daily/weekly
  2374. :type 'integer)
  2375. (defcustom org-scheduled-delay-days 0
  2376. "Number of days before a scheduled item becomes active.
  2377. This variable governs the display in sparse trees and in the agenda.
  2378. The default value (i.e. 0) means: don't delay scheduled item.
  2379. When negative, it means use this number (the absolute value of it)
  2380. even if a scheduled item has a different individual delay time
  2381. specified.
  2382. Custom commands can set this variable in the options section."
  2383. :group 'org-time
  2384. :group 'org-agenda-daily/weekly
  2385. :version "24.4"
  2386. :package-version '(Org . "8.0")
  2387. :type 'integer)
  2388. (defcustom org-read-date-prefer-future t
  2389. "Non-nil means assume future for incomplete date input from user.
  2390. This affects the following situations:
  2391. 1. The user gives a month but not a year.
  2392. For example, if it is April and you enter \"feb 2\", this will be read
  2393. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2394. 2. The user gives a day, but no month.
  2395. For example, if today is the 15th, and you enter \"3\", Org will read
  2396. this as the third of *next* month. However, if you enter \"17\",
  2397. it will be considered as *this* month.
  2398. If you set this variable to the symbol `time', then also the following
  2399. will work:
  2400. 3. If the user gives a time.
  2401. If the time is before now, it will be interpreted as tomorrow.
  2402. Currently none of this works for ISO week specifications.
  2403. When this option is nil, the current day, month and year will always be
  2404. used as defaults.
  2405. See also `org-agenda-jump-prefer-future'."
  2406. :group 'org-time
  2407. :type '(choice
  2408. (const :tag "Never" nil)
  2409. (const :tag "Check month and day" t)
  2410. (const :tag "Check month, day, and time" time)))
  2411. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2412. "Should the agenda jump command prefer the future for incomplete dates?
  2413. The default is to do the same as configured in `org-read-date-prefer-future'.
  2414. But you can also set a deviating value here.
  2415. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2416. :group 'org-agenda
  2417. :group 'org-time
  2418. :version "24.1"
  2419. :type '(choice
  2420. (const :tag "Use org-read-date-prefer-future"
  2421. org-read-date-prefer-future)
  2422. (const :tag "Never" nil)
  2423. (const :tag "Always" t)))
  2424. (defcustom org-read-date-force-compatible-dates t
  2425. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2426. Depending on the system Emacs is running on, certain dates cannot
  2427. be represented with the type used internally to represent time.
  2428. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2429. correctly. Some systems allow for earlier dates, some for later,
  2430. some for both. One way to find out is to insert any date into an
  2431. Org buffer, putting the cursor on the year and hitting S-up and
  2432. S-down to test the range.
  2433. When this variable is set to t, the date/time prompt will not let
  2434. you specify dates outside the 1970-2037 range, so it is certain that
  2435. these dates will work in whatever version of Emacs you are
  2436. running, and also that you can move a file from one Emacs implementation
  2437. to another. Whenever Org is forcing the year for you, it will display
  2438. a message and beep.
  2439. When this variable is nil, Org will check if the date is
  2440. representable in the specific Emacs implementation you are using.
  2441. If not, it will force a year, usually the current year, and beep
  2442. to remind you. Currently this setting is not recommended because
  2443. the likelihood that you will open your Org files in an Emacs that
  2444. has limited date range is not negligible.
  2445. A workaround for this problem is to use diary sexp dates for time
  2446. stamps outside of this range."
  2447. :group 'org-time
  2448. :version "24.1"
  2449. :type 'boolean)
  2450. (defcustom org-read-date-display-live t
  2451. "Non-nil means display current interpretation of date prompt live.
  2452. This display will be in an overlay, in the minibuffer."
  2453. :group 'org-time
  2454. :type 'boolean)
  2455. (defvaralias 'org-popup-calendar-for-date-prompt
  2456. 'org-read-date-popup-calendar)
  2457. (defcustom org-read-date-popup-calendar t
  2458. "Non-nil means pop up a calendar when prompting for a date.
  2459. In the calendar, the date can be selected with mouse-1. However, the
  2460. minibuffer will also be active, and you can simply enter the date as well.
  2461. When nil, only the minibuffer will be available."
  2462. :group 'org-time
  2463. :type 'boolean)
  2464. (defcustom org-extend-today-until 0
  2465. "The hour when your day really ends. Must be an integer.
  2466. This has influence for the following applications:
  2467. - When switching the agenda to \"today\". It it is still earlier than
  2468. the time given here, the day recognized as TODAY is actually yesterday.
  2469. - When a date is read from the user and it is still before the time given
  2470. here, the current date and time will be assumed to be yesterday, 23:59.
  2471. Also, timestamps inserted in capture templates follow this rule.
  2472. IMPORTANT: This is a feature whose implementation is and likely will
  2473. remain incomplete. Really, it is only here because past midnight seems to
  2474. be the favorite working time of John Wiegley :-)"
  2475. :group 'org-time
  2476. :type 'integer)
  2477. (defcustom org-use-effective-time nil
  2478. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2479. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2480. \"effective time\" of any timestamps between midnight and 8am will be
  2481. 23:59 of the previous day."
  2482. :group 'org-time
  2483. :version "24.1"
  2484. :type 'boolean)
  2485. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2486. "When non-nil, use the last clock out time for `org-todo'.
  2487. Note that this option has precedence over the combined use of
  2488. `org-use-effective-time' and `org-extend-today-until'."
  2489. :group 'org-time
  2490. :version "24.4"
  2491. :package-version '(Org . "8.0")
  2492. :type 'boolean)
  2493. (defcustom org-edit-timestamp-down-means-later nil
  2494. "Non-nil means S-down will increase the time in a time stamp.
  2495. When nil, S-up will increase."
  2496. :group 'org-time
  2497. :type 'boolean)
  2498. (defcustom org-calendar-follow-timestamp-change t
  2499. "Non-nil means make the calendar window follow timestamp changes.
  2500. When a timestamp is modified and the calendar window is visible, it will be
  2501. moved to the new date."
  2502. :group 'org-time
  2503. :type 'boolean)
  2504. (defgroup org-tags nil
  2505. "Options concerning tags in Org mode."
  2506. :tag "Org Tags"
  2507. :group 'org)
  2508. (defcustom org-tag-alist nil
  2509. "Default tags available in Org files.
  2510. The value of this variable is an alist. Associations either:
  2511. (TAG)
  2512. (TAG . SELECT)
  2513. (SPECIAL)
  2514. where TAG is a tag as a string, SELECT is character, used to
  2515. select that tag through the fast tag selection interface, and
  2516. SPECIAL is one of the following keywords: `:startgroup',
  2517. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2518. `:newline'. These keywords are used to define a hierarchy of
  2519. tags. See manual for details.
  2520. When this variable is nil, Org mode bases tag input on what is
  2521. already in the buffer. The value can be overridden locally by
  2522. using a TAGS keyword, e.g.,
  2523. #+TAGS: tag1 tag2
  2524. See also `org-tag-persistent-alist' to sidestep this behavior."
  2525. :group 'org-tags
  2526. :type '(repeat
  2527. (choice
  2528. (cons :tag "Tag with key"
  2529. (string :tag "Tag name")
  2530. (character :tag "Access char"))
  2531. (list :tag "Tag" (string :tag "Tag name"))
  2532. (const :tag "Start radio group" (:startgroup))
  2533. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2534. (const :tag "Group tags delimiter" (:grouptags))
  2535. (const :tag "End radio group" (:endgroup))
  2536. (const :tag "End tag group, non distinct" (:endgrouptag))
  2537. (const :tag "New line" (:newline)))))
  2538. (defcustom org-tag-persistent-alist nil
  2539. "Tags always available in Org files.
  2540. The value of this variable is an alist. Associations either:
  2541. (TAG)
  2542. (TAG . SELECT)
  2543. (SPECIAL)
  2544. where TAG is a tag as a string, SELECT is a character, used to
  2545. select that tag through the fast tag selection interface, and
  2546. SPECIAL is one of the following keywords: `:startgroup',
  2547. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2548. `:newline'. These keywords are used to define a hierarchy of
  2549. tags. See manual for details.
  2550. Unlike to `org-tag-alist', tags defined in this variable do not
  2551. depend on a local TAGS keyword. Instead, to disable these tags
  2552. on a per-file basis, insert anywhere in the file:
  2553. #+STARTUP: noptag"
  2554. :group 'org-tags
  2555. :type '(repeat
  2556. (choice
  2557. (cons :tag "Tag with key"
  2558. (string :tag "Tag name")
  2559. (character :tag "Access char"))
  2560. (list :tag "Tag" (string :tag "Tag name"))
  2561. (const :tag "Start radio group" (:startgroup))
  2562. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2563. (const :tag "Group tags delimiter" (:grouptags))
  2564. (const :tag "End radio group" (:endgroup))
  2565. (const :tag "End tag group, non distinct" (:endgrouptag))
  2566. (const :tag "New line" (:newline)))))
  2567. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2568. "If non-nil, always offer completion for all tags of all agenda files.
  2569. Setting this variable locally allows for dynamic generation of tag
  2570. completions in capture buffers.
  2571. (add-hook \\='org-capture-mode-hook
  2572. (lambda ()
  2573. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2574. :group 'org-tags
  2575. :version "24.1"
  2576. :type 'boolean)
  2577. (defvar org-file-tags nil
  2578. "List of tags that can be inherited by all entries in the file.
  2579. The tags will be inherited if the variable `org-use-tag-inheritance'
  2580. says they should be.
  2581. This variable is populated from #+FILETAGS lines.")
  2582. (defcustom org-use-fast-tag-selection 'auto
  2583. "Non-nil means use fast tag selection scheme.
  2584. This is a special interface to select and deselect tags with single keys.
  2585. When nil, fast selection is never used.
  2586. When the symbol `auto', fast selection is used if and only if selection
  2587. characters for tags have been configured, either through the variable
  2588. `org-tag-alist' or through a #+TAGS line in the buffer.
  2589. When t, fast selection is always used and selection keys are assigned
  2590. automatically if necessary."
  2591. :group 'org-tags
  2592. :type '(choice
  2593. (const :tag "Always" t)
  2594. (const :tag "Never" nil)
  2595. (const :tag "When selection characters are configured" auto)))
  2596. (defcustom org-fast-tag-selection-single-key nil
  2597. "Non-nil means fast tag selection exits after first change.
  2598. When nil, you have to press RET to exit it.
  2599. During fast tag selection, you can toggle this flag with `C-c'.
  2600. This variable can also have the value `expert'. In this case, the window
  2601. displaying the tags menu is not even shown, until you press C-c again."
  2602. :group 'org-tags
  2603. :type '(choice
  2604. (const :tag "No" nil)
  2605. (const :tag "Yes" t)
  2606. (const :tag "Expert" expert)))
  2607. (defvar org-fast-tag-selection-include-todo nil
  2608. "Non-nil means fast tags selection interface will also offer TODO states.
  2609. This is an undocumented feature, you should not rely on it.")
  2610. (defcustom org-tags-column -77
  2611. "The column to which tags should be indented in a headline.
  2612. If this number is positive, it specifies the column. If it is negative,
  2613. it means that the tags should be flushright to that column. For example,
  2614. -80 works well for a normal 80 character screen.
  2615. When 0, place tags directly after headline text, with only one space in
  2616. between."
  2617. :group 'org-tags
  2618. :type 'integer)
  2619. (defcustom org-auto-align-tags t
  2620. "Non-nil keeps tags aligned when modifying headlines.
  2621. Some operations (i.e. demoting) change the length of a headline and
  2622. therefore shift the tags around. With this option turned on, after
  2623. each such operation the tags are again aligned to `org-tags-column'."
  2624. :group 'org-tags
  2625. :type 'boolean)
  2626. (defcustom org-use-tag-inheritance t
  2627. "Non-nil means tags in levels apply also for sublevels.
  2628. When nil, only the tags directly given in a specific line apply there.
  2629. This may also be a list of tags that should be inherited, or a regexp that
  2630. matches tags that should be inherited. Additional control is possible
  2631. with the variable `org-tags-exclude-from-inheritance' which gives an
  2632. explicit list of tags to be excluded from inheritance, even if the value of
  2633. `org-use-tag-inheritance' would select it for inheritance.
  2634. If this option is t, a match early-on in a tree can lead to a large
  2635. number of matches in the subtree when constructing the agenda or creating
  2636. a sparse tree. If you only want to see the first match in a tree during
  2637. a search, check out the variable `org-tags-match-list-sublevels'."
  2638. :group 'org-tags
  2639. :type '(choice
  2640. (const :tag "Not" nil)
  2641. (const :tag "Always" t)
  2642. (repeat :tag "Specific tags" (string :tag "Tag"))
  2643. (regexp :tag "Tags matched by regexp")))
  2644. (defcustom org-tags-exclude-from-inheritance nil
  2645. "List of tags that should never be inherited.
  2646. This is a way to exclude a few tags from inheritance. For way to do
  2647. the opposite, to actively allow inheritance for selected tags,
  2648. see the variable `org-use-tag-inheritance'."
  2649. :group 'org-tags
  2650. :type '(repeat (string :tag "Tag")))
  2651. (defun org-tag-inherit-p (tag)
  2652. "Check if TAG is one that should be inherited."
  2653. (cond
  2654. ((member tag org-tags-exclude-from-inheritance) nil)
  2655. ((eq org-use-tag-inheritance t) t)
  2656. ((not org-use-tag-inheritance) nil)
  2657. ((stringp org-use-tag-inheritance)
  2658. (string-match org-use-tag-inheritance tag))
  2659. ((listp org-use-tag-inheritance)
  2660. (member tag org-use-tag-inheritance))
  2661. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2662. (defcustom org-tags-match-list-sublevels t
  2663. "Non-nil means list also sublevels of headlines matching a search.
  2664. This variable applies to tags/property searches, and also to stuck
  2665. projects because this search is based on a tags match as well.
  2666. When set to the symbol `indented', sublevels are indented with
  2667. leading dots.
  2668. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2669. the sublevels of a headline matching a tag search often also match
  2670. the same search. Listing all of them can create very long lists.
  2671. Setting this variable to nil causes subtrees of a match to be skipped.
  2672. This variable is semi-obsolete and probably should always be true. It
  2673. is better to limit inheritance to certain tags using the variables
  2674. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2675. :group 'org-tags
  2676. :type '(choice
  2677. (const :tag "No, don't list them" nil)
  2678. (const :tag "Yes, do list them" t)
  2679. (const :tag "List them, indented with leading dots" indented)))
  2680. (defcustom org-tags-sort-function nil
  2681. "When set, tags are sorted using this function as a comparator."
  2682. :group 'org-tags
  2683. :type '(choice
  2684. (const :tag "No sorting" nil)
  2685. (const :tag "Alphabetical" org-string-collate-lessp)
  2686. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2687. (function :tag "Custom function" nil)))
  2688. (defvar org-tags-history nil
  2689. "History of minibuffer reads for tags.")
  2690. (defvar org-last-tags-completion-table nil
  2691. "The last used completion table for tags.")
  2692. (defvar org-after-tags-change-hook nil
  2693. "Hook that is run after the tags in a line have changed.")
  2694. (defgroup org-properties nil
  2695. "Options concerning properties in Org mode."
  2696. :tag "Org Properties"
  2697. :group 'org)
  2698. (defcustom org-property-format "%-10s %s"
  2699. "How property key/value pairs should be formatted by `indent-line'.
  2700. When `indent-line' hits a property definition, it will format the line
  2701. according to this format, mainly to make sure that the values are
  2702. lined-up with respect to each other."
  2703. :group 'org-properties
  2704. :type 'string)
  2705. (defcustom org-properties-postprocess-alist nil
  2706. "Alist of properties and functions to adjust inserted values.
  2707. Elements of this alist must be of the form
  2708. ([string] [function])
  2709. where [string] must be a property name and [function] must be a
  2710. lambda expression: this lambda expression must take one argument,
  2711. the value to adjust, and return the new value as a string.
  2712. For example, this element will allow the property \"Remaining\"
  2713. to be updated wrt the relation between the \"Effort\" property
  2714. and the clock summary:
  2715. ((\"Remaining\" (lambda(value)
  2716. (let ((clocksum (org-clock-sum-current-item))
  2717. (effort (org-duration-to-minutes
  2718. (org-entry-get (point) \"Effort\"))))
  2719. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2720. :group 'org-properties
  2721. :version "24.1"
  2722. :type '(alist :key-type (string :tag "Property")
  2723. :value-type (function :tag "Function")))
  2724. (defcustom org-use-property-inheritance nil
  2725. "Non-nil means properties apply also for sublevels.
  2726. This setting is chiefly used during property searches. Turning it on can
  2727. cause significant overhead when doing a search, which is why it is not
  2728. on by default.
  2729. When nil, only the properties directly given in the current entry count.
  2730. When t, every property is inherited. The value may also be a list of
  2731. properties that should have inheritance, or a regular expression matching
  2732. properties that should be inherited.
  2733. However, note that some special properties use inheritance under special
  2734. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2735. and the properties ending in \"_ALL\" when they are used as descriptor
  2736. for valid values of a property.
  2737. Note for programmers:
  2738. When querying an entry with `org-entry-get', you can control if inheritance
  2739. should be used. By default, `org-entry-get' looks only at the local
  2740. properties. You can request inheritance by setting the inherit argument
  2741. to t (to force inheritance) or to `selective' (to respect the setting
  2742. in this variable)."
  2743. :group 'org-properties
  2744. :type '(choice
  2745. (const :tag "Not" nil)
  2746. (const :tag "Always" t)
  2747. (repeat :tag "Specific properties" (string :tag "Property"))
  2748. (regexp :tag "Properties matched by regexp")))
  2749. (defun org-property-inherit-p (property)
  2750. "Return a non-nil value if PROPERTY should be inherited."
  2751. (cond
  2752. ((eq org-use-property-inheritance t) t)
  2753. ((not org-use-property-inheritance) nil)
  2754. ((stringp org-use-property-inheritance)
  2755. (string-match org-use-property-inheritance property))
  2756. ((listp org-use-property-inheritance)
  2757. (member-ignore-case property org-use-property-inheritance))
  2758. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2759. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2760. "The default column format, if no other format has been defined.
  2761. This variable can be set on the per-file basis by inserting a line
  2762. #+COLUMNS: %25ITEM ....."
  2763. :group 'org-properties
  2764. :type 'string)
  2765. (defcustom org-columns-ellipses ".."
  2766. "The ellipses to be used when a field in column view is truncated.
  2767. When this is the empty string, as many characters as possible are shown,
  2768. but then there will be no visual indication that the field has been truncated.
  2769. When this is a string of length N, the last N characters of a truncated
  2770. field are replaced by this string. If the column is narrower than the
  2771. ellipses string, only part of the ellipses string will be shown."
  2772. :group 'org-properties
  2773. :type 'string)
  2774. (defconst org-global-properties-fixed
  2775. '(("VISIBILITY_ALL" . "folded children content all")
  2776. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2777. "List of property/value pairs that can be inherited by any entry.
  2778. These are fixed values, for the preset properties. The user variable
  2779. that can be used to add to this list is `org-global-properties'.
  2780. The entries in this list are cons cells where the car is a property
  2781. name and cdr is a string with the value. If the value represents
  2782. multiple items like an \"_ALL\" property, separate the items by
  2783. spaces.")
  2784. (defcustom org-global-properties nil
  2785. "List of property/value pairs that can be inherited by any entry.
  2786. This list will be combined with the constant `org-global-properties-fixed'.
  2787. The entries in this list are cons cells where the car is a property
  2788. name and cdr is a string with the value.
  2789. You can set buffer-local values for the same purpose in the variable
  2790. `org-file-properties' this by adding lines like
  2791. #+PROPERTY: NAME VALUE"
  2792. :group 'org-properties
  2793. :type '(repeat
  2794. (cons (string :tag "Property")
  2795. (string :tag "Value"))))
  2796. (defvar-local org-file-properties nil
  2797. "List of property/value pairs that can be inherited by any entry.
  2798. Valid for the current buffer.
  2799. This variable is populated from #+PROPERTY lines.")
  2800. (defgroup org-agenda nil
  2801. "Options concerning agenda views in Org mode."
  2802. :tag "Org Agenda"
  2803. :group 'org)
  2804. (defvar-local org-category nil
  2805. "Variable used by Org files to set a category for agenda display.
  2806. Such files should use a file variable to set it, for example
  2807. # -*- mode: org; org-category: \"ELisp\"
  2808. or contain a special line
  2809. #+CATEGORY: ELisp
  2810. If the file does not specify a category, then file's base name
  2811. is used instead.")
  2812. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2813. (defcustom org-agenda-files nil
  2814. "The files to be used for agenda display.
  2815. If an entry is a directory, all files in that directory that are matched
  2816. by `org-agenda-file-regexp' will be part of the file list.
  2817. If the value of the variable is not a list but a single file name, then
  2818. the list of agenda files is actually stored and maintained in that file,
  2819. one agenda file per line. In this file paths can be given relative to
  2820. `org-directory'. Tilde expansion and environment variable substitution
  2821. are also made.
  2822. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2823. and removed with `\\[org-remove-file]'."
  2824. :group 'org-agenda
  2825. :type '(choice
  2826. (repeat :tag "List of files and directories" file)
  2827. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2828. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2829. "Regular expression to match files for `org-agenda-files'.
  2830. If any element in the list in that variable contains a directory instead
  2831. of a normal file, all files in that directory that are matched by this
  2832. regular expression will be included."
  2833. :group 'org-agenda
  2834. :type 'regexp)
  2835. (defvaralias 'org-agenda-multi-occur-extra-files
  2836. 'org-agenda-text-search-extra-files)
  2837. (defcustom org-agenda-text-search-extra-files nil
  2838. "List of extra files to be searched by text search commands.
  2839. These files will be searched in addition to the agenda files by the
  2840. commands `org-search-view' (`\\[org-agenda] s') \
  2841. and `org-occur-in-agenda-files'.
  2842. Note that these files will only be searched for text search commands,
  2843. not for the other agenda views like todo lists, tag searches or the weekly
  2844. agenda. This variable is intended to list notes and possibly archive files
  2845. that should also be searched by these two commands.
  2846. In fact, if the first element in the list is the symbol `agenda-archives',
  2847. then all archive files of all agenda files will be added to the search
  2848. scope."
  2849. :group 'org-agenda
  2850. :type '(set :greedy t
  2851. (const :tag "Agenda Archives" agenda-archives)
  2852. (repeat :inline t (file))))
  2853. (defcustom org-agenda-skip-unavailable-files nil
  2854. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2855. A nil value means to remove them, after a query, from the list."
  2856. :group 'org-agenda
  2857. :type 'boolean)
  2858. (defcustom org-agenda-diary-file 'diary-file
  2859. "File to which to add new entries with the `i' key in agenda and calendar.
  2860. When this is the symbol `diary-file', the functionality in the Emacs
  2861. calendar will be used to add entries to the `diary-file'. But when this
  2862. points to a file, `org-agenda-diary-entry' will be used instead."
  2863. :group 'org-agenda
  2864. :type '(choice
  2865. (const :tag "The standard Emacs diary file" diary-file)
  2866. (file :tag "Special Org file diary entries")))
  2867. (defgroup org-latex nil
  2868. "Options for embedding LaTeX code into Org mode."
  2869. :tag "Org LaTeX"
  2870. :group 'org)
  2871. (defcustom org-format-latex-options
  2872. '(:foreground default :background default :scale 1.0
  2873. :html-foreground "Black" :html-background "Transparent"
  2874. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2875. "Options for creating images from LaTeX fragments.
  2876. This is a property list with the following properties:
  2877. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2878. `default' means use the foreground of the default face.
  2879. `auto' means use the foreground from the text face.
  2880. :background the background color, or \"Transparent\".
  2881. `default' means use the background of the default face.
  2882. `auto' means use the background from the text face.
  2883. :scale a scaling factor for the size of the images, to get more pixels
  2884. :html-foreground, :html-background, :html-scale
  2885. the same numbers for HTML export.
  2886. :matchers a list indicating which matchers should be used to
  2887. find LaTeX fragments. Valid members of this list are:
  2888. \"begin\" find environments
  2889. \"$1\" find single characters surrounded by $.$
  2890. \"$\" find math expressions surrounded by $...$
  2891. \"$$\" find math expressions surrounded by $$....$$
  2892. \"\\(\" find math expressions surrounded by \\(...\\)
  2893. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2894. :group 'org-latex
  2895. :type 'plist)
  2896. (defcustom org-format-latex-signal-error t
  2897. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2898. When nil, just push out a message."
  2899. :group 'org-latex
  2900. :version "24.1"
  2901. :type 'boolean)
  2902. (defcustom org-latex-to-mathml-jar-file nil
  2903. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2904. Use this to specify additional executable file say a jar file.
  2905. When using MathToWeb as the converter, specify the full-path to
  2906. your mathtoweb.jar file."
  2907. :group 'org-latex
  2908. :version "24.1"
  2909. :type '(choice
  2910. (const :tag "None" nil)
  2911. (file :tag "JAR file" :must-match t)))
  2912. (defcustom org-latex-to-mathml-convert-command nil
  2913. "Command to convert LaTeX fragments to MathML.
  2914. Replace format-specifiers in the command as noted below and use
  2915. `shell-command' to convert LaTeX to MathML.
  2916. %j: Executable file in fully expanded form as specified by
  2917. `org-latex-to-mathml-jar-file'.
  2918. %I: Input LaTeX file in fully expanded form.
  2919. %i: The latex fragment to be converted.
  2920. %o: Output MathML file.
  2921. This command is used by `org-create-math-formula'.
  2922. When using MathToWeb as the converter, set this option to
  2923. \"java -jar %j -unicode -force -df %o %I\".
  2924. When using LaTeXML set this option to
  2925. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2926. :group 'org-latex
  2927. :version "24.1"
  2928. :type '(choice
  2929. (const :tag "None" nil)
  2930. (string :tag "\nShell command")))
  2931. (defcustom org-preview-latex-default-process 'dvipng
  2932. "The default process to convert LaTeX fragments to image files.
  2933. All available processes and theirs documents can be found in
  2934. `org-preview-latex-process-alist', which see."
  2935. :group 'org-latex
  2936. :version "26.1"
  2937. :package-version '(Org . "9.0")
  2938. :type 'symbol)
  2939. (defcustom org-preview-latex-process-alist
  2940. '((dvipng
  2941. :programs ("latex" "dvipng")
  2942. :description "dvi > png"
  2943. :message "you need to install the programs: latex and dvipng."
  2944. :image-input-type "dvi"
  2945. :image-output-type "png"
  2946. :image-size-adjust (1.0 . 1.0)
  2947. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2948. :image-converter ("dvipng -D %D -T tight -o %O %f"))
  2949. (dvisvgm
  2950. :programs ("latex" "dvisvgm")
  2951. :description "dvi > svg"
  2952. :message "you need to install the programs: latex and dvisvgm."
  2953. :image-input-type "dvi"
  2954. :image-output-type "svg"
  2955. :image-size-adjust (1.7 . 1.5)
  2956. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2957. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2958. (imagemagick
  2959. :programs ("latex" "convert")
  2960. :description "pdf > png"
  2961. :message "you need to install the programs: latex and imagemagick."
  2962. :image-input-type "pdf"
  2963. :image-output-type "png"
  2964. :image-size-adjust (1.0 . 1.0)
  2965. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2966. :image-converter
  2967. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2968. "Definitions of external processes for LaTeX previewing.
  2969. Org mode can use some external commands to generate TeX snippet's images for
  2970. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2971. `org-create-formula-image' how to call them.
  2972. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2973. PROPERTIES accepts the following attributes:
  2974. :programs list of strings, required programs.
  2975. :description string, describe the process.
  2976. :message string, message it when required programs cannot be found.
  2977. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2978. :image-output-type string, output file type of image converter (e.g., \"png\").
  2979. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2980. image size showed in buffer and the cdr element is for
  2981. HTML file. This option is only useful for process
  2982. developers, users should use variable
  2983. `org-format-latex-options' instead.
  2984. :post-clean list of strings, files matched are to be cleaned up once
  2985. the image is generated. When nil, the files with \".dvi\",
  2986. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2987. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2988. be cleaned up.
  2989. :latex-header list of strings, the LaTeX header of the snippet file.
  2990. When nil, the fallback value is used instead, which is
  2991. controlled by `org-format-latex-header',
  2992. `org-latex-default-packages-alist' and
  2993. `org-latex-packages-alist', which see.
  2994. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2995. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2996. replaced with values defined below.
  2997. :image-converter list of image converter commands strings. Each of them is
  2998. given to the shell and supports any of the following
  2999. place-holders defined below.
  3000. Place-holders used by `:image-converter' and `:latex-compiler':
  3001. %f input file name
  3002. %b base name of input file
  3003. %o base directory of input file
  3004. %O absolute output file name
  3005. Place-holders only used by `:image-converter':
  3006. %D dpi, which is used to adjust image size by some processing commands.
  3007. %S the image size scale ratio, which is used to adjust image size by some
  3008. processing commands."
  3009. :group 'org-latex
  3010. :version "26.1"
  3011. :package-version '(Org . "9.0")
  3012. :type '(alist :tag "LaTeX to image backends"
  3013. :value-type (plist)))
  3014. (defcustom org-preview-latex-image-directory "ltximg/"
  3015. "Path to store latex preview images.
  3016. A relative path here creates many directories relative to the
  3017. processed Org files paths. An absolute path puts all preview
  3018. images at the same place."
  3019. :group 'org-latex
  3020. :version "26.1"
  3021. :package-version '(Org . "9.0")
  3022. :type 'string)
  3023. (defun org-format-latex-mathml-available-p ()
  3024. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3025. (save-match-data
  3026. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3027. org-latex-to-mathml-convert-command)
  3028. (let ((executable (car (split-string
  3029. org-latex-to-mathml-convert-command))))
  3030. (when (executable-find executable)
  3031. (if (string-match
  3032. "%j" org-latex-to-mathml-convert-command)
  3033. (file-readable-p org-latex-to-mathml-jar-file)
  3034. t))))))
  3035. (defcustom org-format-latex-header "\\documentclass{article}
  3036. \\usepackage[usenames]{color}
  3037. \[PACKAGES]
  3038. \[DEFAULT-PACKAGES]
  3039. \\pagestyle{empty} % do not remove
  3040. % The settings below are copied from fullpage.sty
  3041. \\setlength{\\textwidth}{\\paperwidth}
  3042. \\addtolength{\\textwidth}{-3cm}
  3043. \\setlength{\\oddsidemargin}{1.5cm}
  3044. \\addtolength{\\oddsidemargin}{-2.54cm}
  3045. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3046. \\setlength{\\textheight}{\\paperheight}
  3047. \\addtolength{\\textheight}{-\\headheight}
  3048. \\addtolength{\\textheight}{-\\headsep}
  3049. \\addtolength{\\textheight}{-\\footskip}
  3050. \\addtolength{\\textheight}{-3cm}
  3051. \\setlength{\\topmargin}{1.5cm}
  3052. \\addtolength{\\topmargin}{-2.54cm}"
  3053. "The document header used for processing LaTeX fragments.
  3054. It is imperative that this header make sure that no page number
  3055. appears on the page. The package defined in the variables
  3056. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3057. will either replace the placeholder \"[PACKAGES]\" in this
  3058. header, or they will be appended."
  3059. :group 'org-latex
  3060. :type 'string)
  3061. (defun org-set-packages-alist (var val)
  3062. "Set the packages alist and make sure it has 3 elements per entry."
  3063. (set var (mapcar (lambda (x)
  3064. (if (and (consp x) (= (length x) 2))
  3065. (list (car x) (nth 1 x) t)
  3066. x))
  3067. val)))
  3068. (defun org-get-packages-alist (var)
  3069. "Get the packages alist and make sure it has 3 elements per entry."
  3070. (mapcar (lambda (x)
  3071. (if (and (consp x) (= (length x) 2))
  3072. (list (car x) (nth 1 x) t)
  3073. x))
  3074. (default-value var)))
  3075. (defcustom org-latex-default-packages-alist
  3076. '(("AUTO" "inputenc" t ("pdflatex"))
  3077. ("T1" "fontenc" t ("pdflatex"))
  3078. ("" "graphicx" t)
  3079. ("" "grffile" t)
  3080. ("" "longtable" nil)
  3081. ("" "wrapfig" nil)
  3082. ("" "rotating" nil)
  3083. ("normalem" "ulem" t)
  3084. ("" "amsmath" t)
  3085. ("" "textcomp" t)
  3086. ("" "amssymb" t)
  3087. ("" "capt-of" nil)
  3088. ("" "hyperref" nil))
  3089. "Alist of default packages to be inserted in the header.
  3090. Change this only if one of the packages here causes an
  3091. incompatibility with another package you are using.
  3092. The packages in this list are needed by one part or another of
  3093. Org mode to function properly:
  3094. - inputenc, fontenc: for basic font and character selection
  3095. - graphicx: for including images
  3096. - grffile: allow periods and spaces in graphics file names
  3097. - longtable: For multipage tables
  3098. - wrapfig: for figure placement
  3099. - rotating: for sideways figures and tables
  3100. - ulem: for underline and strike-through
  3101. - amsmath: for subscript and superscript and math environments
  3102. - textcomp, amssymb: for various symbols used
  3103. for interpreting the entities in `org-entities'. You can skip
  3104. some of these packages if you don't use any of their symbols.
  3105. - capt-of: for captions outside of floats
  3106. - hyperref: for cross references
  3107. Therefore you should not modify this variable unless you know
  3108. what you are doing. The one reason to change it anyway is that
  3109. you might be loading some other package that conflicts with one
  3110. of the default packages. Each element is either a cell or
  3111. a string.
  3112. A cell is of the format
  3113. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3114. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3115. when compiling LaTeX snippets into images for inclusion into
  3116. non-LaTeX output.
  3117. COMPILERS is a list of compilers that should include the package,
  3118. see `org-latex-compiler'. If the document compiler is not in the
  3119. list, and the list is non-nil, the package will not be inserted
  3120. in the final document.
  3121. A string will be inserted as-is in the header of the document."
  3122. :group 'org-latex
  3123. :group 'org-export-latex
  3124. :set 'org-set-packages-alist
  3125. :get 'org-get-packages-alist
  3126. :version "26.1"
  3127. :package-version '(Org . "8.3")
  3128. :type '(repeat
  3129. (choice
  3130. (list :tag "options/package pair"
  3131. (string :tag "options")
  3132. (string :tag "package")
  3133. (boolean :tag "Snippet")
  3134. (choice
  3135. (const :tag "For all compilers" nil)
  3136. (repeat :tag "Allowed compiler" string)))
  3137. (string :tag "A line of LaTeX"))))
  3138. (defcustom org-latex-packages-alist nil
  3139. "Alist of packages to be inserted in every LaTeX header.
  3140. These will be inserted after `org-latex-default-packages-alist'.
  3141. Each element is either a cell or a string.
  3142. A cell is of the format:
  3143. (\"options\" \"package\" SNIPPET-FLAG)
  3144. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3145. needed when turning LaTeX snippets into images for inclusion into
  3146. non-LaTeX output.
  3147. COMPILERS is a list of compilers that should include the package,
  3148. see `org-latex-compiler'. If the document compiler is not in the
  3149. list, and the list is non-nil, the package will not be inserted
  3150. in the final document.
  3151. A string will be inserted as-is in the header of the document.
  3152. Make sure that you only list packages here which:
  3153. - you want in every file;
  3154. - do not conflict with the setup in `org-format-latex-header';
  3155. - do not conflict with the default packages in
  3156. `org-latex-default-packages-alist'."
  3157. :group 'org-latex
  3158. :group 'org-export-latex
  3159. :set 'org-set-packages-alist
  3160. :get 'org-get-packages-alist
  3161. :type '(repeat
  3162. (choice
  3163. (list :tag "options/package pair"
  3164. (string :tag "options")
  3165. (string :tag "package")
  3166. (boolean :tag "Snippet"))
  3167. (string :tag "A line of LaTeX"))))
  3168. (defgroup org-appearance nil
  3169. "Settings for Org mode appearance."
  3170. :tag "Org Appearance"
  3171. :group 'org)
  3172. (defcustom org-level-color-stars-only nil
  3173. "Non-nil means fontify only the stars in each headline.
  3174. When nil, the entire headline is fontified.
  3175. Changing it requires restart of `font-lock-mode' to become effective
  3176. also in regions already fontified."
  3177. :group 'org-appearance
  3178. :type 'boolean)
  3179. (defcustom org-hide-leading-stars nil
  3180. "Non-nil means hide the first N-1 stars in a headline.
  3181. This works by using the face `org-hide' for these stars. This
  3182. face is white for a light background, and black for a dark
  3183. background. You may have to customize the face `org-hide' to
  3184. make this work.
  3185. Changing it requires restart of `font-lock-mode' to become effective
  3186. also in regions already fontified.
  3187. You may also set this on a per-file basis by adding one of the following
  3188. lines to the buffer:
  3189. #+STARTUP: hidestars
  3190. #+STARTUP: showstars"
  3191. :group 'org-appearance
  3192. :type 'boolean)
  3193. (defcustom org-hidden-keywords nil
  3194. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3195. For example, a value \\='(title) for this list makes the document's title
  3196. appear in the buffer without the initial \"#+TITLE:\" part."
  3197. :group 'org-appearance
  3198. :version "24.1"
  3199. :type '(set (const :tag "#+AUTHOR" author)
  3200. (const :tag "#+DATE" date)
  3201. (const :tag "#+EMAIL" email)
  3202. (const :tag "#+TITLE" title)))
  3203. (defcustom org-custom-properties nil
  3204. "List of properties (as strings) with a special meaning.
  3205. The default use of these custom properties is to let the user
  3206. hide them with `org-toggle-custom-properties-visibility'."
  3207. :group 'org-properties
  3208. :group 'org-appearance
  3209. :version "24.3"
  3210. :type '(repeat (string :tag "Property Name")))
  3211. (defcustom org-fontify-done-headline nil
  3212. "Non-nil means change the face of a headline if it is marked DONE.
  3213. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3214. When this is non-nil, the headline after the keyword is set to the
  3215. `org-headline-done' as an additional indication."
  3216. :group 'org-appearance
  3217. :type 'boolean)
  3218. (defcustom org-fontify-emphasized-text t
  3219. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3220. Changing this variable requires a restart of Emacs to take effect."
  3221. :group 'org-appearance
  3222. :type 'boolean)
  3223. (defcustom org-fontify-whole-heading-line nil
  3224. "Non-nil means fontify the whole line for headings.
  3225. This is useful when setting a background color for the
  3226. org-level-* faces."
  3227. :group 'org-appearance
  3228. :type 'boolean)
  3229. (defcustom org-highlight-latex-and-related nil
  3230. "Non-nil means highlight LaTeX related syntax in the buffer.
  3231. When non nil, the value should be a list containing any of the
  3232. following symbols:
  3233. `native' Highlight LaTeX snippets and environments natively.
  3234. `latex' Highlight LaTeX snippets and environments.
  3235. `script' Highlight subscript and superscript.
  3236. `entities' Highlight entities."
  3237. :group 'org-appearance
  3238. :version "24.4"
  3239. :package-version '(Org . "8.0")
  3240. :type '(choice
  3241. (const :tag "No highlighting" nil)
  3242. (set :greedy t :tag "Highlight"
  3243. (const :tag "LaTeX snippets and environments (native)" native)
  3244. (const :tag "LaTeX snippets and environments" latex)
  3245. (const :tag "Subscript and superscript" script)
  3246. (const :tag "Entities" entities))))
  3247. (defcustom org-hide-emphasis-markers nil
  3248. "Non-nil mean font-lock should hide the emphasis marker characters."
  3249. :group 'org-appearance
  3250. :type 'boolean
  3251. :safe #'booleanp)
  3252. (defcustom org-hide-macro-markers nil
  3253. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3254. :group 'org-appearance
  3255. :type 'boolean)
  3256. (defcustom org-pretty-entities nil
  3257. "Non-nil means show entities as UTF8 characters.
  3258. When nil, the \\name form remains in the buffer."
  3259. :group 'org-appearance
  3260. :version "24.1"
  3261. :type 'boolean)
  3262. (defcustom org-pretty-entities-include-sub-superscripts t
  3263. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3264. :group 'org-appearance
  3265. :version "24.1"
  3266. :type 'boolean)
  3267. (defvar org-emph-re nil
  3268. "Regular expression for matching emphasis.
  3269. After a match, the match groups contain these elements:
  3270. 0 The match of the full regular expression, including the characters
  3271. before and after the proper match
  3272. 1 The character before the proper match, or empty at beginning of line
  3273. 2 The proper match, including the leading and trailing markers
  3274. 3 The leading marker like * or /, indicating the type of highlighting
  3275. 4 The text between the emphasis markers, not including the markers
  3276. 5 The character after the match, empty at the end of a line")
  3277. (defvar org-verbatim-re nil
  3278. "Regular expression for matching verbatim text.")
  3279. (defvar org-emphasis-regexp-components) ; defined just below
  3280. (defvar org-emphasis-alist) ; defined just below
  3281. (defun org-set-emph-re (var val)
  3282. "Set variable and compute the emphasis regular expression."
  3283. (set var val)
  3284. (when (and (boundp 'org-emphasis-alist)
  3285. (boundp 'org-emphasis-regexp-components)
  3286. org-emphasis-alist org-emphasis-regexp-components)
  3287. (pcase-let*
  3288. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3289. (body (if (<= nl 0) body
  3290. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3291. (template
  3292. (format (concat "\\([%s]\\|^\\)" ;before markers
  3293. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3294. "\\([%s]\\|$\\)") ;after markers
  3295. pre border border body border post)))
  3296. (setq org-emph-re (format template "*/_+"))
  3297. (setq org-verbatim-re (format template "=~")))))
  3298. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3299. ;; set this option proved cumbersome. See this message/thread:
  3300. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3301. (defvar org-emphasis-regexp-components
  3302. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3303. "Components used to build the regular expression for emphasis.
  3304. This is a list with five entries. Terminology: In an emphasis string
  3305. like \" *strong word* \", we call the initial space PREMATCH, the final
  3306. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3307. and \"trong wor\" is the body. The different components in this variable
  3308. specify what is allowed/forbidden in each part:
  3309. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3310. post Chars allowed as postmatch. End of line will be allowed too.
  3311. border The chars *forbidden* as border characters.
  3312. body-regexp A regexp like \".\" to match a body character. Don't use
  3313. non-shy groups here, and don't allow newline here.
  3314. newline The maximum number of newlines allowed in an emphasis exp.
  3315. You need to reload Org or to restart Emacs after setting this.")
  3316. (defcustom org-emphasis-alist
  3317. '(("*" bold)
  3318. ("/" italic)
  3319. ("_" underline)
  3320. ("=" org-verbatim verbatim)
  3321. ("~" org-code verbatim)
  3322. ("+" (:strike-through t)))
  3323. "Alist of characters and faces to emphasize text.
  3324. Text starting and ending with a special character will be emphasized,
  3325. for example *bold*, _underlined_ and /italic/. This variable sets the
  3326. marker characters and the face to be used by font-lock for highlighting
  3327. in Org buffers.
  3328. You need to reload Org or to restart Emacs after customizing this."
  3329. :group 'org-appearance
  3330. :set 'org-set-emph-re
  3331. :version "24.4"
  3332. :package-version '(Org . "8.0")
  3333. :type '(repeat
  3334. (list
  3335. (string :tag "Marker character")
  3336. (choice
  3337. (face :tag "Font-lock-face")
  3338. (plist :tag "Face property list"))
  3339. (option (const verbatim)))))
  3340. (defvar org-protecting-blocks '("src" "example" "export")
  3341. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3342. This is needed for font-lock setup.")
  3343. ;;; Functions and variables from their packages
  3344. ;; Declared here to avoid compiler warnings
  3345. (defvar mark-active)
  3346. ;; Various packages
  3347. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3348. (declare-function calendar-forward-day "cal-move" (arg))
  3349. (declare-function calendar-goto-date "cal-move" (date))
  3350. (declare-function calendar-goto-today "cal-move" ())
  3351. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3352. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3353. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3354. (declare-function cdlatex-tab "ext:cdlatex" ())
  3355. (declare-function dired-get-filename
  3356. "dired"
  3357. (&optional localp no-error-if-not-filep))
  3358. (declare-function iswitchb-read-buffer
  3359. "iswitchb"
  3360. (prompt &optional
  3361. default require-match _predicate start matches-set))
  3362. (declare-function org-agenda-change-all-lines
  3363. "org-agenda"
  3364. (newhead hdmarker &optional fixface just-this))
  3365. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3366. "org-agenda"
  3367. (&optional end))
  3368. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3369. (declare-function org-agenda-format-item
  3370. "org-agenda"
  3371. (extra txt &optional level category tags dotime
  3372. remove-re habitp))
  3373. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3374. (declare-function org-agenda-save-markers-for-cut-and-paste
  3375. "org-agenda"
  3376. (beg end))
  3377. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3378. (declare-function org-agenda-skip "org-agenda" ())
  3379. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3380. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3381. (declare-function org-indent-mode "org-indent" (&optional arg))
  3382. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3383. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3384. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3385. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3386. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3387. (declare-function parse-time-string "parse-time" (string))
  3388. (defvar align-mode-rules-list)
  3389. (defvar calc-embedded-close-formula)
  3390. (defvar calc-embedded-open-formula)
  3391. (defvar calc-embedded-open-mode)
  3392. (defvar font-lock-unfontify-region-function)
  3393. (defvar iswitchb-temp-buflist)
  3394. (defvar org-agenda-tags-todo-honor-ignore-options)
  3395. (defvar remember-data-file)
  3396. (defvar texmathp-why)
  3397. ;;;###autoload
  3398. (defun turn-on-orgtbl ()
  3399. "Unconditionally turn on `orgtbl-mode'."
  3400. (require 'org-table)
  3401. (orgtbl-mode 1))
  3402. (defun org-at-table-p (&optional table-type)
  3403. "Non-nil if the cursor is inside an Org table.
  3404. If TABLE-TYPE is non-nil, also check for table.el-type tables."
  3405. (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
  3406. (or (not (derived-mode-p 'org-mode))
  3407. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3408. (and e (or table-type
  3409. (eq 'org (org-element-property :type e))))))))
  3410. (defun org-at-table.el-p ()
  3411. "Non-nil when point is at a table.el table."
  3412. (and (org-match-line "[ \t]*[|+]")
  3413. (let ((element (org-element-at-point)))
  3414. (and (eq (org-element-type element) 'table)
  3415. (eq (org-element-property :type element) 'table.el)))))
  3416. (defun org-at-table-hline-p ()
  3417. "Non-nil when point is inside a hline in a table.
  3418. Assume point is already in a table."
  3419. (org-match-line org-table-hline-regexp))
  3420. (defun org-table-map-tables (function &optional quietly)
  3421. "Apply FUNCTION to the start of all tables in the buffer."
  3422. (org-with-wide-buffer
  3423. (goto-char (point-min))
  3424. (while (re-search-forward org-table-any-line-regexp nil t)
  3425. (unless quietly
  3426. (message "Mapping tables: %d%%"
  3427. (floor (* 100.0 (point)) (buffer-size))))
  3428. (beginning-of-line 1)
  3429. (when (and (looking-at org-table-line-regexp)
  3430. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3431. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3432. (save-excursion (funcall function))
  3433. (or (looking-at org-table-line-regexp)
  3434. (forward-char 1)))
  3435. (re-search-forward org-table-any-border-regexp nil 1)))
  3436. (unless quietly (message "Mapping tables: done")))
  3437. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3438. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3439. (declare-function org-resolve-clocks "org-clock"
  3440. (&optional also-non-dangling-p prompt last-valid))
  3441. (defun org-at-TBLFM-p (&optional pos)
  3442. "Non-nil when point (or POS) is in #+TBLFM line."
  3443. (save-excursion
  3444. (goto-char (or pos (point)))
  3445. (beginning-of-line)
  3446. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3447. (eq (org-element-type (org-element-at-point)) 'table))))
  3448. (defvar org-clock-start-time)
  3449. (defvar org-clock-marker (make-marker)
  3450. "Marker recording the last clock-in.")
  3451. (defvar org-clock-hd-marker (make-marker)
  3452. "Marker recording the last clock-in, but the headline position.")
  3453. (defvar org-clock-heading ""
  3454. "The heading of the current clock entry.")
  3455. (defun org-clock-is-active ()
  3456. "Return the buffer where the clock is currently running.
  3457. Return nil if no clock is running."
  3458. (marker-buffer org-clock-marker))
  3459. (defun org-check-running-clock ()
  3460. "Check if the current buffer contains the running clock.
  3461. If yes, offer to stop it and to save the buffer with the changes."
  3462. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3463. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3464. (buffer-name))))
  3465. (org-clock-out)
  3466. (when (y-or-n-p "Save changed buffer?")
  3467. (save-buffer))))
  3468. (defun org-clocktable-try-shift (dir n)
  3469. "Check if this line starts a clock table, if yes, shift the time block."
  3470. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3471. (org-clocktable-shift dir n)))
  3472. ;;;###autoload
  3473. (defun org-clock-persistence-insinuate ()
  3474. "Set up hooks for clock persistence."
  3475. (require 'org-clock)
  3476. (add-hook 'org-mode-hook 'org-clock-load)
  3477. (add-hook 'kill-emacs-hook 'org-clock-save))
  3478. (defgroup org-archive nil
  3479. "Options concerning archiving in Org mode."
  3480. :tag "Org Archive"
  3481. :group 'org-structure)
  3482. (defcustom org-archive-location "%s_archive::"
  3483. "The location where subtrees should be archived.
  3484. The value of this variable is a string, consisting of two parts,
  3485. separated by a double-colon. The first part is a filename and
  3486. the second part is a headline.
  3487. When the filename is omitted, archiving happens in the same file.
  3488. %s in the filename will be replaced by the current file
  3489. name (without the directory part). Archiving to a different file
  3490. is useful to keep archived entries from contributing to the
  3491. Org Agenda.
  3492. The archived entries will be filed as subtrees of the specified
  3493. headline. When the headline is omitted, the subtrees are simply
  3494. filed away at the end of the file, as top-level entries. Also in
  3495. the heading you can use %s to represent the file name, this can be
  3496. useful when using the same archive for a number of different files.
  3497. Here are a few examples:
  3498. \"%s_archive::\"
  3499. If the current file is Projects.org, archive in file
  3500. Projects.org_archive, as top-level trees. This is the default.
  3501. \"::* Archived Tasks\"
  3502. Archive in the current file, under the top-level headline
  3503. \"* Archived Tasks\".
  3504. \"~/org/archive.org::\"
  3505. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3506. \"~/org/archive.org::* From %s\"
  3507. Archive in file ~/org/archive.org (absolute path), under headlines
  3508. \"From FILENAME\" where file name is the current file name.
  3509. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3510. The \"datetree/\" string is special, signifying to archive
  3511. items to the datetree. Items are placed in either the CLOSED
  3512. date of the item, or the current date if there is no CLOSED date.
  3513. The heading will be a subentry to the current date. There doesn't
  3514. need to be a heading, but there always needs to be a slash after
  3515. datetree. For example, to store archived items directly in the
  3516. datetree, use \"~/org/datetree.org::datetree/\".
  3517. \"basement::** Finished Tasks\"
  3518. Archive in file ./basement (relative path), as level 3 trees
  3519. below the level 2 heading \"** Finished Tasks\".
  3520. You may set this option on a per-file basis by adding to the buffer a
  3521. line like
  3522. #+ARCHIVE: basement::** Finished Tasks
  3523. You may also define it locally for a subtree by setting an ARCHIVE property
  3524. in the entry. If such a property is found in an entry, or anywhere up
  3525. the hierarchy, it will be used."
  3526. :group 'org-archive
  3527. :type 'string)
  3528. (defcustom org-agenda-skip-archived-trees t
  3529. "Non-nil means the agenda will skip any items located in archived trees.
  3530. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3531. variable is no longer recommended, you should leave it at the value t.
  3532. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3533. :group 'org-archive
  3534. :group 'org-agenda-skip
  3535. :type 'boolean)
  3536. (defcustom org-columns-skip-archived-trees t
  3537. "Non-nil means ignore archived trees when creating column view."
  3538. :group 'org-archive
  3539. :group 'org-properties
  3540. :type 'boolean)
  3541. (defcustom org-cycle-open-archived-trees nil
  3542. "Non-nil means `org-cycle' will open archived trees.
  3543. An archived tree is a tree marked with the tag ARCHIVE.
  3544. When nil, archived trees will stay folded. You can still open them with
  3545. normal outline commands like `show-all', but not with the cycling commands."
  3546. :group 'org-archive
  3547. :group 'org-cycle
  3548. :type 'boolean)
  3549. (defcustom org-sparse-tree-open-archived-trees nil
  3550. "Non-nil means sparse tree construction shows matches in archived trees.
  3551. When nil, matches in these trees are highlighted, but the trees are kept in
  3552. collapsed state."
  3553. :group 'org-archive
  3554. :group 'org-sparse-trees
  3555. :type 'boolean)
  3556. (defcustom org-sparse-tree-default-date-type nil
  3557. "The default date type when building a sparse tree.
  3558. When this is nil, a date is a scheduled or a deadline timestamp.
  3559. Otherwise, these types are allowed:
  3560. all: all timestamps
  3561. active: only active timestamps (<...>)
  3562. inactive: only inactive timestamps ([...])
  3563. scheduled: only scheduled timestamps
  3564. deadline: only deadline timestamps"
  3565. :type '(choice (const :tag "Scheduled or deadline" nil)
  3566. (const :tag "All timestamps" all)
  3567. (const :tag "Only active timestamps" active)
  3568. (const :tag "Only inactive timestamps" inactive)
  3569. (const :tag "Only scheduled timestamps" scheduled)
  3570. (const :tag "Only deadline timestamps" deadline)
  3571. (const :tag "Only closed timestamps" closed))
  3572. :version "26.1"
  3573. :package-version '(Org . "8.3")
  3574. :group 'org-sparse-trees)
  3575. (defun org-cycle-hide-archived-subtrees (state)
  3576. "Re-hide all archived subtrees after a visibility state change.
  3577. STATE should be one of the symbols listed in the docstring of
  3578. `org-cycle-hook'."
  3579. (when (and (not org-cycle-open-archived-trees)
  3580. (not (memq state '(overview folded))))
  3581. (save-excursion
  3582. (let* ((globalp (memq state '(contents all)))
  3583. (beg (if globalp (point-min) (point)))
  3584. (end (if globalp (point-max) (org-end-of-subtree t))))
  3585. (org-hide-archived-subtrees beg end)
  3586. (goto-char beg)
  3587. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3588. (message "%s" (substitute-command-keys
  3589. "Subtree is archived and stays closed. Use \
  3590. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3591. (defun org-force-cycle-archived ()
  3592. "Cycle subtree even if it is archived."
  3593. (interactive)
  3594. (setq this-command 'org-cycle)
  3595. (let ((org-cycle-open-archived-trees t))
  3596. (call-interactively 'org-cycle)))
  3597. (defun org-hide-archived-subtrees (beg end)
  3598. "Re-hide all archived subtrees after a visibility state change."
  3599. (org-with-wide-buffer
  3600. (let ((case-fold-search nil)
  3601. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3602. (goto-char beg)
  3603. ;; Include headline point is currently on.
  3604. (beginning-of-line)
  3605. (while (and (< (point) end) (re-search-forward re end t))
  3606. (when (member org-archive-tag (org-get-tags nil t))
  3607. (org-flag-subtree t)
  3608. (org-end-of-subtree t))))))
  3609. (defun org-flag-subtree (flag)
  3610. (save-excursion
  3611. (org-back-to-heading t)
  3612. (org-flag-region (line-end-position)
  3613. (progn (org-end-of-subtree t) (point))
  3614. flag
  3615. 'outline)))
  3616. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3617. ;; Declare Column View Code
  3618. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3619. (declare-function org-columns-compute "org-colview" (property))
  3620. ;; Declare ID code
  3621. (declare-function org-id-store-link "org-id")
  3622. (declare-function org-id-locations-load "org-id")
  3623. (declare-function org-id-locations-save "org-id")
  3624. (defvar org-id-track-globally)
  3625. ;;; Variables for pre-computed regular expressions, all buffer local
  3626. (defvar-local org-todo-regexp nil
  3627. "Matches any of the TODO state keywords.
  3628. Since TODO keywords are case-sensitive, `case-fold-search' is
  3629. expected to be bound to nil when matching against this regexp.")
  3630. (defvar-local org-not-done-regexp nil
  3631. "Matches any of the TODO state keywords except the last one.
  3632. Since TODO keywords are case-sensitive, `case-fold-search' is
  3633. expected to be bound to nil when matching against this regexp.")
  3634. (defvar-local org-not-done-heading-regexp nil
  3635. "Matches a TODO headline that is not done.
  3636. Since TODO keywords are case-sensitive, `case-fold-search' is
  3637. expected to be bound to nil when matching against this regexp.")
  3638. (defvar-local org-todo-line-regexp nil
  3639. "Matches a headline and puts TODO state into group 2 if present.
  3640. Since TODO keywords are case-sensitive, `case-fold-search' is
  3641. expected to be bound to nil when matching against this regexp.")
  3642. (defvar-local org-complex-heading-regexp nil
  3643. "Matches a headline and puts everything into groups:
  3644. group 1: Stars
  3645. group 2: The TODO keyword, maybe
  3646. group 3: Priority cookie
  3647. group 4: True headline
  3648. group 5: Tags
  3649. Since TODO keywords are case-sensitive, `case-fold-search' is
  3650. expected to be bound to nil when matching against this regexp.")
  3651. (defvar-local org-complex-heading-regexp-format nil
  3652. "Printf format to make regexp to match an exact headline.
  3653. This regexp will match the headline of any node which has the
  3654. exact headline text that is put into the format, but may have any
  3655. TODO state, priority and tags.")
  3656. (defvar-local org-todo-line-tags-regexp nil
  3657. "Matches a headline and puts TODO state into group 2 if present.
  3658. Also put tags into group 4 if tags are present.")
  3659. (defconst org-plain-time-of-day-regexp
  3660. (concat
  3661. "\\(\\<[012]?[0-9]"
  3662. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3663. "\\(--?"
  3664. "\\(\\<[012]?[0-9]"
  3665. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3666. "\\)?")
  3667. "Regular expression to match a plain time or time range.
  3668. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3669. groups carry important information:
  3670. 0 the full match
  3671. 1 the first time, range or not
  3672. 8 the second time, if it is a range.")
  3673. (defconst org-plain-time-extension-regexp
  3674. (concat
  3675. "\\(\\<[012]?[0-9]"
  3676. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3677. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3678. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3679. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3680. groups carry important information:
  3681. 0 the full match
  3682. 7 hours of duration
  3683. 9 minutes of duration")
  3684. (defconst org-stamp-time-of-day-regexp
  3685. (concat
  3686. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3687. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  3688. "\\(--?"
  3689. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3690. "Regular expression to match a timestamp time or time range.
  3691. After a match, the following groups carry important information:
  3692. 0 the full match
  3693. 1 date plus weekday, for back referencing to make sure both times are on the same day
  3694. 2 the first time, range or not
  3695. 4 the second time, if it is a range.")
  3696. (defconst org-startup-options
  3697. '(("fold" org-startup-folded t)
  3698. ("overview" org-startup-folded t)
  3699. ("nofold" org-startup-folded nil)
  3700. ("showall" org-startup-folded nil)
  3701. ("showeverything" org-startup-folded showeverything)
  3702. ("content" org-startup-folded content)
  3703. ("indent" org-startup-indented t)
  3704. ("noindent" org-startup-indented nil)
  3705. ("hidestars" org-hide-leading-stars t)
  3706. ("showstars" org-hide-leading-stars nil)
  3707. ("odd" org-odd-levels-only t)
  3708. ("oddeven" org-odd-levels-only nil)
  3709. ("align" org-startup-align-all-tables t)
  3710. ("noalign" org-startup-align-all-tables nil)
  3711. ("shrink" org-startup-shrink-all-tables t)
  3712. ("inlineimages" org-startup-with-inline-images t)
  3713. ("noinlineimages" org-startup-with-inline-images nil)
  3714. ("latexpreview" org-startup-with-latex-preview t)
  3715. ("nolatexpreview" org-startup-with-latex-preview nil)
  3716. ("customtime" org-display-custom-times t)
  3717. ("logdone" org-log-done time)
  3718. ("lognotedone" org-log-done note)
  3719. ("nologdone" org-log-done nil)
  3720. ("lognoteclock-out" org-log-note-clock-out t)
  3721. ("nolognoteclock-out" org-log-note-clock-out nil)
  3722. ("logrepeat" org-log-repeat state)
  3723. ("lognoterepeat" org-log-repeat note)
  3724. ("logdrawer" org-log-into-drawer t)
  3725. ("nologdrawer" org-log-into-drawer nil)
  3726. ("logstatesreversed" org-log-states-order-reversed t)
  3727. ("nologstatesreversed" org-log-states-order-reversed nil)
  3728. ("nologrepeat" org-log-repeat nil)
  3729. ("logreschedule" org-log-reschedule time)
  3730. ("lognotereschedule" org-log-reschedule note)
  3731. ("nologreschedule" org-log-reschedule nil)
  3732. ("logredeadline" org-log-redeadline time)
  3733. ("lognoteredeadline" org-log-redeadline note)
  3734. ("nologredeadline" org-log-redeadline nil)
  3735. ("logrefile" org-log-refile time)
  3736. ("lognoterefile" org-log-refile note)
  3737. ("nologrefile" org-log-refile nil)
  3738. ("fninline" org-footnote-define-inline t)
  3739. ("nofninline" org-footnote-define-inline nil)
  3740. ("fnlocal" org-footnote-section nil)
  3741. ("fnauto" org-footnote-auto-label t)
  3742. ("fnprompt" org-footnote-auto-label nil)
  3743. ("fnconfirm" org-footnote-auto-label confirm)
  3744. ("fnplain" org-footnote-auto-label plain)
  3745. ("fnadjust" org-footnote-auto-adjust t)
  3746. ("nofnadjust" org-footnote-auto-adjust nil)
  3747. ("constcgs" constants-unit-system cgs)
  3748. ("constSI" constants-unit-system SI)
  3749. ("noptag" org-tag-persistent-alist nil)
  3750. ("hideblocks" org-hide-block-startup t)
  3751. ("nohideblocks" org-hide-block-startup nil)
  3752. ("beamer" org-startup-with-beamer-mode t)
  3753. ("entitiespretty" org-pretty-entities t)
  3754. ("entitiesplain" org-pretty-entities nil))
  3755. "Variable associated with STARTUP options for Org.
  3756. Each element is a list of three items: the startup options (as written
  3757. in the #+STARTUP line), the corresponding variable, and the value to set
  3758. this variable to if the option is found. An optional forth element PUSH
  3759. means to push this value onto the list in the variable.")
  3760. (defcustom org-group-tags t
  3761. "When non-nil (the default), use group tags.
  3762. This can be turned on/off through `org-toggle-tags-groups'."
  3763. :group 'org-tags
  3764. :group 'org-startup
  3765. :type 'boolean)
  3766. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3767. (defun org-toggle-tags-groups ()
  3768. "Toggle support for group tags.
  3769. Support for group tags is controlled by the option
  3770. `org-group-tags', which is non-nil by default."
  3771. (interactive)
  3772. (setq org-group-tags (not org-group-tags))
  3773. (cond ((and (derived-mode-p 'org-agenda-mode)
  3774. org-group-tags)
  3775. (org-agenda-redo))
  3776. ((derived-mode-p 'org-mode)
  3777. (let ((org-inhibit-startup t)) (org-mode))))
  3778. (message "Groups tags support has been turned %s"
  3779. (if org-group-tags "on" "off")))
  3780. (defun org--tag-add-to-alist (alist1 alist2)
  3781. "Merge tags from ALIST1 into ALIST2.
  3782. Duplicates tags outside a group are removed. Keywords and order
  3783. are preserved.
  3784. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3785. See `org-tag-alist' for their structure."
  3786. (cond
  3787. ((null alist2) alist1)
  3788. ((null alist1) alist2)
  3789. (t
  3790. (let ((to-add nil)
  3791. (group-flag nil))
  3792. (dolist (tag-pair alist1)
  3793. (pcase tag-pair
  3794. (`(,(or :startgrouptag :startgroup))
  3795. (setq group-flag t)
  3796. (push tag-pair to-add))
  3797. (`(,(or :endgrouptag :endgroup))
  3798. (setq group-flag nil)
  3799. (push tag-pair to-add))
  3800. (`(,(or :grouptags :newline))
  3801. (push tag-pair to-add))
  3802. (`(,tag . ,_)
  3803. ;; Remove duplicates from ALIST1, unless they are in
  3804. ;; a group. Indeed, it makes sense to have a tag appear in
  3805. ;; multiple groups.
  3806. (when (or group-flag (not (assoc tag alist2)))
  3807. (push tag-pair to-add)))
  3808. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3809. ;; Preserve order of ALIST1.
  3810. (append (nreverse to-add) alist2)))))
  3811. (defun org-set-regexps-and-options (&optional tags-only)
  3812. "Precompute regular expressions used in the current buffer.
  3813. When optional argument TAGS-ONLY is non-nil, only compute tags
  3814. related expressions."
  3815. (when (derived-mode-p 'org-mode)
  3816. (let ((alist (org--setup-collect-keywords
  3817. (org-make-options-regexp
  3818. (append '("FILETAGS" "TAGS" "SETUPFILE")
  3819. (and (not tags-only)
  3820. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3821. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3822. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  3823. ;; Startup options. Get this early since it does change
  3824. ;; behavior for other options (e.g., tags).
  3825. (let ((startup (cdr (assq 'startup alist))))
  3826. (dolist (option startup)
  3827. (let ((entry (assoc-string option org-startup-options t)))
  3828. (when entry
  3829. (let ((var (nth 1 entry))
  3830. (val (nth 2 entry)))
  3831. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  3832. (unless (listp (symbol-value var))
  3833. (set (make-local-variable var) nil))
  3834. (add-to-list var val)))))))
  3835. (setq-local org-file-tags
  3836. (mapcar #'org-add-prop-inherited
  3837. (cdr (assq 'filetags alist))))
  3838. (setq org-current-tag-alist
  3839. (org--tag-add-to-alist
  3840. org-tag-persistent-alist
  3841. (let ((tags (cdr (assq 'tags alist))))
  3842. (if tags (org-tag-string-to-alist tags)
  3843. org-tag-alist))))
  3844. (setq org-tag-groups-alist
  3845. (org-tag-alist-to-groups org-current-tag-alist))
  3846. (unless tags-only
  3847. ;; File properties.
  3848. (setq-local org-file-properties (cdr (assq 'property alist)))
  3849. ;; Archive location.
  3850. (let ((archive (cdr (assq 'archive alist))))
  3851. (when archive (setq-local org-archive-location archive)))
  3852. ;; Category.
  3853. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  3854. (when cat
  3855. (setq-local org-category (intern cat))
  3856. (setq-local org-file-properties
  3857. (org--update-property-plist
  3858. "CATEGORY" cat org-file-properties))))
  3859. ;; Columns.
  3860. (let ((column (cdr (assq 'columns alist))))
  3861. (when column (setq-local org-columns-default-format column)))
  3862. ;; Constants.
  3863. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  3864. ;; Link abbreviations.
  3865. (let ((links (cdr (assq 'link alist))))
  3866. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3867. ;; Priorities.
  3868. (let ((priorities (cdr (assq 'priorities alist))))
  3869. (when priorities
  3870. (setq-local org-highest-priority (nth 0 priorities))
  3871. (setq-local org-lowest-priority (nth 1 priorities))
  3872. (setq-local org-default-priority (nth 2 priorities))))
  3873. ;; Scripts.
  3874. (let ((scripts (assq 'scripts alist)))
  3875. (when scripts
  3876. (setq-local org-use-sub-superscripts (cdr scripts))))
  3877. ;; TODO keywords.
  3878. (setq-local org-todo-kwd-alist nil)
  3879. (setq-local org-todo-key-alist nil)
  3880. (setq-local org-todo-key-trigger nil)
  3881. (setq-local org-todo-keywords-1 nil)
  3882. (setq-local org-done-keywords nil)
  3883. (setq-local org-todo-heads nil)
  3884. (setq-local org-todo-sets nil)
  3885. (setq-local org-todo-log-states nil)
  3886. (let ((todo-sequences
  3887. (or (nreverse (cdr (assq 'todo alist)))
  3888. (let ((d (default-value 'org-todo-keywords)))
  3889. (if (not (stringp (car d))) d
  3890. ;; XXX: Backward compatibility code.
  3891. (list (cons org-todo-interpretation d)))))))
  3892. (dolist (sequence todo-sequences)
  3893. (let* ((sequence (or (run-hook-with-args-until-success
  3894. 'org-todo-setup-filter-hook sequence)
  3895. sequence))
  3896. (sequence-type (car sequence))
  3897. (keywords (cdr sequence))
  3898. (sep (member "|" keywords))
  3899. names alist)
  3900. (dolist (k (remove "|" keywords))
  3901. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3902. k)
  3903. (error "Invalid TODO keyword %s" k))
  3904. (let ((name (match-string 1 k))
  3905. (key (match-string 2 k))
  3906. (log (org-extract-log-state-settings k)))
  3907. (push name names)
  3908. (push (cons name (and key (string-to-char key))) alist)
  3909. (when log (push log org-todo-log-states))))
  3910. (let* ((names (nreverse names))
  3911. (done (if sep (org-remove-keyword-keys (cdr sep))
  3912. (last names)))
  3913. (head (car names))
  3914. (tail (list sequence-type head (car done) (org-last done))))
  3915. (add-to-list 'org-todo-heads head 'append)
  3916. (push names org-todo-sets)
  3917. (setq org-done-keywords (append org-done-keywords done nil))
  3918. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3919. (setq org-todo-key-alist
  3920. (append org-todo-key-alist
  3921. (and alist
  3922. (append '((:startgroup))
  3923. (nreverse alist)
  3924. '((:endgroup))))))
  3925. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3926. (setq org-todo-sets (nreverse org-todo-sets)
  3927. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3928. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3929. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3930. ;; Compute the regular expressions and other local variables.
  3931. ;; Using `org-outline-regexp-bol' would complicate them much,
  3932. ;; because of the fixed white space at the end of that string.
  3933. (unless org-done-keywords
  3934. (setq org-done-keywords
  3935. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3936. (setq org-not-done-keywords
  3937. (org-delete-all org-done-keywords
  3938. (copy-sequence org-todo-keywords-1))
  3939. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3940. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3941. org-not-done-heading-regexp
  3942. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3943. org-todo-line-regexp
  3944. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3945. org-complex-heading-regexp
  3946. (concat "^\\(\\*+\\)"
  3947. "\\(?: +" org-todo-regexp "\\)?"
  3948. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3949. "\\(?: +\\(.*?\\)\\)??"
  3950. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3951. "[ \t]*$")
  3952. org-complex-heading-regexp-format
  3953. (concat "^\\(\\*+\\)"
  3954. "\\(?: +" org-todo-regexp "\\)?"
  3955. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3956. "\\(?: +"
  3957. ;; Stats cookies can be stuck to body.
  3958. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3959. "\\(%s\\)"
  3960. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3961. "\\)"
  3962. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3963. "[ \t]*$")
  3964. org-todo-line-tags-regexp
  3965. (concat "^\\(\\*+\\)"
  3966. "\\(?: +" org-todo-regexp "\\)?"
  3967. "\\(?: +\\(.*?\\)\\)??"
  3968. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3969. "[ \t]*$"))
  3970. (org-compute-latex-and-related-regexp)))))
  3971. (defun org--setup-collect-keywords (regexp &optional files alist)
  3972. "Return setup keywords values as an alist.
  3973. REGEXP matches a subset of setup keywords. FILES is a list of
  3974. file names already visited. It is used to avoid circular setup
  3975. files. ALIST, when non-nil, is the alist computed so far.
  3976. Return value contains the following keys: `archive', `category',
  3977. `columns', `constants', `filetags', `link', `priorities',
  3978. `property', `scripts', `startup', `tags' and `todo'."
  3979. (org-with-wide-buffer
  3980. (goto-char (point-min))
  3981. (let ((case-fold-search t))
  3982. (while (re-search-forward regexp nil t)
  3983. (let ((element (org-element-at-point)))
  3984. (when (eq (org-element-type element) 'keyword)
  3985. (let ((key (org-element-property :key element))
  3986. (value (org-element-property :value element)))
  3987. (cond
  3988. ((equal key "ARCHIVE")
  3989. (when (org-string-nw-p value)
  3990. (push (cons 'archive value) alist)))
  3991. ((equal key "CATEGORY") (push (cons 'category value) alist))
  3992. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  3993. ((equal key "CONSTANTS")
  3994. (let* ((constants (assq 'constants alist))
  3995. (store (cdr constants)))
  3996. (dolist (pair (split-string value))
  3997. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  3998. pair)
  3999. (let* ((name (match-string 1 pair))
  4000. (value (match-string 2 pair))
  4001. (old (assoc name store)))
  4002. (if old (setcdr old value)
  4003. (push (cons name value) store)))))
  4004. (if constants (setcdr constants store)
  4005. (push (cons 'constants store) alist))))
  4006. ((equal key "FILETAGS")
  4007. (when (org-string-nw-p value)
  4008. (let ((old (assq 'filetags alist))
  4009. (new (apply #'nconc
  4010. (mapcar (lambda (x) (org-split-string x ":"))
  4011. (split-string value)))))
  4012. (if old (setcdr old (append new (cdr old)))
  4013. (push (cons 'filetags new) alist)))))
  4014. ((equal key "LINK")
  4015. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4016. (let ((links (assq 'link alist))
  4017. (pair (cons (match-string-no-properties 1 value)
  4018. (match-string-no-properties 2 value))))
  4019. (if links (push pair (cdr links))
  4020. (push (list 'link pair) alist)))))
  4021. ((equal key "OPTIONS")
  4022. (when (and (org-string-nw-p value)
  4023. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4024. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4025. ((equal key "PRIORITIES")
  4026. (push (cons 'priorities
  4027. (let ((prio (split-string value)))
  4028. (if (< (length prio) 3) '(?A ?C ?B)
  4029. (mapcar #'string-to-char prio))))
  4030. alist))
  4031. ((equal key "PROPERTY")
  4032. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4033. (let* ((property (assq 'property alist))
  4034. (value (org--update-property-plist
  4035. (match-string-no-properties 1 value)
  4036. (match-string-no-properties 2 value)
  4037. (cdr property))))
  4038. (if property (setcdr property value)
  4039. (push (cons 'property value) alist)))))
  4040. ((equal key "STARTUP")
  4041. (let ((startup (assq 'startup alist)))
  4042. (if startup
  4043. (setcdr startup
  4044. (append (cdr startup) (split-string value)))
  4045. (push (cons 'startup (split-string value)) alist))))
  4046. ((equal key "TAGS")
  4047. (let ((tag-cell (assq 'tags alist)))
  4048. (if tag-cell
  4049. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4050. (push (cons 'tags value) alist))))
  4051. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4052. (let ((todo (assq 'todo alist))
  4053. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4054. (split-string value))))
  4055. (if todo (push value (cdr todo))
  4056. (push (list 'todo value) alist))))
  4057. ((equal key "SETUPFILE")
  4058. (unless buffer-read-only ; Do not check in Gnus messages.
  4059. (let ((f (and (org-string-nw-p value)
  4060. (expand-file-name (org-strip-quotes value)))))
  4061. (when (and f (file-readable-p f) (not (member f files)))
  4062. (with-temp-buffer
  4063. (setq default-directory (file-name-directory f))
  4064. (insert-file-contents f)
  4065. (setq alist
  4066. ;; Fake Org mode to benefit from cache
  4067. ;; without recurring needlessly.
  4068. (let ((major-mode 'org-mode))
  4069. (org--setup-collect-keywords
  4070. regexp (cons f files) alist)))))))))))))))
  4071. alist)
  4072. (defun org-tag-string-to-alist (s)
  4073. "Return tag alist associated to string S.
  4074. S is a value for TAGS keyword or produced with
  4075. `org-tag-alist-to-string'. Return value is an alist suitable for
  4076. `org-tag-alist' or `org-tag-persistent-alist'."
  4077. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4078. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  4079. "\\(?:(\\(.\\))\\)?\\'"))
  4080. alist group-flag)
  4081. (dolist (tokens lines (cdr (nreverse alist)))
  4082. (push '(:newline) alist)
  4083. (while tokens
  4084. (let ((token (pop tokens)))
  4085. (pcase token
  4086. ("{"
  4087. (push '(:startgroup) alist)
  4088. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4089. ("}"
  4090. (push '(:endgroup) alist)
  4091. (setq group-flag nil))
  4092. ("["
  4093. (push '(:startgrouptag) alist)
  4094. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4095. ("]"
  4096. (push '(:endgrouptag) alist)
  4097. (setq group-flag nil))
  4098. (":"
  4099. (push '(:grouptags) alist))
  4100. ((guard (string-match tag-re token))
  4101. (let ((tag (match-string 1 token))
  4102. (key (and (match-beginning 2)
  4103. (string-to-char (match-string 2 token)))))
  4104. ;; Push all tags in groups, no matter if they already
  4105. ;; appear somewhere else in the list.
  4106. (when (or group-flag (not (assoc tag alist)))
  4107. (push (cons tag key) alist))))))))))
  4108. (defun org-tag-alist-to-string (alist &optional skip-key)
  4109. "Return tag string associated to ALIST.
  4110. ALIST is an alist, as defined in `org-tag-alist' or
  4111. `org-tag-persistent-alist', or produced with
  4112. `org-tag-string-to-alist'.
  4113. Return value is a string suitable as a value for \"TAGS\"
  4114. keyword.
  4115. When optional argument SKIP-KEY is non-nil, skip selection keys
  4116. next to tags."
  4117. (mapconcat (lambda (token)
  4118. (pcase token
  4119. (`(:startgroup) "{")
  4120. (`(:endgroup) "}")
  4121. (`(:startgrouptag) "[")
  4122. (`(:endgrouptag) "]")
  4123. (`(:grouptags) ":")
  4124. (`(:newline) "\\n")
  4125. ((and
  4126. (guard (not skip-key))
  4127. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4128. (format "%s(%c)" tag key))
  4129. (`(,(and tag (pred stringp)) . ,_) tag)
  4130. (_ (user-error "Invalid tag token: %S" token))))
  4131. alist
  4132. " "))
  4133. (defun org-tag-alist-to-groups (alist)
  4134. "Return group alist from tag ALIST.
  4135. ALIST is an alist, as defined in `org-tag-alist' or
  4136. `org-tag-persistent-alist', or produced with
  4137. `org-tag-string-to-alist'. Return value is an alist following
  4138. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4139. a string, summarizing TAGS, as a list of strings."
  4140. (let (groups group-status current-group)
  4141. (dolist (token alist (nreverse groups))
  4142. (pcase token
  4143. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4144. (`(,(or :endgroup :endgrouptag))
  4145. (when (eq group-status 'append)
  4146. (push (nreverse current-group) groups))
  4147. (setq group-status nil current-group nil))
  4148. (`(:grouptags) (setq group-status 'append))
  4149. ((and `(,tag . ,_) (guard group-status))
  4150. (if (eq group-status 'append) (push tag current-group)
  4151. (setq current-group (list tag))))
  4152. (_ nil)))))
  4153. (defvar org--file-cache (make-hash-table :test #'equal)
  4154. "Hash table to store contents of files referenced via a URL.
  4155. This is the cache of file URLs read using `org-file-contents'.")
  4156. (defun org-reset-file-cache ()
  4157. "Reset the cache of files downloaded by `org-file-contents'."
  4158. (clrhash org--file-cache))
  4159. (defun org-file-url-p (file)
  4160. "Non-nil if FILE is a URL."
  4161. (require 'ffap)
  4162. (string-match-p ffap-url-regexp file))
  4163. (defun org-file-contents (file &optional noerror nocache)
  4164. "Return the contents of FILE, as a string.
  4165. FILE can be a file name or URL.
  4166. If FILE is a URL, download the contents. If the URL contents are
  4167. already cached in the `org--file-cache' hash table, the download step
  4168. is skipped.
  4169. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4170. from file or URL.
  4171. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4172. is available. This option applies only if FILE is a URL."
  4173. (let* ((is-url (org-file-url-p file))
  4174. (cache (and is-url
  4175. (not nocache)
  4176. (gethash file org--file-cache))))
  4177. (cond
  4178. (cache)
  4179. (is-url
  4180. (with-current-buffer (url-retrieve-synchronously file)
  4181. (goto-char (point-min))
  4182. ;; Move point to after the url-retrieve header.
  4183. (search-forward "\n\n" nil :move)
  4184. ;; Search for the success code only in the url-retrieve header.
  4185. (if (save-excursion
  4186. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4187. ;; Update the cache `org--file-cache' and return contents.
  4188. (puthash file
  4189. (buffer-substring-no-properties (point) (point-max))
  4190. org--file-cache)
  4191. (funcall (if noerror #'message #'user-error)
  4192. "Unable to fetch file from %S"
  4193. file))))
  4194. (t
  4195. (with-temp-buffer
  4196. (condition-case nil
  4197. (progn
  4198. (insert-file-contents file)
  4199. (buffer-string))
  4200. (file-error
  4201. (funcall (if noerror #'message #'user-error)
  4202. "Unable to read file %S"
  4203. file))))))))
  4204. (defun org-extract-log-state-settings (x)
  4205. "Extract the log state setting from a TODO keyword string.
  4206. This will extract info from a string like \"WAIT(w@/!)\"."
  4207. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4208. (let ((kw (match-string 1 x))
  4209. (log1 (and (match-end 3) (match-string 3 x)))
  4210. (log2 (and (match-end 4) (match-string 4 x))))
  4211. (and (or log1 log2)
  4212. (list kw
  4213. (and log1 (if (equal log1 "!") 'time 'note))
  4214. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4215. (defun org-remove-keyword-keys (list)
  4216. "Remove a pair of parenthesis at the end of each string in LIST."
  4217. (mapcar (lambda (x)
  4218. (if (string-match "(.*)$" x)
  4219. (substring x 0 (match-beginning 0))
  4220. x))
  4221. list))
  4222. (defun org-assign-fast-keys (alist)
  4223. "Assign fast keys to a keyword-key alist.
  4224. Respect keys that are already there."
  4225. (let (new e (alt ?0))
  4226. (while (setq e (pop alist))
  4227. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4228. (cdr e)) ;; Key already assigned.
  4229. (push e new)
  4230. (let ((clist (string-to-list (downcase (car e))))
  4231. (used (append new alist)))
  4232. (when (= (car clist) ?@)
  4233. (pop clist))
  4234. (while (and clist (rassoc (car clist) used))
  4235. (pop clist))
  4236. (unless clist
  4237. (while (rassoc alt used)
  4238. (cl-incf alt)))
  4239. (push (cons (car e) (or (car clist) alt)) new))))
  4240. (nreverse new)))
  4241. ;;; Some variables used in various places
  4242. (defvar org-window-configuration nil
  4243. "Used in various places to store a window configuration.")
  4244. (defvar org-selected-window nil
  4245. "Used in various places to store a window configuration.")
  4246. (defvar org-finish-function nil
  4247. "Function to be called when `C-c C-c' is used.
  4248. This is for getting out of special buffers like capture.")
  4249. (defvar org-last-state)
  4250. ;; Defined somewhere in this file, but used before definition.
  4251. (defvar org-entities) ;; defined in org-entities.el
  4252. (defvar org-struct-menu)
  4253. (defvar org-org-menu)
  4254. (defvar org-tbl-menu)
  4255. ;;;; Define the Org mode
  4256. ;; We use a before-change function to check if a table might need
  4257. ;; an update.
  4258. (defvar org-table-may-need-update t
  4259. "Indicates that a table might need an update.
  4260. This variable is set by `org-before-change-function'.
  4261. `org-table-align' sets it back to nil.")
  4262. (defun org-before-change-function (_beg _end)
  4263. "Every change indicates that a table might need an update."
  4264. (setq org-table-may-need-update t))
  4265. (defvar org-mode-map)
  4266. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4267. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4268. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4269. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4270. (defvar org-table-buffer-is-an nil)
  4271. (defvar bidi-paragraph-direction)
  4272. (defvar buffer-face-mode-face)
  4273. (require 'outline)
  4274. ;; Other stuff we need.
  4275. (require 'time-date)
  4276. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4277. (require 'easymenu)
  4278. (autoload 'easy-menu-add "easymenu")
  4279. (require 'overlay)
  4280. ;; (require 'org-macs) moved higher up in the file before it is first used
  4281. (require 'org-entities)
  4282. ;; (require 'org-compat) moved higher up in the file before it is first used
  4283. (require 'org-faces)
  4284. (require 'org-list)
  4285. (require 'org-pcomplete)
  4286. (require 'org-src)
  4287. (require 'org-footnote)
  4288. (require 'org-macro)
  4289. ;; babel
  4290. (require 'ob)
  4291. ;;;###autoload
  4292. (define-derived-mode org-mode outline-mode "Org"
  4293. "Outline-based notes management and organizer, alias
  4294. \"Carsten's outline-mode for keeping track of everything.\"
  4295. Org mode develops organizational tasks around a NOTES file which
  4296. contains information about projects as plain text. Org mode is
  4297. implemented on top of Outline mode, which is ideal to keep the content
  4298. of large files well structured. It supports ToDo items, deadlines and
  4299. time stamps, which magically appear in the diary listing of the Emacs
  4300. calendar. Tables are easily created with a built-in table editor.
  4301. Plain text URL-like links connect to websites, emails (VM), Usenet
  4302. messages (Gnus), BBDB entries, and any files related to the project.
  4303. For printing and sharing of notes, an Org file (or a part of it)
  4304. can be exported as a structured ASCII or HTML file.
  4305. The following commands are available:
  4306. \\{org-mode-map}"
  4307. (org-load-modules-maybe)
  4308. (org-install-agenda-files-menu)
  4309. (when org-link-descriptive (add-to-invisibility-spec '(org-link)))
  4310. (add-to-invisibility-spec '(org-hide-block . t))
  4311. (add-to-invisibility-spec '(org-hide-drawer . t))
  4312. (setq-local outline-regexp org-outline-regexp)
  4313. (setq-local outline-level 'org-outline-level)
  4314. (setq bidi-paragraph-direction 'left-to-right)
  4315. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4316. (unless org-display-table
  4317. (setq org-display-table (make-display-table)))
  4318. (set-display-table-slot
  4319. org-display-table 4
  4320. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4321. org-ellipsis)))
  4322. (setq buffer-display-table org-display-table))
  4323. (org-set-regexps-and-options)
  4324. (org-set-font-lock-defaults)
  4325. (when (and org-tag-faces (not org-tags-special-faces-re))
  4326. ;; tag faces set outside customize.... force initialization.
  4327. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4328. ;; Calc embedded
  4329. (setq-local calc-embedded-open-mode "# ")
  4330. ;; Modify a few syntax entries
  4331. (modify-syntax-entry ?\" "\"")
  4332. (modify-syntax-entry ?\\ "_")
  4333. (modify-syntax-entry ?~ "_")
  4334. (modify-syntax-entry ?< "(>")
  4335. (modify-syntax-entry ?> ")<")
  4336. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4337. ;; Activate before-change-function
  4338. (setq-local org-table-may-need-update t)
  4339. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4340. ;; Check for running clock before killing a buffer
  4341. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4342. ;; Initialize macros templates.
  4343. (org-macro-initialize-templates)
  4344. ;; Initialize radio targets.
  4345. (org-update-radio-target-regexp)
  4346. ;; Indentation.
  4347. (setq-local indent-line-function 'org-indent-line)
  4348. (setq-local indent-region-function 'org-indent-region)
  4349. ;; Filling and auto-filling.
  4350. (org-setup-filling)
  4351. ;; Comments.
  4352. (org-setup-comments-handling)
  4353. ;; Initialize cache.
  4354. (org-element-cache-reset)
  4355. ;; Beginning/end of defun
  4356. (setq-local beginning-of-defun-function 'org-backward-element)
  4357. (setq-local end-of-defun-function
  4358. (lambda ()
  4359. (if (not (org-at-heading-p))
  4360. (org-forward-element)
  4361. (org-forward-element)
  4362. (forward-char -1))))
  4363. ;; Next error for sparse trees
  4364. (setq-local next-error-function 'org-occur-next-match)
  4365. ;; Make commit log messages from Org documents easier.
  4366. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4367. ;; Make sure dependence stuff works reliably, even for users who set it
  4368. ;; too late :-(
  4369. (if org-enforce-todo-dependencies
  4370. (add-hook 'org-blocker-hook
  4371. 'org-block-todo-from-children-or-siblings-or-parent)
  4372. (remove-hook 'org-blocker-hook
  4373. 'org-block-todo-from-children-or-siblings-or-parent))
  4374. (if org-enforce-todo-checkbox-dependencies
  4375. (add-hook 'org-blocker-hook
  4376. 'org-block-todo-from-checkboxes)
  4377. (remove-hook 'org-blocker-hook
  4378. 'org-block-todo-from-checkboxes))
  4379. ;; Align options lines
  4380. (setq-local
  4381. align-mode-rules-list
  4382. '((org-in-buffer-settings
  4383. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4384. (modes . '(org-mode)))))
  4385. ;; Make isearch reveal context
  4386. (setq-local outline-isearch-open-invisible-function
  4387. (lambda (&rest _) (org-show-context 'isearch)))
  4388. ;; Setup the pcomplete hooks
  4389. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4390. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4391. (setq-local pcomplete-default-completion-function 'ignore)
  4392. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4393. (setq-local pcomplete-termination-string "")
  4394. (setq-local buffer-face-mode-face 'org-default)
  4395. ;; If empty file that did not turn on Org mode automatically, make
  4396. ;; it to.
  4397. (when (and org-insert-mode-line-in-empty-file
  4398. (called-interactively-p 'any)
  4399. (= (point-min) (point-max)))
  4400. (insert "# -*- mode: org -*-\n\n"))
  4401. (unless org-inhibit-startup
  4402. (org-unmodified
  4403. (when org-startup-with-beamer-mode (org-beamer-mode))
  4404. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4405. (org-table-map-tables
  4406. (cond ((and org-startup-align-all-tables
  4407. org-startup-shrink-all-tables)
  4408. (lambda () (org-table-align) (org-table-shrink)))
  4409. (org-startup-align-all-tables #'org-table-align)
  4410. (t #'org-table-shrink))
  4411. t))
  4412. (when org-startup-with-inline-images (org-display-inline-images))
  4413. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4414. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4415. (when org-startup-truncated (setq truncate-lines t))
  4416. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4417. ;; Try to set `org-hide' face correctly.
  4418. (let ((foreground (org-find-invisible-foreground)))
  4419. (when foreground
  4420. (set-face-foreground 'org-hide foreground))))
  4421. ;; Update `customize-package-emacs-version-alist'
  4422. (add-to-list 'customize-package-emacs-version-alist
  4423. '(Org ("8.0" . "24.4")
  4424. ("8.1" . "24.4")
  4425. ("8.2" . "24.4")
  4426. ("8.2.7" . "24.4")
  4427. ("8.3" . "26.1")
  4428. ("9.0" . "26.1")
  4429. ("9.1" . "26.1")
  4430. ("9.2" . "27.1")))
  4431. (defvar org-mode-transpose-word-syntax-table
  4432. (let ((st (make-syntax-table text-mode-syntax-table)))
  4433. (dolist (c org-emphasis-alist st)
  4434. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4435. (when (fboundp 'abbrev-table-put)
  4436. (abbrev-table-put org-mode-abbrev-table
  4437. :parents (list text-mode-abbrev-table)))
  4438. (defun org-find-invisible-foreground ()
  4439. (let ((candidates (remove
  4440. "unspecified-bg"
  4441. (nconc
  4442. (list (face-background 'default)
  4443. (face-background 'org-default))
  4444. (mapcar
  4445. (lambda (alist)
  4446. (when (boundp alist)
  4447. (cdr (assq 'background-color (symbol-value alist)))))
  4448. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4449. (list (face-foreground 'org-hide))))))
  4450. (car (remove nil candidates))))
  4451. (defun org-current-time (&optional rounding-minutes past)
  4452. "Current time, possibly rounded to ROUNDING-MINUTES.
  4453. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4454. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4455. the rounding returns a past time."
  4456. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4457. (car org-time-stamp-rounding-minutes)))
  4458. (time (decode-time)) res)
  4459. (if (< r 1)
  4460. (current-time)
  4461. (setq res
  4462. (apply 'encode-time
  4463. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4464. (nthcdr 2 time))))
  4465. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4466. (seconds-to-time (- (float-time res) (* r 60)))
  4467. res))))
  4468. (defun org-today ()
  4469. "Return today date, considering `org-extend-today-until'."
  4470. (time-to-days
  4471. (time-subtract (current-time)
  4472. (list 0 (* 3600 org-extend-today-until) 0))))
  4473. ;;;; Font-Lock stuff, including the activators
  4474. (require 'font-lock)
  4475. (defconst org-match-sexp-depth 3
  4476. "Number of stacked braces for sub/superscript matching.")
  4477. (defun org-create-multibrace-regexp (left right n)
  4478. "Create a regular expression which will match a balanced sexp.
  4479. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4480. as single character strings.
  4481. The regexp returned will match the entire expression including the
  4482. delimiters. It will also define a single group which contains the
  4483. match except for the outermost delimiters. The maximum depth of
  4484. stacked delimiters is N. Escaping delimiters is not possible."
  4485. (let* ((nothing (concat "[^" left right "]*?"))
  4486. (or "\\|")
  4487. (re nothing)
  4488. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4489. (while (> n 1)
  4490. (setq n (1- n)
  4491. re (concat re or next)
  4492. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4493. (concat left "\\(" re "\\)" right)))
  4494. (defconst org-match-substring-regexp
  4495. (concat
  4496. "\\(\\S-\\)\\([_^]\\)\\("
  4497. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4498. "\\|"
  4499. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4500. "\\|"
  4501. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4502. "The regular expression matching a sub- or superscript.")
  4503. (defconst org-match-substring-with-braces-regexp
  4504. (concat
  4505. "\\(\\S-\\)\\([_^]\\)"
  4506. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4507. "The regular expression matching a sub- or superscript, forcing braces.")
  4508. (defvar org-emph-face nil)
  4509. (defun org-do-emphasis-faces (limit)
  4510. "Run through the buffer and emphasize strings."
  4511. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4512. (car org-emphasis-regexp-components))))
  4513. (catch :exit
  4514. (while (re-search-forward quick-re limit t)
  4515. (let* ((marker (match-string 2))
  4516. (verbatim? (member marker '("~" "="))))
  4517. (when (save-excursion
  4518. (goto-char (match-beginning 0))
  4519. (and
  4520. ;; Do not match table hlines.
  4521. (not (and (equal marker "+")
  4522. (org-match-line
  4523. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4524. ;; Do not match headline stars. Do not consider
  4525. ;; stars of a headline as closing marker for bold
  4526. ;; markup either.
  4527. (not (and (equal marker "*")
  4528. (save-excursion
  4529. (forward-char)
  4530. (skip-chars-backward "*")
  4531. (looking-at-p org-outline-regexp-bol))))
  4532. ;; Match full emphasis markup regexp.
  4533. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4534. ;; Do not span over paragraph boundaries.
  4535. (not (string-match-p org-element-paragraph-separate
  4536. (match-string 2)))
  4537. ;; Do not span over cells in table rows.
  4538. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4539. (string-match-p "|" (match-string 4))))))
  4540. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  4541. (font-lock-prepend-text-property
  4542. (match-beginning 2) (match-end 2) 'face face)
  4543. (when verbatim?
  4544. (org-remove-flyspell-overlays-in
  4545. (match-beginning 0) (match-end 0))
  4546. (remove-text-properties (match-beginning 2) (match-end 2)
  4547. '(display t invisible t intangible t)))
  4548. (add-text-properties (match-beginning 2) (match-end 2)
  4549. '(font-lock-multiline t org-emphasis t))
  4550. (when org-hide-emphasis-markers
  4551. (add-text-properties (match-end 4) (match-beginning 5)
  4552. '(invisible org-link))
  4553. (add-text-properties (match-beginning 3) (match-end 3)
  4554. '(invisible org-link)))
  4555. (throw :exit t))))))))
  4556. (defun org-emphasize (&optional char)
  4557. "Insert or change an emphasis, i.e. a font like bold or italic.
  4558. If there is an active region, change that region to a new emphasis.
  4559. If there is no region, just insert the marker characters and position
  4560. the cursor between them.
  4561. CHAR should be the marker character. If it is a space, it means to
  4562. remove the emphasis of the selected region.
  4563. If CHAR is not given (for example in an interactive call) it will be
  4564. prompted for."
  4565. (interactive)
  4566. (let ((erc org-emphasis-regexp-components)
  4567. (string "") beg end move s)
  4568. (if (org-region-active-p)
  4569. (setq beg (region-beginning)
  4570. end (region-end)
  4571. string (buffer-substring beg end))
  4572. (setq move t))
  4573. (unless char
  4574. (message "Emphasis marker or tag: [%s]"
  4575. (mapconcat #'car org-emphasis-alist ""))
  4576. (setq char (read-char-exclusive)))
  4577. (if (equal char ?\s)
  4578. (setq s ""
  4579. move nil)
  4580. (unless (assoc (char-to-string char) org-emphasis-alist)
  4581. (user-error "No such emphasis marker: \"%c\"" char))
  4582. (setq s (char-to-string char)))
  4583. (while (and (> (length string) 1)
  4584. (equal (substring string 0 1) (substring string -1))
  4585. (assoc (substring string 0 1) org-emphasis-alist))
  4586. (setq string (substring string 1 -1)))
  4587. (setq string (concat s string s))
  4588. (when beg (delete-region beg end))
  4589. (unless (or (bolp)
  4590. (string-match (concat "[" (nth 0 erc) "\n]")
  4591. (char-to-string (char-before (point)))))
  4592. (insert " "))
  4593. (unless (or (eobp)
  4594. (string-match (concat "[" (nth 1 erc) "\n]")
  4595. (char-to-string (char-after (point)))))
  4596. (insert " ") (backward-char 1))
  4597. (insert string)
  4598. (and move (backward-char 1))))
  4599. (defconst org-nonsticky-props
  4600. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4601. (defsubst org-rear-nonsticky-at (pos)
  4602. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4603. (defun org-activate-links (limit)
  4604. "Add link properties to links.
  4605. This includes angle, plain, and bracket links."
  4606. (catch :exit
  4607. (while (re-search-forward org-link-any-re limit t)
  4608. (let* ((start (match-beginning 0))
  4609. (end (match-end 0))
  4610. (style (cond ((eq ?< (char-after start)) 'angle)
  4611. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4612. (t 'plain))))
  4613. (when (and (memq style org-highlight-links)
  4614. ;; Do not confuse plain links with tags.
  4615. (not (and (eq style 'plain)
  4616. (let ((face (get-text-property
  4617. (max (1- start) (point-min)) 'face)))
  4618. (if (consp face) (memq 'org-tag face)
  4619. (eq 'org-tag face))))))
  4620. (let* ((link-object (save-excursion
  4621. (goto-char start)
  4622. (save-match-data (org-element-link-parser))))
  4623. (link (org-element-property :raw-link link-object))
  4624. (type (org-element-property :type link-object))
  4625. (path (org-element-property :path link-object))
  4626. (properties ;for link's visible part
  4627. (list
  4628. 'face (pcase (org-link-get-parameter type :face)
  4629. ((and (pred functionp) face) (funcall face path))
  4630. ((and (pred facep) face) face)
  4631. ((and (pred consp) face) face) ;anonymous
  4632. (_ 'org-link))
  4633. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4634. 'highlight)
  4635. 'keymap (or (org-link-get-parameter type :keymap)
  4636. org-mouse-map)
  4637. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4638. ((and (pred stringp) echo) echo)
  4639. ((and (pred functionp) echo) echo)
  4640. (_ (concat "LINK: " link)))
  4641. 'htmlize-link (pcase (org-link-get-parameter type
  4642. :htmlize-link)
  4643. ((and (pred functionp) f) (funcall f))
  4644. (_ `(:uri ,link)))
  4645. 'font-lock-multiline t)))
  4646. (org-remove-flyspell-overlays-in start end)
  4647. (org-rear-nonsticky-at end)
  4648. (if (not (eq 'bracket style))
  4649. (add-text-properties start end properties)
  4650. ;; Handle invisible parts in bracket links.
  4651. (remove-text-properties start end '(invisible nil))
  4652. (let ((hidden
  4653. (append `(invisible
  4654. ,(or (org-link-get-parameter type :display)
  4655. 'org-link))
  4656. properties))
  4657. (visible-start (or (match-beginning 4) (match-beginning 2)))
  4658. (visible-end (or (match-end 4) (match-end 2))))
  4659. (add-text-properties start visible-start hidden)
  4660. (add-text-properties visible-start visible-end properties)
  4661. (add-text-properties visible-end end hidden)
  4662. (org-rear-nonsticky-at visible-start)
  4663. (org-rear-nonsticky-at visible-end)))
  4664. (let ((f (org-link-get-parameter type :activate-func)))
  4665. (when (functionp f)
  4666. (funcall f start end path (eq style 'bracket))))
  4667. (throw :exit t))))) ;signal success
  4668. nil))
  4669. (defun org-activate-code (limit)
  4670. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4671. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4672. (remove-text-properties (match-beginning 0) (match-end 0)
  4673. '(display t invisible t intangible t))
  4674. t))
  4675. (defcustom org-src-fontify-natively t
  4676. "When non-nil, fontify code in code blocks.
  4677. See also the `org-block' face."
  4678. :type 'boolean
  4679. :version "26.1"
  4680. :package-version '(Org . "8.3")
  4681. :group 'org-appearance
  4682. :group 'org-babel)
  4683. (defcustom org-allow-promoting-top-level-subtree nil
  4684. "When non-nil, allow promoting a top level subtree.
  4685. The leading star of the top level headline will be replaced
  4686. by a #."
  4687. :type 'boolean
  4688. :version "24.1"
  4689. :group 'org-appearance)
  4690. (defun org-fontify-meta-lines-and-blocks (limit)
  4691. (condition-case nil
  4692. (org-fontify-meta-lines-and-blocks-1 limit)
  4693. (error (message "Org mode fontification error in %S at %d"
  4694. (current-buffer)
  4695. (line-number-at-pos)))))
  4696. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4697. "Fontify #+ lines and blocks."
  4698. (let ((case-fold-search t))
  4699. (when (re-search-forward
  4700. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  4701. limit t)
  4702. (let ((beg (match-beginning 0))
  4703. (block-start (match-end 0))
  4704. (block-end nil)
  4705. (lang (match-string 7))
  4706. (beg1 (line-beginning-position 2))
  4707. (dc1 (downcase (match-string 2)))
  4708. (dc3 (downcase (match-string 3)))
  4709. end end1 quoting block-type)
  4710. (cond
  4711. ((and (match-end 4) (equal dc3 "+begin"))
  4712. ;; Truly a block
  4713. (setq block-type (downcase (match-string 5))
  4714. quoting (member block-type org-protecting-blocks))
  4715. (when (re-search-forward
  4716. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  4717. nil t) ;; on purpose, we look further than LIMIT
  4718. (setq end (min (point-max) (match-end 0))
  4719. end1 (min (point-max) (1- (match-beginning 0))))
  4720. (setq block-end (match-beginning 0))
  4721. (when quoting
  4722. (org-remove-flyspell-overlays-in beg1 end1)
  4723. (remove-text-properties beg end
  4724. '(display t invisible t intangible t)))
  4725. (add-text-properties
  4726. beg end '(font-lock-fontified t font-lock-multiline t))
  4727. (add-text-properties beg beg1 '(face org-meta-line))
  4728. (org-remove-flyspell-overlays-in beg beg1)
  4729. (add-text-properties ; For end_src
  4730. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  4731. (org-remove-flyspell-overlays-in end1 end)
  4732. (cond
  4733. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4734. (org-src-font-lock-fontify-block lang block-start block-end)
  4735. (add-text-properties beg1 block-end '(src-block t)))
  4736. (quoting
  4737. (add-text-properties beg1 (min (point-max) (1+ end1))
  4738. (list 'face
  4739. (list :inherit
  4740. (let ((face-name
  4741. (intern (format "org-block-%s" lang))))
  4742. (append (and (facep face-name) (list face-name))
  4743. '(org-block))))))) ; end of source block
  4744. ((not org-fontify-quote-and-verse-blocks))
  4745. ((string= block-type "quote")
  4746. (add-face-text-property
  4747. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  4748. ((string= block-type "verse")
  4749. (add-face-text-property
  4750. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  4751. (add-text-properties beg beg1 '(face org-block-begin-line))
  4752. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  4753. '(face org-block-end-line))
  4754. t))
  4755. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  4756. (org-remove-flyspell-overlays-in
  4757. (match-beginning 0)
  4758. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4759. (add-text-properties
  4760. beg (match-end 3)
  4761. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4762. '(font-lock-fontified t invisible t)
  4763. '(font-lock-fontified t face org-document-info-keyword)))
  4764. (add-text-properties
  4765. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4766. (if (string-equal dc1 "+title:")
  4767. '(font-lock-fontified t face org-document-title)
  4768. '(font-lock-fontified t face org-document-info))))
  4769. ((string-prefix-p "+caption" dc1)
  4770. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4771. (remove-text-properties (match-beginning 0) (match-end 0)
  4772. '(display t invisible t intangible t))
  4773. ;; Handle short captions.
  4774. (save-excursion
  4775. (beginning-of-line)
  4776. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  4777. (add-text-properties (line-beginning-position) (match-end 1)
  4778. '(font-lock-fontified t face org-meta-line))
  4779. (add-text-properties (match-end 0) (line-end-position)
  4780. '(font-lock-fontified t face org-block))
  4781. t)
  4782. ((member dc3 '(" " ""))
  4783. (org-remove-flyspell-overlays-in beg (match-end 0))
  4784. (add-text-properties
  4785. beg (match-end 0)
  4786. '(font-lock-fontified t face font-lock-comment-face)))
  4787. (t ;; just any other in-buffer setting, but not indented
  4788. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4789. (remove-text-properties (match-beginning 0) (match-end 0)
  4790. '(display t invisible t intangible t))
  4791. (add-text-properties beg (match-end 0)
  4792. '(font-lock-fontified t face org-meta-line))
  4793. t))))))
  4794. (defun org-fontify-drawers (limit)
  4795. "Fontify drawers."
  4796. (when (re-search-forward org-drawer-regexp limit t)
  4797. (add-text-properties
  4798. (match-beginning 0) (match-end 0)
  4799. '(font-lock-fontified t face org-special-keyword))
  4800. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4801. t))
  4802. (defun org-fontify-macros (limit)
  4803. "Fontify macros."
  4804. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4805. (let ((begin (match-beginning 0))
  4806. (opening-end (match-beginning 1)))
  4807. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4808. (match-string 1))
  4809. (let ((end (match-end 1))
  4810. (closing-start (match-beginning 1)))
  4811. (add-text-properties
  4812. begin end
  4813. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4814. (org-remove-flyspell-overlays-in begin end)
  4815. (when org-hide-macro-markers
  4816. (add-text-properties begin opening-end '(invisible t))
  4817. (add-text-properties closing-start end '(invisible t)))
  4818. t)))))
  4819. (defun org-fontify-extend-region (beg end _old-len)
  4820. (let ((begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4821. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4822. (extend (lambda (r1 r2 dir)
  4823. (let ((re (replace-regexp-in-string "\\(begin\\|end\\)" r1
  4824. (replace-regexp-in-string "[][]" r2
  4825. (match-string-no-properties 0)))))
  4826. (re-search-forward (regexp-quote re) nil t dir)))))
  4827. (save-match-data
  4828. (save-excursion
  4829. (goto-char beg)
  4830. (back-to-indentation)
  4831. (cond ((looking-at end-re)
  4832. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4833. ((looking-at begin-re)
  4834. (cons beg (or (funcall extend "end" "]" 1) end)))
  4835. (t (cons beg end)))))))
  4836. (defun org-activate-footnote-links (limit)
  4837. "Add text properties for footnotes."
  4838. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4839. (when fn
  4840. (let* ((beg (nth 1 fn))
  4841. (end (nth 2 fn))
  4842. (label (car fn))
  4843. (referencep (/= (line-beginning-position) beg)))
  4844. (when (and referencep (nth 3 fn))
  4845. (save-excursion
  4846. (goto-char beg)
  4847. (search-forward (or label "fn:"))
  4848. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4849. (add-text-properties beg end
  4850. (list 'mouse-face 'highlight
  4851. 'keymap org-mouse-map
  4852. 'help-echo
  4853. (if referencep "Footnote reference"
  4854. "Footnote definition")
  4855. 'font-lock-fontified t
  4856. 'font-lock-multiline t
  4857. 'face 'org-footnote))))))
  4858. (defun org-activate-dates (limit)
  4859. "Add text properties for dates."
  4860. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4861. (not (equal (char-before (match-beginning 0)) 91)))
  4862. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4863. (add-text-properties (match-beginning 0) (match-end 0)
  4864. (list 'mouse-face 'highlight
  4865. 'keymap org-mouse-map))
  4866. (org-rear-nonsticky-at (match-end 0))
  4867. (when org-display-custom-times
  4868. ;; If it's a date range, activate custom time for second date.
  4869. (when (match-end 3)
  4870. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4871. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4872. t))
  4873. (defun org-activate-target-links (limit)
  4874. "Add text properties for target matches."
  4875. (when org-target-link-regexp
  4876. (let ((case-fold-search t))
  4877. ;; `org-target-link-regexp' matches one character before the
  4878. ;; actual target.
  4879. (unless (bolp) (forward-char -1))
  4880. (when (re-search-forward org-target-link-regexp limit t)
  4881. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4882. (add-text-properties (match-beginning 1) (match-end 1)
  4883. (list 'mouse-face 'highlight
  4884. 'keymap org-mouse-map
  4885. 'help-echo "Radio target link"
  4886. 'org-linked-text t))
  4887. (org-rear-nonsticky-at (match-end 1))
  4888. t))))
  4889. (defvar org-latex-and-related-regexp nil
  4890. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4891. (defun org-compute-latex-and-related-regexp ()
  4892. "Compute regular expression for LaTeX, entities and sub/superscript.
  4893. Result depends on variable `org-highlight-latex-and-related'."
  4894. (let ((re-sub
  4895. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4896. ((eq org-use-sub-superscripts '{})
  4897. (list org-match-substring-with-braces-regexp))
  4898. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4899. (re-latex
  4900. (when (or (memq 'latex org-highlight-latex-and-related)
  4901. (memq 'native org-highlight-latex-and-related))
  4902. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4903. (delq nil
  4904. (mapcar (lambda (x)
  4905. (and (member (car x) matchers) (nth 1 x)))
  4906. org-latex-regexps)))))
  4907. (re-entities
  4908. (when (memq 'entities org-highlight-latex-and-related)
  4909. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4910. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4911. (setq-local org-latex-and-related-regexp
  4912. (mapconcat #'identity
  4913. (append re-latex re-entities re-sub)
  4914. "\\|"))))
  4915. (defun org-do-latex-and-related (_limit)
  4916. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4917. Stop at first highlighted object, if any. Return t if some
  4918. highlighting was done, nil otherwise."
  4919. (when (org-string-nw-p org-latex-and-related-regexp)
  4920. (catch 'found
  4921. (while (re-search-forward org-latex-and-related-regexp
  4922. nil t) ;; on purpose, we ignore LIMIT
  4923. (unless (cl-some (lambda (f) (memq f '(org-code org-verbatim underline
  4924. org-special-keyword)))
  4925. (save-excursion
  4926. (goto-char (1+ (match-beginning 0)))
  4927. (face-at-point nil t)))
  4928. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4929. '(?_ ?^))
  4930. 1
  4931. 0))
  4932. (start (+ offset (match-beginning 0)))
  4933. (end (match-end 0)))
  4934. (if (memq 'native org-highlight-latex-and-related)
  4935. (org-src-font-lock-fontify-block "latex" start end)
  4936. (font-lock-prepend-text-property start end
  4937. 'face 'org-latex-and-related))
  4938. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4939. '(font-lock-multiline t)))
  4940. (throw 'found t)))
  4941. nil)))
  4942. (defun org-restart-font-lock ()
  4943. "Restart `font-lock-mode', to force refontification."
  4944. (when (and (boundp 'font-lock-mode) font-lock-mode)
  4945. (font-lock-mode -1)
  4946. (font-lock-mode 1)))
  4947. (defun org-activate-tags (limit)
  4948. (when (re-search-forward org-tag-line-re limit t)
  4949. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4950. (add-text-properties (match-beginning 1) (match-end 1)
  4951. (list 'mouse-face 'highlight
  4952. 'keymap org-mouse-map))
  4953. (org-rear-nonsticky-at (match-end 1))
  4954. t))
  4955. (defun org-outline-level ()
  4956. "Compute the outline level of the heading at point.
  4957. If this is called at a normal headline, the level is the number
  4958. of stars. Use `org-reduced-level' to remove the effect of
  4959. `org-odd-levels'. Unlike to `org-current-level', this function
  4960. takes into consideration inlinetasks."
  4961. (org-with-wide-buffer
  4962. (end-of-line)
  4963. (if (re-search-backward org-outline-regexp-bol nil t)
  4964. (1- (- (match-end 0) (match-beginning 0)))
  4965. 0)))
  4966. (defvar org-font-lock-keywords nil)
  4967. (defsubst org-re-property (property &optional literal allow-null value)
  4968. "Return a regexp matching a PROPERTY line.
  4969. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4970. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4971. non-nil, match properties even without a value.
  4972. Match group 3 is set to the value when it exists. If there is no
  4973. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4974. With optional argument VALUE, match only property lines with
  4975. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4976. unless LITERAL is non-nil."
  4977. (concat
  4978. "^\\(?4:[ \t]*\\)"
  4979. (format "\\(?1::\\(?2:%s\\):\\)"
  4980. (if literal property (regexp-quote property)))
  4981. (cond (value
  4982. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4983. (if literal value (regexp-quote value))))
  4984. (allow-null
  4985. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4986. (t
  4987. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4988. (defconst org-property-re
  4989. (org-re-property "\\S-+" 'literal t)
  4990. "Regular expression matching a property line.
  4991. There are four matching groups:
  4992. 1: :PROPKEY: including the leading and trailing colon,
  4993. 2: PROPKEY without the leading and trailing colon,
  4994. 3: PROPVAL without leading or trailing spaces,
  4995. 4: the indentation of the current line,
  4996. 5: trailing whitespace.")
  4997. (defvar org-font-lock-hook nil
  4998. "Functions to be called for special font lock stuff.")
  4999. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5000. (defvar org-font-lock-set-keywords-hook nil
  5001. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5002. This is called after `org-font-lock-extra-keywords' is defined, but before
  5003. it is installed to be used by font lock. This can be useful if something
  5004. needs to be inserted at a specific position in the font-lock sequence.")
  5005. (defun org-font-lock-hook (limit)
  5006. "Run `org-font-lock-hook' within LIMIT."
  5007. (run-hook-with-args 'org-font-lock-hook limit))
  5008. (defun org-set-font-lock-defaults ()
  5009. "Set font lock defaults for the current buffer."
  5010. (let* ((em org-fontify-emphasized-text)
  5011. (lk org-highlight-links)
  5012. (org-font-lock-extra-keywords
  5013. (list
  5014. ;; Call the hook
  5015. '(org-font-lock-hook)
  5016. ;; Headlines
  5017. `(,(if org-fontify-whole-heading-line
  5018. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5019. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5020. (1 (org-get-level-face 1))
  5021. (2 (org-get-level-face 2))
  5022. (3 (org-get-level-face 3)))
  5023. ;; Table lines
  5024. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5025. (1 'org-table t))
  5026. ;; Table internals
  5027. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5028. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5029. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5030. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5031. ;; Drawers
  5032. '(org-fontify-drawers)
  5033. ;; Properties
  5034. (list org-property-re
  5035. '(1 'org-special-keyword t)
  5036. '(3 'org-property-value t))
  5037. ;; Link related fontification.
  5038. '(org-activate-links)
  5039. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5040. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5041. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5042. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5043. ;; Targets.
  5044. (list org-radio-target-regexp '(0 'org-target t))
  5045. (list org-target-regexp '(0 'org-target t))
  5046. ;; Diary sexps.
  5047. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5048. ;; Macro
  5049. '(org-fontify-macros)
  5050. ;; TODO keyword
  5051. (list (format org-heading-keyword-regexp-format
  5052. org-todo-regexp)
  5053. '(2 (org-get-todo-face 2) t))
  5054. ;; DONE
  5055. (if org-fontify-done-headline
  5056. (list (format org-heading-keyword-regexp-format
  5057. (concat
  5058. "\\(?:"
  5059. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5060. "\\)"))
  5061. '(2 'org-headline-done t))
  5062. nil)
  5063. ;; Priorities
  5064. '(org-font-lock-add-priority-faces)
  5065. ;; Tags
  5066. '(org-font-lock-add-tag-faces)
  5067. ;; Tags groups
  5068. (when (and org-group-tags org-tag-groups-alist)
  5069. (list (concat org-outline-regexp-bol ".+\\(:"
  5070. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5071. ":\\).*$")
  5072. '(1 'org-tag-group prepend)))
  5073. ;; Special keywords
  5074. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5075. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5076. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5077. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5078. ;; Emphasis
  5079. (when em '(org-do-emphasis-faces))
  5080. ;; Checkboxes
  5081. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5082. 1 'org-checkbox prepend)
  5083. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5084. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5085. (0 (org-get-checkbox-statistics-face) t)))
  5086. ;; Description list items
  5087. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5088. 1 'org-list-dt prepend)
  5089. ;; ARCHIVEd headings
  5090. (list (concat
  5091. org-outline-regexp-bol
  5092. "\\(.*:" org-archive-tag ":.*\\)")
  5093. '(1 'org-archived prepend))
  5094. ;; Specials
  5095. '(org-do-latex-and-related)
  5096. '(org-fontify-entities)
  5097. '(org-raise-scripts)
  5098. ;; Code
  5099. '(org-activate-code (1 'org-code t))
  5100. ;; COMMENT
  5101. (list (format
  5102. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5103. org-todo-regexp
  5104. org-comment-string)
  5105. '(9 'org-special-keyword t))
  5106. ;; Blocks and meta lines
  5107. '(org-fontify-meta-lines-and-blocks))))
  5108. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5109. (run-hooks 'org-font-lock-set-keywords-hook)
  5110. ;; Now set the full font-lock-keywords
  5111. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5112. (setq-local font-lock-defaults
  5113. '(org-font-lock-keywords t nil nil backward-paragraph))
  5114. (setq-local font-lock-extend-after-change-region-function
  5115. #'org-fontify-extend-region)
  5116. (kill-local-variable 'font-lock-keywords)
  5117. nil))
  5118. (defun org-toggle-pretty-entities ()
  5119. "Toggle the composition display of entities as UTF8 characters."
  5120. (interactive)
  5121. (setq-local org-pretty-entities (not org-pretty-entities))
  5122. (org-restart-font-lock)
  5123. (if org-pretty-entities
  5124. (message "Entities are now displayed as UTF8 characters")
  5125. (save-restriction
  5126. (widen)
  5127. (decompose-region (point-min) (point-max))
  5128. (message "Entities are now displayed as plain text"))))
  5129. (defvar-local org-custom-properties-overlays nil
  5130. "List of overlays used for custom properties.")
  5131. (defun org-toggle-custom-properties-visibility ()
  5132. "Display or hide properties in `org-custom-properties'."
  5133. (interactive)
  5134. (if org-custom-properties-overlays
  5135. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5136. (setq org-custom-properties-overlays nil))
  5137. (when org-custom-properties
  5138. (org-with-wide-buffer
  5139. (goto-char (point-min))
  5140. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5141. (while (re-search-forward regexp nil t)
  5142. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5143. (when (and end (< (point) end))
  5144. ;; Hide first custom property in current drawer.
  5145. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5146. (overlay-put o 'invisible t)
  5147. (overlay-put o 'org-custom-property t)
  5148. (push o org-custom-properties-overlays))
  5149. ;; Hide additional custom properties in the same drawer.
  5150. (while (re-search-forward regexp end t)
  5151. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5152. (overlay-put o 'invisible t)
  5153. (overlay-put o 'org-custom-property t)
  5154. (push o org-custom-properties-overlays)))))
  5155. ;; Each entry is limited to a single property drawer.
  5156. (outline-next-heading)))))))
  5157. (defun org-fontify-entities (limit)
  5158. "Find an entity to fontify."
  5159. (let (ee)
  5160. (when org-pretty-entities
  5161. (catch 'match
  5162. ;; "\_ "-family is left out on purpose. Only the first one,
  5163. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5164. ;; confusing when adding a second white space character.
  5165. (while (re-search-forward
  5166. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5167. limit t)
  5168. (when (and (not (org-at-comment-p))
  5169. (setq ee (org-entity-get (match-string 1)))
  5170. (= (length (nth 6 ee)) 1))
  5171. (let* ((end (if (equal (match-string 2) "{}")
  5172. (match-end 2)
  5173. (match-end 1))))
  5174. (add-text-properties
  5175. (match-beginning 0) end
  5176. (list 'font-lock-fontified t))
  5177. (compose-region (match-beginning 0) end
  5178. (nth 6 ee) nil)
  5179. (backward-char 1)
  5180. (throw 'match t))))
  5181. nil))))
  5182. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5183. "Fontify string S like in Org mode."
  5184. (with-temp-buffer
  5185. (insert s)
  5186. (let ((org-odd-levels-only odd-levels))
  5187. (org-mode)
  5188. (org-font-lock-ensure)
  5189. (buffer-string))))
  5190. (defvar org-m nil)
  5191. (defvar org-l nil)
  5192. (defvar org-f nil)
  5193. (defun org-get-level-face (n)
  5194. "Get the right face for match N in font-lock matching of headlines."
  5195. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5196. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5197. (if org-cycle-level-faces
  5198. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5199. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5200. (cond
  5201. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5202. ((eq n 2) org-f)
  5203. (t (unless org-level-color-stars-only org-f))))
  5204. (defun org-face-from-face-or-color (context inherit face-or-color)
  5205. "Create a face list that inherits INHERIT, but sets the foreground color.
  5206. When FACE-OR-COLOR is not a string, just return it."
  5207. (if (stringp face-or-color)
  5208. (list :inherit inherit
  5209. (cdr (assoc context org-faces-easy-properties))
  5210. face-or-color)
  5211. face-or-color))
  5212. (defun org-get-todo-face (kwd)
  5213. "Get the right face for a TODO keyword KWD.
  5214. If KWD is a number, get the corresponding match group."
  5215. (when (numberp kwd) (setq kwd (match-string kwd)))
  5216. (or (org-face-from-face-or-color
  5217. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5218. (and (member kwd org-done-keywords) 'org-done)
  5219. 'org-todo))
  5220. (defun org-get-priority-face (priority)
  5221. "Get the right face for PRIORITY.
  5222. PRIORITY is a character."
  5223. (or (org-face-from-face-or-color
  5224. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5225. 'org-priority))
  5226. (defun org-get-tag-face (tag)
  5227. "Get the right face for TAG.
  5228. If TAG is a number, get the corresponding match group."
  5229. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5230. (or (org-face-from-face-or-color
  5231. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5232. 'org-tag)))
  5233. (defun org-font-lock-add-priority-faces (limit)
  5234. "Add the special priority faces."
  5235. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5236. (add-text-properties
  5237. (match-beginning 1) (match-end 1)
  5238. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5239. 'font-lock-fontified t))))
  5240. (defun org-font-lock-add-tag-faces (limit)
  5241. "Add the special tag faces."
  5242. (when (and org-tag-faces org-tags-special-faces-re)
  5243. (while (re-search-forward org-tags-special-faces-re limit t)
  5244. (add-text-properties (match-beginning 1) (match-end 1)
  5245. (list 'face (org-get-tag-face 1)
  5246. 'font-lock-fontified t))
  5247. (backward-char 1))))
  5248. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5249. "Remove fontification and activation overlays from links."
  5250. (font-lock-default-unfontify-region beg end)
  5251. (let* ((buffer-undo-list t)
  5252. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5253. (inhibit-modification-hooks t)
  5254. deactivate-mark buffer-file-name buffer-file-truename)
  5255. (decompose-region beg end)
  5256. (remove-text-properties beg end
  5257. '(mouse-face t keymap t org-linked-text t
  5258. invisible t intangible t
  5259. org-emphasis t))
  5260. (org-remove-font-lock-display-properties beg end)))
  5261. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5262. ((raise 0.3) (height 0.7))
  5263. ((raise -0.5))
  5264. ((raise 0.5)))
  5265. "Display properties for showing superscripts and subscripts.")
  5266. (defun org-remove-font-lock-display-properties (beg end)
  5267. "Remove specific display properties that have been added by font lock.
  5268. The will remove the raise properties that are used to show superscripts
  5269. and subscripts."
  5270. (let (next prop)
  5271. (while (< beg end)
  5272. (setq next (next-single-property-change beg 'display nil end)
  5273. prop (get-text-property beg 'display))
  5274. (when (member prop org-script-display)
  5275. (put-text-property beg next 'display nil))
  5276. (setq beg next))))
  5277. (defun org-raise-scripts (limit)
  5278. "Add raise properties to sub/superscripts."
  5279. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5280. (re-search-forward
  5281. (if (eq org-use-sub-superscripts t)
  5282. org-match-substring-regexp
  5283. org-match-substring-with-braces-regexp)
  5284. limit t))
  5285. (let* ((pos (point)) table-p comment-p
  5286. (mpos (match-beginning 3))
  5287. (emph-p (get-text-property mpos 'org-emphasis))
  5288. (link-p (get-text-property mpos 'mouse-face))
  5289. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5290. (goto-char (point-at-bol))
  5291. (setq table-p (looking-at-p org-table-dataline-regexp)
  5292. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5293. (goto-char pos)
  5294. ;; Handle a_b^c
  5295. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5296. (unless (or comment-p emph-p link-p keyw-p)
  5297. (put-text-property (match-beginning 3) (match-end 0)
  5298. 'display
  5299. (if (equal (char-after (match-beginning 2)) ?^)
  5300. (nth (if table-p 3 1) org-script-display)
  5301. (nth (if table-p 2 0) org-script-display)))
  5302. (add-text-properties (match-beginning 2) (match-end 2)
  5303. (list 'invisible t))
  5304. (when (and (eq (char-after (match-beginning 3)) ?{)
  5305. (eq (char-before (match-end 3)) ?}))
  5306. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5307. (list 'invisible t))
  5308. (add-text-properties (1- (match-end 3)) (match-end 3)
  5309. (list 'invisible t))))
  5310. t)))
  5311. (defun org-remove-empty-overlays-at (pos)
  5312. "Remove outline overlays that do not contain non-white stuff."
  5313. (dolist (o (overlays-at pos))
  5314. (and (eq 'outline (overlay-get o 'invisible))
  5315. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5316. (overlay-end o))))
  5317. (delete-overlay o))))
  5318. (defun org-show-empty-lines-in-parent ()
  5319. "Move to the parent and re-show empty lines before visible headlines."
  5320. (save-excursion
  5321. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5322. (org-cycle-show-empty-lines context))))
  5323. (defun org-files-list ()
  5324. "Return `org-agenda-files' list, plus all open Org files.
  5325. This is useful for operations that need to scan all of a user's
  5326. open and agenda-wise Org files."
  5327. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5328. (dolist (buf (buffer-list))
  5329. (with-current-buffer buf
  5330. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5331. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5332. :test #'equal))))
  5333. files))
  5334. (defsubst org-entry-beginning-position ()
  5335. "Return the beginning position of the current entry."
  5336. (save-excursion (org-back-to-heading t) (point)))
  5337. (defsubst org-entry-end-position ()
  5338. "Return the end position of the current entry."
  5339. (save-excursion (outline-next-heading) (point)))
  5340. (defun org-subtree-end-visible-p ()
  5341. "Is the end of the current subtree visible?"
  5342. (pos-visible-in-window-p
  5343. (save-excursion (org-end-of-subtree t) (point))))
  5344. (defun org-first-headline-recenter ()
  5345. "Move cursor to the first headline and recenter the headline."
  5346. (let ((window (get-buffer-window)))
  5347. (when window
  5348. (goto-char (point-min))
  5349. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5350. (set-window-start window (line-beginning-position))))))
  5351. ;;; Visibility (headlines, blocks, drawers)
  5352. ;;;; Headlines visibility
  5353. (defun org-show-entry ()
  5354. "Show the body directly following this heading.
  5355. Show the heading too, if it is currently invisible."
  5356. (interactive)
  5357. (save-excursion
  5358. (ignore-errors
  5359. (org-back-to-heading t)
  5360. (org-flag-region
  5361. (line-end-position 0)
  5362. (save-excursion
  5363. (if (re-search-forward
  5364. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5365. (match-beginning 1)
  5366. (point-max)))
  5367. nil
  5368. 'outline))))
  5369. (defun org-show-children (&optional level)
  5370. "Show all direct subheadings of this heading.
  5371. Prefix arg LEVEL is how many levels below the current level
  5372. should be shown. Default is enough to cause the following
  5373. heading to appear."
  5374. (interactive "p")
  5375. (save-excursion
  5376. (org-back-to-heading t)
  5377. (let* ((current-level (funcall outline-level))
  5378. (max-level (org-get-valid-level
  5379. current-level
  5380. (if level (prefix-numeric-value level) 1)))
  5381. (end (save-excursion (org-end-of-subtree t t)))
  5382. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5383. (past-first-child nil)
  5384. ;; Make sure to skip inlinetasks.
  5385. (re (format regexp-fmt
  5386. current-level
  5387. (cond
  5388. ((not (featurep 'org-inlinetask)) "")
  5389. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5390. 3))
  5391. (t (1- org-inlinetask-min-level))))))
  5392. ;; Display parent heading.
  5393. (org-flag-heading nil)
  5394. (forward-line)
  5395. ;; Display children. First child may be deeper than expected
  5396. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5397. ;; MAX-LEVEL accordingly.
  5398. (while (re-search-forward re end t)
  5399. (unless past-first-child
  5400. (setq re (format regexp-fmt
  5401. current-level
  5402. (max (funcall outline-level) max-level)))
  5403. (setq past-first-child t))
  5404. (org-flag-heading nil)))))
  5405. (defun org-show-subtree ()
  5406. "Show everything after this heading at deeper levels."
  5407. (interactive)
  5408. (org-flag-region
  5409. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5410. ;;;; Blocks visibility
  5411. (defun org-hide-block-toggle-maybe ()
  5412. "Toggle visibility of block at point.
  5413. Unlike to `org-hide-block-toggle', this function does not throw
  5414. an error. Return a non-nil value when toggling is successful."
  5415. (interactive)
  5416. (ignore-errors (org-hide-block-toggle)))
  5417. (defun org-hide-block-toggle (&optional force)
  5418. "Toggle the visibility of the current block.
  5419. When optional argument FORCE is `off', make block visible. If it
  5420. is non-nil, hide it unconditionally. Throw an error when not at
  5421. a block. Return a non-nil value when toggling is successful."
  5422. (interactive)
  5423. (let ((element (org-element-at-point)))
  5424. (unless (memq (org-element-type element)
  5425. '(center-block comment-block dynamic-block example-block
  5426. export-block quote-block special-block
  5427. src-block verse-block))
  5428. (user-error "Not at a block"))
  5429. (let* ((post (org-element-property :post-affiliated element))
  5430. (start (save-excursion
  5431. (goto-char post)
  5432. (line-end-position)))
  5433. (end (save-excursion
  5434. (goto-char (org-element-property :end element))
  5435. (skip-chars-backward " \t\n")
  5436. (line-end-position))))
  5437. ;; Do nothing when not before or at the block opening line or at
  5438. ;; the block closing line.
  5439. (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
  5440. (cond ((eq force 'off)
  5441. (org-flag-region start end nil 'org-hide-block))
  5442. (force
  5443. (org-flag-region start end t 'org-hide-block))
  5444. ((eq (get-char-property start 'invisible) 'org-hide-block)
  5445. (org-flag-region start end nil 'org-hide-block))
  5446. (t
  5447. (org-flag-region start end t 'org-hide-block)))
  5448. ;; When the block is hidden away, make sure point is left in
  5449. ;; a visible part of the buffer.
  5450. (when (invisible-p (max (1- (point)) (point-min)))
  5451. (goto-char post))
  5452. ;; Signal success.
  5453. t))))
  5454. (defun org-hide-block-toggle-all ()
  5455. "Toggle the visibility of all blocks in the current buffer."
  5456. (org-block-map 'org-hide-block-toggle))
  5457. (defun org-hide-block-all ()
  5458. "Fold all blocks in the current buffer."
  5459. (interactive)
  5460. (org-show-all '(blocks))
  5461. (org-block-map 'org-hide-block-toggle-maybe))
  5462. ;;;; Drawers visibility
  5463. (defun org-cycle-hide-drawers (state &optional exceptions)
  5464. "Re-hide all drawers after a visibility state change.
  5465. STATE should be one of the symbols listed in the docstring of
  5466. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  5467. a list of strings specifying which drawers should not be hidden."
  5468. (when (and (derived-mode-p 'org-mode)
  5469. (not (memq state '(overview folded contents))))
  5470. (save-excursion
  5471. (let* ((globalp (eq state 'all))
  5472. (beg (if globalp (point-min) (point)))
  5473. (end (if globalp (point-max)
  5474. (if (eq state 'children)
  5475. (save-excursion (outline-next-heading) (point))
  5476. (org-end-of-subtree t)))))
  5477. (goto-char beg)
  5478. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  5479. (unless (member-ignore-case (match-string 1) exceptions)
  5480. (let ((drawer (org-element-at-point)))
  5481. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5482. (org-flag-drawer t drawer)
  5483. ;; Make sure to skip drawer entirely or we might flag
  5484. ;; it another time when matching its ending line with
  5485. ;; `org-drawer-regexp'.
  5486. (goto-char (org-element-property :end drawer))))))))))
  5487. (defun org-flag-drawer (flag &optional element)
  5488. "When FLAG is non-nil, hide the drawer we are at.
  5489. Otherwise make it visible. When optional argument ELEMENT is
  5490. a parsed drawer, as returned by `org-element-at-point', hide or
  5491. show that drawer instead."
  5492. (let ((drawer (or element
  5493. (and (save-excursion
  5494. (beginning-of-line)
  5495. (looking-at-p org-drawer-regexp))
  5496. (org-element-at-point)))))
  5497. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5498. (let ((post (org-element-property :post-affiliated drawer)))
  5499. (org-flag-region
  5500. (save-excursion (goto-char post) (line-end-position))
  5501. (save-excursion (goto-char (org-element-property :end drawer))
  5502. (skip-chars-backward " \t\n")
  5503. (line-end-position))
  5504. flag 'org-hide-drawer)
  5505. ;; When the drawer is hidden away, make sure point lies in
  5506. ;; a visible part of the buffer.
  5507. (when (invisible-p (max (1- (point)) (point-min)))
  5508. (goto-char post))))))
  5509. ;;;; Visibility cycling
  5510. (defvar-local org-cycle-global-status nil)
  5511. (put 'org-cycle-global-status 'org-state t)
  5512. (defvar-local org-cycle-subtree-status nil)
  5513. (put 'org-cycle-subtree-status 'org-state t)
  5514. (defun org-show-all (&optional types)
  5515. "Show all contents in the visible part of the buffer.
  5516. By default, the function expands headings, blocks and drawers.
  5517. When optional argument TYPE is a list of symbols among `blocks',
  5518. `drawers' and `headings', to only expand one specific type."
  5519. (interactive)
  5520. (dolist (type (or types '(blocks drawers headings)))
  5521. (org-flag-region (point-min) (point-max) nil
  5522. (pcase type
  5523. (`blocks 'org-hide-block)
  5524. (`drawers 'org-hide-drawer)
  5525. (`headings 'outline)
  5526. (_ (error "Invalid type: %S" type))))))
  5527. ;;;###autoload
  5528. (defun org-cycle (&optional arg)
  5529. "TAB-action and visibility cycling for Org mode.
  5530. This is the command invoked in Org mode by the `TAB' key. Its main
  5531. purpose is outline visibility cycling, but it also invokes other actions
  5532. in special contexts.
  5533. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5534. the entire
  5535. buffer through 3 states (global cycling)
  5536. 1. OVERVIEW: Show only top-level headlines.
  5537. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5538. 3. SHOW ALL: Show everything.
  5539. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5540. switch to the startup visibility,
  5541. determined by the variable `org-startup-folded', and by any VISIBILITY
  5542. properties in the buffer.
  5543. With a `\\[universal-argument] \\[universal-argument] \
  5544. \\[universal-argument]' prefix argument, show the entire buffer, including
  5545. any drawers.
  5546. When inside a table, re-align the table and move to the next field.
  5547. When point is at the beginning of a headline, rotate the subtree started
  5548. by this line through 3 different states (local cycling)
  5549. 1. FOLDED: Only the main headline is shown.
  5550. 2. CHILDREN: The main headline and the direct children are shown.
  5551. From this state, you can move to one of the children
  5552. and zoom in further.
  5553. 3. SUBTREE: Show the entire subtree, including body text.
  5554. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5555. When point is at the beginning of an empty headline and the variable
  5556. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5557. of the headline by demoting and promoting it to likely levels. This
  5558. speeds up creation document structure by pressing `TAB' once or several
  5559. times right after creating a new headline.
  5560. When there is a numeric prefix, go up to a heading with level ARG, do
  5561. a `show-subtree' and return to the previous cursor position. If ARG
  5562. is negative, go up that many levels.
  5563. When point is not at the beginning of a headline, execute the global
  5564. binding for `TAB', which is re-indenting the line. See the option
  5565. `org-cycle-emulate-tab' for details.
  5566. As a special case, if point is at the beginning of the buffer and there is
  5567. no headline in line 1, this function will act as if called with prefix arg
  5568. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  5569. prefix arg, but only
  5570. if the variable `org-cycle-global-at-bob' is t."
  5571. (interactive "P")
  5572. (org-load-modules-maybe)
  5573. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5574. (and org-cycle-level-after-item/entry-creation
  5575. (or (org-cycle-level)
  5576. (org-cycle-item-indentation))))
  5577. (let* ((limit-level
  5578. (or org-cycle-max-level
  5579. (and (boundp 'org-inlinetask-min-level)
  5580. org-inlinetask-min-level
  5581. (1- org-inlinetask-min-level))))
  5582. (nstars (and limit-level
  5583. (if org-odd-levels-only
  5584. (and limit-level (1- (* limit-level 2)))
  5585. limit-level)))
  5586. (org-outline-regexp
  5587. (if (not (derived-mode-p 'org-mode))
  5588. outline-regexp
  5589. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5590. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5591. (not (looking-at org-outline-regexp))))
  5592. (org-cycle-hook
  5593. (if bob-special
  5594. (delq 'org-optimize-window-after-visibility-change
  5595. (copy-sequence org-cycle-hook))
  5596. org-cycle-hook))
  5597. (pos (point)))
  5598. (cond
  5599. ((equal arg '(16))
  5600. (setq last-command 'dummy)
  5601. (org-set-startup-visibility)
  5602. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5603. ((equal arg '(64))
  5604. (org-show-all)
  5605. (org-unlogged-message "Entire buffer visible, including drawers"))
  5606. ((equal arg '(4)) (org-cycle-internal-global))
  5607. ;; Try hiding block at point.
  5608. ((org-hide-block-toggle-maybe))
  5609. ;; Try cdlatex TAB completion
  5610. ((org-try-cdlatex-tab))
  5611. ;; Table: enter it or move to the next field.
  5612. ((org-at-table-p 'any)
  5613. (if (org-at-table.el-p)
  5614. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  5615. Use `\\[org-edit-special]' to edit table.el tables"))
  5616. (if arg (org-table-edit-field t)
  5617. (org-table-justify-field-maybe)
  5618. (call-interactively 'org-table-next-field))))
  5619. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  5620. ;; Global cycling: delegate to `org-cycle-internal-global'.
  5621. (bob-special (org-cycle-internal-global))
  5622. ;; Drawers: delegate to `org-flag-drawer'.
  5623. ((save-excursion
  5624. (beginning-of-line 1)
  5625. (looking-at org-drawer-regexp))
  5626. (org-flag-drawer ; toggle block visibility
  5627. (not (get-char-property (match-end 0) 'invisible))))
  5628. ;; Show-subtree, ARG levels up from here.
  5629. ((integerp arg)
  5630. (save-excursion
  5631. (org-back-to-heading)
  5632. (outline-up-heading (if (< arg 0) (- arg)
  5633. (- (funcall outline-level) arg)))
  5634. (org-show-subtree)))
  5635. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5636. ((and (featurep 'org-inlinetask)
  5637. (org-inlinetask-at-task-p)
  5638. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5639. (org-inlinetask-toggle-visibility))
  5640. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5641. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  5642. (save-excursion (move-beginning-of-line 1)
  5643. (looking-at org-outline-regexp)))
  5644. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5645. (org-cycle-internal-local))
  5646. ;; From there: TAB emulation and template completion.
  5647. (buffer-read-only (org-back-to-heading))
  5648. ((run-hook-with-args-until-success
  5649. 'org-tab-after-check-for-cycling-hook))
  5650. ((run-hook-with-args-until-success
  5651. 'org-tab-before-tab-emulation-hook))
  5652. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5653. (or (not (bolp))
  5654. (not (looking-at org-outline-regexp))))
  5655. (call-interactively (global-key-binding "\t")))
  5656. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  5657. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5658. (or (and (eq org-cycle-emulate-tab 'white)
  5659. (= (match-end 0) (point-at-eol)))
  5660. (and (eq org-cycle-emulate-tab 'whitestart)
  5661. (>= (match-end 0) pos))))
  5662. t
  5663. (eq org-cycle-emulate-tab t))
  5664. (call-interactively (global-key-binding "\t")))
  5665. (t (save-excursion
  5666. (org-back-to-heading)
  5667. (org-cycle)))))))
  5668. (defun org-cycle-internal-global ()
  5669. "Do the global cycling action."
  5670. ;; Hack to avoid display of messages for .org attachments in Gnus
  5671. (let ((ga (string-match "\\*fontification" (buffer-name))))
  5672. (cond
  5673. ((and (eq last-command this-command)
  5674. (eq org-cycle-global-status 'overview))
  5675. ;; We just created the overview - now do table of contents
  5676. ;; This can be slow in very large buffers, so indicate action
  5677. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5678. (unless ga (org-unlogged-message "CONTENTS..."))
  5679. (org-content)
  5680. (unless ga (org-unlogged-message "CONTENTS...done"))
  5681. (setq org-cycle-global-status 'contents)
  5682. (run-hook-with-args 'org-cycle-hook 'contents))
  5683. ((and (eq last-command this-command)
  5684. (eq org-cycle-global-status 'contents))
  5685. ;; We just showed the table of contents - now show everything
  5686. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5687. (org-show-all '(headings blocks))
  5688. (unless ga (org-unlogged-message "SHOW ALL"))
  5689. (setq org-cycle-global-status 'all)
  5690. (run-hook-with-args 'org-cycle-hook 'all))
  5691. (t
  5692. ;; Default action: go to overview
  5693. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5694. (org-overview)
  5695. (unless ga (org-unlogged-message "OVERVIEW"))
  5696. (setq org-cycle-global-status 'overview)
  5697. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5698. (defvar org-called-with-limited-levels nil
  5699. "Non-nil when `org-with-limited-levels' is currently active.")
  5700. (defun org-cycle-internal-local ()
  5701. "Do the local cycling action."
  5702. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5703. ;; First, determine end of headline (EOH), end of subtree or item
  5704. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5705. (save-excursion
  5706. (if (org-at-item-p)
  5707. (progn
  5708. (beginning-of-line)
  5709. (setq struct (org-list-struct))
  5710. (setq eoh (point-at-eol))
  5711. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5712. (setq has-children (org-list-has-child-p (point) struct)))
  5713. (org-back-to-heading)
  5714. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5715. (setq eos (save-excursion (org-end-of-subtree t t)
  5716. (when (bolp) (backward-char)) (point)))
  5717. (setq has-children
  5718. (or (save-excursion
  5719. (let ((level (funcall outline-level)))
  5720. (outline-next-heading)
  5721. (and (org-at-heading-p t)
  5722. (> (funcall outline-level) level))))
  5723. (save-excursion
  5724. (org-list-search-forward (org-item-beginning-re) eos t)))))
  5725. ;; Determine end invisible part of buffer (EOL)
  5726. (beginning-of-line 2)
  5727. (while (and (not (eobp)) ;This is like `next-line'.
  5728. (get-char-property (1- (point)) 'invisible))
  5729. (goto-char (next-single-char-property-change (point) 'invisible))
  5730. (and (eolp) (beginning-of-line 2)))
  5731. (setq eol (point)))
  5732. ;; Find out what to do next and set `this-command'
  5733. (cond
  5734. ((= eos eoh)
  5735. ;; Nothing is hidden behind this heading
  5736. (unless (org-before-first-heading-p)
  5737. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  5738. (org-unlogged-message "EMPTY ENTRY")
  5739. (setq org-cycle-subtree-status nil)
  5740. (save-excursion
  5741. (goto-char eos)
  5742. (outline-next-heading)
  5743. (when (org-invisible-p) (org-flag-heading nil))))
  5744. ((and (or (>= eol eos)
  5745. (not (string-match "\\S-" (buffer-substring eol eos))))
  5746. (or has-children
  5747. (not (setq children-skipped
  5748. org-cycle-skip-children-state-if-no-children))))
  5749. ;; Entire subtree is hidden in one line: children view
  5750. (unless (org-before-first-heading-p)
  5751. (run-hook-with-args 'org-pre-cycle-hook 'children))
  5752. (if (org-at-item-p)
  5753. (org-list-set-item-visibility (point-at-bol) struct 'children)
  5754. (org-show-entry)
  5755. (org-with-limited-levels (org-show-children))
  5756. (org-show-set-visibility 'canonical)
  5757. ;; Fold every list in subtree to top-level items.
  5758. (when (eq org-cycle-include-plain-lists 'integrate)
  5759. (save-excursion
  5760. (org-back-to-heading)
  5761. (while (org-list-search-forward (org-item-beginning-re) eos t)
  5762. (beginning-of-line 1)
  5763. (let* ((struct (org-list-struct))
  5764. (prevs (org-list-prevs-alist struct))
  5765. (end (org-list-get-bottom-point struct)))
  5766. (dolist (e (org-list-get-all-items (point) struct prevs))
  5767. (org-list-set-item-visibility e struct 'folded))
  5768. (goto-char (if (< end eos) end eos)))))))
  5769. (org-unlogged-message "CHILDREN")
  5770. (save-excursion
  5771. (goto-char eos)
  5772. (outline-next-heading)
  5773. (when (org-invisible-p) (org-flag-heading nil)))
  5774. (setq org-cycle-subtree-status 'children)
  5775. (unless (org-before-first-heading-p)
  5776. (run-hook-with-args 'org-cycle-hook 'children)))
  5777. ((or children-skipped
  5778. (and (eq last-command this-command)
  5779. (eq org-cycle-subtree-status 'children)))
  5780. ;; We just showed the children, or no children are there,
  5781. ;; now show everything.
  5782. (unless (org-before-first-heading-p)
  5783. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  5784. (org-flag-region eoh eos nil 'outline)
  5785. (org-unlogged-message
  5786. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  5787. (setq org-cycle-subtree-status 'subtree)
  5788. (unless (org-before-first-heading-p)
  5789. (run-hook-with-args 'org-cycle-hook 'subtree)))
  5790. (t
  5791. ;; Default action: hide the subtree.
  5792. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  5793. (org-flag-region eoh eos t 'outline)
  5794. (org-unlogged-message "FOLDED")
  5795. (setq org-cycle-subtree-status 'folded)
  5796. (unless (org-before-first-heading-p)
  5797. (run-hook-with-args 'org-cycle-hook 'folded))))))
  5798. ;;;###autoload
  5799. (defun org-global-cycle (&optional arg)
  5800. "Cycle the global visibility. For details see `org-cycle'.
  5801. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  5802. With a numeric prefix, show all headlines up to that level."
  5803. (interactive "P")
  5804. (let ((org-cycle-include-plain-lists
  5805. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  5806. (cond
  5807. ((integerp arg)
  5808. (org-show-all '(headings blocks))
  5809. (outline-hide-sublevels arg)
  5810. (setq org-cycle-global-status 'contents))
  5811. ((equal arg '(4))
  5812. (org-set-startup-visibility)
  5813. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  5814. (t
  5815. (org-cycle '(4))))))
  5816. (defun org-set-startup-visibility ()
  5817. "Set the visibility required by startup options and properties."
  5818. (cond
  5819. ((eq org-startup-folded t)
  5820. (org-overview))
  5821. ((eq org-startup-folded 'content)
  5822. (org-content))
  5823. ((or (eq org-startup-folded 'showeverything)
  5824. (eq org-startup-folded nil))
  5825. (org-show-all)))
  5826. (unless (eq org-startup-folded 'showeverything)
  5827. (when org-hide-block-startup (org-hide-block-all))
  5828. (org-set-visibility-according-to-property)
  5829. (org-cycle-hide-archived-subtrees 'all)
  5830. (org-cycle-hide-drawers 'all)
  5831. (org-cycle-show-empty-lines t)))
  5832. (defun org-set-visibility-according-to-property ()
  5833. "Switch subtree visibility according to VISIBILITY property."
  5834. (interactive)
  5835. (let ((regexp (org-re-property "VISIBILITY")))
  5836. (org-with-point-at 1
  5837. (while (re-search-forward regexp nil t)
  5838. (let ((state (match-string 3)))
  5839. (if (not (org-at-property-p)) (outline-next-heading)
  5840. (save-excursion
  5841. (org-back-to-heading t)
  5842. (outline-hide-subtree)
  5843. (org-reveal)
  5844. (pcase state
  5845. ("folded"
  5846. (outline-hide-subtree))
  5847. ("children"
  5848. (org-show-hidden-entry)
  5849. (org-show-children))
  5850. ("content"
  5851. (save-excursion
  5852. (save-restriction
  5853. (org-narrow-to-subtree)
  5854. (org-content))))
  5855. ((or "all" "showall")
  5856. (outline-show-subtree))
  5857. (_ nil)))
  5858. (org-end-of-subtree)))))))
  5859. (defun org-overview ()
  5860. "Switch to overview mode, showing only top-level headlines.
  5861. This shows all headlines with a level equal or greater than the level
  5862. of the first headline in the buffer. This is important, because if the
  5863. first headline is not level one, then (hide-sublevels 1) gives confusing
  5864. results."
  5865. (interactive)
  5866. (save-excursion
  5867. (let ((level
  5868. (save-excursion
  5869. (goto-char (point-min))
  5870. (when (re-search-forward org-outline-regexp-bol nil t)
  5871. (goto-char (match-beginning 0))
  5872. (funcall outline-level)))))
  5873. (and level (outline-hide-sublevels level)))))
  5874. (defun org-content (&optional arg)
  5875. "Show all headlines in the buffer, like a table of contents.
  5876. With numerical argument N, show content up to level N."
  5877. (interactive "P")
  5878. (org-overview)
  5879. (save-excursion
  5880. ;; Visit all headings and show their offspring
  5881. (and (integerp arg) (org-overview))
  5882. (goto-char (point-max))
  5883. (catch 'exit
  5884. (while (and (progn (condition-case nil
  5885. (outline-previous-visible-heading 1)
  5886. (error (goto-char (point-min))))
  5887. t)
  5888. (looking-at org-outline-regexp))
  5889. (if (integerp arg)
  5890. (org-show-children (1- arg))
  5891. (outline-show-branches))
  5892. (when (bobp) (throw 'exit nil))))))
  5893. (defun org-optimize-window-after-visibility-change (state)
  5894. "Adjust the window after a change in outline visibility.
  5895. This function is the default value of the hook `org-cycle-hook'."
  5896. (when (get-buffer-window (current-buffer))
  5897. (cond
  5898. ((eq state 'content) nil)
  5899. ((eq state 'all) nil)
  5900. ((eq state 'folded) nil)
  5901. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  5902. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  5903. (defun org-clean-visibility-after-subtree-move ()
  5904. "Fix visibility issues after moving a subtree."
  5905. ;; First, find a reasonable region to look at:
  5906. ;; Start two siblings above, end three below
  5907. (let* ((beg (save-excursion
  5908. (and (org-get-last-sibling)
  5909. (org-get-last-sibling))
  5910. (point)))
  5911. (end (save-excursion
  5912. (and (org-get-next-sibling)
  5913. (org-get-next-sibling)
  5914. (org-get-next-sibling))
  5915. (if (org-at-heading-p)
  5916. (point-at-eol)
  5917. (point))))
  5918. (level (looking-at "\\*+"))
  5919. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5920. (save-excursion
  5921. (save-restriction
  5922. (narrow-to-region beg end)
  5923. (when re
  5924. ;; Properly fold already folded siblings
  5925. (goto-char (point-min))
  5926. (while (re-search-forward re nil t)
  5927. (when (and (not (org-invisible-p))
  5928. (org-invisible-p (line-end-position)))
  5929. (outline-hide-entry))))
  5930. (org-cycle-hide-drawers 'all)
  5931. (org-cycle-show-empty-lines 'overview)))))
  5932. (defun org-cycle-show-empty-lines (state)
  5933. "Show empty lines above all visible headlines.
  5934. The region to be covered depends on STATE when called through
  5935. `org-cycle-hook'. Lisp program can use t for STATE to get the
  5936. entire buffer covered. Note that an empty line is only shown if there
  5937. are at least `org-cycle-separator-lines' empty lines before the headline."
  5938. (when (/= org-cycle-separator-lines 0)
  5939. (save-excursion
  5940. (let* ((n (abs org-cycle-separator-lines))
  5941. (re (cond
  5942. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  5943. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  5944. (t (let ((ns (number-to-string (- n 2))))
  5945. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  5946. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  5947. beg end)
  5948. (cond
  5949. ((memq state '(overview contents t))
  5950. (setq beg (point-min) end (point-max)))
  5951. ((memq state '(children folded))
  5952. (setq beg (point)
  5953. end (progn (org-end-of-subtree t t)
  5954. (line-beginning-position 2)))))
  5955. (when beg
  5956. (goto-char beg)
  5957. (while (re-search-forward re end t)
  5958. (unless (get-char-property (match-end 1) 'invisible)
  5959. (let ((e (match-end 1))
  5960. (b (if (>= org-cycle-separator-lines 0)
  5961. (match-beginning 1)
  5962. (save-excursion
  5963. (goto-char (match-beginning 0))
  5964. (skip-chars-backward " \t\n")
  5965. (line-end-position)))))
  5966. (org-flag-region b e nil 'outline))))))))
  5967. ;; Never hide empty lines at the end of the file.
  5968. (save-excursion
  5969. (goto-char (point-max))
  5970. (outline-previous-heading)
  5971. (outline-end-of-heading)
  5972. (when (and (looking-at "[ \t\n]+")
  5973. (= (match-end 0) (point-max)))
  5974. (org-flag-region (point) (match-end 0) nil 'outline))))
  5975. ;;;; Reveal point location
  5976. (defun org-show-context (&optional key)
  5977. "Make sure point and context are visible.
  5978. Optional argument KEY, when non-nil, is a symbol. See
  5979. `org-show-context-detail' for allowed values and how much is to
  5980. be shown."
  5981. (org-show-set-visibility
  5982. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  5983. ((cdr (assq key org-show-context-detail)))
  5984. (t (cdr (assq 'default org-show-context-detail))))))
  5985. (defun org-show-set-visibility (detail)
  5986. "Set visibility around point according to DETAIL.
  5987. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  5988. `tree', `canonical' or t. See `org-show-context-detail' for more
  5989. information."
  5990. ;; Show current heading and possibly its entry, following headline
  5991. ;; or all children.
  5992. (if (and (org-at-heading-p) (not (eq detail 'local)))
  5993. (org-flag-heading nil)
  5994. (org-show-entry)
  5995. ;; If point is hidden within a drawer or a block, make sure to
  5996. ;; expose it.
  5997. (dolist (o (overlays-at (point)))
  5998. (when (memq (overlay-get o 'invisible)
  5999. '(org-hide-block org-hide-drawer outline))
  6000. (delete-overlay o)))
  6001. (unless (org-before-first-heading-p)
  6002. (org-with-limited-levels
  6003. (cl-case detail
  6004. ((tree canonical t) (org-show-children))
  6005. ((nil minimal ancestors))
  6006. (t (save-excursion
  6007. (outline-next-heading)
  6008. (org-flag-heading nil)))))))
  6009. ;; Show all siblings.
  6010. (when (eq detail 'lineage) (org-show-siblings))
  6011. ;; Show ancestors, possibly with their children.
  6012. (when (memq detail '(ancestors lineage tree canonical t))
  6013. (save-excursion
  6014. (while (org-up-heading-safe)
  6015. (org-flag-heading nil)
  6016. (when (memq detail '(canonical t)) (org-show-entry))
  6017. (when (memq detail '(tree canonical t)) (org-show-children))))))
  6018. (defvar org-reveal-start-hook nil
  6019. "Hook run before revealing a location.")
  6020. (defun org-reveal (&optional siblings)
  6021. "Show current entry, hierarchy above it, and the following headline.
  6022. This can be used to show a consistent set of context around
  6023. locations exposed with `org-show-context'.
  6024. With optional argument SIBLINGS, on each level of the hierarchy all
  6025. siblings are shown. This repairs the tree structure to what it would
  6026. look like when opened with hierarchical calls to `org-cycle'.
  6027. With a \\[universal-argument] \\[universal-argument] prefix, \
  6028. go to the parent and show the entire tree."
  6029. (interactive "P")
  6030. (run-hooks 'org-reveal-start-hook)
  6031. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6032. ((equal siblings '(16))
  6033. (save-excursion
  6034. (when (org-up-heading-safe)
  6035. (org-show-subtree)
  6036. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6037. (t (org-show-set-visibility 'lineage))))
  6038. ;;; Indirect buffer display of subtrees
  6039. (defvar org-indirect-dedicated-frame nil
  6040. "This is the frame being used for indirect tree display.")
  6041. (defvar org-last-indirect-buffer nil)
  6042. (defun org-tree-to-indirect-buffer (&optional arg)
  6043. "Create indirect buffer and narrow it to current subtree.
  6044. With a numerical prefix ARG, go up to this level and then take that tree.
  6045. If ARG is negative, go up that many levels.
  6046. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6047. indirect buffer previously made with this command, to avoid proliferation of
  6048. indirect buffers. However, when you call the command with a \
  6049. `\\[universal-argument]' prefix, or
  6050. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6051. so that you can work with several indirect buffers at the same time. If
  6052. `org-indirect-buffer-display' is `dedicated-frame', the \
  6053. `\\[universal-argument]' prefix also
  6054. requests that a new frame be made for the new buffer, so that the dedicated
  6055. frame is not changed."
  6056. (interactive "P")
  6057. (let ((cbuf (current-buffer))
  6058. (cwin (selected-window))
  6059. (pos (point))
  6060. beg end level heading ibuf)
  6061. (save-excursion
  6062. (org-back-to-heading t)
  6063. (when (numberp arg)
  6064. (setq level (org-outline-level))
  6065. (when (< arg 0) (setq arg (+ level arg)))
  6066. (while (> (setq level (org-outline-level)) arg)
  6067. (org-up-heading-safe)))
  6068. (setq beg (point)
  6069. heading (org-get-heading 'no-tags))
  6070. (org-end-of-subtree t t)
  6071. (when (org-at-heading-p) (backward-char 1))
  6072. (setq end (point)))
  6073. (when (and (buffer-live-p org-last-indirect-buffer)
  6074. (not (eq org-indirect-buffer-display 'new-frame))
  6075. (not arg))
  6076. (kill-buffer org-last-indirect-buffer))
  6077. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6078. org-last-indirect-buffer ibuf)
  6079. (cond
  6080. ((or (eq org-indirect-buffer-display 'new-frame)
  6081. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6082. (select-frame (make-frame))
  6083. (delete-other-windows)
  6084. (pop-to-buffer-same-window ibuf)
  6085. (org-set-frame-title heading))
  6086. ((eq org-indirect-buffer-display 'dedicated-frame)
  6087. (raise-frame
  6088. (select-frame (or (and org-indirect-dedicated-frame
  6089. (frame-live-p org-indirect-dedicated-frame)
  6090. org-indirect-dedicated-frame)
  6091. (setq org-indirect-dedicated-frame (make-frame)))))
  6092. (delete-other-windows)
  6093. (pop-to-buffer-same-window ibuf)
  6094. (org-set-frame-title (concat "Indirect: " heading)))
  6095. ((eq org-indirect-buffer-display 'current-window)
  6096. (pop-to-buffer-same-window ibuf))
  6097. ((eq org-indirect-buffer-display 'other-window)
  6098. (pop-to-buffer ibuf))
  6099. (t (error "Invalid value")))
  6100. (narrow-to-region beg end)
  6101. (org-show-all '(headings blocks))
  6102. (goto-char pos)
  6103. (run-hook-with-args 'org-cycle-hook 'all)
  6104. (and (window-live-p cwin) (select-window cwin))))
  6105. (defun org-get-indirect-buffer (&optional buffer heading)
  6106. (setq buffer (or buffer (current-buffer)))
  6107. (let ((n 1) (base (buffer-name buffer)) bname)
  6108. (while (buffer-live-p
  6109. (get-buffer
  6110. (setq bname
  6111. (concat base "-"
  6112. (if heading (concat heading "-" (number-to-string n))
  6113. (number-to-string n))))))
  6114. (setq n (1+ n)))
  6115. (condition-case nil
  6116. (make-indirect-buffer buffer bname 'clone)
  6117. (error (make-indirect-buffer buffer bname)))))
  6118. (defun org-set-frame-title (title)
  6119. "Set the title of the current frame to the string TITLE."
  6120. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6121. ;;;; Structure editing
  6122. ;;; Inserting headlines
  6123. (defun org--line-empty-p (n)
  6124. "Is the Nth next line empty?
  6125. Counts the current line as N = 1 and the previous line as N = 0;
  6126. see `beginning-of-line'."
  6127. (save-excursion
  6128. (and (not (bobp))
  6129. (or (beginning-of-line n) t)
  6130. (save-match-data
  6131. (looking-at "[ \t]*$")))))
  6132. (defun org-previous-line-empty-p ()
  6133. "Is the previous line a blank line?
  6134. When NEXT is non-nil, check the next line instead."
  6135. (org--line-empty-p 0))
  6136. (defun org-next-line-empty-p ()
  6137. "Is the previous line a blank line?
  6138. When NEXT is non-nil, check the next line instead."
  6139. (org--line-empty-p 2))
  6140. (defun org--blank-before-heading-p (&optional parent)
  6141. "Non-nil when an empty line should precede a new heading here.
  6142. When optional argument PARENT is non-nil, consider parent
  6143. headline instead of current one."
  6144. (pcase (assq 'heading org-blank-before-new-entry)
  6145. (`(heading . auto)
  6146. (save-excursion
  6147. (org-with-limited-levels
  6148. (unless (and (org-before-first-heading-p)
  6149. (not (outline-next-heading)))
  6150. (org-back-to-heading t)
  6151. (when parent (org-up-heading-safe))
  6152. (cond ((not (bobp))
  6153. (org-previous-line-empty-p))
  6154. ((outline-next-heading)
  6155. (org-previous-line-empty-p))
  6156. ;; Ignore trailing spaces on last buffer line.
  6157. ((progn (skip-chars-backward " \t") (bolp))
  6158. (org-previous-line-empty-p))
  6159. (t nil))))))
  6160. (`(heading . ,value) value)
  6161. (_ nil)))
  6162. (defun org-insert-heading (&optional arg invisible-ok top)
  6163. "Insert a new heading or an item with the same depth at point.
  6164. If point is at the beginning of a heading, insert a new heading
  6165. or a new headline above the current one. When at the beginning
  6166. of a regular line of text, turn it into a heading.
  6167. If point is in the middle of a line, split it and create a new
  6168. headline with the text in the current line after point (see
  6169. `org-M-RET-may-split-line' on how to modify this behavior). As
  6170. a special case, on a headline, splitting can only happen on the
  6171. title itself. E.g., this excludes breaking stars or tags.
  6172. With a `\\[universal-argument]' prefix, set \
  6173. `org-insert-heading-respect-content' to
  6174. a non-nil value for the duration of the command. This forces the
  6175. insertion of a heading after the current subtree, independently
  6176. on the location of point.
  6177. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6178. insert the heading at the end of the tree
  6179. above the current heading. For example, if point is within a
  6180. 2nd-level heading, then it will insert a 2nd-level heading at
  6181. the end of the 1st-level parent subtree.
  6182. When INVISIBLE-OK is set, stop at invisible headlines when going
  6183. back. This is important for non-interactive uses of the
  6184. command.
  6185. When optional argument TOP is non-nil, insert a level 1 heading,
  6186. unconditionally."
  6187. (interactive "P")
  6188. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6189. (level (org-current-level))
  6190. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6191. (cond
  6192. ((or org-insert-heading-respect-content
  6193. (member arg '((4) (16)))
  6194. (and (not invisible-ok)
  6195. (invisible-p (max (1- (point)) (point-min)))))
  6196. ;; Position point at the location of insertion. Make sure we
  6197. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6198. (org-with-limited-levels
  6199. (if (not level) (outline-next-heading) ;before first headline
  6200. (org-back-to-heading invisible-ok)
  6201. (when (equal arg '(16)) (org-up-heading-safe))
  6202. (org-end-of-subtree)))
  6203. (unless (bolp) (insert "\n"))
  6204. (unless (and blank? (org-previous-line-empty-p))
  6205. (org-N-empty-lines-before-current (if blank? 1 0)))
  6206. (insert stars " ")
  6207. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6208. ;; is visible.
  6209. (unless invisible-ok
  6210. (pcase (get-char-property-and-overlay (point) 'invisible)
  6211. (`(outline . ,o)
  6212. (move-overlay o (overlay-start o) (line-end-position 0)))
  6213. (_ nil))))
  6214. ;; At a headline...
  6215. ((org-at-heading-p)
  6216. (cond ((bolp)
  6217. (when blank? (save-excursion (insert "\n")))
  6218. (save-excursion (insert stars " \n"))
  6219. (unless (and blank? (org-previous-line-empty-p))
  6220. (org-N-empty-lines-before-current (if blank? 1 0)))
  6221. (end-of-line))
  6222. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6223. (org-match-line org-complex-heading-regexp)
  6224. (org-pos-in-match-range (point) 4))
  6225. ;; Grab the text that should moved to the new headline.
  6226. ;; Preserve tags.
  6227. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6228. (if (looking-at "[ \t]*$") (replace-match "")
  6229. (org-align-tags))
  6230. (end-of-line)
  6231. (when blank? (insert "\n"))
  6232. (insert "\n" stars " ")
  6233. (when (org-string-nw-p split) (insert split))))
  6234. (t
  6235. (end-of-line)
  6236. (when blank? (insert "\n"))
  6237. (insert "\n" stars " "))))
  6238. ;; On regular text, turn line into a headline or split, if
  6239. ;; appropriate.
  6240. ((bolp)
  6241. (insert stars " ")
  6242. (unless (and blank? (org-previous-line-empty-p))
  6243. (org-N-empty-lines-before-current (if blank? 1 0))))
  6244. (t
  6245. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6246. (end-of-line))
  6247. (insert "\n" stars " ")
  6248. (unless (and blank? (org-previous-line-empty-p))
  6249. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6250. (run-hooks 'org-insert-heading-hook))
  6251. (defun org-N-empty-lines-before-current (n)
  6252. "Make the number of empty lines before current exactly N.
  6253. So this will delete or add empty lines."
  6254. (let ((column (current-column)))
  6255. (beginning-of-line)
  6256. (unless (bobp)
  6257. (let ((start (save-excursion
  6258. (skip-chars-backward " \r\t\n")
  6259. (line-end-position))))
  6260. (delete-region start (line-end-position 0))))
  6261. (insert (make-string n ?\n))
  6262. (move-to-column column)))
  6263. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6264. "Return the heading of the current entry, without the stars.
  6265. When NO-TAGS is non-nil, don't include tags.
  6266. When NO-TODO is non-nil, don't include TODO keywords.
  6267. When NO-PRIORITY is non-nil, don't include priority cookie.
  6268. When NO-COMMENT is non-nil, don't include COMMENT string.
  6269. Return nil before first heading."
  6270. (unless (org-before-first-heading-p)
  6271. (save-excursion
  6272. (org-back-to-heading t)
  6273. (let ((case-fold-search nil))
  6274. (looking-at org-complex-heading-regexp)
  6275. (let ((todo (and (not no-todo) (match-string 2)))
  6276. (priority (and (not no-priority) (match-string 3)))
  6277. (headline (pcase (match-string 4)
  6278. (`nil "")
  6279. ((and (guard no-comment) h)
  6280. (replace-regexp-in-string
  6281. (eval-when-compile
  6282. (format "\\`%s[ \t]+" org-comment-string))
  6283. "" h))
  6284. (h h)))
  6285. (tags (and (not no-tags) (match-string 5))))
  6286. (mapconcat #'identity
  6287. (delq nil (list todo priority headline tags))
  6288. " "))))))
  6289. (defun org-heading-components ()
  6290. "Return the components of the current heading.
  6291. This is a list with the following elements:
  6292. - the level as an integer
  6293. - the reduced level, different if `org-odd-levels-only' is set.
  6294. - the TODO keyword, or nil
  6295. - the priority character, like ?A, or nil if no priority is given
  6296. - the headline text itself, or the tags string if no headline text
  6297. - the tags string, or nil."
  6298. (save-excursion
  6299. (org-back-to-heading t)
  6300. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6301. (list (length (match-string 1))
  6302. (org-reduced-level (length (match-string 1)))
  6303. (match-string-no-properties 2)
  6304. (and (match-end 3) (aref (match-string 3) 2))
  6305. (match-string-no-properties 4)
  6306. (match-string-no-properties 5)))))
  6307. (defun org-get-entry ()
  6308. "Get the entry text, after heading, entire subtree."
  6309. (save-excursion
  6310. (org-back-to-heading t)
  6311. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6312. (defun org-edit-headline (&optional heading)
  6313. "Edit the current headline.
  6314. Set it to HEADING when provided."
  6315. (interactive)
  6316. (org-with-wide-buffer
  6317. (org-back-to-heading t)
  6318. (let ((case-fold-search nil))
  6319. (when (looking-at org-complex-heading-regexp)
  6320. (let* ((old (match-string-no-properties 4))
  6321. (new (save-match-data
  6322. (org-trim (or heading (read-string "Edit: " old))))))
  6323. (unless (equal old new)
  6324. (if old (replace-match new t t nil 4)
  6325. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6326. (insert " " new))
  6327. (org-align-tags)
  6328. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6329. (defun org-insert-heading-after-current ()
  6330. "Insert a new heading with same level as current, after current subtree."
  6331. (interactive)
  6332. (org-back-to-heading)
  6333. (org-insert-heading)
  6334. (org-move-subtree-down)
  6335. (end-of-line 1))
  6336. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6337. "Insert heading with `org-insert-heading-respect-content' set to t."
  6338. (interactive)
  6339. (org-insert-heading '(4) invisible-ok))
  6340. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6341. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6342. (interactive)
  6343. (org-insert-todo-heading force-state '(4)))
  6344. (defun org-insert-todo-heading (arg &optional force-heading)
  6345. "Insert a new heading with the same level and TODO state as current heading.
  6346. If the heading has no TODO state, or if the state is DONE, use
  6347. the first state (TODO by default). Also with one prefix arg,
  6348. force first state. With two prefix args, force inserting at the
  6349. end of the parent subtree.
  6350. When called at a plain list item, insert a new item with an
  6351. unchecked check box."
  6352. (interactive "P")
  6353. (when (or force-heading (not (org-insert-item 'checkbox)))
  6354. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6355. force-heading))
  6356. (save-excursion
  6357. (org-forward-heading-same-level -1)
  6358. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6359. (let* ((new-mark-x
  6360. (if (or (equal arg '(4))
  6361. (not (match-beginning 2))
  6362. (member (match-string 2) org-done-keywords))
  6363. (car org-todo-keywords-1)
  6364. (match-string 2)))
  6365. (new-mark
  6366. (or
  6367. (run-hook-with-args-until-success
  6368. 'org-todo-get-default-hook new-mark-x nil)
  6369. new-mark-x)))
  6370. (beginning-of-line 1)
  6371. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6372. (if org-treat-insert-todo-heading-as-state-change
  6373. (org-todo new-mark)
  6374. (insert new-mark " "))))
  6375. (when org-provide-todo-statistics
  6376. (org-update-parent-todo-statistics))))
  6377. (defun org-insert-subheading (arg)
  6378. "Insert a new subheading and demote it.
  6379. Works for outline headings and for plain lists alike."
  6380. (interactive "P")
  6381. (org-insert-heading arg)
  6382. (cond
  6383. ((org-at-heading-p) (org-do-demote))
  6384. ((org-at-item-p) (org-indent-item))))
  6385. (defun org-insert-todo-subheading (arg)
  6386. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6387. Works for outline headings and for plain lists alike."
  6388. (interactive "P")
  6389. (org-insert-todo-heading arg)
  6390. (cond
  6391. ((org-at-heading-p) (org-do-demote))
  6392. ((org-at-item-p) (org-indent-item))))
  6393. ;;; Promotion and Demotion
  6394. (defvar org-after-demote-entry-hook nil
  6395. "Hook run after an entry has been demoted.
  6396. The cursor will be at the beginning of the entry.
  6397. When a subtree is being demoted, the hook will be called for each node.")
  6398. (defvar org-after-promote-entry-hook nil
  6399. "Hook run after an entry has been promoted.
  6400. The cursor will be at the beginning of the entry.
  6401. When a subtree is being promoted, the hook will be called for each node.")
  6402. (defun org-promote-subtree ()
  6403. "Promote the entire subtree.
  6404. See also `org-promote'."
  6405. (interactive)
  6406. (save-excursion
  6407. (org-with-limited-levels (org-map-tree 'org-promote)))
  6408. (org-fix-position-after-promote))
  6409. (defun org-demote-subtree ()
  6410. "Demote the entire subtree.
  6411. See `org-demote' and `org-promote'."
  6412. (interactive)
  6413. (save-excursion
  6414. (org-with-limited-levels (org-map-tree 'org-demote)))
  6415. (org-fix-position-after-promote))
  6416. (defun org-do-promote ()
  6417. "Promote the current heading higher up the tree.
  6418. If the region is active in `transient-mark-mode', promote all
  6419. headings in the region."
  6420. (interactive)
  6421. (save-excursion
  6422. (if (org-region-active-p)
  6423. (org-map-region 'org-promote (region-beginning) (region-end))
  6424. (org-promote)))
  6425. (org-fix-position-after-promote))
  6426. (defun org-do-demote ()
  6427. "Demote the current heading lower down the tree.
  6428. If the region is active in `transient-mark-mode', demote all
  6429. headings in the region."
  6430. (interactive)
  6431. (save-excursion
  6432. (if (org-region-active-p)
  6433. (org-map-region 'org-demote (region-beginning) (region-end))
  6434. (org-demote)))
  6435. (org-fix-position-after-promote))
  6436. (defun org-fix-position-after-promote ()
  6437. "Fix cursor position and indentation after demoting/promoting."
  6438. (let ((pos (point)))
  6439. (when (save-excursion
  6440. (beginning-of-line)
  6441. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6442. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6443. (cond ((eobp) (insert " "))
  6444. ((eolp) (insert " "))
  6445. ((equal (char-after) ?\s) (forward-char 1))))))
  6446. (defun org-current-level ()
  6447. "Return the level of the current entry, or nil if before the first headline.
  6448. The level is the number of stars at the beginning of the
  6449. headline. Use `org-reduced-level' to remove the effect of
  6450. `org-odd-levels'. Unlike to `org-outline-level', this function
  6451. ignores inlinetasks."
  6452. (let ((level (org-with-limited-levels (org-outline-level))))
  6453. (and (> level 0) level)))
  6454. (defun org-get-previous-line-level ()
  6455. "Return the outline depth of the last headline before the current line.
  6456. Returns 0 for the first headline in the buffer, and nil if before the
  6457. first headline."
  6458. (and (org-current-level)
  6459. (or (and (/= (line-beginning-position) (point-min))
  6460. (save-excursion (beginning-of-line 0) (org-current-level)))
  6461. 0)))
  6462. (defun org-reduced-level (l)
  6463. "Compute the effective level of a heading.
  6464. This takes into account the setting of `org-odd-levels-only'."
  6465. (cond
  6466. ((zerop l) 0)
  6467. (org-odd-levels-only (1+ (floor (/ l 2))))
  6468. (t l)))
  6469. (defun org-level-increment ()
  6470. "Return the number of stars that will be added or removed at a
  6471. time to headlines when structure editing, based on the value of
  6472. `org-odd-levels-only'."
  6473. (if org-odd-levels-only 2 1))
  6474. (defun org-get-valid-level (level &optional change)
  6475. "Rectify a level change under the influence of `org-odd-levels-only'.
  6476. LEVEL is a current level, CHANGE is by how much the level should
  6477. be modified. Even if CHANGE is nil, LEVEL may be returned
  6478. modified because even level numbers will become the next higher
  6479. odd number. Returns values greater than 0."
  6480. (if org-odd-levels-only
  6481. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6482. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6483. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6484. (max 1 (+ level (or change 0)))))
  6485. (defun org-promote ()
  6486. "Promote the current heading higher up the tree."
  6487. (org-with-wide-buffer
  6488. (org-back-to-heading t)
  6489. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6490. after-change-functions))
  6491. (level (save-match-data (funcall outline-level)))
  6492. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6493. (diff (abs (- level (length up-head) -1))))
  6494. (cond
  6495. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6496. (replace-match "# " nil t))
  6497. ((= level 1)
  6498. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6499. (t (replace-match up-head nil t)))
  6500. (unless (= level 1)
  6501. (when org-auto-align-tags (org-align-tags))
  6502. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6503. (run-hooks 'org-after-promote-entry-hook))))
  6504. (defun org-demote ()
  6505. "Demote the current heading lower down the tree."
  6506. (org-with-wide-buffer
  6507. (org-back-to-heading t)
  6508. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6509. after-change-functions))
  6510. (level (save-match-data (funcall outline-level)))
  6511. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6512. (diff (abs (- level (length down-head) -1))))
  6513. (replace-match down-head nil t)
  6514. (when org-auto-align-tags (org-align-tags))
  6515. (when org-adapt-indentation (org-fixup-indentation diff))
  6516. (run-hooks 'org-after-demote-entry-hook))))
  6517. (defun org-cycle-level ()
  6518. "Cycle the level of an empty headline through possible states.
  6519. This goes first to child, then to parent, level, then up the hierarchy.
  6520. After top level, it switches back to sibling level."
  6521. (interactive)
  6522. (let ((org-adapt-indentation nil))
  6523. (when (org-point-at-end-of-empty-headline)
  6524. (setq this-command 'org-cycle-level) ; Only needed for caching
  6525. (let ((cur-level (org-current-level))
  6526. (prev-level (org-get-previous-line-level)))
  6527. (cond
  6528. ;; If first headline in file, promote to top-level.
  6529. ((= prev-level 0)
  6530. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6531. do (org-do-promote)))
  6532. ;; If same level as prev, demote one.
  6533. ((= prev-level cur-level)
  6534. (org-do-demote))
  6535. ;; If parent is top-level, promote to top level if not already.
  6536. ((= prev-level 1)
  6537. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6538. do (org-do-promote)))
  6539. ;; If top-level, return to prev-level.
  6540. ((= cur-level 1)
  6541. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6542. do (org-do-demote)))
  6543. ;; If less than prev-level, promote one.
  6544. ((< cur-level prev-level)
  6545. (org-do-promote))
  6546. ;; If deeper than prev-level, promote until higher than
  6547. ;; prev-level.
  6548. ((> cur-level prev-level)
  6549. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6550. do (org-do-promote))))
  6551. t))))
  6552. (defun org-map-tree (fun)
  6553. "Call FUN for every heading underneath the current one."
  6554. (org-back-to-heading t)
  6555. (let ((level (funcall outline-level)))
  6556. (save-excursion
  6557. (funcall fun)
  6558. (while (and (progn
  6559. (outline-next-heading)
  6560. (> (funcall outline-level) level))
  6561. (not (eobp)))
  6562. (funcall fun)))))
  6563. (defun org-map-region (fun beg end)
  6564. "Call FUN for every heading between BEG and END."
  6565. (let ((org-ignore-region t))
  6566. (save-excursion
  6567. (setq end (copy-marker end))
  6568. (goto-char beg)
  6569. (when (and (re-search-forward org-outline-regexp-bol nil t)
  6570. (< (point) end))
  6571. (funcall fun))
  6572. (while (and (progn
  6573. (outline-next-heading)
  6574. (< (point) end))
  6575. (not (eobp)))
  6576. (funcall fun)))))
  6577. (defun org-fixup-indentation (diff)
  6578. "Change the indentation in the current entry by DIFF.
  6579. DIFF is an integer. Indentation is done according to the
  6580. following rules:
  6581. - Planning information and property drawers are always indented
  6582. according to the new level of the headline;
  6583. - Footnote definitions and their contents are ignored;
  6584. - Inlinetasks' boundaries are not shifted;
  6585. - Empty lines are ignored;
  6586. - Other lines' indentation are shifted by DIFF columns, unless
  6587. it would introduce a structural change in the document, in
  6588. which case no shifting is done at all.
  6589. Assume point is at a heading or an inlinetask beginning."
  6590. (org-with-wide-buffer
  6591. (narrow-to-region (line-beginning-position)
  6592. (save-excursion
  6593. (if (org-with-limited-levels (org-at-heading-p))
  6594. (org-with-limited-levels (outline-next-heading))
  6595. (org-inlinetask-goto-end))
  6596. (point)))
  6597. (forward-line)
  6598. ;; Indent properly planning info and property drawer.
  6599. (when (looking-at-p org-planning-line-re)
  6600. (org-indent-line)
  6601. (forward-line))
  6602. (when (looking-at org-property-drawer-re)
  6603. (goto-char (match-end 0))
  6604. (forward-line)
  6605. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  6606. (catch 'no-shift
  6607. (when (zerop diff) (throw 'no-shift nil))
  6608. ;; If DIFF is negative, first check if a shift is possible at all
  6609. ;; (e.g., it doesn't break structure). This can only happen if
  6610. ;; some contents are not properly indented.
  6611. (let ((case-fold-search t))
  6612. (when (< diff 0)
  6613. (let ((diff (- diff))
  6614. (forbidden-re (concat org-outline-regexp
  6615. "\\|"
  6616. (substring org-footnote-definition-re 1))))
  6617. (save-excursion
  6618. (while (not (eobp))
  6619. (cond
  6620. ((looking-at-p "[ \t]*$") (forward-line))
  6621. ((and (looking-at-p org-footnote-definition-re)
  6622. (let ((e (org-element-at-point)))
  6623. (and (eq (org-element-type e) 'footnote-definition)
  6624. (goto-char (org-element-property :end e))))))
  6625. ((looking-at-p org-outline-regexp) (forward-line))
  6626. ;; Give up if shifting would move before column 0 or
  6627. ;; if it would introduce a headline or a footnote
  6628. ;; definition.
  6629. (t
  6630. (skip-chars-forward " \t")
  6631. (let ((ind (current-column)))
  6632. (when (or (< ind diff)
  6633. (and (= ind diff) (looking-at-p forbidden-re)))
  6634. (throw 'no-shift nil)))
  6635. ;; Ignore contents of example blocks and source
  6636. ;; blocks if their indentation is meant to be
  6637. ;; preserved. Jump to block's closing line.
  6638. (beginning-of-line)
  6639. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6640. (let ((e (org-element-at-point)))
  6641. (and (memq (org-element-type e)
  6642. '(example-block src-block))
  6643. (or org-src-preserve-indentation
  6644. (org-element-property :preserve-indent e))
  6645. (goto-char (org-element-property :end e))
  6646. (progn (skip-chars-backward " \r\t\n")
  6647. (beginning-of-line)
  6648. t))))
  6649. (forward-line))))))))
  6650. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6651. ;; by DIFF. Also skip contents of source or example blocks
  6652. ;; when indentation is meant to be preserved.
  6653. (while (not (eobp))
  6654. (cond
  6655. ((and (looking-at-p org-footnote-definition-re)
  6656. (let ((e (org-element-at-point)))
  6657. (and (eq (org-element-type e) 'footnote-definition)
  6658. (goto-char (org-element-property :end e))))))
  6659. ((looking-at-p org-outline-regexp) (forward-line))
  6660. ((looking-at-p "[ \t]*$") (forward-line))
  6661. (t
  6662. (indent-line-to (+ (current-indentation) diff))
  6663. (beginning-of-line)
  6664. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6665. (let ((e (org-element-at-point)))
  6666. (and (memq (org-element-type e)
  6667. '(example-block src-block))
  6668. (or org-src-preserve-indentation
  6669. (org-element-property :preserve-indent e))
  6670. (goto-char (org-element-property :end e))
  6671. (progn (skip-chars-backward " \r\t\n")
  6672. (beginning-of-line)
  6673. t))))
  6674. (forward-line)))))))))
  6675. (defun org-convert-to-odd-levels ()
  6676. "Convert an Org file with all levels allowed to one with odd levels.
  6677. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6678. level 5 etc."
  6679. (interactive)
  6680. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6681. (let ((outline-level 'org-outline-level)
  6682. (org-odd-levels-only nil) n)
  6683. (save-excursion
  6684. (goto-char (point-min))
  6685. (while (re-search-forward "^\\*\\*+ " nil t)
  6686. (setq n (- (length (match-string 0)) 2))
  6687. (while (>= (setq n (1- n)) 0)
  6688. (org-demote))
  6689. (end-of-line 1))))))
  6690. (defun org-convert-to-oddeven-levels ()
  6691. "Convert an Org file with only odd levels to one with odd/even levels.
  6692. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6693. file contains a section with an even level, conversion would
  6694. destroy the structure of the file. An error is signaled in this
  6695. case."
  6696. (interactive)
  6697. (goto-char (point-min))
  6698. ;; First check if there are no even levels
  6699. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6700. (org-show-set-visibility 'canonical)
  6701. (error "Not all levels are odd in this file. Conversion not possible"))
  6702. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6703. (let ((outline-regexp org-outline-regexp)
  6704. (outline-level 'org-outline-level)
  6705. (org-odd-levels-only nil) n)
  6706. (save-excursion
  6707. (goto-char (point-min))
  6708. (while (re-search-forward "^\\*\\*+ " nil t)
  6709. (setq n (/ (1- (length (match-string 0))) 2))
  6710. (while (>= (setq n (1- n)) 0)
  6711. (org-promote))
  6712. (end-of-line 1))))))
  6713. (defun org-tr-level (n)
  6714. "Make N odd if required."
  6715. (if org-odd-levels-only (1+ (/ n 2)) n))
  6716. ;;; Vertical tree motion, cutting and pasting of subtrees
  6717. (defun org-move-subtree-up (&optional arg)
  6718. "Move the current subtree up past ARG headlines of the same level."
  6719. (interactive "p")
  6720. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6721. (defun org-move-subtree-down (&optional arg)
  6722. "Move the current subtree down past ARG headlines of the same level."
  6723. (interactive "p")
  6724. (setq arg (prefix-numeric-value arg))
  6725. (org-preserve-local-variables
  6726. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6727. 'org-get-last-sibling))
  6728. (ins-point (make-marker))
  6729. (cnt (abs arg))
  6730. (col (current-column))
  6731. beg end txt folded)
  6732. ;; Select the tree
  6733. (org-back-to-heading)
  6734. (setq beg (point))
  6735. (save-match-data
  6736. (save-excursion (outline-end-of-heading)
  6737. (setq folded (org-invisible-p)))
  6738. (progn (org-end-of-subtree nil t)
  6739. (unless (eobp) (backward-char))))
  6740. (outline-next-heading)
  6741. (setq end (point))
  6742. (goto-char beg)
  6743. ;; Find insertion point, with error handling
  6744. (while (> cnt 0)
  6745. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6746. (goto-char beg)
  6747. (user-error "Cannot move past superior level or buffer limit"))
  6748. (setq cnt (1- cnt)))
  6749. (when (> arg 0)
  6750. ;; Moving forward - still need to move over subtree
  6751. (org-end-of-subtree t t)
  6752. (save-excursion
  6753. (org-back-over-empty-lines)
  6754. (or (bolp) (newline))))
  6755. (move-marker ins-point (point))
  6756. (setq txt (buffer-substring beg end))
  6757. (org-save-markers-in-region beg end)
  6758. (delete-region beg end)
  6759. (org-remove-empty-overlays-at beg)
  6760. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  6761. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  6762. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6763. (let ((bbb (point)))
  6764. (insert-before-markers txt)
  6765. (org-reinstall-markers-in-region bbb)
  6766. (move-marker ins-point bbb))
  6767. (or (bolp) (insert "\n"))
  6768. (goto-char ins-point)
  6769. (org-skip-whitespace)
  6770. (move-marker ins-point nil)
  6771. (if folded
  6772. (outline-hide-subtree)
  6773. (org-show-entry)
  6774. (org-show-children))
  6775. (org-clean-visibility-after-subtree-move)
  6776. ;; move back to the initial column we were at
  6777. (move-to-column col))))
  6778. (defvar org-subtree-clip ""
  6779. "Clipboard for cut and paste of subtrees.
  6780. This is actually only a copy of the kill, because we use the normal kill
  6781. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6782. (defvar org-subtree-clip-folded nil
  6783. "Was the last copied subtree folded?
  6784. This is used to fold the tree back after pasting.")
  6785. (defun org-cut-subtree (&optional n)
  6786. "Cut the current subtree into the clipboard.
  6787. With prefix arg N, cut this many sequential subtrees.
  6788. This is a short-hand for marking the subtree and then cutting it."
  6789. (interactive "p")
  6790. (org-copy-subtree n 'cut))
  6791. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6792. "Copy the current subtree into the clipboard.
  6793. With prefix arg N, copy this many sequential subtrees.
  6794. This is a short-hand for marking the subtree and then copying it.
  6795. If CUT is non-nil, actually cut the subtree.
  6796. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6797. of some markers in the region, even if CUT is non-nil. This is
  6798. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6799. (interactive "p")
  6800. (org-preserve-local-variables
  6801. (let (beg end folded (beg0 (point)))
  6802. (if (called-interactively-p 'any)
  6803. (org-back-to-heading nil) ; take what looks like a subtree
  6804. (org-back-to-heading t)) ; take what is really there
  6805. (setq beg (point))
  6806. (skip-chars-forward " \t\r\n")
  6807. (save-match-data
  6808. (if nosubtrees
  6809. (outline-next-heading)
  6810. (save-excursion (outline-end-of-heading)
  6811. (setq folded (org-invisible-p)))
  6812. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6813. (org-end-of-subtree t t)))
  6814. ;; Include the end of an inlinetask
  6815. (when (and (featurep 'org-inlinetask)
  6816. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6817. "END[ \t]*$")))
  6818. (end-of-line))
  6819. (setq end (point))
  6820. (goto-char beg0)
  6821. (when (> end beg)
  6822. (setq org-subtree-clip-folded folded)
  6823. (when (or cut force-store-markers)
  6824. (org-save-markers-in-region beg end))
  6825. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6826. (setq org-subtree-clip (current-kill 0))
  6827. (message "%s: Subtree(s) with %d characters"
  6828. (if cut "Cut" "Copied")
  6829. (length org-subtree-clip))))))
  6830. (defun org-paste-subtree (&optional level tree for-yank remove)
  6831. "Paste the clipboard as a subtree, with modification of headline level.
  6832. The entire subtree is promoted or demoted in order to match a new headline
  6833. level.
  6834. If the cursor is at the beginning of a headline, the same level as
  6835. that headline is used to paste the tree.
  6836. If not, the new level is derived from the *visible* headings
  6837. before and after the insertion point, and taken to be the inferior headline
  6838. level of the two. So if the previous visible heading is level 3 and the
  6839. next is level 4 (or vice versa), level 4 will be used for insertion.
  6840. This makes sure that the subtree remains an independent subtree and does
  6841. not swallow low level entries.
  6842. You can also force a different level, either by using a numeric prefix
  6843. argument, or by inserting the heading marker by hand. For example, if the
  6844. cursor is after \"*****\", then the tree will be shifted to level 5.
  6845. If optional TREE is given, use this text instead of the kill ring.
  6846. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6847. move back over whitespace before inserting, and move point to the end of
  6848. the inserted text when done.
  6849. When REMOVE is non-nil, remove the subtree from the clipboard."
  6850. (interactive "P")
  6851. (setq tree (or tree (and kill-ring (current-kill 0))))
  6852. (unless (org-kill-is-subtree-p tree)
  6853. (user-error
  6854. (substitute-command-keys
  6855. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6856. (org-with-limited-levels
  6857. (let* ((visp (not (org-invisible-p)))
  6858. (txt tree)
  6859. (old-level (if (string-match org-outline-regexp-bol txt)
  6860. (- (match-end 0) (match-beginning 0) 1)
  6861. -1))
  6862. (force-level
  6863. (cond
  6864. (level (prefix-numeric-value level))
  6865. ;; When point is after the stars in an otherwise empty
  6866. ;; headline, use the number of stars as the forced level.
  6867. ((and (org-match-line "^\\*+[ \t]*$")
  6868. (not (eq ?* (char-after))))
  6869. (org-outline-level))
  6870. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6871. (previous-level
  6872. (save-excursion
  6873. (org-previous-visible-heading 1)
  6874. (if (org-at-heading-p) (org-outline-level) 1)))
  6875. (next-level
  6876. (save-excursion
  6877. (if (org-at-heading-p) (org-outline-level)
  6878. (org-next-visible-heading 1)
  6879. (if (org-at-heading-p) (org-outline-level) 1))))
  6880. (new-level (or force-level (max previous-level next-level)))
  6881. (shift (if (or (= old-level -1)
  6882. (= new-level -1)
  6883. (= old-level new-level))
  6884. 0
  6885. (- new-level old-level)))
  6886. (delta (if (> shift 0) -1 1))
  6887. (func (if (> shift 0) #'org-demote #'org-promote))
  6888. (org-odd-levels-only nil)
  6889. beg end newend)
  6890. ;; Remove the forced level indicator.
  6891. (when (and force-level (not level))
  6892. (delete-region (line-beginning-position) (point)))
  6893. ;; Paste before the next visible heading or at end of buffer,
  6894. ;; unless point is at the beginning of a headline.
  6895. (unless (and (bolp) (org-at-heading-p))
  6896. (org-next-visible-heading 1)
  6897. (unless (bolp) (insert "\n")))
  6898. (setq beg (point))
  6899. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6900. (insert-before-markers txt)
  6901. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6902. (setq newend (point))
  6903. (org-reinstall-markers-in-region beg)
  6904. (setq end (point))
  6905. (goto-char beg)
  6906. (skip-chars-forward " \t\n\r")
  6907. (setq beg (point))
  6908. (when (and (org-invisible-p) visp)
  6909. (save-excursion (outline-show-heading)))
  6910. ;; Shift if necessary.
  6911. (unless (= shift 0)
  6912. (save-restriction
  6913. (narrow-to-region beg end)
  6914. (while (not (= shift 0))
  6915. (org-map-region func (point-min) (point-max))
  6916. (setq shift (+ delta shift)))
  6917. (goto-char (point-min))
  6918. (setq newend (point-max))))
  6919. (when (or for-yank (called-interactively-p 'interactive))
  6920. (message "Clipboard pasted as level %d subtree" new-level))
  6921. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6922. kill-ring
  6923. (equal org-subtree-clip (current-kill 0))
  6924. org-subtree-clip-folded)
  6925. ;; The tree was folded before it was killed/copied
  6926. (outline-hide-subtree))
  6927. (when for-yank (goto-char newend))
  6928. (when remove (pop kill-ring)))))
  6929. (defun org-kill-is-subtree-p (&optional txt)
  6930. "Check if the current kill is an outline subtree, or a set of trees.
  6931. Returns nil if kill does not start with a headline, or if the first
  6932. headline level is not the largest headline level in the tree.
  6933. So this will actually accept several entries of equal levels as well,
  6934. which is OK for `org-paste-subtree'.
  6935. If optional TXT is given, check this string instead of the current kill."
  6936. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6937. (re (org-get-limited-outline-regexp))
  6938. (^re (concat "^" re))
  6939. (start-level (and kill
  6940. (string-match
  6941. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6942. kill)
  6943. (- (match-end 2) (match-beginning 2) 1)))
  6944. (start (1+ (or (match-beginning 2) -1))))
  6945. (if (not start-level)
  6946. (progn
  6947. nil) ;; does not even start with a heading
  6948. (catch 'exit
  6949. (while (setq start (string-match ^re kill (1+ start)))
  6950. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6951. (throw 'exit nil)))
  6952. t))))
  6953. (defvar org-markers-to-move nil
  6954. "Markers that should be moved with a cut-and-paste operation.
  6955. Those markers are stored together with their positions relative to
  6956. the start of the region.")
  6957. (defun org-save-markers-in-region (beg end)
  6958. "Check markers in region.
  6959. If these markers are between BEG and END, record their position relative
  6960. to BEG, so that after moving the block of text, we can put the markers back
  6961. into place.
  6962. This function gets called just before an entry or tree gets cut from the
  6963. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  6964. called immediately, to move the markers with the entries."
  6965. (setq org-markers-to-move nil)
  6966. (when (featurep 'org-clock)
  6967. (org-clock-save-markers-for-cut-and-paste beg end))
  6968. (when (featurep 'org-agenda)
  6969. (org-agenda-save-markers-for-cut-and-paste beg end)))
  6970. (defun org-check-and-save-marker (marker beg end)
  6971. "Check if MARKER is between BEG and END.
  6972. If yes, remember the marker and the distance to BEG."
  6973. (when (and (marker-buffer marker)
  6974. (equal (marker-buffer marker) (current-buffer))
  6975. (>= marker beg) (< marker end))
  6976. (push (cons marker (- marker beg)) org-markers-to-move)))
  6977. (defun org-reinstall-markers-in-region (beg)
  6978. "Move all remembered markers to their position relative to BEG."
  6979. (dolist (x org-markers-to-move)
  6980. (move-marker (car x) (+ beg (cdr x))))
  6981. (setq org-markers-to-move nil))
  6982. (defun org-narrow-to-subtree ()
  6983. "Narrow buffer to the current subtree."
  6984. (interactive)
  6985. (save-excursion
  6986. (save-match-data
  6987. (org-with-limited-levels
  6988. (narrow-to-region
  6989. (progn (org-back-to-heading t) (point))
  6990. (progn (org-end-of-subtree t t)
  6991. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  6992. (point)))))))
  6993. (defun org-toggle-narrow-to-subtree ()
  6994. "Narrow to the subtree at point or widen a narrowed buffer."
  6995. (interactive)
  6996. (if (buffer-narrowed-p)
  6997. (widen)
  6998. (org-narrow-to-subtree)))
  6999. (defun org-narrow-to-block ()
  7000. "Narrow buffer to the current block."
  7001. (interactive)
  7002. (let* ((case-fold-search t)
  7003. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7004. "^[ \t]*#\\+end_.*")))
  7005. (if blockp
  7006. (narrow-to-region (car blockp) (cdr blockp))
  7007. (user-error "Not in a block"))))
  7008. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7009. "Clone the task (subtree) at point N times.
  7010. The clones will be inserted as siblings.
  7011. In interactive use, the user will be prompted for the number of
  7012. clones to be produced. If the entry has a timestamp, the user
  7013. will also be prompted for a time shift, which may be a repeater
  7014. as used in time stamps, for example `+3d'. To disable this,
  7015. you can call the function with a universal prefix argument.
  7016. When a valid repeater is given and the entry contains any time
  7017. stamps, the clones will become a sequence in time, with time
  7018. stamps in the subtree shifted for each clone produced. If SHIFT
  7019. is nil or the empty string, time stamps will be left alone. The
  7020. ID property of the original subtree is removed.
  7021. In each clone, all the CLOCK entries will be removed. This
  7022. prevents Org from considering that the clocked times overlap.
  7023. If the original subtree did contain time stamps with a repeater,
  7024. the following will happen:
  7025. - the repeater will be removed in each clone
  7026. - an additional clone will be produced, with the current, unshifted
  7027. date(s) in the entry.
  7028. - the original entry will be placed *after* all the clones, with
  7029. repeater intact.
  7030. - the start days in the repeater in the original entry will be shifted
  7031. to past the last clone.
  7032. In this way you can spell out a number of instances of a repeating task,
  7033. and still retain the repeater to cover future instances of the task.
  7034. As described above, N+1 clones are produced when the original
  7035. subtree has a repeater. Setting N to 0, then, can be used to
  7036. remove the repeater from a subtree and create a shifted clone
  7037. with the original repeater."
  7038. (interactive "nNumber of clones to produce: ")
  7039. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7040. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7041. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7042. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7043. (shift
  7044. (or shift
  7045. (if (and (not (equal current-prefix-arg '(4)))
  7046. (save-excursion
  7047. (goto-char beg)
  7048. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7049. (read-from-minibuffer
  7050. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7051. ""))) ;No time shift
  7052. (doshift
  7053. (and (org-string-nw-p shift)
  7054. (or (string-match "\\`[ \t]*\\([\\+\\-]?[0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7055. shift)
  7056. (user-error "Invalid shift specification %s" shift)))))
  7057. (goto-char end-of-tree)
  7058. (unless (bolp) (insert "\n"))
  7059. (let* ((end (point))
  7060. (template (buffer-substring beg end))
  7061. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7062. (shift-what (pcase (and doshift (match-string 2 shift))
  7063. (`nil nil)
  7064. ("d" 'day)
  7065. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7066. ("m" 'month)
  7067. ("y" 'year)
  7068. (_ (error "Unsupported time unit"))))
  7069. (nmin 1)
  7070. (nmax n)
  7071. (n-no-remove -1)
  7072. (idprop (org-entry-get nil "ID")))
  7073. (when (and doshift
  7074. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7075. template))
  7076. (delete-region beg end)
  7077. (setq end beg)
  7078. (setq nmin 0)
  7079. (setq nmax (1+ nmax))
  7080. (setq n-no-remove nmax))
  7081. (goto-char end)
  7082. (cl-loop for n from nmin to nmax do
  7083. (insert
  7084. ;; Prepare clone.
  7085. (with-temp-buffer
  7086. (insert template)
  7087. (org-mode)
  7088. (goto-char (point-min))
  7089. (org-show-subtree)
  7090. (and idprop (if org-clone-delete-id
  7091. (org-entry-delete nil "ID")
  7092. (org-id-get-create t)))
  7093. (unless (= n 0)
  7094. (while (re-search-forward org-clock-line-re nil t)
  7095. (delete-region (line-beginning-position)
  7096. (line-beginning-position 2)))
  7097. (goto-char (point-min))
  7098. (while (re-search-forward org-drawer-regexp nil t)
  7099. (org-remove-empty-drawer-at (point))))
  7100. (goto-char (point-min))
  7101. (when doshift
  7102. (while (re-search-forward org-ts-regexp-both nil t)
  7103. (org-timestamp-change (* n shift-n) shift-what))
  7104. (unless (= n n-no-remove)
  7105. (goto-char (point-min))
  7106. (while (re-search-forward org-ts-regexp nil t)
  7107. (save-excursion
  7108. (goto-char (match-beginning 0))
  7109. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7110. (delete-region (match-beginning 1) (match-end 1)))))))
  7111. (buffer-string)))))
  7112. (goto-char beg)))
  7113. ;;; Outline Sorting
  7114. (defun org-sort (&optional with-case)
  7115. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7116. Optional argument WITH-CASE means sort case-sensitively."
  7117. (interactive "P")
  7118. (org-call-with-arg
  7119. (cond ((org-at-table-p) #'org-table-sort-lines)
  7120. ((org-at-item-p) #'org-sort-list)
  7121. (t #'org-sort-entries))
  7122. with-case))
  7123. (defun org-sort-remove-invisible (s)
  7124. "Remove invisible part of links and emphasis markers from string S."
  7125. (remove-text-properties 0 (length s) org-rm-props s)
  7126. (replace-regexp-in-string
  7127. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7128. (replace-regexp-in-string
  7129. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7130. (org-link-display-format s)
  7131. t t) t t))
  7132. (defvar org-priority-regexp) ; defined later in the file
  7133. (defvar org-after-sorting-entries-or-items-hook nil
  7134. "Hook that is run after a bunch of entries or items have been sorted.
  7135. When children are sorted, the cursor is in the parent line when this
  7136. hook gets called. When a region or a plain list is sorted, the cursor
  7137. will be in the first entry of the sorted region/list.")
  7138. (defun org-sort-entries
  7139. (&optional with-case sorting-type getkey-func compare-func property
  7140. interactive?)
  7141. "Sort entries on a certain level of an outline tree.
  7142. If there is an active region, the entries in the region are sorted.
  7143. Else, if the cursor is before the first entry, sort the top-level items.
  7144. Else, the children of the entry at point are sorted.
  7145. Sorting can be alphabetically, numerically, by date/time as given by
  7146. a time stamp, by a property, by priority order, or by a custom function.
  7147. The command prompts for the sorting type unless it has been given to the
  7148. function through the SORTING-TYPE argument, which needs to be a character,
  7149. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7150. the precise meaning of each character:
  7151. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7152. c By creation time, which is assumed to be the first inactive time stamp
  7153. at the beginning of a line.
  7154. d By deadline date/time.
  7155. k By clocking time.
  7156. n Numerically, by converting the beginning of the entry/item to a number.
  7157. o By order of TODO keywords.
  7158. p By priority according to the cookie.
  7159. r By the value of a property.
  7160. s By scheduled date/time.
  7161. t By date/time, either the first active time stamp in the entry, or, if
  7162. none exist, by the first inactive one.
  7163. Capital letters will reverse the sort order.
  7164. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7165. called with point at the beginning of the record. It must return a
  7166. value that is compatible with COMPARE-FUNC, the function used to
  7167. compare entries.
  7168. Comparing entries ignores case by default. However, with an optional argument
  7169. WITH-CASE, the sorting considers case as well.
  7170. Sorting is done against the visible part of the headlines, it ignores hidden
  7171. links.
  7172. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7173. A non-nil value for INTERACTIVE? is used to signal that this
  7174. function is being called interactively."
  7175. (interactive (list current-prefix-arg nil nil nil nil t))
  7176. (let ((case-func (if with-case 'identity 'downcase))
  7177. start beg end stars re re2
  7178. txt what tmp)
  7179. ;; Find beginning and end of region to sort
  7180. (cond
  7181. ((org-region-active-p)
  7182. ;; we will sort the region
  7183. (setq end (region-end)
  7184. what "region")
  7185. (goto-char (region-beginning))
  7186. (unless (org-at-heading-p) (outline-next-heading))
  7187. (setq start (point)))
  7188. ((or (org-at-heading-p)
  7189. (ignore-errors (progn (org-back-to-heading) t)))
  7190. ;; we will sort the children of the current headline
  7191. (org-back-to-heading)
  7192. (setq start (point)
  7193. end (progn (org-end-of-subtree t t)
  7194. (or (bolp) (insert "\n"))
  7195. (when (>= (org-back-over-empty-lines) 1)
  7196. (forward-line 1))
  7197. (point))
  7198. what "children")
  7199. (goto-char start)
  7200. (outline-show-subtree)
  7201. (outline-next-heading))
  7202. (t
  7203. ;; we will sort the top-level entries in this file
  7204. (goto-char (point-min))
  7205. (or (org-at-heading-p) (outline-next-heading))
  7206. (setq start (point))
  7207. (goto-char (point-max))
  7208. (beginning-of-line 1)
  7209. (when (looking-at ".*?\\S-")
  7210. ;; File ends in a non-white line
  7211. (end-of-line 1)
  7212. (insert "\n"))
  7213. (setq end (point-max))
  7214. (setq what "top-level")
  7215. (goto-char start)
  7216. (org-show-all '(headings blocks))))
  7217. (setq beg (point))
  7218. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7219. (looking-at "\\(\\*+\\)")
  7220. (setq stars (match-string 1)
  7221. re (concat "^" (regexp-quote stars) " +")
  7222. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7223. txt (buffer-substring beg end))
  7224. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7225. (when (and (not (equal stars "*")) (string-match re2 txt))
  7226. (user-error "Region to sort contains a level above the first entry"))
  7227. (unless sorting-type
  7228. (message
  7229. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7230. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7231. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7232. what)
  7233. (setq sorting-type (read-char-exclusive)))
  7234. (unless getkey-func
  7235. (and (= (downcase sorting-type) ?f)
  7236. (setq getkey-func
  7237. (or (and interactive?
  7238. (org-read-function
  7239. "Function for extracting keys: "))
  7240. (error "Missing key extractor")))))
  7241. (and (= (downcase sorting-type) ?r)
  7242. (not property)
  7243. (setq property
  7244. (completing-read "Property: "
  7245. (mapcar #'list (org-buffer-property-keys t))
  7246. nil t)))
  7247. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7248. (message "Sorting entries...")
  7249. (save-restriction
  7250. (narrow-to-region start end)
  7251. (let ((restore-clock?
  7252. ;; The clock marker is lost when using `sort-subr'; mark
  7253. ;; the clock with temporary `:org-clock-marker-backup'
  7254. ;; text property.
  7255. (when (and (eq (org-clock-is-active) (current-buffer))
  7256. (<= start (marker-position org-clock-marker))
  7257. (>= end (marker-position org-clock-marker)))
  7258. (with-silent-modifications
  7259. (put-text-property (1- org-clock-marker) org-clock-marker
  7260. :org-clock-marker-backup t))
  7261. t))
  7262. (dcst (downcase sorting-type))
  7263. (case-fold-search nil)
  7264. (now (current-time)))
  7265. (org-preserve-local-variables
  7266. (sort-subr
  7267. (/= dcst sorting-type)
  7268. ;; This function moves to the beginning character of the
  7269. ;; "record" to be sorted.
  7270. (lambda nil
  7271. (if (re-search-forward re nil t)
  7272. (goto-char (match-beginning 0))
  7273. (goto-char (point-max))))
  7274. ;; This function moves to the last character of the "record" being
  7275. ;; sorted.
  7276. (lambda nil
  7277. (save-match-data
  7278. (condition-case nil
  7279. (outline-forward-same-level 1)
  7280. (error
  7281. (goto-char (point-max))))))
  7282. ;; This function returns the value that gets sorted against.
  7283. (lambda ()
  7284. (cond
  7285. ((= dcst ?n)
  7286. (string-to-number
  7287. (org-sort-remove-invisible (org-get-heading t t t t))))
  7288. ((= dcst ?a)
  7289. (funcall case-func
  7290. (org-sort-remove-invisible (org-get-heading t t t t))))
  7291. ((= dcst ?k)
  7292. (or (get-text-property (point) :org-clock-minutes) 0))
  7293. ((= dcst ?t)
  7294. (let ((end (save-excursion (outline-next-heading) (point))))
  7295. (if (or (re-search-forward org-ts-regexp end t)
  7296. (re-search-forward org-ts-regexp-both end t))
  7297. (org-time-string-to-seconds (match-string 0))
  7298. (float-time now))))
  7299. ((= dcst ?c)
  7300. (let ((end (save-excursion (outline-next-heading) (point))))
  7301. (if (re-search-forward
  7302. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7303. end t)
  7304. (org-time-string-to-seconds (match-string 0))
  7305. (float-time now))))
  7306. ((= dcst ?s)
  7307. (let ((end (save-excursion (outline-next-heading) (point))))
  7308. (if (re-search-forward org-scheduled-time-regexp end t)
  7309. (org-time-string-to-seconds (match-string 1))
  7310. (float-time now))))
  7311. ((= dcst ?d)
  7312. (let ((end (save-excursion (outline-next-heading) (point))))
  7313. (if (re-search-forward org-deadline-time-regexp end t)
  7314. (org-time-string-to-seconds (match-string 1))
  7315. (float-time now))))
  7316. ((= dcst ?p)
  7317. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7318. (string-to-char (match-string 2))
  7319. org-default-priority))
  7320. ((= dcst ?r)
  7321. (or (org-entry-get nil property) ""))
  7322. ((= dcst ?o)
  7323. (when (looking-at org-complex-heading-regexp)
  7324. (let* ((m (match-string 2))
  7325. (s (if (member m org-done-keywords) '- '+)))
  7326. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7327. ((= dcst ?f)
  7328. (if getkey-func
  7329. (progn
  7330. (setq tmp (funcall getkey-func))
  7331. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7332. tmp)
  7333. (error "Invalid key function `%s'" getkey-func)))
  7334. (t (error "Invalid sorting type `%c'" sorting-type))))
  7335. nil
  7336. (cond
  7337. ((= dcst ?a) 'org-string-collate-lessp)
  7338. ((= dcst ?f)
  7339. (or compare-func
  7340. (and interactive?
  7341. (org-read-function
  7342. (concat "Function for comparing keys "
  7343. "(empty for default `sort-subr' predicate): ")
  7344. 'allow-empty))))
  7345. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7346. (when restore-clock?
  7347. (move-marker org-clock-marker
  7348. (1+ (next-single-property-change
  7349. start :org-clock-marker-backup)))
  7350. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7351. '(:org-clock-marker-backup t)))))
  7352. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7353. (message "Sorting entries...done")))
  7354. (defun org-contextualize-keys (alist contexts)
  7355. "Return valid elements in ALIST depending on CONTEXTS.
  7356. `org-agenda-custom-commands' or `org-capture-templates' are the
  7357. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7358. or `org-capture-templates-contexts' are the associated contexts
  7359. definitions."
  7360. (let ((contexts
  7361. ;; normalize contexts
  7362. (mapcar
  7363. (lambda(c) (cond ((listp (cadr c))
  7364. (list (car c) (car c) (nth 1 c)))
  7365. ((string= "" (cadr c))
  7366. (list (car c) (car c) (nth 2 c)))
  7367. (t c)))
  7368. contexts))
  7369. (a alist) r s)
  7370. ;; loop over all commands or templates
  7371. (dolist (c a)
  7372. (let (vrules repl)
  7373. (cond
  7374. ((not (assoc (car c) contexts))
  7375. (push c r))
  7376. ((and (assoc (car c) contexts)
  7377. (setq vrules (org-contextualize-validate-key
  7378. (car c) contexts)))
  7379. (mapc (lambda (vr)
  7380. (unless (equal (car vr) (cadr vr))
  7381. (setq repl vr)))
  7382. vrules)
  7383. (if (not repl) (push c r)
  7384. (push (cadr repl) s)
  7385. (push
  7386. (cons (car c)
  7387. (cdr (or (assoc (cadr repl) alist)
  7388. (error "Undefined key `%s' as contextual replacement for `%s'"
  7389. (cadr repl) (car c)))))
  7390. r))))))
  7391. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7392. (delq
  7393. nil
  7394. (delete-dups
  7395. (mapcar (lambda (x)
  7396. (let ((tpl (car x)))
  7397. (unless (delq
  7398. nil
  7399. (mapcar (lambda (y)
  7400. (equal y tpl))
  7401. s))
  7402. x)))
  7403. (reverse r))))))
  7404. (defun org-contextualize-validate-key (key contexts)
  7405. "Check CONTEXTS for agenda or capture KEY."
  7406. (let (res)
  7407. (dolist (r contexts)
  7408. (dolist (rr (car (last r)))
  7409. (when
  7410. (and (equal key (car r))
  7411. (if (functionp rr) (funcall rr)
  7412. (or (and (eq (car rr) 'in-file)
  7413. (buffer-file-name)
  7414. (string-match (cdr rr) (buffer-file-name)))
  7415. (and (eq (car rr) 'in-mode)
  7416. (string-match (cdr rr) (symbol-name major-mode)))
  7417. (and (eq (car rr) 'in-buffer)
  7418. (string-match (cdr rr) (buffer-name)))
  7419. (when (and (eq (car rr) 'not-in-file)
  7420. (buffer-file-name))
  7421. (not (string-match (cdr rr) (buffer-file-name))))
  7422. (when (eq (car rr) 'not-in-mode)
  7423. (not (string-match (cdr rr) (symbol-name major-mode))))
  7424. (when (eq (car rr) 'not-in-buffer)
  7425. (not (string-match (cdr rr) (buffer-name)))))))
  7426. (push r res))))
  7427. (delete-dups (delq nil res))))
  7428. ;; Defined to provide a value for defcustom, since there is no
  7429. ;; string-collate-greaterp in Emacs.
  7430. (defun org-string-collate-greaterp (s1 s2)
  7431. "Return non-nil if S1 is greater than S2 in collation order."
  7432. (not (org-string-collate-lessp s1 s2)))
  7433. ;;;###autoload
  7434. (defun org-run-like-in-org-mode (cmd)
  7435. "Run a command, pretending that the current buffer is in Org mode.
  7436. This will temporarily bind local variables that are typically bound in
  7437. Org mode to the values they have in Org mode, and then interactively
  7438. call CMD."
  7439. (org-load-modules-maybe)
  7440. (let (binds)
  7441. (dolist (var (org-get-local-variables))
  7442. (when (or (not (boundp (car var)))
  7443. (eq (symbol-value (car var))
  7444. (default-value (car var))))
  7445. (push (list (car var) `(quote ,(cadr var))) binds)))
  7446. (eval `(let ,binds
  7447. (call-interactively (quote ,cmd))))))
  7448. (defun org-get-category (&optional pos force-refresh)
  7449. "Get the category applying to position POS."
  7450. (save-match-data
  7451. (when force-refresh (org-refresh-category-properties))
  7452. (let ((pos (or pos (point))))
  7453. (or (get-text-property pos 'org-category)
  7454. (progn (org-refresh-category-properties)
  7455. (get-text-property pos 'org-category))))))
  7456. ;;; Refresh properties
  7457. (defun org-refresh-properties (dprop tprop)
  7458. "Refresh buffer text properties.
  7459. DPROP is the drawer property and TPROP is either the
  7460. corresponding text property to set, or an alist with each element
  7461. being a text property (as a symbol) and a function to apply to
  7462. the value of the drawer property."
  7463. (let* ((case-fold-search t)
  7464. (inhibit-read-only t)
  7465. (inherit? (org-property-inherit-p dprop))
  7466. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7467. (global (and inherit? (org--property-global-value dprop nil))))
  7468. (with-silent-modifications
  7469. (org-with-point-at 1
  7470. ;; Set global values (e.g., values defined through
  7471. ;; "#+PROPERTY:" keywords) to the whole buffer.
  7472. (when global (put-text-property (point-min) (point-max) tprop global))
  7473. ;; Set local values.
  7474. (while (re-search-forward property-re nil t)
  7475. (when (org-at-property-p)
  7476. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7477. (outline-next-heading))))))
  7478. (defun org-refresh-property (tprop p &optional inherit)
  7479. "Refresh the buffer text property TPROP from the drawer property P.
  7480. The refresh happens only for the current headline, or the whole
  7481. sub-tree if optional argument INHERIT is non-nil."
  7482. (unless (org-before-first-heading-p)
  7483. (save-excursion
  7484. (org-back-to-heading t)
  7485. (let ((start (point))
  7486. (end (save-excursion
  7487. (if inherit (org-end-of-subtree t t)
  7488. (or (outline-next-heading) (point-max))))))
  7489. (if (symbolp tprop)
  7490. ;; TPROP is a text property symbol.
  7491. (put-text-property start end tprop p)
  7492. ;; TPROP is an alist with (property . function) elements.
  7493. (pcase-dolist (`(,prop . ,f) tprop)
  7494. (put-text-property start end prop (funcall f p))))))))
  7495. (defun org-refresh-category-properties ()
  7496. "Refresh category text properties in the buffer."
  7497. (let ((case-fold-search t)
  7498. (inhibit-read-only t)
  7499. (default-category
  7500. (cond ((null org-category)
  7501. (if buffer-file-name
  7502. (file-name-sans-extension
  7503. (file-name-nondirectory buffer-file-name))
  7504. "???"))
  7505. ((symbolp org-category) (symbol-name org-category))
  7506. (t org-category))))
  7507. (with-silent-modifications
  7508. (org-with-wide-buffer
  7509. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  7510. ;; This is the default category for the buffer. If none is
  7511. ;; found, fall-back to `org-category' or buffer file name.
  7512. (put-text-property
  7513. (point-min) (point-max)
  7514. 'org-category
  7515. (catch 'buffer-category
  7516. (goto-char (point-max))
  7517. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7518. (let ((element (org-element-at-point)))
  7519. (when (eq (org-element-type element) 'keyword)
  7520. (throw 'buffer-category
  7521. (org-element-property :value element)))))
  7522. default-category))
  7523. ;; Set sub-tree specific categories.
  7524. (goto-char (point-min))
  7525. (let ((regexp (org-re-property "CATEGORY")))
  7526. (while (re-search-forward regexp nil t)
  7527. (let ((value (match-string-no-properties 3)))
  7528. (when (org-at-property-p)
  7529. (put-text-property
  7530. (save-excursion (org-back-to-heading t) (point))
  7531. (save-excursion (org-end-of-subtree t t) (point))
  7532. 'org-category
  7533. value)))))))))
  7534. (defun org-refresh-stats-properties ()
  7535. "Refresh stats text properties in the buffer."
  7536. (with-silent-modifications
  7537. (org-with-point-at 1
  7538. (let ((regexp (concat org-outline-regexp-bol
  7539. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7540. (while (re-search-forward regexp nil t)
  7541. (let* ((numerator (string-to-number (match-string 1)))
  7542. (denominator (and (match-end 2)
  7543. (string-to-number (match-string 2))))
  7544. (stats (cond ((not denominator) numerator) ;percent
  7545. ((= denominator 0) 0)
  7546. (t (/ (* numerator 100) denominator)))))
  7547. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7548. 'org-stats stats)))))))
  7549. (defun org-refresh-effort-properties ()
  7550. "Refresh effort properties"
  7551. (org-refresh-properties
  7552. org-effort-property
  7553. '((effort . identity)
  7554. (effort-minutes . org-duration-to-minutes))))
  7555. (defun org-find-file-at-mouse (ev)
  7556. "Open file link or URL at mouse."
  7557. (interactive "e")
  7558. (mouse-set-point ev)
  7559. (org-open-at-point 'in-emacs))
  7560. (defun org-open-at-mouse (ev)
  7561. "Open file link or URL at mouse.
  7562. See the docstring of `org-open-file' for details."
  7563. (interactive "e")
  7564. (mouse-set-point ev)
  7565. (when (eq major-mode 'org-agenda-mode)
  7566. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7567. (org-open-at-point))
  7568. (defvar org-window-config-before-follow-link nil
  7569. "The window configuration before following a link.
  7570. This is saved in case the need arises to restore it.")
  7571. (defun org--file-default-apps ()
  7572. "Return the default applications for this operating system."
  7573. (pcase system-type
  7574. (`darwin org-file-apps-macos)
  7575. (`windows-nt org-file-apps-windowsnt)
  7576. (_ org-file-apps-gnu)))
  7577. (defun org--file-apps-entry-dlink-p (entry)
  7578. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7579. It assumes that is the case when the entry uses a regular
  7580. expression which has at least one grouping construct and the
  7581. action is either a Lisp form or a command string containing
  7582. \"%1\", i.e., using at least one subexpression match as
  7583. a parameter."
  7584. (pcase entry
  7585. (`(,selector . ,action)
  7586. (and (stringp selector)
  7587. (> (regexp-opt-depth selector) 0)
  7588. (or (and (stringp action)
  7589. (string-match "%[0-9]" action))
  7590. (consp action))))
  7591. (_ nil)))
  7592. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7593. "Convert extensions to regular expressions in the cars of LIST.
  7594. Also, weed out any non-string entries, because the return value
  7595. is used only for regexp matching.
  7596. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7597. point to the symbol `emacs', indicating that the file should be
  7598. opened in Emacs."
  7599. (append
  7600. (delq nil
  7601. (mapcar (lambda (x)
  7602. (unless (not (stringp (car x)))
  7603. (if (string-match "\\W" (car x))
  7604. x
  7605. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7606. list))
  7607. (when add-auto-mode
  7608. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7609. ;;;###autoload
  7610. (defun org-open-file (path &optional in-emacs line search)
  7611. "Open the file at PATH.
  7612. First, this expands any special file name abbreviations. Then the
  7613. configuration variable `org-file-apps' is checked if it contains an
  7614. entry for this file type, and if yes, the corresponding command is launched.
  7615. If no application is found, Emacs simply visits the file.
  7616. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7617. With a double \\[universal-argument] \\[universal-argument] \
  7618. prefix arg, Org tries to avoid opening in Emacs
  7619. and to use an external application to visit the file.
  7620. Optional LINE specifies a line to go to, optional SEARCH a string
  7621. to search for. If LINE or SEARCH is given, the file will be
  7622. opened in Emacs, unless an entry from `org-file-apps' that makes
  7623. use of groups in a regexp matches.
  7624. If you want to change the way frames are used when following a
  7625. link, please customize `org-link-frame-setup'.
  7626. If the file does not exist, throw an error."
  7627. (let* ((file (if (equal path "") buffer-file-name
  7628. (substitute-in-file-name (expand-file-name path))))
  7629. (file-apps (append org-file-apps (org--file-default-apps)))
  7630. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7631. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7632. file-apps))
  7633. (remp (and (assq 'remote apps) (file-remote-p file)))
  7634. (dirp (unless remp (file-directory-p file)))
  7635. (file (if (and dirp org-open-directory-means-index-dot-org)
  7636. (concat (file-name-as-directory file) "index.org")
  7637. file))
  7638. (a-m-a-p (assq 'auto-mode apps))
  7639. (dfile (downcase file))
  7640. ;; Reconstruct the original link from the PATH, LINE and
  7641. ;; SEARCH args.
  7642. (link (cond (line (concat file "::" (number-to-string line)))
  7643. (search (concat file "::" search))
  7644. (t file)))
  7645. (dlink (downcase link))
  7646. (ext
  7647. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7648. (match-string 1 dfile)))
  7649. (save-position-maybe
  7650. (let ((old-buffer (current-buffer))
  7651. (old-pos (point))
  7652. (old-mode major-mode))
  7653. (lambda ()
  7654. (and (derived-mode-p 'org-mode)
  7655. (eq old-mode 'org-mode)
  7656. (or (not (eq old-buffer (current-buffer)))
  7657. (not (eq old-pos (point))))
  7658. (org-mark-ring-push old-pos old-buffer)))))
  7659. cmd link-match-data)
  7660. (cond
  7661. ((member in-emacs '((16) system))
  7662. (setq cmd (cdr (assq 'system apps))))
  7663. (in-emacs (setq cmd 'emacs))
  7664. (t
  7665. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7666. (and dirp (cdr (assq 'directory apps)))
  7667. ;; First, try matching against apps-dlink if we
  7668. ;; get a match here, store the match data for
  7669. ;; later.
  7670. (let ((match (assoc-default dlink apps-dlink
  7671. 'string-match)))
  7672. (if match
  7673. (progn (setq link-match-data (match-data))
  7674. match)
  7675. (progn (setq in-emacs (or in-emacs line search))
  7676. nil))) ; if we have no match in apps-dlink,
  7677. ; always open the file in emacs if line or search
  7678. ; is given (for backwards compatibility)
  7679. (assoc-default dfile
  7680. (org--file-apps-regexp-alist apps a-m-a-p)
  7681. 'string-match)
  7682. (cdr (assoc ext apps))
  7683. (cdr (assq t apps))))))
  7684. (when (eq cmd 'system)
  7685. (setq cmd (cdr (assq 'system apps))))
  7686. (when (eq cmd 'default)
  7687. (setq cmd (cdr (assoc t apps))))
  7688. (when (eq cmd 'mailcap)
  7689. (require 'mailcap)
  7690. (mailcap-parse-mailcaps)
  7691. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7692. (command (mailcap-mime-info mime-type)))
  7693. (if (stringp command)
  7694. (setq cmd command)
  7695. (setq cmd 'emacs))))
  7696. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7697. (not (file-exists-p file))
  7698. (not org-open-non-existing-files))
  7699. (user-error "No such file: %s" file))
  7700. (cond
  7701. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7702. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7703. (while (string-match "['\"]%s['\"]" cmd)
  7704. (setq cmd (replace-match "%s" t t cmd)))
  7705. (setq cmd (replace-regexp-in-string
  7706. "%s"
  7707. (shell-quote-argument (convert-standard-filename file))
  7708. cmd
  7709. nil t))
  7710. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7711. (save-match-data
  7712. (let ((match-index 1)
  7713. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7714. (set-match-data link-match-data)
  7715. (while (<= match-index number-of-groups)
  7716. (let ((regex (concat "%" (number-to-string match-index)))
  7717. (replace-with (match-string match-index dlink)))
  7718. (while (string-match regex cmd)
  7719. (setq cmd (replace-match replace-with t t cmd))))
  7720. (setq match-index (+ match-index 1)))))
  7721. (save-window-excursion
  7722. (message "Running %s...done" cmd)
  7723. (start-process-shell-command cmd nil cmd)
  7724. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7725. ((or (stringp cmd)
  7726. (eq cmd 'emacs))
  7727. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7728. (widen)
  7729. (cond (line (org-goto-line line)
  7730. (when (derived-mode-p 'org-mode) (org-reveal)))
  7731. (search (condition-case err
  7732. (org-link-search search)
  7733. ;; Save position before error-ing out so user
  7734. ;; can easily move back to the original buffer.
  7735. (error (funcall save-position-maybe)
  7736. (error (nth 1 err)))))))
  7737. ((functionp cmd)
  7738. (save-match-data
  7739. (set-match-data link-match-data)
  7740. (condition-case nil
  7741. (funcall cmd file link)
  7742. ;; FIXME: Remove this check when most default installations
  7743. ;; of Emacs have at least Org 9.0.
  7744. ((debug wrong-number-of-arguments wrong-type-argument
  7745. invalid-function)
  7746. (user-error "Please see Org News for version 9.0 about \
  7747. `org-file-apps'--Lisp error: %S" cmd)))))
  7748. ((consp cmd)
  7749. ;; FIXME: Remove this check when most default installations of
  7750. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7751. ;; fall back to `org-link-frame-setup' for an old usage of
  7752. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7753. (user-error "Please see Org News for version 9.0 about \
  7754. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7755. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7756. (funcall save-position-maybe)))
  7757. ;;;###autoload
  7758. (defun org-open-at-point-global ()
  7759. "Follow a link or a time-stamp like Org mode does.
  7760. Also follow links and emails as seen by `thing-at-point'.
  7761. This command can be called in any mode to follow an external
  7762. link or a time-stamp that has Org mode syntax. Its behavior
  7763. is undefined when called on internal links like fuzzy links.
  7764. Raise a user error when there is nothing to follow."
  7765. (interactive)
  7766. (let ((tap-url (thing-at-point 'url))
  7767. (tap-email (thing-at-point 'email)))
  7768. (cond ((org-in-regexp org-link-any-re)
  7769. (org-link-open-from-string (match-string-no-properties 0)))
  7770. ((or (org-in-regexp org-ts-regexp-both nil t)
  7771. (org-in-regexp org-tsr-regexp-both nil t))
  7772. (org-follow-timestamp-link))
  7773. (tap-url (org-link-open-from-string tap-url))
  7774. (tap-email (org-link-open-from-string
  7775. (concat "mailto:" tap-email)))
  7776. (t (user-error "No link found")))))
  7777. (defvar org-open-at-point-functions nil
  7778. "Hook that is run when following a link at point.
  7779. Functions in this hook must return t if they identify and follow
  7780. a link at point. If they don't find anything interesting at point,
  7781. they must return nil.")
  7782. (defun org-open-at-point (&optional arg)
  7783. "Open link, timestamp, footnote or tags at point.
  7784. When point is on a link, follow it. Normally, files will be
  7785. opened by an appropriate application. If the optional prefix
  7786. argument ARG is non-nil, Emacs will visit the file. With
  7787. a double prefix argument, try to open outside of Emacs, in the
  7788. application the system uses for this file type.
  7789. When point is on a timestamp, open the agenda at the day
  7790. specified.
  7791. When point is a footnote definition, move to the first reference
  7792. found. If it is on a reference, move to the associated
  7793. definition.
  7794. When point is on a headline, display a list of every link in the
  7795. entry, so it is possible to pick one, or all, of them. If point
  7796. is on a tag, call `org-tags-view' instead.
  7797. On top of syntactically correct links, this function also tries
  7798. to open links and time-stamps in comments, node properties, and
  7799. keywords if point is on something looking like a timestamp or
  7800. a link."
  7801. (interactive "P")
  7802. (org-load-modules-maybe)
  7803. (setq org-window-config-before-follow-link (current-window-configuration))
  7804. (org-remove-occur-highlights nil nil t)
  7805. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  7806. (let* ((context
  7807. ;; Only consider supported types, even if they are not the
  7808. ;; closest one.
  7809. (org-element-lineage
  7810. (org-element-context)
  7811. '(clock comment comment-block footnote-definition
  7812. footnote-reference headline inline-src-block inlinetask
  7813. keyword link node-property planning src-block timestamp)
  7814. t))
  7815. (type (org-element-type context))
  7816. (value (org-element-property :value context)))
  7817. (cond
  7818. ((not type) (user-error "No link found"))
  7819. ;; No valid link at point. For convenience, look if something
  7820. ;; looks like a link under point in some specific places.
  7821. ((memq type '(comment comment-block node-property keyword))
  7822. (call-interactively #'org-open-at-point-global))
  7823. ;; On a headline or an inlinetask, but not on a timestamp,
  7824. ;; a link, a footnote reference.
  7825. ((memq type '(headline inlinetask))
  7826. (org-match-line org-complex-heading-regexp)
  7827. (if (and (match-beginning 5)
  7828. (>= (point) (match-beginning 5))
  7829. (< (point) (match-end 5)))
  7830. ;; On tags.
  7831. (org-tags-view
  7832. arg
  7833. (save-excursion
  7834. (let* ((beg (match-beginning 5))
  7835. (end (match-end 5))
  7836. (beg-tag (or (search-backward ":" beg 'at-limit) (point)))
  7837. (end-tag (search-forward ":" end nil 2)))
  7838. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  7839. ;; Not on tags.
  7840. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  7841. (`(nil . ,_)
  7842. (require 'org-attach)
  7843. (org-attach-reveal 'if-exists))
  7844. (`(,links . ,links-end)
  7845. (dolist (link (if (stringp links) (list links) links))
  7846. (search-forward link nil links-end)
  7847. (goto-char (match-beginning 0))
  7848. (org-open-at-point))))))
  7849. ;; On a footnote reference or at definition's label.
  7850. ((or (eq type 'footnote-reference)
  7851. (and (eq type 'footnote-definition)
  7852. (save-excursion
  7853. ;; Do not validate action when point is on the
  7854. ;; spaces right after the footnote label, in order
  7855. ;; to be on par with behavior on links.
  7856. (skip-chars-forward " \t")
  7857. (let ((begin
  7858. (org-element-property :contents-begin context)))
  7859. (if begin (< (point) begin)
  7860. (= (org-element-property :post-affiliated context)
  7861. (line-beginning-position)))))))
  7862. (org-footnote-action))
  7863. ;; On a planning line. Check if we are really on a timestamp.
  7864. ((and (eq type 'planning)
  7865. (org-in-regexp org-ts-regexp-both nil t))
  7866. (org-follow-timestamp-link))
  7867. ;; On a clock line, make sure point is on the timestamp
  7868. ;; before opening it.
  7869. ((and (eq type 'clock)
  7870. value
  7871. (>= (point) (org-element-property :begin value))
  7872. (<= (point) (org-element-property :end value)))
  7873. (org-follow-timestamp-link))
  7874. ((eq type 'src-block) (org-babel-open-src-block-result))
  7875. ;; Do nothing on white spaces after an object.
  7876. ((>= (point)
  7877. (save-excursion
  7878. (goto-char (org-element-property :end context))
  7879. (skip-chars-backward " \t")
  7880. (point)))
  7881. (user-error "No link found"))
  7882. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  7883. ((eq type 'timestamp) (org-follow-timestamp-link))
  7884. ((eq type 'link) (org-link-open context arg))
  7885. (t (user-error "No link found")))))
  7886. (run-hook-with-args 'org-follow-link-hook))
  7887. ;;;###autoload
  7888. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  7889. "Offer links in the current entry and return the selected link.
  7890. If there is only one link, return it.
  7891. If NTH is an integer, return the NTH link found.
  7892. If ZERO is a string, check also this string for a link, and if
  7893. there is one, return it."
  7894. (with-current-buffer buffer
  7895. (org-with-wide-buffer
  7896. (goto-char marker)
  7897. (let ((cnt ?0)
  7898. have-zero end links link c)
  7899. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  7900. (push (match-string 0 zero) links)
  7901. (setq cnt (1- cnt) have-zero t))
  7902. (save-excursion
  7903. (org-back-to-heading t)
  7904. (setq end (save-excursion (outline-next-heading) (point)))
  7905. (while (re-search-forward org-link-any-re end t)
  7906. (push (match-string 0) links))
  7907. (setq links (org-uniquify (reverse links))))
  7908. (cond
  7909. ((null links)
  7910. (message "No links"))
  7911. ((equal (length links) 1)
  7912. (setq link (car links)))
  7913. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  7914. (setq link (nth (if have-zero nth (1- nth)) links)))
  7915. (t ; we have to select a link
  7916. (save-excursion
  7917. (save-window-excursion
  7918. (delete-other-windows)
  7919. (with-output-to-temp-buffer "*Select Link*"
  7920. (dolist (l links)
  7921. (cond
  7922. ((not (string-match org-link-bracket-re l))
  7923. (princ (format "[%c] %s\n" (cl-incf cnt)
  7924. (org-unbracket-string "<" ">" l))))
  7925. ((match-end 3)
  7926. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  7927. (match-string 3 l) (match-string 1 l))))
  7928. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  7929. (match-string 1 l)))))))
  7930. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  7931. (message "Select link to open, RET to open all:")
  7932. (setq c (read-char-exclusive))
  7933. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  7934. (when (equal c ?q) (user-error "Abort"))
  7935. (if (equal c ?\C-m)
  7936. (setq link links)
  7937. (setq nth (- c ?0))
  7938. (when have-zero (setq nth (1+ nth)))
  7939. (unless (and (integerp nth) (>= (length links) nth))
  7940. (user-error "Invalid link selection"))
  7941. (setq link (nth (1- nth) links)))))
  7942. (cons link end)))))
  7943. ;;; File search
  7944. (defun org-do-occur (regexp &optional cleanup)
  7945. "Call the Emacs command `occur'.
  7946. If CLEANUP is non-nil, remove the printout of the regular expression
  7947. in the *Occur* buffer. This is useful if the regex is long and not useful
  7948. to read."
  7949. (occur regexp)
  7950. (when cleanup
  7951. (let ((cwin (selected-window)) win beg end)
  7952. (when (setq win (get-buffer-window "*Occur*"))
  7953. (select-window win))
  7954. (goto-char (point-min))
  7955. (when (re-search-forward "match[a-z]+" nil t)
  7956. (setq beg (match-end 0))
  7957. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  7958. (setq end (1- (match-beginning 0)))))
  7959. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  7960. (goto-char (point-min))
  7961. (select-window cwin))))
  7962. ;;; The Mark Ring
  7963. (defvar org-mark-ring nil
  7964. "Mark ring for positions before jumps in Org mode.")
  7965. (defvar org-mark-ring-last-goto nil
  7966. "Last position in the mark ring used to go back.")
  7967. ;; Fill and close the ring
  7968. (setq org-mark-ring nil)
  7969. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  7970. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  7971. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  7972. org-mark-ring)
  7973. (defun org-mark-ring-push (&optional pos buffer)
  7974. "Put the current position into the mark ring and rotate it.
  7975. Also push position into the Emacs mark ring. If optional
  7976. argument POS and BUFFER are not nil, mark this location instead."
  7977. (interactive)
  7978. (let ((pos (or pos (point)))
  7979. (buffer (or buffer (current-buffer))))
  7980. (with-current-buffer buffer
  7981. (org-with-point-at pos (push-mark nil t)))
  7982. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  7983. (move-marker (car org-mark-ring) pos buffer))
  7984. (message
  7985. (substitute-command-keys
  7986. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  7987. (defun org-mark-ring-goto (&optional n)
  7988. "Jump to the previous position in the mark ring.
  7989. With prefix arg N, jump back that many stored positions. When
  7990. called several times in succession, walk through the entire ring.
  7991. Org mode commands jumping to a different position in the current file,
  7992. or to another Org file, automatically push the old position onto the ring."
  7993. (interactive "p")
  7994. (let (p m)
  7995. (if (eq last-command this-command)
  7996. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  7997. (setq p org-mark-ring))
  7998. (setq org-mark-ring-last-goto p)
  7999. (setq m (car p))
  8000. (pop-to-buffer-same-window (marker-buffer m))
  8001. (goto-char m)
  8002. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  8003. ;;; Following specific links
  8004. (defvar org-agenda-buffer-tmp-name)
  8005. (defvar org-agenda-start-on-weekday)
  8006. (defun org-follow-timestamp-link ()
  8007. "Open an agenda view for the time-stamp date/range at point."
  8008. (cond
  8009. ((org-at-date-range-p t)
  8010. (let ((org-agenda-start-on-weekday)
  8011. (t1 (match-string 1))
  8012. (t2 (match-string 2)) tt1 tt2)
  8013. (setq tt1 (time-to-days (org-time-string-to-time t1))
  8014. tt2 (time-to-days (org-time-string-to-time t2)))
  8015. (let ((org-agenda-buffer-tmp-name
  8016. (format "*Org Agenda(a:%s)"
  8017. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  8018. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  8019. ((org-at-timestamp-p 'lax)
  8020. (let ((org-agenda-buffer-tmp-name
  8021. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  8022. (org-agenda-list nil (time-to-days (org-time-string-to-time
  8023. (substring (match-string 1) 0 10)))
  8024. 1)))
  8025. (t (error "This should not happen"))))
  8026. ;;; Following file links
  8027. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  8028. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  8029. (declare-function mailcap-mime-info
  8030. "mailcap" (string &optional request no-decode))
  8031. (defvar org-wait nil)
  8032. ;;;; Refiling
  8033. (defun org-get-org-file ()
  8034. "Read a filename, with default directory `org-directory'."
  8035. (let ((default (or org-default-notes-file remember-data-file)))
  8036. (read-file-name (format "File name [%s]: " default)
  8037. (file-name-as-directory org-directory)
  8038. default)))
  8039. (defun org-notes-order-reversed-p ()
  8040. "Check if the current file should receive notes in reversed order."
  8041. (cond
  8042. ((not org-reverse-note-order) nil)
  8043. ((eq t org-reverse-note-order) t)
  8044. ((not (listp org-reverse-note-order)) nil)
  8045. (t (catch 'exit
  8046. (dolist (entry org-reverse-note-order)
  8047. (when (string-match (car entry) buffer-file-name)
  8048. (throw 'exit (cdr entry))))))))
  8049. (defvar org-refile-target-table nil
  8050. "The list of refile targets, created by `org-refile'.")
  8051. (defvar org-agenda-new-buffers nil
  8052. "Buffers created to visit agenda files.")
  8053. (defvar org-refile-cache nil
  8054. "Cache for refile targets.")
  8055. (defvar org-refile-markers nil
  8056. "All the markers used for caching refile locations.")
  8057. (defun org-refile-marker (pos)
  8058. "Get a new refile marker, but only if caching is in use."
  8059. (if (not org-refile-use-cache)
  8060. pos
  8061. (let ((m (make-marker)))
  8062. (move-marker m pos)
  8063. (push m org-refile-markers)
  8064. m)))
  8065. (defun org-refile-cache-clear ()
  8066. "Clear the refile cache and disable all the markers."
  8067. (dolist (m org-refile-markers) (move-marker m nil))
  8068. (setq org-refile-markers nil)
  8069. (setq org-refile-cache nil)
  8070. (message "Refile cache has been cleared"))
  8071. (defun org-refile-cache-check-set (set)
  8072. "Check if all the markers in the cache still have live buffers."
  8073. (let (marker)
  8074. (catch 'exit
  8075. (while (and set (setq marker (nth 3 (pop set))))
  8076. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  8077. (when (and marker (null (marker-buffer marker)))
  8078. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  8079. (sit-for 3)
  8080. (throw 'exit nil)))
  8081. t)))
  8082. (defun org-refile-cache-put (set &rest identifiers)
  8083. "Push the refile targets SET into the cache, under IDENTIFIERS."
  8084. (let* ((key (sha1 (prin1-to-string identifiers)))
  8085. (entry (assoc key org-refile-cache)))
  8086. (if entry
  8087. (setcdr entry set)
  8088. (push (cons key set) org-refile-cache))))
  8089. (defun org-refile-cache-get (&rest identifiers)
  8090. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  8091. (cond
  8092. ((not org-refile-cache) nil)
  8093. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  8094. (t
  8095. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  8096. org-refile-cache))))
  8097. (and set (org-refile-cache-check-set set) set)))))
  8098. (defvar org-outline-path-cache nil
  8099. "Alist between buffer positions and outline paths.
  8100. It value is an alist (POSITION . PATH) where POSITION is the
  8101. buffer position at the beginning of an entry and PATH is a list
  8102. of strings describing the outline path for that entry, in reverse
  8103. order.")
  8104. (defun org-refile-get-targets (&optional default-buffer)
  8105. "Produce a table with refile targets."
  8106. (let ((case-fold-search nil)
  8107. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  8108. (entries (or org-refile-targets '((nil . (:level . 1)))))
  8109. targets tgs files desc descre)
  8110. (message "Getting targets...")
  8111. (with-current-buffer (or default-buffer (current-buffer))
  8112. (dolist (entry entries)
  8113. (setq files (car entry) desc (cdr entry))
  8114. (cond
  8115. ((null files) (setq files (list (current-buffer))))
  8116. ((eq files 'org-agenda-files)
  8117. (setq files (org-agenda-files 'unrestricted)))
  8118. ((and (symbolp files) (fboundp files))
  8119. (setq files (funcall files)))
  8120. ((and (symbolp files) (boundp files))
  8121. (setq files (symbol-value files))))
  8122. (when (stringp files) (setq files (list files)))
  8123. (cond
  8124. ((eq (car desc) :tag)
  8125. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  8126. ((eq (car desc) :todo)
  8127. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  8128. ((eq (car desc) :regexp)
  8129. (setq descre (cdr desc)))
  8130. ((eq (car desc) :level)
  8131. (setq descre (concat "^\\*\\{" (number-to-string
  8132. (if org-odd-levels-only
  8133. (1- (* 2 (cdr desc)))
  8134. (cdr desc)))
  8135. "\\}[ \t]")))
  8136. ((eq (car desc) :maxlevel)
  8137. (setq descre (concat "^\\*\\{1," (number-to-string
  8138. (if org-odd-levels-only
  8139. (1- (* 2 (cdr desc)))
  8140. (cdr desc)))
  8141. "\\}[ \t]")))
  8142. (t (error "Bad refiling target description %s" desc)))
  8143. (dolist (f files)
  8144. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  8145. (or
  8146. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  8147. (progn
  8148. (when (bufferp f)
  8149. (setq f (buffer-file-name (buffer-base-buffer f))))
  8150. (setq f (and f (expand-file-name f)))
  8151. (when (eq org-refile-use-outline-path 'file)
  8152. (push (list (file-name-nondirectory f) f nil nil) tgs))
  8153. (when (eq org-refile-use-outline-path 'buffer-name)
  8154. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  8155. (when (eq org-refile-use-outline-path 'full-file-path)
  8156. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  8157. (org-with-wide-buffer
  8158. (goto-char (point-min))
  8159. (setq org-outline-path-cache nil)
  8160. (while (re-search-forward descre nil t)
  8161. (beginning-of-line)
  8162. (let ((case-fold-search nil))
  8163. (looking-at org-complex-heading-regexp))
  8164. (let ((begin (point))
  8165. (heading (match-string-no-properties 4)))
  8166. (unless (or (and
  8167. org-refile-target-verify-function
  8168. (not
  8169. (funcall org-refile-target-verify-function)))
  8170. (not heading))
  8171. (let ((re (format org-complex-heading-regexp-format
  8172. (regexp-quote heading)))
  8173. (target
  8174. (if (not org-refile-use-outline-path) heading
  8175. (mapconcat
  8176. #'identity
  8177. (append
  8178. (pcase org-refile-use-outline-path
  8179. (`file (list (file-name-nondirectory
  8180. (buffer-file-name
  8181. (buffer-base-buffer)))))
  8182. (`full-file-path
  8183. (list (buffer-file-name
  8184. (buffer-base-buffer))))
  8185. (`buffer-name
  8186. (list (buffer-name
  8187. (buffer-base-buffer))))
  8188. (_ nil))
  8189. (mapcar (lambda (s) (replace-regexp-in-string
  8190. "/" "\\/" s nil t))
  8191. (org-get-outline-path t t)))
  8192. "/"))))
  8193. (push (list target f re (org-refile-marker (point)))
  8194. tgs)))
  8195. (when (= (point) begin)
  8196. ;; Verification function has not moved point.
  8197. (end-of-line)))))))
  8198. (when org-refile-use-cache
  8199. (org-refile-cache-put tgs (buffer-file-name) descre))
  8200. (setq targets (append tgs targets))))))
  8201. (message "Getting targets...done")
  8202. (delete-dups (nreverse targets))))
  8203. (defun org--get-outline-path-1 (&optional use-cache)
  8204. "Return outline path to current headline.
  8205. Outline path is a list of strings, in reverse order. When
  8206. optional argument USE-CACHE is non-nil, make use of a cache. See
  8207. `org-get-outline-path' for details.
  8208. Assume buffer is widened and point is on a headline."
  8209. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  8210. (let ((p (point))
  8211. (heading (let ((case-fold-search nil))
  8212. (looking-at org-complex-heading-regexp)
  8213. (if (not (match-end 4)) ""
  8214. ;; Remove statistics cookies.
  8215. (org-trim
  8216. (org-link-display-format
  8217. (replace-regexp-in-string
  8218. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  8219. (match-string-no-properties 4))))))))
  8220. (if (org-up-heading-safe)
  8221. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  8222. (when use-cache
  8223. (push (cons p path) org-outline-path-cache))
  8224. path)
  8225. ;; This is a new root node. Since we assume we are moving
  8226. ;; forward, we can drop previous cache so as to limit number
  8227. ;; of associations there.
  8228. (let ((path (list heading)))
  8229. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  8230. path)))))
  8231. (defun org-get-outline-path (&optional with-self use-cache)
  8232. "Return the outline path to the current entry.
  8233. An outline path is a list of ancestors for current headline, as
  8234. a list of strings. Statistics cookies are removed and links are
  8235. replaced with their description, if any, or their path otherwise.
  8236. When optional argument WITH-SELF is non-nil, the path also
  8237. includes the current headline.
  8238. When optional argument USE-CACHE is non-nil, cache outline paths
  8239. between calls to this function so as to avoid backtracking. This
  8240. argument is useful when planning to find more than one outline
  8241. path in the same document. In that case, there are two
  8242. conditions to satisfy:
  8243. - `org-outline-path-cache' is set to nil before starting the
  8244. process;
  8245. - outline paths are computed by increasing buffer positions."
  8246. (org-with-wide-buffer
  8247. (and (or (and with-self (org-back-to-heading t))
  8248. (org-up-heading-safe))
  8249. (reverse (org--get-outline-path-1 use-cache)))))
  8250. (defun org-format-outline-path (path &optional width prefix separator)
  8251. "Format the outline path PATH for display.
  8252. WIDTH is the maximum number of characters that is available.
  8253. PREFIX is a prefix to be included in the returned string,
  8254. such as the file name.
  8255. SEPARATOR is inserted between the different parts of the path,
  8256. the default is \"/\"."
  8257. (setq width (or width 79))
  8258. (setq path (delq nil path))
  8259. (unless (> width 0)
  8260. (user-error "Argument `width' must be positive"))
  8261. (setq separator (or separator "/"))
  8262. (let* ((org-odd-levels-only nil)
  8263. (fpath (concat
  8264. prefix (and prefix path separator)
  8265. (mapconcat
  8266. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  8267. (cl-loop for head in path
  8268. for n from 0
  8269. collect (org-add-props
  8270. head nil 'face
  8271. (nth (% n org-n-level-faces) org-level-faces)))
  8272. separator))))
  8273. (when (> (length fpath) width)
  8274. (if (< width 7)
  8275. ;; It's unlikely that `width' will be this small, but don't
  8276. ;; waste characters by adding ".." if it is.
  8277. (setq fpath (substring fpath 0 width))
  8278. (setf (substring fpath (- width 2)) "..")))
  8279. fpath))
  8280. (defun org-display-outline-path (&optional file current separator just-return-string)
  8281. "Display the current outline path in the echo area.
  8282. If FILE is non-nil, prepend the output with the file name.
  8283. If CURRENT is non-nil, append the current heading to the output.
  8284. SEPARATOR is passed through to `org-format-outline-path'. It separates
  8285. the different parts of the path and defaults to \"/\".
  8286. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  8287. (interactive "P")
  8288. (let* (case-fold-search
  8289. (bfn (buffer-file-name (buffer-base-buffer)))
  8290. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  8291. res)
  8292. (when current (setq path (append path
  8293. (save-excursion
  8294. (org-back-to-heading t)
  8295. (when (looking-at org-complex-heading-regexp)
  8296. (list (match-string 4)))))))
  8297. (setq res
  8298. (org-format-outline-path
  8299. path
  8300. (1- (frame-width))
  8301. (and file bfn (concat (file-name-nondirectory bfn) separator))
  8302. separator))
  8303. (if just-return-string
  8304. (org-no-properties res)
  8305. (org-unlogged-message "%s" res))))
  8306. (defvar org-refile-history nil
  8307. "History for refiling operations.")
  8308. (defvar org-after-refile-insert-hook nil
  8309. "Hook run after `org-refile' has inserted its stuff at the new location.
  8310. Note that this is still *before* the stuff will be removed from
  8311. the *old* location.")
  8312. (defvar org-capture-last-stored-marker)
  8313. (defvar org-refile-keep nil
  8314. "Non-nil means `org-refile' will copy instead of refile.")
  8315. (defun org-copy ()
  8316. "Like `org-refile', but copy."
  8317. (interactive)
  8318. (let ((org-refile-keep t))
  8319. (org-refile nil nil nil "Copy")))
  8320. (defun org-refile (&optional arg default-buffer rfloc msg)
  8321. "Move the entry or entries at point to another heading.
  8322. The list of target headings is compiled using the information in
  8323. `org-refile-targets', which see.
  8324. At the target location, the entry is filed as a subitem of the
  8325. target heading. Depending on `org-reverse-note-order', the new
  8326. subitem will either be the first or the last subitem.
  8327. If there is an active region, all entries in that region will be
  8328. refiled. However, the region must fulfill the requirement that
  8329. the first heading sets the top-level of the moved text.
  8330. With a `\\[universal-argument]' ARG, the command will only visit the target \
  8331. location
  8332. and not actually move anything.
  8333. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  8334. location where the last
  8335. refiling operation has put the subtree.
  8336. With a numeric prefix argument of `2', refile to the running clock.
  8337. With a numeric prefix argument of `3', emulate `org-refile-keep'
  8338. being set to t and copy to the target location, don't move it.
  8339. Beware that keeping refiled entries may result in duplicated ID
  8340. properties.
  8341. RFLOC can be a refile location obtained in a different way.
  8342. MSG is a string to replace \"Refile\" in the default prompt with
  8343. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  8344. See also `org-refile-use-outline-path'.
  8345. If you are using target caching (see `org-refile-use-cache'), you
  8346. have to clear the target cache in order to find new targets.
  8347. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  8348. prefix argument (`C-u C-u C-u C-c C-w')."
  8349. (interactive "P")
  8350. (if (member arg '(0 (64)))
  8351. (org-refile-cache-clear)
  8352. (let* ((actionmsg (cond (msg msg)
  8353. ((equal arg 3) "Refile (and keep)")
  8354. (t "Refile")))
  8355. (regionp (org-region-active-p))
  8356. (region-start (and regionp (region-beginning)))
  8357. (region-end (and regionp (region-end)))
  8358. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  8359. pos it nbuf file level reversed)
  8360. (setq last-command nil)
  8361. (when regionp
  8362. (goto-char region-start)
  8363. (beginning-of-line)
  8364. (setq region-start (point))
  8365. (unless (or (org-kill-is-subtree-p
  8366. (buffer-substring region-start region-end))
  8367. (prog1 org-refile-active-region-within-subtree
  8368. (let ((s (point-at-eol)))
  8369. (org-toggle-heading)
  8370. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  8371. (user-error "The region is not a (sequence of) subtree(s)")))
  8372. (if (equal arg '(16))
  8373. (org-refile-goto-last-stored)
  8374. (when (or
  8375. (and (equal arg 2)
  8376. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  8377. (prog1
  8378. (setq it (list (or org-clock-heading "running clock")
  8379. (buffer-file-name
  8380. (marker-buffer org-clock-hd-marker))
  8381. ""
  8382. (marker-position org-clock-hd-marker)))
  8383. (setq arg nil)))
  8384. (setq it
  8385. (or rfloc
  8386. (let (heading-text)
  8387. (save-excursion
  8388. (unless (and arg (listp arg))
  8389. (org-back-to-heading t)
  8390. (setq heading-text
  8391. (replace-regexp-in-string
  8392. org-link-bracket-re
  8393. "\\3"
  8394. (or (nth 4 (org-heading-components))
  8395. ""))))
  8396. (org-refile-get-location
  8397. (cond ((and arg (listp arg)) "Goto")
  8398. (regionp (concat actionmsg " region to"))
  8399. (t (concat actionmsg " subtree \""
  8400. heading-text "\" to")))
  8401. default-buffer
  8402. (and (not (equal '(4) arg))
  8403. org-refile-allow-creating-parent-nodes)))))))
  8404. (setq file (nth 1 it)
  8405. pos (nth 3 it))
  8406. (when (and (not arg)
  8407. pos
  8408. (equal (buffer-file-name) file)
  8409. (if regionp
  8410. (and (>= pos region-start)
  8411. (<= pos region-end))
  8412. (and (>= pos (point))
  8413. (< pos (save-excursion
  8414. (org-end-of-subtree t t))))))
  8415. (error "Cannot refile to position inside the tree or region"))
  8416. (setq nbuf (or (find-buffer-visiting file)
  8417. (find-file-noselect file)))
  8418. (if (and arg (not (equal arg 3)))
  8419. (progn
  8420. (pop-to-buffer-same-window nbuf)
  8421. (goto-char (cond (pos)
  8422. ((org-notes-order-reversed-p) (point-min))
  8423. (t (point-max))))
  8424. (org-show-context 'org-goto))
  8425. (if regionp
  8426. (progn
  8427. (org-kill-new (buffer-substring region-start region-end))
  8428. (org-save-markers-in-region region-start region-end))
  8429. (org-copy-subtree 1 nil t))
  8430. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  8431. (find-file-noselect file)))
  8432. (setq reversed (org-notes-order-reversed-p))
  8433. (org-with-wide-buffer
  8434. (if pos
  8435. (progn
  8436. (goto-char pos)
  8437. (setq level (org-get-valid-level (funcall outline-level) 1))
  8438. (goto-char
  8439. (if reversed
  8440. (or (outline-next-heading) (point-max))
  8441. (or (save-excursion (org-get-next-sibling))
  8442. (org-end-of-subtree t t)
  8443. (point-max)))))
  8444. (setq level 1)
  8445. (if (not reversed)
  8446. (goto-char (point-max))
  8447. (goto-char (point-min))
  8448. (or (outline-next-heading) (goto-char (point-max)))))
  8449. (unless (bolp) (newline))
  8450. (org-paste-subtree level nil nil t)
  8451. ;; Record information, according to `org-log-refile'.
  8452. ;; Do not prompt for a note when refiling multiple
  8453. ;; headlines, however. Simply add a time stamp.
  8454. (cond
  8455. ((not org-log-refile))
  8456. (regionp
  8457. (org-map-region
  8458. (lambda () (org-add-log-setup 'refile nil nil 'time))
  8459. (point)
  8460. (+ (point) (- region-end region-start))))
  8461. (t
  8462. (org-add-log-setup 'refile nil nil org-log-refile)))
  8463. (and org-auto-align-tags
  8464. (let ((org-loop-over-headlines-in-active-region nil))
  8465. (org-align-tags)))
  8466. (let ((bookmark-name (plist-get org-bookmark-names-plist
  8467. :last-refile)))
  8468. (when bookmark-name
  8469. (with-demoted-errors
  8470. (bookmark-set bookmark-name))))
  8471. ;; If we are refiling for capture, make sure that the
  8472. ;; last-capture pointers point here
  8473. (when (bound-and-true-p org-capture-is-refiling)
  8474. (let ((bookmark-name (plist-get org-bookmark-names-plist
  8475. :last-capture-marker)))
  8476. (when bookmark-name
  8477. (with-demoted-errors
  8478. (bookmark-set bookmark-name))))
  8479. (move-marker org-capture-last-stored-marker (point)))
  8480. (when (fboundp 'deactivate-mark) (deactivate-mark))
  8481. (run-hooks 'org-after-refile-insert-hook)))
  8482. (unless org-refile-keep
  8483. (if regionp
  8484. (delete-region (point) (+ (point) (- region-end region-start)))
  8485. (org-preserve-local-variables
  8486. (delete-region
  8487. (and (org-back-to-heading t) (point))
  8488. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
  8489. (when (featurep 'org-inlinetask)
  8490. (org-inlinetask-remove-END-maybe))
  8491. (setq org-markers-to-move nil)
  8492. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  8493. (defun org-refile-goto-last-stored ()
  8494. "Go to the location where the last refile was stored."
  8495. (interactive)
  8496. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  8497. (message "This is the location of the last refile"))
  8498. (defun org-refile--get-location (refloc tbl)
  8499. "When user refile to REFLOC, find the associated target in TBL.
  8500. Also check `org-refile-target-table'."
  8501. (car (delq
  8502. nil
  8503. (mapcar
  8504. (lambda (r) (or (assoc r tbl)
  8505. (assoc r org-refile-target-table)))
  8506. (list (replace-regexp-in-string "/$" "" refloc)
  8507. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  8508. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  8509. "Prompt the user for a refile location, using PROMPT.
  8510. PROMPT should not be suffixed with a colon and a space, because
  8511. this function appends the default value from
  8512. `org-refile-history' automatically, if that is not empty."
  8513. (let ((org-refile-targets org-refile-targets)
  8514. (org-refile-use-outline-path org-refile-use-outline-path))
  8515. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  8516. (unless org-refile-target-table
  8517. (user-error "No refile targets"))
  8518. (let* ((cbuf (current-buffer))
  8519. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  8520. (cfunc (if (and org-refile-use-outline-path
  8521. org-outline-path-complete-in-steps)
  8522. #'org-olpath-completing-read
  8523. #'completing-read))
  8524. (extra (if org-refile-use-outline-path "/" ""))
  8525. (cbnex (concat (buffer-name) extra))
  8526. (filename (and cfn (expand-file-name cfn)))
  8527. (tbl (mapcar
  8528. (lambda (x)
  8529. (if (and (not (member org-refile-use-outline-path
  8530. '(file full-file-path)))
  8531. (not (equal filename (nth 1 x))))
  8532. (cons (concat (car x) extra " ("
  8533. (file-name-nondirectory (nth 1 x)) ")")
  8534. (cdr x))
  8535. (cons (concat (car x) extra) (cdr x))))
  8536. org-refile-target-table))
  8537. (completion-ignore-case t)
  8538. cdef
  8539. (prompt (concat prompt
  8540. (or (and (car org-refile-history)
  8541. (concat " (default " (car org-refile-history) ")"))
  8542. (and (assoc cbnex tbl) (setq cdef cbnex)
  8543. (concat " (default " cbnex ")"))) ": "))
  8544. pa answ parent-target child parent old-hist)
  8545. (setq old-hist org-refile-history)
  8546. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  8547. nil 'org-refile-history (or cdef (car org-refile-history))))
  8548. (if (setq pa (org-refile--get-location answ tbl))
  8549. (progn
  8550. (org-refile-check-position pa)
  8551. (when (or (not org-refile-history)
  8552. (not (eq old-hist org-refile-history))
  8553. (not (equal (car pa) (car org-refile-history))))
  8554. (setq org-refile-history
  8555. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  8556. org-refile-history
  8557. (cdr org-refile-history))))
  8558. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  8559. (pop org-refile-history)))
  8560. pa)
  8561. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  8562. (progn
  8563. (setq parent (match-string 1 answ)
  8564. child (match-string 2 answ))
  8565. (setq parent-target (org-refile--get-location parent tbl))
  8566. (when (and parent-target
  8567. (or (eq new-nodes t)
  8568. (and (eq new-nodes 'confirm)
  8569. (y-or-n-p (format "Create new node \"%s\"? "
  8570. child)))))
  8571. (org-refile-new-child parent-target child)))
  8572. (user-error "Invalid target location")))))
  8573. (declare-function org-string-nw-p "org-macs" (s))
  8574. (defun org-refile-check-position (refile-pointer)
  8575. "Check if the refile pointer matches the headline to which it points."
  8576. (let* ((file (nth 1 refile-pointer))
  8577. (re (nth 2 refile-pointer))
  8578. (pos (nth 3 refile-pointer))
  8579. buffer)
  8580. (if (and (not (markerp pos)) (not file))
  8581. (user-error "Please indicate a target file in the refile path")
  8582. (when (org-string-nw-p re)
  8583. (setq buffer (if (markerp pos)
  8584. (marker-buffer pos)
  8585. (or (find-buffer-visiting file)
  8586. (find-file-noselect file))))
  8587. (with-current-buffer buffer
  8588. (org-with-wide-buffer
  8589. (goto-char pos)
  8590. (beginning-of-line 1)
  8591. (unless (looking-at-p re)
  8592. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  8593. (defun org-refile-new-child (parent-target child)
  8594. "Use refile target PARENT-TARGET to add new CHILD below it."
  8595. (unless parent-target
  8596. (error "Cannot find parent for new node"))
  8597. (let ((file (nth 1 parent-target))
  8598. (pos (nth 3 parent-target))
  8599. level)
  8600. (with-current-buffer (or (find-buffer-visiting file)
  8601. (find-file-noselect file))
  8602. (org-with-wide-buffer
  8603. (if pos
  8604. (goto-char pos)
  8605. (goto-char (point-max))
  8606. (unless (bolp) (newline)))
  8607. (when (looking-at org-outline-regexp)
  8608. (setq level (funcall outline-level))
  8609. (org-end-of-subtree t t))
  8610. (org-back-over-empty-lines)
  8611. (insert "\n" (make-string
  8612. (if pos (org-get-valid-level level 1) 1) ?*)
  8613. " " child "\n")
  8614. (beginning-of-line 0)
  8615. (list (concat (car parent-target) "/" child) file "" (point))))))
  8616. (defun org-olpath-completing-read (prompt collection &rest args)
  8617. "Read an outline path like a file name."
  8618. (let ((thetable collection))
  8619. (apply #'completing-read
  8620. prompt
  8621. (lambda (string predicate &optional flag)
  8622. (cond
  8623. ((eq flag nil) (try-completion string thetable))
  8624. ((eq flag t)
  8625. (let ((l (length string)))
  8626. (mapcar (lambda (x)
  8627. (let ((r (substring x l))
  8628. (f (if (string-match " ([^)]*)$" x)
  8629. (match-string 0 x)
  8630. "")))
  8631. (if (string-match "/" r)
  8632. (concat string (substring r 0 (match-end 0)) f)
  8633. x)))
  8634. (all-completions string thetable predicate))))
  8635. ;; Exact match?
  8636. ((eq flag 'lambda) (assoc string thetable))))
  8637. args)))
  8638. ;;;; Dynamic blocks
  8639. (defun org-find-dblock (name)
  8640. "Find the first dynamic block with name NAME in the buffer.
  8641. If not found, stay at current position and return nil."
  8642. (let ((case-fold-search t) pos)
  8643. (save-excursion
  8644. (goto-char (point-min))
  8645. (setq pos (and (re-search-forward
  8646. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  8647. (match-beginning 0))))
  8648. (when pos (goto-char pos))
  8649. pos))
  8650. (defun org-create-dblock (plist)
  8651. "Create a dynamic block section, with parameters taken from PLIST.
  8652. PLIST must contain a :name entry which is used as the name of the block."
  8653. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  8654. (end-of-line 1)
  8655. (newline))
  8656. (let ((col (current-column))
  8657. (name (plist-get plist :name)))
  8658. (insert "#+BEGIN: " name)
  8659. (while plist
  8660. (if (eq (car plist) :name)
  8661. (setq plist (cddr plist))
  8662. (insert " " (prin1-to-string (pop plist)))))
  8663. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  8664. (beginning-of-line -2)))
  8665. (defun org-prepare-dblock ()
  8666. "Prepare dynamic block for refresh.
  8667. This empties the block, puts the cursor at the insert position and returns
  8668. the property list including an extra property :name with the block name."
  8669. (unless (looking-at org-dblock-start-re)
  8670. (user-error "Not at a dynamic block"))
  8671. (let* ((begdel (1+ (match-end 0)))
  8672. (name (org-no-properties (match-string 1)))
  8673. (params (append (list :name name)
  8674. (read (concat "(" (match-string 3) ")")))))
  8675. (save-excursion
  8676. (beginning-of-line 1)
  8677. (skip-chars-forward " \t")
  8678. (setq params (plist-put params :indentation-column (current-column))))
  8679. (unless (re-search-forward org-dblock-end-re nil t)
  8680. (error "Dynamic block not terminated"))
  8681. (setq params
  8682. (append params
  8683. (list :content (buffer-substring
  8684. begdel (match-beginning 0)))))
  8685. (delete-region begdel (match-beginning 0))
  8686. (goto-char begdel)
  8687. (open-line 1)
  8688. params))
  8689. (defun org-map-dblocks (&optional command)
  8690. "Apply COMMAND to all dynamic blocks in the current buffer.
  8691. If COMMAND is not given, use `org-update-dblock'."
  8692. (let ((cmd (or command 'org-update-dblock)))
  8693. (save-excursion
  8694. (goto-char (point-min))
  8695. (while (re-search-forward org-dblock-start-re nil t)
  8696. (goto-char (match-beginning 0))
  8697. (save-excursion
  8698. (condition-case nil
  8699. (funcall cmd)
  8700. (error (message "Error during update of dynamic block"))))
  8701. (unless (re-search-forward org-dblock-end-re nil t)
  8702. (error "Dynamic block not terminated"))))))
  8703. (defcustom org-dynamic-block-alist nil
  8704. "Alist defining all the Org dynamic blocks.
  8705. The key is the dynamic block type name, as a string. The value
  8706. is the function used to insert the dynamic block."
  8707. :group 'org-block
  8708. :package-version '(Org . "9.3")
  8709. :type '(alist :tag "Dynamic block name"
  8710. :key-type string
  8711. :value-type function)
  8712. :safe #'listp)
  8713. (defun org-dynamic-block-function (type)
  8714. "Return function associated to a given dynamic block type.
  8715. TYPE is the dynamic block type, as a string."
  8716. (cdr (assoc type org-dynamic-block-alist)))
  8717. (defun org-dynamic-block-types ()
  8718. "List all defined dynamic block types."
  8719. (mapcar #'car org-dynamic-block-alist))
  8720. (defun org-dynamic-block-define (type func)
  8721. "Define dynamic block TYPE with FUNC."
  8722. (push (cons type func) org-dynamic-block-alist))
  8723. (defun org-dynamic-block-insert-dblock (type)
  8724. "Insert a dynamic block of type TYPE.
  8725. When used interactively, select the dynamic block types among
  8726. defined types, per `org-dynamic-block-define'."
  8727. (interactive (list (completing-read "Dynamic block: "
  8728. (org-dynamic-block-types))))
  8729. (pcase (org-dynamic-block-function type)
  8730. (`nil (error "No such dynamic block: %S" type))
  8731. ((and f (pred functionp)) (funcall f))
  8732. (_ (error "Invalid function for dynamic block %S" type))))
  8733. (defun org-dblock-update (&optional arg)
  8734. "User command for updating dynamic blocks.
  8735. Update the dynamic block at point. With prefix ARG, update all dynamic
  8736. blocks in the buffer."
  8737. (interactive "P")
  8738. (if arg
  8739. (org-update-all-dblocks)
  8740. (or (looking-at org-dblock-start-re)
  8741. (org-beginning-of-dblock))
  8742. (org-update-dblock)))
  8743. (defun org-update-dblock ()
  8744. "Update the dynamic block at point.
  8745. This means to empty the block, parse for parameters and then call
  8746. the correct writing function."
  8747. (interactive)
  8748. (save-excursion
  8749. (let* ((win (selected-window))
  8750. (pos (point))
  8751. (line (org-current-line))
  8752. (params (org-prepare-dblock))
  8753. (name (plist-get params :name))
  8754. (indent (plist-get params :indentation-column))
  8755. (cmd (intern (concat "org-dblock-write:" name))))
  8756. (message "Updating dynamic block `%s' at line %d..." name line)
  8757. (funcall cmd params)
  8758. (message "Updating dynamic block `%s' at line %d...done" name line)
  8759. (goto-char pos)
  8760. (when (and indent (> indent 0))
  8761. (setq indent (make-string indent ?\ ))
  8762. (save-excursion
  8763. (select-window win)
  8764. (org-beginning-of-dblock)
  8765. (forward-line 1)
  8766. (while (not (looking-at org-dblock-end-re))
  8767. (insert indent)
  8768. (beginning-of-line 2))
  8769. (when (looking-at org-dblock-end-re)
  8770. (and (looking-at "[ \t]+")
  8771. (replace-match ""))
  8772. (insert indent)))))))
  8773. (defun org-beginning-of-dblock ()
  8774. "Find the beginning of the dynamic block at point.
  8775. Error if there is no such block at point."
  8776. (let ((pos (point))
  8777. beg)
  8778. (end-of-line 1)
  8779. (if (and (re-search-backward org-dblock-start-re nil t)
  8780. (setq beg (match-beginning 0))
  8781. (re-search-forward org-dblock-end-re nil t)
  8782. (> (match-end 0) pos))
  8783. (goto-char beg)
  8784. (goto-char pos)
  8785. (error "Not in a dynamic block"))))
  8786. (defun org-update-all-dblocks ()
  8787. "Update all dynamic blocks in the buffer.
  8788. This function can be used in a hook."
  8789. (interactive)
  8790. (when (derived-mode-p 'org-mode)
  8791. (org-map-dblocks 'org-update-dblock)))
  8792. ;;;; Completion
  8793. (declare-function org-export-backend-options "ox" (cl-x) t)
  8794. (defun org-get-export-keywords ()
  8795. "Return a list of all currently understood export keywords.
  8796. Export keywords include options, block names, attributes and
  8797. keywords relative to each registered export back-end."
  8798. (let (keywords)
  8799. (dolist (backend
  8800. (bound-and-true-p org-export-registered-backends)
  8801. (delq nil keywords))
  8802. ;; Back-end name (for keywords, like #+LATEX:)
  8803. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  8804. (dolist (option-entry (org-export-backend-options backend))
  8805. ;; Back-end options.
  8806. (push (nth 1 option-entry) keywords)))))
  8807. (defconst org-options-keywords
  8808. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  8809. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  8810. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  8811. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  8812. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  8813. (defcustom org-structure-template-alist
  8814. '(("a" . "export ascii")
  8815. ("c" . "center")
  8816. ("C" . "comment")
  8817. ("e" . "example")
  8818. ("E" . "export")
  8819. ("h" . "export html")
  8820. ("l" . "export latex")
  8821. ("q" . "quote")
  8822. ("s" . "src")
  8823. ("v" . "verse"))
  8824. "An alist of keys and block types.
  8825. `org-insert-structure-template' will display a menu with this
  8826. list of templates to choose from. The block type is inserted,
  8827. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  8828. The menu keys are defined by the car of each entry in this alist.
  8829. If two entries have the keys \"a\" and \"aa\" respectively, the
  8830. former will be inserted by typing \"a TAB/RET/SPC\" and the
  8831. latter will be inserted by typing \"aa\". If an entry with the
  8832. key \"aab\" is later added, it can be inserted by typing \"ab\".
  8833. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  8834. block can be inserted by pressing TAB after the string \"<KEY\"."
  8835. :group 'org-edit-structure
  8836. :type '(repeat
  8837. (cons (string :tag "Key")
  8838. (string :tag "Template")))
  8839. :package-version '(Org . "9.2"))
  8840. (defun org--check-org-structure-template-alist (&optional checklist)
  8841. "Check whether `org-structure-template-alist' is set up correctly.
  8842. In particular, check if the Org 9.2 format is used as opposed to
  8843. previous format.
  8844. "
  8845. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  8846. (or (eval checklist)
  8847. org-structure-template-alist))))
  8848. (when elm
  8849. (org-display-warning
  8850. (format "
  8851. Please update the entries of `%s'.
  8852. In Org 9.2 the format was changed from something like
  8853. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  8854. to something like
  8855. (\"s\" . \"src\")
  8856. Please refer to the documentation of `org-structure-template-alist'.
  8857. The following entries must be updated:
  8858. %s"
  8859. (or checklist 'org-structure-template-alist)
  8860. (pp-to-string elm))))))
  8861. (defun org--insert-structure-template-mks ()
  8862. "Present `org-structure-template-alist' with `org-mks'.
  8863. Menus are added if keys require more than one keystroke. Tabs
  8864. are added to single key entries when more than one stroke is
  8865. needed. Keys longer than two characters are reduced to two
  8866. characters."
  8867. (org--check-org-structure-template-alist)
  8868. (let* (case-fold-search
  8869. (templates (append org-structure-template-alist
  8870. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  8871. (keys (mapcar #'car templates))
  8872. (start-letters
  8873. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  8874. ;; Sort each element of `org-structure-template-alist' into
  8875. ;; sublists according to the first letter.
  8876. (superlist
  8877. (mapcar (lambda (letter)
  8878. (list letter
  8879. (cl-remove-if-not
  8880. (apply-partially #'string-match-p (concat "^" letter))
  8881. templates :key #'car)))
  8882. start-letters)))
  8883. (org-mks
  8884. (apply #'append
  8885. ;; Make an `org-mks' table. If only one element is
  8886. ;; present in a sublist, make it part of the top-menu,
  8887. ;; otherwise make a submenu according to the starting
  8888. ;; letter and populate it.
  8889. (mapcar (lambda (sublist)
  8890. (if (eq 1 (length (cadr sublist)))
  8891. (mapcar (lambda (elm)
  8892. (list (substring (car elm) 0 1)
  8893. (cdr elm) ""))
  8894. (cadr sublist))
  8895. ;; Create submenu.
  8896. (let* ((topkey (car sublist))
  8897. (elms (cadr sublist))
  8898. (keys (mapcar #'car elms))
  8899. (long (> (length elms) 3)))
  8900. (append
  8901. (list
  8902. ;; Make a description of the submenu.
  8903. (list topkey
  8904. (concat
  8905. (mapconcat #'cdr
  8906. (cl-subseq elms 0 (if long 3 (length elms)))
  8907. ", ")
  8908. (when long ", ..."))))
  8909. ;; List of entries in submenu.
  8910. (cl-mapcar #'list
  8911. (org--insert-structure-template-unique-keys keys)
  8912. (mapcar #'cdr elms)
  8913. (make-list (length elms) ""))))))
  8914. superlist))
  8915. "Select a key\n============"
  8916. "Key: ")))
  8917. (defun org--insert-structure-template-unique-keys (keys)
  8918. "Make a list of unique, two characters long elements from KEYS.
  8919. Elements of length one have a tab appended. Elements of length
  8920. two are kept as is. Longer elements are truncated to length two.
  8921. If an element cannot be made unique, an error is raised."
  8922. (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  8923. menu-keys)
  8924. (dolist (key orderd-keys)
  8925. (let ((potential-key
  8926. (cl-case (length key)
  8927. (1 (concat key "\t"))
  8928. (2 key)
  8929. (otherwise
  8930. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  8931. (mapcar (apply-partially #'concat (substring key 0 1))
  8932. (split-string (substring key 1) "" t)))))))
  8933. (if (or (not potential-key) (assoc potential-key menu-keys))
  8934. (user-error "Could not make unique key for %s." key)
  8935. (push (cons potential-key key) menu-keys))))
  8936. (mapcar #'car
  8937. (cl-sort menu-keys #'<
  8938. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8939. (defun org-insert-structure-template (type)
  8940. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8941. Select a block from `org-structure-template-alist' then type
  8942. either RET, TAB or SPC to write the block type. With an active
  8943. region, wrap the region in the block. Otherwise, insert an empty
  8944. block."
  8945. (interactive
  8946. (list (pcase (org--insert-structure-template-mks)
  8947. (`("\t" . ,_) (read-string "Structure type: "))
  8948. (`(,_ ,choice . ,_) choice))))
  8949. (let* ((region? (use-region-p))
  8950. (region-start (and region? (region-beginning)))
  8951. (region-end (and region? (copy-marker (region-end))))
  8952. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8953. (verbatim? (string-match-p
  8954. (concat "\\`" (regexp-opt '("example" "export" "src")))
  8955. type)))
  8956. (when region? (goto-char region-start))
  8957. (let ((column (current-indentation)))
  8958. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8959. (beginning-of-line)
  8960. (insert "\n"))
  8961. (save-excursion
  8962. (indent-to column)
  8963. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  8964. (when region?
  8965. (when verbatim? (org-escape-code-in-region (point) region-end))
  8966. (goto-char region-end)
  8967. ;; Ignore empty lines at the end of the region.
  8968. (skip-chars-backward " \r\t\n")
  8969. (end-of-line))
  8970. (unless (bolp) (insert "\n"))
  8971. (indent-to column)
  8972. (insert (format "#+end_%s" (car (split-string type))))
  8973. (if (looking-at "[ \t]*$") (replace-match "")
  8974. (insert "\n"))
  8975. (when (and (eobp) (not (bolp))) (insert "\n")))
  8976. (if extended? (end-of-line)
  8977. (forward-line)
  8978. (skip-chars-forward " \t")))))
  8979. ;;;; TODO, DEADLINE, Comments
  8980. (defun org-toggle-comment ()
  8981. "Change the COMMENT state of an entry."
  8982. (interactive)
  8983. (save-excursion
  8984. (org-back-to-heading)
  8985. (let ((case-fold-search nil))
  8986. (looking-at org-complex-heading-regexp))
  8987. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8988. (skip-chars-forward " \t")
  8989. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8990. (if (org-in-commented-heading-p t)
  8991. (delete-region (point)
  8992. (progn (search-forward " " (line-end-position) 'move)
  8993. (skip-chars-forward " \t")
  8994. (point)))
  8995. (insert org-comment-string)
  8996. (unless (eolp) (insert " ")))))
  8997. (defvar org-last-todo-state-is-todo nil
  8998. "This is non-nil when the last TODO state change led to a TODO state.
  8999. If the last change removed the TODO tag or switched to DONE, then
  9000. this is nil.")
  9001. (defvar org-todo-setup-filter-hook nil
  9002. "Hook for functions that pre-filter todo specs.
  9003. Each function takes a todo spec and returns either nil or the spec
  9004. transformed into canonical form." )
  9005. (defvar org-todo-get-default-hook nil
  9006. "Hook for functions that get a default item for todo.
  9007. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  9008. nil or a string to be used for the todo mark." )
  9009. (defvar org-agenda-headline-snapshot-before-repeat)
  9010. (defun org-current-effective-time ()
  9011. "Return current time adjusted for `org-extend-today-until' variable."
  9012. (let* ((ct (org-current-time))
  9013. (dct (decode-time ct))
  9014. (ct1
  9015. (cond
  9016. (org-use-last-clock-out-time-as-effective-time
  9017. (or (org-clock-get-last-clock-out-time) ct))
  9018. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  9019. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  9020. (t ct))))
  9021. ct1))
  9022. (defun org-todo-yesterday (&optional arg)
  9023. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  9024. (interactive "P")
  9025. (if (eq major-mode 'org-agenda-mode)
  9026. (apply 'org-agenda-todo-yesterday arg)
  9027. (let* ((org-use-effective-time t)
  9028. (hour (nth 2 (decode-time (org-current-time))))
  9029. (org-extend-today-until (1+ hour)))
  9030. (org-todo arg))))
  9031. (defvar org-block-entry-blocking ""
  9032. "First entry preventing the TODO state change.")
  9033. (defun org-cancel-repeater ()
  9034. "Cancel a repeater by setting its numeric value to zero."
  9035. (interactive)
  9036. (save-excursion
  9037. (org-back-to-heading t)
  9038. (let ((bound1 (point))
  9039. (bound0 (save-excursion (outline-next-heading) (point))))
  9040. (when (and (re-search-forward
  9041. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  9042. org-deadline-time-regexp "\\)\\|\\("
  9043. org-ts-regexp "\\)")
  9044. bound0 t)
  9045. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  9046. bound1 t))
  9047. (replace-match "0" t nil nil 1)))))
  9048. (defvar org-state)
  9049. (defvar org-blocked-by-checkboxes)
  9050. (defun org-todo (&optional arg)
  9051. "Change the TODO state of an item.
  9052. The state of an item is given by a keyword at the start of the heading,
  9053. like
  9054. *** TODO Write paper
  9055. *** DONE Call mom
  9056. The different keywords are specified in the variable `org-todo-keywords'.
  9057. By default the available states are \"TODO\" and \"DONE\". So, for this
  9058. example: when the item starts with TODO, it is changed to DONE.
  9059. When it starts with DONE, the DONE is removed. And when neither TODO nor
  9060. DONE are present, add TODO at the beginning of the heading.
  9061. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  9062. state.
  9063. With numeric prefix ARG, switch to that state.
  9064. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  9065. next set of TODO \
  9066. keywords (nextset).
  9067. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  9068. prefix, circumvent any state blocking.
  9069. With a numeric prefix arg of 0, inhibit note taking for the change.
  9070. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  9071. When called through ELisp, arg is also interpreted in the following way:
  9072. `none' -> empty state
  9073. \"\" -> switch to empty state
  9074. `done' -> switch to DONE
  9075. `nextset' -> switch to the next set of keywords
  9076. `previousset' -> switch to the previous set of keywords
  9077. \"WAITING\" -> switch to the specified keyword, but only if it
  9078. really is a member of `org-todo-keywords'."
  9079. (interactive "P")
  9080. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9081. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9082. 'region-start-level 'region))
  9083. org-loop-over-headlines-in-active-region)
  9084. (org-map-entries
  9085. `(org-todo ,arg)
  9086. org-loop-over-headlines-in-active-region
  9087. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  9088. (when (equal arg '(16)) (setq arg 'nextset))
  9089. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  9090. (let ((org-blocker-hook org-blocker-hook)
  9091. commentp
  9092. case-fold-search)
  9093. (when (equal arg '(64))
  9094. (setq arg nil org-blocker-hook nil))
  9095. (when (and org-blocker-hook
  9096. (or org-inhibit-blocking
  9097. (org-entry-get nil "NOBLOCKING")))
  9098. (setq org-blocker-hook nil))
  9099. (save-excursion
  9100. (catch 'exit
  9101. (org-back-to-heading t)
  9102. (when (org-in-commented-heading-p t)
  9103. (org-toggle-comment)
  9104. (setq commentp t))
  9105. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  9106. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  9107. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  9108. (let* ((match-data (match-data))
  9109. (startpos (copy-marker (line-beginning-position)))
  9110. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  9111. (org-log-done org-log-done)
  9112. (org-log-repeat org-log-repeat)
  9113. (org-todo-log-states org-todo-log-states)
  9114. (org-inhibit-logging
  9115. (if (equal arg 0)
  9116. (progn (setq arg nil) 'note) org-inhibit-logging))
  9117. (this (match-string 1))
  9118. (hl-pos (match-beginning 0))
  9119. (head (org-get-todo-sequence-head this))
  9120. (ass (assoc head org-todo-kwd-alist))
  9121. (interpret (nth 1 ass))
  9122. (done-word (nth 3 ass))
  9123. (final-done-word (nth 4 ass))
  9124. (org-last-state (or this ""))
  9125. (completion-ignore-case t)
  9126. (member (member this org-todo-keywords-1))
  9127. (tail (cdr member))
  9128. (org-state (cond
  9129. ((and org-todo-key-trigger
  9130. (or (and (equal arg '(4))
  9131. (eq org-use-fast-todo-selection 'prefix))
  9132. (and (not arg) org-use-fast-todo-selection
  9133. (not (eq org-use-fast-todo-selection
  9134. 'prefix)))))
  9135. ;; Use fast selection.
  9136. (org-fast-todo-selection))
  9137. ((and (equal arg '(4))
  9138. (or (not org-use-fast-todo-selection)
  9139. (not org-todo-key-trigger)))
  9140. ;; Read a state with completion.
  9141. (completing-read
  9142. "State: " (mapcar #'list org-todo-keywords-1)
  9143. nil t))
  9144. ((eq arg 'right)
  9145. (if this
  9146. (if tail (car tail) nil)
  9147. (car org-todo-keywords-1)))
  9148. ((eq arg 'left)
  9149. (unless (equal member org-todo-keywords-1)
  9150. (if this
  9151. (nth (- (length org-todo-keywords-1)
  9152. (length tail) 2)
  9153. org-todo-keywords-1)
  9154. (org-last org-todo-keywords-1))))
  9155. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  9156. (setq arg nil))) ;hack to fall back to cycling
  9157. (arg
  9158. ;; User or caller requests a specific state.
  9159. (cond
  9160. ((equal arg "") nil)
  9161. ((eq arg 'none) nil)
  9162. ((eq arg 'done) (or done-word (car org-done-keywords)))
  9163. ((eq arg 'nextset)
  9164. (or (car (cdr (member head org-todo-heads)))
  9165. (car org-todo-heads)))
  9166. ((eq arg 'previousset)
  9167. (let ((org-todo-heads (reverse org-todo-heads)))
  9168. (or (car (cdr (member head org-todo-heads)))
  9169. (car org-todo-heads))))
  9170. ((car (member arg org-todo-keywords-1)))
  9171. ((stringp arg)
  9172. (user-error "State `%s' not valid in this file" arg))
  9173. ((nth (1- (prefix-numeric-value arg))
  9174. org-todo-keywords-1))))
  9175. ((null member) (or head (car org-todo-keywords-1)))
  9176. ((equal this final-done-word) nil) ;-> make empty
  9177. ((null tail) nil) ;-> first entry
  9178. ((memq interpret '(type priority))
  9179. (if (eq this-command last-command)
  9180. (car tail)
  9181. (if (> (length tail) 0)
  9182. (or done-word (car org-done-keywords))
  9183. nil)))
  9184. (t
  9185. (car tail))))
  9186. (org-state (or
  9187. (run-hook-with-args-until-success
  9188. 'org-todo-get-default-hook org-state org-last-state)
  9189. org-state))
  9190. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  9191. (change-plist (list :type 'todo-state-change :from this :to org-state
  9192. :position startpos))
  9193. dolog now-done-p)
  9194. (when org-blocker-hook
  9195. (let (org-blocked-by-checkboxes block-reason)
  9196. (setq org-last-todo-state-is-todo
  9197. (not (member this org-done-keywords)))
  9198. (unless (save-excursion
  9199. (save-match-data
  9200. (org-with-wide-buffer
  9201. (run-hook-with-args-until-failure
  9202. 'org-blocker-hook change-plist))))
  9203. (setq block-reason (if org-blocked-by-checkboxes
  9204. "contained checkboxes"
  9205. (format "\"%s\"" org-block-entry-blocking)))
  9206. (if (called-interactively-p 'interactive)
  9207. (user-error "TODO state change from %s to %s blocked (by %s)"
  9208. this org-state block-reason)
  9209. ;; Fail silently.
  9210. (message "TODO state change from %s to %s blocked (by %s)"
  9211. this org-state block-reason)
  9212. (throw 'exit nil)))))
  9213. (store-match-data match-data)
  9214. (replace-match next t t)
  9215. (cond ((equal this org-state)
  9216. (message "TODO state was already %s" (org-trim next)))
  9217. ((not (pos-visible-in-window-p hl-pos))
  9218. (message "TODO state changed to %s" (org-trim next))))
  9219. (unless head
  9220. (setq head (org-get-todo-sequence-head org-state)
  9221. ass (assoc head org-todo-kwd-alist)
  9222. interpret (nth 1 ass)
  9223. done-word (nth 3 ass)
  9224. final-done-word (nth 4 ass)))
  9225. (when (memq arg '(nextset previousset))
  9226. (message "Keyword-Set %d/%d: %s"
  9227. (- (length org-todo-sets) -1
  9228. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  9229. (length org-todo-sets)
  9230. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  9231. (setq org-last-todo-state-is-todo
  9232. (not (member org-state org-done-keywords)))
  9233. (setq now-done-p (and (member org-state org-done-keywords)
  9234. (not (member this org-done-keywords))))
  9235. (and logging (org-local-logging logging))
  9236. (when (and (or org-todo-log-states org-log-done)
  9237. (not (eq org-inhibit-logging t))
  9238. (not (memq arg '(nextset previousset))))
  9239. ;; We need to look at recording a time and note.
  9240. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  9241. (nth 2 (assoc this org-todo-log-states))))
  9242. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  9243. (setq dolog 'time))
  9244. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  9245. (and org-state
  9246. (member org-state org-not-done-keywords)
  9247. (not (member this org-not-done-keywords))))
  9248. ;; This is now a todo state and was not one before
  9249. ;; If there was a CLOSED time stamp, get rid of it.
  9250. (org-add-planning-info nil nil 'closed))
  9251. (when (and now-done-p org-log-done)
  9252. ;; It is now done, and it was not done before.
  9253. (org-add-planning-info 'closed (org-current-effective-time))
  9254. (when (and (not dolog) (eq 'note org-log-done))
  9255. (org-add-log-setup 'done org-state this 'note)))
  9256. (when (and org-state dolog)
  9257. ;; This is a non-nil state, and we need to log it.
  9258. (org-add-log-setup 'state org-state this dolog)))
  9259. ;; Fixup tag positioning.
  9260. (org-todo-trigger-tag-changes org-state)
  9261. (when org-auto-align-tags (org-align-tags))
  9262. (when org-provide-todo-statistics
  9263. (org-update-parent-todo-statistics))
  9264. (when (bound-and-true-p org-clock-out-when-done)
  9265. (org-clock-out-if-current))
  9266. (run-hooks 'org-after-todo-state-change-hook)
  9267. (when (and arg (not (member org-state org-done-keywords)))
  9268. (setq head (org-get-todo-sequence-head org-state)))
  9269. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  9270. ;; Do we need to trigger a repeat?
  9271. (when now-done-p
  9272. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  9273. ;; This is for the agenda, take a snapshot of the headline.
  9274. (save-match-data
  9275. (setq org-agenda-headline-snapshot-before-repeat
  9276. (org-get-heading))))
  9277. (org-auto-repeat-maybe org-state))
  9278. ;; Fixup cursor location if close to the keyword.
  9279. (when (and (outline-on-heading-p)
  9280. (not (bolp))
  9281. (save-excursion (beginning-of-line 1)
  9282. (looking-at org-todo-line-regexp))
  9283. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  9284. (goto-char (or (match-end 2) (match-end 1)))
  9285. (and (looking-at " ") (just-one-space)))
  9286. (when org-trigger-hook
  9287. (save-excursion
  9288. (run-hook-with-args 'org-trigger-hook change-plist)))
  9289. (when commentp (org-toggle-comment))))))))
  9290. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  9291. "Block turning an entry into a TODO, using the hierarchy.
  9292. This checks whether the current task should be blocked from state
  9293. changes. Such blocking occurs when:
  9294. 1. The task has children which are not all in a completed state.
  9295. 2. A task has a parent with the property :ORDERED:, and there
  9296. are siblings prior to the current task with incomplete
  9297. status.
  9298. 3. The parent of the task is blocked because it has siblings that should
  9299. be done first, or is child of a block grandparent TODO entry."
  9300. (if (not org-enforce-todo-dependencies)
  9301. t ; if locally turned off don't block
  9302. (catch 'dont-block
  9303. ;; If this is not a todo state change, or if this entry is already DONE,
  9304. ;; do not block
  9305. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  9306. (member (plist-get change-plist :from)
  9307. (cons 'done org-done-keywords))
  9308. (member (plist-get change-plist :to)
  9309. (cons 'todo org-not-done-keywords))
  9310. (not (plist-get change-plist :to)))
  9311. (throw 'dont-block t))
  9312. ;; If this task has children, and any are undone, it's blocked
  9313. (save-excursion
  9314. (org-back-to-heading t)
  9315. (let ((this-level (funcall outline-level)))
  9316. (outline-next-heading)
  9317. (let ((child-level (funcall outline-level)))
  9318. (while (and (not (eobp))
  9319. (> child-level this-level))
  9320. ;; this todo has children, check whether they are all
  9321. ;; completed
  9322. (when (and (not (org-entry-is-done-p))
  9323. (org-entry-is-todo-p))
  9324. (setq org-block-entry-blocking (org-get-heading))
  9325. (throw 'dont-block nil))
  9326. (outline-next-heading)
  9327. (setq child-level (funcall outline-level))))))
  9328. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  9329. ;; any previous siblings are undone, it's blocked
  9330. (save-excursion
  9331. (org-back-to-heading t)
  9332. (let* ((pos (point))
  9333. (parent-pos (and (org-up-heading-safe) (point)))
  9334. (case-fold-search nil))
  9335. (unless parent-pos (throw 'dont-block t)) ; no parent
  9336. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  9337. (forward-line 1)
  9338. (re-search-forward org-not-done-heading-regexp pos t))
  9339. (setq org-block-entry-blocking (match-string 0))
  9340. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  9341. ;; Search further up the hierarchy, to see if an ancestor is blocked
  9342. (while t
  9343. (goto-char parent-pos)
  9344. (unless (looking-at org-not-done-heading-regexp)
  9345. (throw 'dont-block t)) ; do not block, parent is not a TODO
  9346. (setq pos (point))
  9347. (setq parent-pos (and (org-up-heading-safe) (point)))
  9348. (unless parent-pos (throw 'dont-block t)) ; no parent
  9349. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  9350. (forward-line 1)
  9351. (re-search-forward org-not-done-heading-regexp pos t)
  9352. (setq org-block-entry-blocking (org-get-heading)))
  9353. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  9354. (defcustom org-track-ordered-property-with-tag nil
  9355. "Should the ORDERED property also be shown as a tag?
  9356. The ORDERED property decides if an entry should require subtasks to be
  9357. completed in sequence. Since a property is not very visible, setting
  9358. this option means that toggling the ORDERED property with the command
  9359. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  9360. not relevant for the behavior, but it makes things more visible.
  9361. Note that toggling the tag with tags commands will not change the property
  9362. and therefore not influence behavior!
  9363. This can be t, meaning the tag ORDERED should be used, It can also be a
  9364. string to select a different tag for this task."
  9365. :group 'org-todo
  9366. :type '(choice
  9367. (const :tag "No tracking" nil)
  9368. (const :tag "Track with ORDERED tag" t)
  9369. (string :tag "Use other tag")))
  9370. (defun org-toggle-ordered-property ()
  9371. "Toggle the ORDERED property of the current entry.
  9372. For better visibility, you can track the value of this property with a tag.
  9373. See variable `org-track-ordered-property-with-tag'."
  9374. (interactive)
  9375. (let* ((t1 org-track-ordered-property-with-tag)
  9376. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  9377. (save-excursion
  9378. (org-back-to-heading)
  9379. (if (org-entry-get nil "ORDERED")
  9380. (progn
  9381. (org-delete-property "ORDERED")
  9382. (and tag (org-toggle-tag tag 'off))
  9383. (message "Subtasks can be completed in arbitrary order"))
  9384. (org-entry-put nil "ORDERED" "t")
  9385. (and tag (org-toggle-tag tag 'on))
  9386. (message "Subtasks must be completed in sequence")))))
  9387. (defun org-block-todo-from-checkboxes (change-plist)
  9388. "Block turning an entry into a TODO, using checkboxes.
  9389. This checks whether the current task should be blocked from state
  9390. changes because there are unchecked boxes in this entry."
  9391. (if (not org-enforce-todo-checkbox-dependencies)
  9392. t ; if locally turned off don't block
  9393. (catch 'dont-block
  9394. ;; If this is not a todo state change, or if this entry is already DONE,
  9395. ;; do not block
  9396. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  9397. (member (plist-get change-plist :from)
  9398. (cons 'done org-done-keywords))
  9399. (member (plist-get change-plist :to)
  9400. (cons 'todo org-not-done-keywords))
  9401. (not (plist-get change-plist :to)))
  9402. (throw 'dont-block t))
  9403. ;; If this task has checkboxes that are not checked, it's blocked
  9404. (save-excursion
  9405. (org-back-to-heading t)
  9406. (let ((beg (point)) end)
  9407. (outline-next-heading)
  9408. (setq end (point))
  9409. (goto-char beg)
  9410. (when (org-list-search-forward
  9411. (concat (org-item-beginning-re)
  9412. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  9413. "\\[[- ]\\]")
  9414. end t)
  9415. (when (boundp 'org-blocked-by-checkboxes)
  9416. (setq org-blocked-by-checkboxes t))
  9417. (throw 'dont-block nil))))
  9418. t))) ; do not block
  9419. (defun org-entry-blocked-p ()
  9420. "Non-nil if entry at point is blocked."
  9421. (and (not (org-entry-get nil "NOBLOCKING"))
  9422. (member (org-entry-get nil "TODO") org-not-done-keywords)
  9423. (not (run-hook-with-args-until-failure
  9424. 'org-blocker-hook
  9425. (list :type 'todo-state-change
  9426. :position (point)
  9427. :from 'todo
  9428. :to 'done)))))
  9429. (defun org-update-statistics-cookies (all)
  9430. "Update the statistics cookie, either from TODO or from checkboxes.
  9431. This should be called with the cursor in a line with a statistics
  9432. cookie. When called with a \\[universal-argument] prefix, update
  9433. all statistics cookies in the buffer."
  9434. (interactive "P")
  9435. (if all
  9436. (progn
  9437. (org-update-checkbox-count 'all)
  9438. (org-map-entries 'org-update-parent-todo-statistics))
  9439. (if (not (org-at-heading-p))
  9440. (org-update-checkbox-count)
  9441. (let ((pos (point-marker))
  9442. end l1 l2)
  9443. (ignore-errors (org-back-to-heading t))
  9444. (if (not (org-at-heading-p))
  9445. (org-update-checkbox-count)
  9446. (setq l1 (org-outline-level))
  9447. (setq end (save-excursion
  9448. (outline-next-heading)
  9449. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  9450. (point)))
  9451. (if (and (save-excursion
  9452. (re-search-forward
  9453. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  9454. (not (save-excursion (re-search-forward
  9455. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  9456. (org-update-checkbox-count)
  9457. (if (and l2 (> l2 l1))
  9458. (progn
  9459. (goto-char end)
  9460. (org-update-parent-todo-statistics))
  9461. (goto-char pos)
  9462. (beginning-of-line 1)
  9463. (while (re-search-forward
  9464. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  9465. (point-at-eol) t)
  9466. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  9467. (goto-char pos)
  9468. (move-marker pos nil)))))
  9469. (defvar org-entry-property-inherited-from) ;; defined below
  9470. (defun org-update-parent-todo-statistics ()
  9471. "Update any statistics cookie in the parent of the current headline.
  9472. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  9473. the entire subtree and this will travel up the hierarchy and update
  9474. statistics everywhere."
  9475. (let* ((prop (save-excursion (org-up-heading-safe)
  9476. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  9477. (recursive (or (not org-hierarchical-todo-statistics)
  9478. (and prop (string-match "\\<recursive\\>" prop))))
  9479. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  9480. 0))
  9481. (first t)
  9482. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  9483. level ltoggle l1 new ndel
  9484. (cnt-all 0) (cnt-done 0) is-percent kwd
  9485. checkbox-beg cookie-present)
  9486. (catch 'exit
  9487. (save-excursion
  9488. (beginning-of-line 1)
  9489. (setq ltoggle (funcall outline-level))
  9490. ;; Three situations are to consider:
  9491. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  9492. ;; to the top-level ancestor on the headline;
  9493. ;; 2. If parent has "recursive" property, repeat up to the
  9494. ;; headline setting that property, taking inheritance into
  9495. ;; account;
  9496. ;; 3. Else, move up to direct parent and proceed only once.
  9497. (while (and (setq level (org-up-heading-safe))
  9498. (or recursive first)
  9499. (>= (point) lim))
  9500. (setq first nil cookie-present nil)
  9501. (unless (and level
  9502. (not (string-match
  9503. "\\<checkbox\\>"
  9504. (downcase (or (org-entry-get nil "COOKIE_DATA")
  9505. "")))))
  9506. (throw 'exit nil))
  9507. (while (re-search-forward box-re (point-at-eol) t)
  9508. (setq cnt-all 0 cnt-done 0 cookie-present t)
  9509. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  9510. (save-match-data
  9511. (unless (outline-next-heading) (throw 'exit nil))
  9512. (while (and (looking-at org-complex-heading-regexp)
  9513. (> (setq l1 (length (match-string 1))) level))
  9514. (setq kwd (and (or recursive (= l1 ltoggle))
  9515. (match-string 2)))
  9516. (if (or (eq org-provide-todo-statistics 'all-headlines)
  9517. (and (eq org-provide-todo-statistics t)
  9518. (or (member kwd org-done-keywords)))
  9519. (and (listp org-provide-todo-statistics)
  9520. (stringp (car org-provide-todo-statistics))
  9521. (or (member kwd org-provide-todo-statistics)
  9522. (member kwd org-done-keywords)))
  9523. (and (listp org-provide-todo-statistics)
  9524. (listp (car org-provide-todo-statistics))
  9525. (or (member kwd (car org-provide-todo-statistics))
  9526. (and (member kwd org-done-keywords)
  9527. (member kwd (cadr org-provide-todo-statistics))))))
  9528. (setq cnt-all (1+ cnt-all))
  9529. (and (eq org-provide-todo-statistics t)
  9530. kwd
  9531. (setq cnt-all (1+ cnt-all))))
  9532. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  9533. (member kwd org-done-keywords))
  9534. (and (listp org-provide-todo-statistics)
  9535. (listp (car org-provide-todo-statistics))
  9536. (member kwd org-done-keywords)
  9537. (member kwd (cadr org-provide-todo-statistics)))
  9538. (and (listp org-provide-todo-statistics)
  9539. (stringp (car org-provide-todo-statistics))
  9540. (member kwd org-done-keywords)))
  9541. (setq cnt-done (1+ cnt-done)))
  9542. (outline-next-heading)))
  9543. (setq new
  9544. (if is-percent
  9545. (format "[%d%%]" (floor (* 100.0 cnt-done)
  9546. (max 1 cnt-all)))
  9547. (format "[%d/%d]" cnt-done cnt-all))
  9548. ndel (- (match-end 0) checkbox-beg))
  9549. (goto-char checkbox-beg)
  9550. (insert new)
  9551. (delete-region (point) (+ (point) ndel))
  9552. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  9553. (when cookie-present
  9554. (run-hook-with-args 'org-after-todo-statistics-hook
  9555. cnt-done (- cnt-all cnt-done))))))
  9556. (run-hooks 'org-todo-statistics-hook)))
  9557. (defvar org-after-todo-statistics-hook nil
  9558. "Hook that is called after a TODO statistics cookie has been updated.
  9559. Each function is called with two arguments: the number of not-done entries
  9560. and the number of done entries.
  9561. For example, the following function, when added to this hook, will switch
  9562. an entry to DONE when all children are done, and back to TODO when new
  9563. entries are set to a TODO status. Note that this hook is only called
  9564. when there is a statistics cookie in the headline!
  9565. (defun org-summary-todo (n-done n-not-done)
  9566. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  9567. (let (org-log-done org-log-states) ; turn off logging
  9568. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  9569. ")
  9570. (defvar org-todo-statistics-hook nil
  9571. "Hook that is run whenever Org thinks TODO statistics should be updated.
  9572. This hook runs even if there is no statistics cookie present, in which case
  9573. `org-after-todo-statistics-hook' would not run.")
  9574. (defun org-todo-trigger-tag-changes (state)
  9575. "Apply the changes defined in `org-todo-state-tags-triggers'."
  9576. (let ((l org-todo-state-tags-triggers)
  9577. changes)
  9578. (when (or (not state) (equal state ""))
  9579. (setq changes (append changes (cdr (assoc "" l)))))
  9580. (when (and (stringp state) (> (length state) 0))
  9581. (setq changes (append changes (cdr (assoc state l)))))
  9582. (when (member state org-not-done-keywords)
  9583. (setq changes (append changes (cdr (assq 'todo l)))))
  9584. (when (member state org-done-keywords)
  9585. (setq changes (append changes (cdr (assq 'done l)))))
  9586. (dolist (c changes)
  9587. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  9588. (defun org-local-logging (value)
  9589. "Get logging settings from a property VALUE."
  9590. ;; Directly set the variables, they are already local.
  9591. (setq org-log-done nil
  9592. org-log-repeat nil
  9593. org-todo-log-states nil)
  9594. (dolist (w (split-string value))
  9595. (let (a)
  9596. (cond
  9597. ((setq a (assoc w org-startup-options))
  9598. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  9599. (set (nth 1 a) (nth 2 a))))
  9600. ((setq a (org-extract-log-state-settings w))
  9601. (and (member (car a) org-todo-keywords-1)
  9602. (push a org-todo-log-states)))))))
  9603. (defun org-get-todo-sequence-head (kwd)
  9604. "Return the head of the TODO sequence to which KWD belongs.
  9605. If KWD is not set, check if there is a text property remembering the
  9606. right sequence."
  9607. (let (p)
  9608. (cond
  9609. ((not kwd)
  9610. (or (get-text-property (point-at-bol) 'org-todo-head)
  9611. (progn
  9612. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  9613. nil (point-at-eol)))
  9614. (get-text-property p 'org-todo-head))))
  9615. ((not (member kwd org-todo-keywords-1))
  9616. (car org-todo-keywords-1))
  9617. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  9618. (defun org-fast-todo-selection ()
  9619. "Fast TODO keyword selection with single keys.
  9620. Returns the new TODO keyword, or nil if no state change should occur."
  9621. (let* ((fulltable org-todo-key-alist)
  9622. (done-keywords org-done-keywords) ;; needed for the faces.
  9623. (maxlen (apply 'max (mapcar
  9624. (lambda (x)
  9625. (if (stringp (car x)) (string-width (car x)) 0))
  9626. fulltable)))
  9627. (expert nil)
  9628. (fwidth (+ maxlen 3 1 3))
  9629. (ncol (/ (- (window-width) 4) fwidth))
  9630. tg cnt e c tbl
  9631. groups ingroup)
  9632. (save-excursion
  9633. (save-window-excursion
  9634. (if expert
  9635. (set-buffer (get-buffer-create " *Org todo*"))
  9636. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  9637. (erase-buffer)
  9638. (setq-local org-done-keywords done-keywords)
  9639. (setq tbl fulltable cnt 0)
  9640. (while (setq e (pop tbl))
  9641. (cond
  9642. ((equal e '(:startgroup))
  9643. (push '() groups) (setq ingroup t)
  9644. (unless (= cnt 0)
  9645. (setq cnt 0)
  9646. (insert "\n"))
  9647. (insert "{ "))
  9648. ((equal e '(:endgroup))
  9649. (setq ingroup nil cnt 0)
  9650. (insert "}\n"))
  9651. ((equal e '(:newline))
  9652. (unless (= cnt 0)
  9653. (setq cnt 0)
  9654. (insert "\n")
  9655. (setq e (car tbl))
  9656. (while (equal (car tbl) '(:newline))
  9657. (insert "\n")
  9658. (setq tbl (cdr tbl)))))
  9659. (t
  9660. (setq tg (car e) c (cdr e))
  9661. (when ingroup (push tg (car groups)))
  9662. (setq tg (org-add-props tg nil 'face
  9663. (org-get-todo-face tg)))
  9664. (when (and (= cnt 0) (not ingroup)) (insert " "))
  9665. (insert "[" c "] " tg (make-string
  9666. (- fwidth 4 (length tg)) ?\ ))
  9667. (when (and (= (setq cnt (1+ cnt)) ncol)
  9668. ;; Avoid lines with just a closing delimiter.
  9669. (not (equal (car tbl) '(:endgroup))))
  9670. (insert "\n")
  9671. (when ingroup (insert " "))
  9672. (setq cnt 0)))))
  9673. (insert "\n")
  9674. (goto-char (point-min))
  9675. (unless expert (org-fit-window-to-buffer))
  9676. (message "[a-z..]:Set [SPC]:clear")
  9677. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  9678. (cond
  9679. ((or (= c ?\C-g)
  9680. (and (= c ?q) (not (rassoc c fulltable))))
  9681. (setq quit-flag t))
  9682. ((= c ?\ ) nil)
  9683. ((setq e (rassoc c fulltable) tg (car e))
  9684. tg)
  9685. (t (setq quit-flag t)))))))
  9686. (defun org-entry-is-todo-p ()
  9687. (member (org-get-todo-state) org-not-done-keywords))
  9688. (defun org-entry-is-done-p ()
  9689. (member (org-get-todo-state) org-done-keywords))
  9690. (defun org-get-todo-state ()
  9691. "Return the TODO keyword of the current subtree."
  9692. (save-excursion
  9693. (org-back-to-heading t)
  9694. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9695. (match-end 2)
  9696. (match-string 2))))
  9697. (defun org-at-date-range-p (&optional inactive-ok)
  9698. "Non-nil if point is inside a date range.
  9699. When optional argument INACTIVE-OK is non-nil, also consider
  9700. inactive time ranges.
  9701. When this function returns a non-nil value, match data is set
  9702. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  9703. on INACTIVE-OK."
  9704. (interactive)
  9705. (save-excursion
  9706. (catch 'exit
  9707. (let ((pos (point)))
  9708. (skip-chars-backward "^[<\r\n")
  9709. (skip-chars-backward "<[")
  9710. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9711. (>= (match-end 0) pos)
  9712. (throw 'exit t))
  9713. (skip-chars-backward "^<[\r\n")
  9714. (skip-chars-backward "<[")
  9715. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9716. (>= (match-end 0) pos)
  9717. (throw 'exit t)))
  9718. nil)))
  9719. (defun org-get-repeat (&optional timestamp)
  9720. "Check if there is a time-stamp with repeater in this entry.
  9721. Return the repeater, as a string, or nil. Also return nil when
  9722. this function is called before first heading.
  9723. When optional argument TIMESTAMP is a string, extract the
  9724. repeater from there instead."
  9725. (save-match-data
  9726. (cond (timestamp
  9727. (and (string-match org-repeat-re timestamp)
  9728. (match-string-no-properties 1 timestamp)))
  9729. ((org-before-first-heading-p) nil)
  9730. (t
  9731. (save-excursion
  9732. (org-back-to-heading t)
  9733. (let ((end (org-entry-end-position)))
  9734. (catch :repeat
  9735. (while (re-search-forward org-repeat-re end t)
  9736. (when (save-match-data (org-at-timestamp-p 'agenda))
  9737. (throw :repeat (match-string-no-properties 1)))))))))))
  9738. (defvar org-last-changed-timestamp)
  9739. (defvar org-last-inserted-timestamp)
  9740. (defvar org-log-post-message)
  9741. (defvar org-log-note-purpose)
  9742. (defvar org-log-note-how nil)
  9743. (defvar org-log-note-extra)
  9744. (defun org-auto-repeat-maybe (done-word)
  9745. "Check if the current headline contains a repeated time-stamp.
  9746. If yes, set TODO state back to what it was and change the base date
  9747. of repeating deadline/scheduled time stamps to new date.
  9748. This function is run automatically after each state change to a DONE state."
  9749. (let* ((repeat (org-get-repeat))
  9750. (aa (assoc org-last-state org-todo-kwd-alist))
  9751. (interpret (nth 1 aa))
  9752. (head (nth 2 aa))
  9753. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  9754. (msg "Entry repeats: ")
  9755. (org-log-done nil)
  9756. (org-todo-log-states nil)
  9757. (end (copy-marker (org-entry-end-position))))
  9758. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  9759. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  9760. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  9761. (and (stringp org-todo-repeat-to-state)
  9762. org-todo-repeat-to-state)
  9763. (and org-todo-repeat-to-state org-last-state))))
  9764. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  9765. to-state)
  9766. ((eq interpret 'type) org-last-state)
  9767. (head)
  9768. (t 'none))))
  9769. (org-back-to-heading t)
  9770. (org-add-planning-info nil nil 'closed)
  9771. ;; When `org-log-repeat' is non-nil or entry contains
  9772. ;; a clock, set LAST_REPEAT property.
  9773. (when (or org-log-repeat
  9774. (catch :clock
  9775. (save-excursion
  9776. (while (re-search-forward org-clock-line-re end t)
  9777. (when (org-at-clock-log-p) (throw :clock t))))))
  9778. (org-entry-put nil "LAST_REPEAT" (format-time-string
  9779. (org-time-stamp-format t t))))
  9780. (when org-log-repeat
  9781. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  9782. (memq 'org-add-log-note post-command-hook))
  9783. ;; We are already setup for some record.
  9784. (when (eq org-log-repeat 'note)
  9785. ;; Make sure we take a note, not only a time stamp.
  9786. (setq org-log-note-how 'note))
  9787. ;; Set up for taking a record.
  9788. (org-add-log-setup 'state
  9789. (or done-word (car org-done-keywords))
  9790. org-last-state
  9791. org-log-repeat)))
  9792. ;; Time-stamps without a repeater are usually skipped. However,
  9793. ;; a SCHEDULED time-stamp without one is removed, as they are no
  9794. ;; longer relevant.
  9795. (save-excursion
  9796. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  9797. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  9798. (org-remove-timestamp-with-keyword org-scheduled-string))))
  9799. ;; Update every time-stamp with a repeater in the entry.
  9800. (let ((planning-re (regexp-opt
  9801. (list org-scheduled-string org-deadline-string))))
  9802. (while (re-search-forward org-repeat-re end t)
  9803. (let* ((ts (match-string 0))
  9804. (type (if (not (org-at-planning-p)) "Plain:"
  9805. (save-excursion
  9806. (re-search-backward
  9807. planning-re (line-beginning-position) t)
  9808. (match-string 0)))))
  9809. (when (and (org-at-timestamp-p 'agenda)
  9810. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  9811. (let ((n (string-to-number (match-string 2 ts)))
  9812. (what (match-string 3 ts)))
  9813. (when (equal what "w") (setq n (* n 7) what "d"))
  9814. (when (and (equal what "h")
  9815. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  9816. ts)))
  9817. (user-error
  9818. "Cannot repeat in %d hour(s) because no hour has been set"
  9819. n))
  9820. ;; Preparation, see if we need to modify the start
  9821. ;; date for the change.
  9822. (when (match-end 1)
  9823. (let ((time (save-match-data (org-time-string-to-time ts)))
  9824. (repeater-type (match-string 1 ts)))
  9825. (cond
  9826. ((equal "." repeater-type)
  9827. ;; Shift starting date to today.
  9828. (org-timestamp-change (- (org-today) (time-to-days time))
  9829. 'day))
  9830. ((equal "+" repeater-type)
  9831. (let ((nshiftmax 10)
  9832. (nshift 0))
  9833. (while (or (= nshift 0)
  9834. (not (time-less-p (current-time) time)))
  9835. (when (= nshiftmax (cl-incf nshift))
  9836. (or (y-or-n-p
  9837. (format "%d repeater intervals were not \
  9838. enough to shift date past today. Continue? "
  9839. nshift))
  9840. (user-error "Abort")))
  9841. (org-timestamp-change n (cdr (assoc what whata)))
  9842. (org-in-regexp org-ts-regexp3)
  9843. (setq ts (match-string 1))
  9844. (setq time
  9845. (save-match-data
  9846. (org-time-string-to-time ts)))))
  9847. (org-timestamp-change (- n) (cdr (assoc what whata)))
  9848. ;; Rematch, so that we have everything in place
  9849. ;; for the real shift.
  9850. (org-in-regexp org-ts-regexp3)
  9851. (setq ts (match-string 1))
  9852. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  9853. ts)))))
  9854. (save-excursion
  9855. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  9856. (setq msg
  9857. (concat msg type " " org-last-changed-timestamp " ")))))))
  9858. (run-hooks 'org-todo-repeat-hook)
  9859. (setq org-log-post-message msg)
  9860. (message msg))))
  9861. (defun org-show-todo-tree (arg)
  9862. "Make a compact tree which shows all headlines marked with TODO.
  9863. The tree will show the lines where the regexp matches, and all higher
  9864. headlines above the match.
  9865. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  9866. With a numeric prefix N, construct a sparse tree for the Nth element
  9867. of `org-todo-keywords-1'."
  9868. (interactive "P")
  9869. (let ((case-fold-search nil)
  9870. (kwd-re
  9871. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  9872. ((equal arg '(4))
  9873. (let ((kwd
  9874. (completing-read "Keyword (or KWD1|KWD2|...): "
  9875. (mapcar #'list org-todo-keywords-1))))
  9876. (concat "\\("
  9877. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  9878. "\\)\\>")))
  9879. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  9880. (regexp-quote (nth (1- (prefix-numeric-value arg))
  9881. org-todo-keywords-1)))
  9882. (t (user-error "Invalid prefix argument: %s" arg)))))
  9883. (message "%d TODO entries found"
  9884. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  9885. (defun org--deadline-or-schedule (arg type time)
  9886. "Insert DEADLINE or SCHEDULE information in current entry.
  9887. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  9888. `org-schedule' for information about ARG and TIME arguments."
  9889. (let* ((deadline? (eq type 'deadline))
  9890. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9891. (log (if deadline? org-log-redeadline org-log-reschedule))
  9892. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9893. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9894. ;; Save repeater cookie from either TIME or current scheduled
  9895. ;; time stamp. We are going to insert it back at the end of
  9896. ;; the process.
  9897. (repeater (or (and (org-string-nw-p time)
  9898. ;; We use `org-repeat-re' because we need
  9899. ;; to tell the difference between a real
  9900. ;; repeater and a time delta, e.g. "+2d".
  9901. (string-match org-repeat-re time)
  9902. (match-string 1 time))
  9903. (and (org-string-nw-p old-date)
  9904. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9905. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9906. old-date)
  9907. (match-string 1 old-date)))))
  9908. (pcase arg
  9909. (`(4)
  9910. (if (not old-date)
  9911. (message (if deadline? "Entry had no deadline to remove"
  9912. "Entry was not scheduled"))
  9913. (when (and old-date log)
  9914. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9915. nil old-date log))
  9916. (org-remove-timestamp-with-keyword keyword)
  9917. (message (if deadline? "Entry no longer has a deadline."
  9918. "Entry is no longer scheduled."))))
  9919. (`(16)
  9920. (save-excursion
  9921. (org-back-to-heading t)
  9922. (let ((regexp (if deadline? org-deadline-time-regexp
  9923. org-scheduled-time-regexp)))
  9924. (if (not (re-search-forward regexp (line-end-position 2) t))
  9925. (user-error (if deadline? "No deadline information to update"
  9926. "No scheduled information to update"))
  9927. (let* ((rpl0 (match-string 1))
  9928. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9929. (msg (if deadline? "Warn starting from" "Delay until")))
  9930. (replace-match
  9931. (concat keyword
  9932. " <" rpl
  9933. (format " -%dd"
  9934. (abs (- (time-to-days
  9935. (save-match-data
  9936. (org-read-date
  9937. nil t nil msg old-date-time)))
  9938. (time-to-days old-date-time))))
  9939. ">") t t))))))
  9940. (_
  9941. (org-add-planning-info type time 'closed)
  9942. (when (and old-date
  9943. log
  9944. (not (equal old-date org-last-inserted-timestamp)))
  9945. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9946. org-last-inserted-timestamp
  9947. old-date
  9948. log))
  9949. (when repeater
  9950. (save-excursion
  9951. (org-back-to-heading t)
  9952. (when (re-search-forward
  9953. (concat keyword " " org-last-inserted-timestamp)
  9954. (line-end-position 2)
  9955. t)
  9956. (goto-char (1- (match-end 0)))
  9957. (insert " " repeater)
  9958. (setq org-last-inserted-timestamp
  9959. (concat (substring org-last-inserted-timestamp 0 -1)
  9960. " " repeater
  9961. (substring org-last-inserted-timestamp -1))))))
  9962. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9963. org-last-inserted-timestamp)))))
  9964. (defun org-deadline (arg &optional time)
  9965. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  9966. With one universal prefix argument, remove any deadline from the item.
  9967. With two universal prefix arguments, prompt for a warning delay.
  9968. With argument TIME, set the deadline at the corresponding date. TIME
  9969. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9970. (interactive "P")
  9971. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9972. (org-map-entries
  9973. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9974. nil
  9975. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9976. 'region-start-level
  9977. 'region)
  9978. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9979. (org--deadline-or-schedule arg 'deadline time)))
  9980. (defun org-schedule (arg &optional time)
  9981. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  9982. With one universal prefix argument, remove any scheduling date from the item.
  9983. With two universal prefix arguments, prompt for a delay cookie.
  9984. With argument TIME, scheduled at the corresponding date. TIME can
  9985. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9986. (interactive "P")
  9987. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9988. (org-map-entries
  9989. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9990. nil
  9991. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9992. 'region-start-level
  9993. 'region)
  9994. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9995. (org--deadline-or-schedule arg 'scheduled time)))
  9996. (defun org-get-scheduled-time (pom &optional inherit)
  9997. "Get the scheduled time as a time tuple, of a format suitable
  9998. for calling org-schedule with, or if there is no scheduling,
  9999. returns nil."
  10000. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  10001. (when time
  10002. (apply 'encode-time (org-parse-time-string time)))))
  10003. (defun org-get-deadline-time (pom &optional inherit)
  10004. "Get the deadline as a time tuple, of a format suitable for
  10005. calling org-deadline with, or if there is no scheduling, returns
  10006. nil."
  10007. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  10008. (when time
  10009. (apply 'encode-time (org-parse-time-string time)))))
  10010. (defun org-remove-timestamp-with-keyword (keyword)
  10011. "Remove all time stamps with KEYWORD in the current entry."
  10012. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  10013. beg)
  10014. (save-excursion
  10015. (org-back-to-heading t)
  10016. (setq beg (point))
  10017. (outline-next-heading)
  10018. (while (re-search-backward re beg t)
  10019. (replace-match "")
  10020. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  10021. (equal (char-before) ?\ ))
  10022. (backward-delete-char 1)
  10023. (when (string-match "^[ \t]*$" (buffer-substring
  10024. (point-at-bol) (point-at-eol)))
  10025. (delete-region (point-at-bol)
  10026. (min (point-max) (1+ (point-at-eol))))))))))
  10027. (defvar org-time-was-given) ; dynamically scoped parameter
  10028. (defvar org-end-time-was-given) ; dynamically scoped parameter
  10029. (defun org-at-planning-p ()
  10030. "Non-nil when point is on a planning info line."
  10031. ;; This is as accurate and faster than `org-element-at-point' since
  10032. ;; planning info location is fixed in the section.
  10033. (org-with-wide-buffer
  10034. (beginning-of-line)
  10035. (and (looking-at-p org-planning-line-re)
  10036. (eq (point)
  10037. (ignore-errors
  10038. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  10039. (org-back-to-heading t)
  10040. (org-with-limited-levels (org-back-to-heading t)))
  10041. (line-beginning-position 2))))))
  10042. (defun org-add-planning-info (what &optional time &rest remove)
  10043. "Insert new timestamp with keyword in the planning line.
  10044. WHAT indicates what kind of time stamp to add. It is a symbol
  10045. among `closed', `deadline', `scheduled' and nil. TIME indicates
  10046. the time to use. If none is given, the user is prompted for
  10047. a date. REMOVE indicates what kind of entries to remove. An old
  10048. WHAT entry will also be removed."
  10049. (let (org-time-was-given org-end-time-was-given default-time default-input)
  10050. (catch 'exit
  10051. (when (and (memq what '(scheduled deadline))
  10052. (or (not time)
  10053. (and (stringp time)
  10054. (string-match "^[-+]+[0-9]" time))))
  10055. ;; Try to get a default date/time from existing timestamp
  10056. (save-excursion
  10057. (org-back-to-heading t)
  10058. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  10059. (when (re-search-forward (if (eq what 'scheduled)
  10060. org-scheduled-time-regexp
  10061. org-deadline-time-regexp)
  10062. end t)
  10063. (setq ts (match-string 1)
  10064. default-time (apply 'encode-time (org-parse-time-string ts))
  10065. default-input (and ts (org-get-compact-tod ts)))))))
  10066. (when what
  10067. (setq time
  10068. (if (stringp time)
  10069. ;; This is a string (relative or absolute), set
  10070. ;; proper date.
  10071. (apply #'encode-time
  10072. (org-read-date-analyze
  10073. time default-time (decode-time default-time)))
  10074. ;; If necessary, get the time from the user
  10075. (or time (org-read-date nil 'to-time nil
  10076. (cl-case what
  10077. (deadline "DEADLINE")
  10078. (scheduled "SCHEDULED")
  10079. (otherwise nil))
  10080. default-time default-input)))))
  10081. (org-with-wide-buffer
  10082. (org-back-to-heading t)
  10083. (forward-line)
  10084. (unless (bolp) (insert "\n"))
  10085. (cond ((looking-at-p org-planning-line-re)
  10086. ;; Move to current indentation.
  10087. (skip-chars-forward " \t")
  10088. ;; Check if we have to remove something.
  10089. (dolist (type (if what (cons what remove) remove))
  10090. (save-excursion
  10091. (when (re-search-forward
  10092. (cl-case type
  10093. (closed org-closed-time-regexp)
  10094. (deadline org-deadline-time-regexp)
  10095. (scheduled org-scheduled-time-regexp)
  10096. (otherwise
  10097. (error "Invalid planning type: %s" type)))
  10098. (line-end-position) t)
  10099. ;; Delete until next keyword or end of line.
  10100. (delete-region
  10101. (match-beginning 0)
  10102. (if (re-search-forward org-keyword-time-not-clock-regexp
  10103. (line-end-position)
  10104. t)
  10105. (match-beginning 0)
  10106. (line-end-position))))))
  10107. ;; If there is nothing more to add and no more keyword
  10108. ;; is left, remove the line completely.
  10109. (if (and (looking-at-p "[ \t]*$") (not what))
  10110. (delete-region (line-beginning-position)
  10111. (line-beginning-position 2))
  10112. ;; If we removed last keyword, do not leave trailing
  10113. ;; white space at the end of line.
  10114. (let ((p (point)))
  10115. (save-excursion
  10116. (end-of-line)
  10117. (unless (= (skip-chars-backward " \t" p) 0)
  10118. (delete-region (point) (line-end-position)))))))
  10119. ((not what) (throw 'exit nil)) ; Nothing to do.
  10120. (t (insert-before-markers "\n")
  10121. (backward-char 1)
  10122. (when org-adapt-indentation
  10123. (indent-to-column (1+ (org-outline-level))))))
  10124. (when what
  10125. ;; Insert planning keyword.
  10126. (insert (cl-case what
  10127. (closed org-closed-string)
  10128. (deadline org-deadline-string)
  10129. (scheduled org-scheduled-string)
  10130. (otherwise (error "Invalid planning type: %s" what)))
  10131. " ")
  10132. ;; Insert associated timestamp.
  10133. (let ((ts (org-insert-time-stamp
  10134. time
  10135. (or org-time-was-given
  10136. (and (eq what 'closed) org-log-done-with-time))
  10137. (eq what 'closed)
  10138. nil nil (list org-end-time-was-given))))
  10139. (unless (eolp) (insert " "))
  10140. ts))))))
  10141. (defvar org-log-note-marker (make-marker)
  10142. "Marker pointing at the entry where the note is to be inserted.")
  10143. (defvar org-log-note-purpose nil)
  10144. (defvar org-log-note-state nil)
  10145. (defvar org-log-note-previous-state nil)
  10146. (defvar org-log-note-extra nil)
  10147. (defvar org-log-note-window-configuration nil)
  10148. (defvar org-log-note-return-to (make-marker))
  10149. (defvar org-log-note-effective-time nil
  10150. "Remembered current time so that dynamically scoped
  10151. `org-extend-today-until' affects timestamps in state change log")
  10152. (defvar org-log-post-message nil
  10153. "Message to be displayed after a log note has been stored.
  10154. The auto-repeater uses this.")
  10155. (defun org-add-note ()
  10156. "Add a note to the current entry.
  10157. This is done in the same way as adding a state change note."
  10158. (interactive)
  10159. (org-add-log-setup 'note))
  10160. (defun org-log-beginning (&optional create)
  10161. "Return expected start of log notes in current entry.
  10162. When optional argument CREATE is non-nil, the function creates
  10163. a drawer to store notes, if necessary. Returned position ignores
  10164. narrowing."
  10165. (org-with-wide-buffer
  10166. (let ((drawer (org-log-into-drawer)))
  10167. (cond
  10168. (drawer
  10169. (org-end-of-meta-data)
  10170. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  10171. (end (if (org-at-heading-p) (point)
  10172. (save-excursion (outline-next-heading) (point))))
  10173. (case-fold-search t))
  10174. (catch 'exit
  10175. ;; Try to find existing drawer.
  10176. (while (re-search-forward regexp end t)
  10177. (let ((element (org-element-at-point)))
  10178. (when (eq (org-element-type element) 'drawer)
  10179. (let ((cend (org-element-property :contents-end element)))
  10180. (when (and (not org-log-states-order-reversed) cend)
  10181. (goto-char cend)))
  10182. (throw 'exit nil))))
  10183. ;; No drawer found. Create one, if permitted.
  10184. (when create
  10185. (unless (bolp) (insert "\n"))
  10186. (let ((beg (point)))
  10187. (insert ":" drawer ":\n:END:\n")
  10188. (org-indent-region beg (point))
  10189. (org-flag-region
  10190. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  10191. (end-of-line -1)))))
  10192. (t
  10193. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  10194. (skip-chars-forward " \t\n")
  10195. (beginning-of-line)
  10196. (unless org-log-states-order-reversed
  10197. (org-skip-over-state-notes)
  10198. (skip-chars-backward " \t\n")
  10199. (forward-line)))))
  10200. (if (bolp) (point) (line-beginning-position 2))))
  10201. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  10202. "Set up the post command hook to take a note.
  10203. If this is about to TODO state change, the new state is expected in STATE.
  10204. HOW is an indicator what kind of note should be created.
  10205. EXTRA is additional text that will be inserted into the notes buffer."
  10206. (move-marker org-log-note-marker (point))
  10207. (setq org-log-note-purpose purpose
  10208. org-log-note-state state
  10209. org-log-note-previous-state prev-state
  10210. org-log-note-how how
  10211. org-log-note-extra extra
  10212. org-log-note-effective-time (org-current-effective-time))
  10213. (add-hook 'post-command-hook 'org-add-log-note 'append))
  10214. (defun org-skip-over-state-notes ()
  10215. "Skip past the list of State notes in an entry."
  10216. (when (ignore-errors (goto-char (org-in-item-p)))
  10217. (let* ((struct (org-list-struct))
  10218. (prevs (org-list-prevs-alist struct))
  10219. (regexp
  10220. (concat "[ \t]*- +"
  10221. (replace-regexp-in-string
  10222. " +" " +"
  10223. (org-replace-escapes
  10224. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  10225. `(("%d" . ,org-ts-regexp-inactive)
  10226. ("%D" . ,org-ts-regexp)
  10227. ("%s" . "\\(?:\"\\S-+\"\\)?")
  10228. ("%S" . "\\(?:\"\\S-+\"\\)?")
  10229. ("%t" . ,org-ts-regexp-inactive)
  10230. ("%T" . ,org-ts-regexp)
  10231. ("%u" . ".*?")
  10232. ("%U" . ".*?")))))))
  10233. (while (looking-at-p regexp)
  10234. (goto-char (or (org-list-get-next-item (point) struct prevs)
  10235. (org-list-get-item-end (point) struct)))))))
  10236. (defun org-add-log-note (&optional _purpose)
  10237. "Pop up a window for taking a note, and add this note later."
  10238. (remove-hook 'post-command-hook 'org-add-log-note)
  10239. (setq org-log-note-window-configuration (current-window-configuration))
  10240. (delete-other-windows)
  10241. (move-marker org-log-note-return-to (point))
  10242. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  10243. (goto-char org-log-note-marker)
  10244. (org-switch-to-buffer-other-window "*Org Note*")
  10245. (erase-buffer)
  10246. (if (memq org-log-note-how '(time state))
  10247. (org-store-log-note)
  10248. (let ((org-inhibit-startup t)) (org-mode))
  10249. (insert (format "# Insert note for %s.
  10250. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  10251. (cl-case org-log-note-purpose
  10252. (clock-out "stopped clock")
  10253. (done "closed todo item")
  10254. (reschedule "rescheduling")
  10255. (delschedule "no longer scheduled")
  10256. (redeadline "changing deadline")
  10257. (deldeadline "removing deadline")
  10258. (refile "refiling")
  10259. (note "this entry")
  10260. (state
  10261. (format "state change from \"%s\" to \"%s\""
  10262. (or org-log-note-previous-state "")
  10263. (or org-log-note-state "")))
  10264. (t (error "This should not happen")))))
  10265. (when org-log-note-extra (insert org-log-note-extra))
  10266. (setq-local org-finish-function 'org-store-log-note)
  10267. (run-hooks 'org-log-buffer-setup-hook)))
  10268. (defvar org-note-abort nil) ; dynamically scoped
  10269. (defun org-store-log-note ()
  10270. "Finish taking a log note, and insert it to where it belongs."
  10271. (let ((txt (prog1 (buffer-string)
  10272. (kill-buffer)))
  10273. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  10274. lines)
  10275. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  10276. (setq txt (replace-match "" t t txt)))
  10277. (when (string-match "\\s-+\\'" txt)
  10278. (setq txt (replace-match "" t t txt)))
  10279. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  10280. (when (org-string-nw-p note)
  10281. (setq note
  10282. (org-replace-escapes
  10283. note
  10284. (list (cons "%u" (user-login-name))
  10285. (cons "%U" user-full-name)
  10286. (cons "%t" (format-time-string
  10287. (org-time-stamp-format 'long 'inactive)
  10288. org-log-note-effective-time))
  10289. (cons "%T" (format-time-string
  10290. (org-time-stamp-format 'long nil)
  10291. org-log-note-effective-time))
  10292. (cons "%d" (format-time-string
  10293. (org-time-stamp-format nil 'inactive)
  10294. org-log-note-effective-time))
  10295. (cons "%D" (format-time-string
  10296. (org-time-stamp-format nil nil)
  10297. org-log-note-effective-time))
  10298. (cons "%s" (cond
  10299. ((not org-log-note-state) "")
  10300. ((string-match-p org-ts-regexp
  10301. org-log-note-state)
  10302. (format "\"[%s]\""
  10303. (substring org-log-note-state 1 -1)))
  10304. (t (format "\"%s\"" org-log-note-state))))
  10305. (cons "%S"
  10306. (cond
  10307. ((not org-log-note-previous-state) "")
  10308. ((string-match-p org-ts-regexp
  10309. org-log-note-previous-state)
  10310. (format "\"[%s]\""
  10311. (substring
  10312. org-log-note-previous-state 1 -1)))
  10313. (t (format "\"%s\""
  10314. org-log-note-previous-state)))))))
  10315. (when lines (setq note (concat note " \\\\")))
  10316. (push note lines))
  10317. (when (and lines (not org-note-abort))
  10318. (with-current-buffer (marker-buffer org-log-note-marker)
  10319. (org-with-wide-buffer
  10320. ;; Find location for the new note.
  10321. (goto-char org-log-note-marker)
  10322. (set-marker org-log-note-marker nil)
  10323. ;; Note associated to a clock is to be located right after
  10324. ;; the clock. Do not move point.
  10325. (unless (eq org-log-note-purpose 'clock-out)
  10326. (goto-char (org-log-beginning t)))
  10327. ;; Make sure point is at the beginning of an empty line.
  10328. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  10329. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  10330. ;; In an existing list, add a new item at the top level.
  10331. ;; Otherwise, indent line like a regular one.
  10332. (let ((itemp (org-in-item-p)))
  10333. (if itemp
  10334. (indent-line-to
  10335. (let ((struct (save-excursion
  10336. (goto-char itemp) (org-list-struct))))
  10337. (org-list-get-ind (org-list-get-top-point struct) struct)))
  10338. (org-indent-line)))
  10339. (insert (org-list-bullet-string "-") (pop lines))
  10340. (let ((ind (org-list-item-body-column (line-beginning-position))))
  10341. (dolist (line lines)
  10342. (insert "\n")
  10343. (indent-line-to ind)
  10344. (insert line)))
  10345. (message "Note stored")
  10346. (org-back-to-heading t))
  10347. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  10348. ;; from within `org-add-log-note' because `buffer-undo-list'
  10349. ;; is then modified outside of `org-with-remote-undo'.
  10350. (when (eq this-command 'org-agenda-todo)
  10351. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  10352. ;; Don't add undo information when called from `org-agenda-todo'.
  10353. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  10354. (set-window-configuration org-log-note-window-configuration)
  10355. (with-current-buffer (marker-buffer org-log-note-return-to)
  10356. (goto-char org-log-note-return-to))
  10357. (move-marker org-log-note-return-to nil)
  10358. (when org-log-post-message (message "%s" org-log-post-message))))
  10359. (defun org-remove-empty-drawer-at (pos)
  10360. "Remove an empty drawer at position POS.
  10361. POS may also be a marker."
  10362. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  10363. (org-with-wide-buffer
  10364. (goto-char pos)
  10365. (let ((drawer (org-element-at-point)))
  10366. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  10367. (not (org-element-property :contents-begin drawer)))
  10368. (delete-region (org-element-property :begin drawer)
  10369. (progn (goto-char (org-element-property :end drawer))
  10370. (skip-chars-backward " \r\t\n")
  10371. (forward-line)
  10372. (point))))))))
  10373. (defvar org-ts-type nil)
  10374. (defun org-sparse-tree (&optional arg type)
  10375. "Create a sparse tree, prompt for the details.
  10376. This command can create sparse trees. You first need to select the type
  10377. of match used to create the tree:
  10378. t Show all TODO entries.
  10379. T Show entries with a specific TODO keyword.
  10380. m Show entries selected by a tags/property match.
  10381. p Enter a property name and its value (both with completion on existing
  10382. names/values) and show entries with that property.
  10383. r Show entries matching a regular expression (`/' can be used as well).
  10384. b Show deadlines and scheduled items before a date.
  10385. a Show deadlines and scheduled items after a date.
  10386. d Show deadlines due within `org-deadline-warning-days'.
  10387. D Show deadlines and scheduled items between a date range."
  10388. (interactive "P")
  10389. (setq type (or type org-sparse-tree-default-date-type))
  10390. (setq org-ts-type type)
  10391. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  10392. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  10393. \[c]ycle through date types: %s"
  10394. (cl-case type
  10395. (all "all timestamps")
  10396. (scheduled "only scheduled")
  10397. (deadline "only deadline")
  10398. (active "only active timestamps")
  10399. (inactive "only inactive timestamps")
  10400. (closed "with a closed time-stamp")
  10401. (otherwise "scheduled/deadline")))
  10402. (let ((answer (read-char-exclusive)))
  10403. (cl-case answer
  10404. (?c
  10405. (org-sparse-tree
  10406. arg
  10407. (cadr
  10408. (memq type '(nil all scheduled deadline active inactive closed)))))
  10409. (?d (call-interactively 'org-check-deadlines))
  10410. (?b (call-interactively 'org-check-before-date))
  10411. (?a (call-interactively 'org-check-after-date))
  10412. (?D (call-interactively 'org-check-dates-range))
  10413. (?t (call-interactively 'org-show-todo-tree))
  10414. (?T (org-show-todo-tree '(4)))
  10415. (?m (call-interactively 'org-match-sparse-tree))
  10416. ((?p ?P)
  10417. (let* ((kwd (completing-read
  10418. "Property: " (mapcar #'list (org-buffer-property-keys))))
  10419. (value (completing-read
  10420. "Value: " (mapcar #'list (org-property-values kwd)))))
  10421. (unless (string-match "\\`{.*}\\'" value)
  10422. (setq value (concat "\"" value "\"")))
  10423. (org-match-sparse-tree arg (concat kwd "=" value))))
  10424. ((?r ?R ?/) (call-interactively 'org-occur))
  10425. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  10426. (defvar-local org-occur-highlights nil
  10427. "List of overlays used for occur matches.")
  10428. (defvar-local org-occur-parameters nil
  10429. "Parameters of the active org-occur calls.
  10430. This is a list, each call to org-occur pushes as cons cell,
  10431. containing the regular expression and the callback, onto the list.
  10432. The list can contain several entries if `org-occur' has been called
  10433. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  10434. will only contain one set of parameters. When the highlights are
  10435. removed (for example with `C-c C-c', or with the next edit (depending
  10436. on `org-remove-highlights-with-change'), this variable is emptied
  10437. as well.")
  10438. (defun org-occur (regexp &optional keep-previous callback)
  10439. "Make a compact tree which shows all matches of REGEXP.
  10440. The tree will show the lines where the regexp matches, and any other context
  10441. defined in `org-show-context-detail', which see.
  10442. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  10443. done by a previous call to `org-occur' will be kept, to allow stacking of
  10444. calls to this command.
  10445. Optional argument CALLBACK can be a function of no argument. In this case,
  10446. it is called with point at the end of the match, match data being set
  10447. accordingly. Current match is shown only if the return value is non-nil.
  10448. The function must neither move point nor alter narrowing."
  10449. (interactive "sRegexp: \nP")
  10450. (when (equal regexp "")
  10451. (user-error "Regexp cannot be empty"))
  10452. (unless keep-previous
  10453. (org-remove-occur-highlights nil nil t))
  10454. (push (cons regexp callback) org-occur-parameters)
  10455. (let ((cnt 0))
  10456. (save-excursion
  10457. (goto-char (point-min))
  10458. (when (or (not keep-previous) ; do not want to keep
  10459. (not org-occur-highlights)) ; no previous matches
  10460. ;; hide everything
  10461. (org-overview))
  10462. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  10463. (isearch-no-upper-case-p regexp t)
  10464. org-occur-case-fold-search)))
  10465. (while (re-search-forward regexp nil t)
  10466. (when (or (not callback)
  10467. (save-match-data (funcall callback)))
  10468. (setq cnt (1+ cnt))
  10469. (when org-highlight-sparse-tree-matches
  10470. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  10471. (org-show-context 'occur-tree)))))
  10472. (when org-remove-highlights-with-change
  10473. (add-hook 'before-change-functions 'org-remove-occur-highlights
  10474. nil 'local))
  10475. (unless org-sparse-tree-open-archived-trees
  10476. (org-hide-archived-subtrees (point-min) (point-max)))
  10477. (run-hooks 'org-occur-hook)
  10478. (when (called-interactively-p 'interactive)
  10479. (message "%d match(es) for regexp %s" cnt regexp))
  10480. cnt))
  10481. (defun org-occur-next-match (&optional n _reset)
  10482. "Function for `next-error-function' to find sparse tree matches.
  10483. N is the number of matches to move, when negative move backwards.
  10484. This function always goes back to the starting point when no
  10485. match is found."
  10486. (let* ((limit (if (< n 0) (point-min) (point-max)))
  10487. (search-func (if (< n 0)
  10488. 'previous-single-char-property-change
  10489. 'next-single-char-property-change))
  10490. (n (abs n))
  10491. (pos (point))
  10492. p1)
  10493. (catch 'exit
  10494. (while (setq p1 (funcall search-func (point) 'org-type))
  10495. (when (equal p1 limit)
  10496. (goto-char pos)
  10497. (user-error "No more matches"))
  10498. (when (equal (get-char-property p1 'org-type) 'org-occur)
  10499. (setq n (1- n))
  10500. (when (= n 0)
  10501. (goto-char p1)
  10502. (throw 'exit (point))))
  10503. (goto-char p1))
  10504. (goto-char p1)
  10505. (user-error "No more matches"))))
  10506. (defun org-highlight-new-match (beg end)
  10507. "Highlight from BEG to END and mark the highlight is an occur headline."
  10508. (let ((ov (make-overlay beg end)))
  10509. (overlay-put ov 'face 'secondary-selection)
  10510. (overlay-put ov 'org-type 'org-occur)
  10511. (push ov org-occur-highlights)))
  10512. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  10513. "Remove the occur highlights from the buffer.
  10514. BEG and END are ignored. If NOREMOVE is nil, remove this function
  10515. from the `before-change-functions' in the current buffer."
  10516. (interactive)
  10517. (unless org-inhibit-highlight-removal
  10518. (mapc #'delete-overlay org-occur-highlights)
  10519. (setq org-occur-highlights nil)
  10520. (setq org-occur-parameters nil)
  10521. (unless noremove
  10522. (remove-hook 'before-change-functions
  10523. 'org-remove-occur-highlights 'local))))
  10524. ;;;; Priorities
  10525. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  10526. "Regular expression matching the priority indicator.")
  10527. (defvar org-remove-priority-next-time nil)
  10528. (defun org-priority-up ()
  10529. "Increase the priority of the current item."
  10530. (interactive)
  10531. (org-priority 'up))
  10532. (defun org-priority-down ()
  10533. "Decrease the priority of the current item."
  10534. (interactive)
  10535. (org-priority 'down))
  10536. (defun org-priority (&optional action show)
  10537. "Change the priority of an item.
  10538. When called interactively with a `\\[universal-argument]' prefix,
  10539. show the priority in the minibuffer instead of changing it.
  10540. When called programatically, ACTION can be `set', `up', `down',
  10541. or a character."
  10542. (interactive "P")
  10543. (when show
  10544. ;; Deprecation warning inserted for Org 9.2; once enough time has
  10545. ;; passed the SHOW argument should be removed.
  10546. (warn "`org-priority' called with deprecated SHOW argument"))
  10547. (if (equal action '(4))
  10548. (org-show-priority)
  10549. (unless org-enable-priority-commands
  10550. (user-error "Priority commands are disabled"))
  10551. (setq action (or action 'set))
  10552. (let (current new news have remove)
  10553. (save-excursion
  10554. (org-back-to-heading t)
  10555. (when (looking-at org-priority-regexp)
  10556. (setq current (string-to-char (match-string 2))
  10557. have t))
  10558. (cond
  10559. ((eq action 'remove)
  10560. (setq remove t new ?\ ))
  10561. ((or (eq action 'set)
  10562. (integerp action))
  10563. (if (not (eq action 'set))
  10564. (setq new action)
  10565. (message "Priority %c-%c, SPC to remove: "
  10566. org-highest-priority org-lowest-priority)
  10567. (save-match-data
  10568. (setq new (read-char-exclusive))))
  10569. (when (and (= (upcase org-highest-priority) org-highest-priority)
  10570. (= (upcase org-lowest-priority) org-lowest-priority))
  10571. (setq new (upcase new)))
  10572. (cond ((equal new ?\s) (setq remove t))
  10573. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  10574. (user-error "Priority must be between `%c' and `%c'"
  10575. org-highest-priority org-lowest-priority))))
  10576. ((eq action 'up)
  10577. (setq new (if have
  10578. (1- current) ; normal cycling
  10579. ;; last priority was empty
  10580. (if (eq last-command this-command)
  10581. org-lowest-priority ; wrap around empty to lowest
  10582. ;; default
  10583. (if org-priority-start-cycle-with-default
  10584. org-default-priority
  10585. (1- org-default-priority))))))
  10586. ((eq action 'down)
  10587. (setq new (if have
  10588. (1+ current) ; normal cycling
  10589. ;; last priority was empty
  10590. (if (eq last-command this-command)
  10591. org-highest-priority ; wrap around empty to highest
  10592. ;; default
  10593. (if org-priority-start-cycle-with-default
  10594. org-default-priority
  10595. (1+ org-default-priority))))))
  10596. (t (user-error "Invalid action")))
  10597. (when (or (< (upcase new) org-highest-priority)
  10598. (> (upcase new) org-lowest-priority))
  10599. (if (and (memq action '(up down))
  10600. (not have) (not (eq last-command this-command)))
  10601. ;; `new' is from default priority
  10602. (error
  10603. "The default can not be set, see `org-default-priority' why")
  10604. ;; normal cycling: `new' is beyond highest/lowest priority
  10605. ;; and is wrapped around to the empty priority
  10606. (setq remove t)))
  10607. (setq news (format "%c" new))
  10608. (if have
  10609. (if remove
  10610. (replace-match "" t t nil 1)
  10611. (replace-match news t t nil 2))
  10612. (if remove
  10613. (user-error "No priority cookie found in line")
  10614. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  10615. (if (match-end 2)
  10616. (progn
  10617. (goto-char (match-end 2))
  10618. (insert " [#" news "]"))
  10619. (goto-char (match-beginning 3))
  10620. (insert "[#" news "] "))))
  10621. (org-align-tags))
  10622. (if remove
  10623. (message "Priority removed")
  10624. (message "Priority of current item set to %s" news)))))
  10625. (defun org-show-priority ()
  10626. "Show the priority of the current item.
  10627. This priority is composed of the main priority given with the [#A] cookies,
  10628. and by additional input from the age of a schedules or deadline entry."
  10629. (interactive)
  10630. (let ((pri (if (eq major-mode 'org-agenda-mode)
  10631. (org-get-at-bol 'priority)
  10632. (save-excursion
  10633. (save-match-data
  10634. (beginning-of-line)
  10635. (and (looking-at org-heading-regexp)
  10636. (org-get-priority (match-string 0))))))))
  10637. (message "Priority is %d" (if pri pri -1000))))
  10638. (defun org-get-priority (s)
  10639. "Find priority cookie and return priority."
  10640. (save-match-data
  10641. (if (functionp org-get-priority-function)
  10642. (funcall org-get-priority-function)
  10643. (if (not (string-match org-priority-regexp s))
  10644. (* 1000 (- org-lowest-priority org-default-priority))
  10645. (* 1000 (- org-lowest-priority
  10646. (string-to-char (match-string 2 s))))))))
  10647. ;;;; Tags
  10648. (defvar org-agenda-archives-mode)
  10649. (defvar org-map-continue-from nil
  10650. "Position from where mapping should continue.
  10651. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  10652. (defvar org-scanner-tags nil
  10653. "The current tag list while the tags scanner is running.")
  10654. (defvar org-trust-scanner-tags nil
  10655. "Should `org-get-tags' use the tags for the scanner.
  10656. This is for internal dynamical scoping only.
  10657. When this is non-nil, the function `org-get-tags' will return the value
  10658. of `org-scanner-tags' instead of building the list by itself. This
  10659. can lead to large speed-ups when the tags scanner is used in a file with
  10660. many entries, and when the list of tags is retrieved, for example to
  10661. obtain a list of properties. Building the tags list for each entry in such
  10662. a file becomes an N^2 operation - but with this variable set, it scales
  10663. as N.")
  10664. (defvar org--matcher-tags-todo-only nil)
  10665. (defun org-scan-tags (action matcher todo-only &optional start-level)
  10666. "Scan headline tags with inheritance and produce output ACTION.
  10667. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  10668. or `agenda' to produce an entry list for an agenda view. It can also be
  10669. a Lisp form or a function that should be called at each matched headline, in
  10670. this case the return value is a list of all return values from these calls.
  10671. MATCHER is a function accepting three arguments, returning
  10672. a non-nil value whenever a given set of tags qualifies a headline
  10673. for inclusion. See `org-make-tags-matcher' for more information.
  10674. As a special case, it can also be set to t (respectively nil) in
  10675. order to match all (respectively none) headline.
  10676. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  10677. included in the output.
  10678. START-LEVEL can be a string with asterisks, reducing the scope to
  10679. headlines matching this string."
  10680. (require 'org-agenda)
  10681. (let* ((re (concat "^"
  10682. (if start-level
  10683. ;; Get the correct level to match
  10684. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  10685. org-outline-regexp)
  10686. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  10687. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  10688. (props (list 'face 'default
  10689. 'done-face 'org-agenda-done
  10690. 'undone-face 'default
  10691. 'mouse-face 'highlight
  10692. 'org-not-done-regexp org-not-done-regexp
  10693. 'org-todo-regexp org-todo-regexp
  10694. 'org-complex-heading-regexp org-complex-heading-regexp
  10695. 'help-echo
  10696. (format "mouse-2 or RET jump to Org file %S"
  10697. (abbreviate-file-name
  10698. (or (buffer-file-name (buffer-base-buffer))
  10699. (buffer-name (buffer-base-buffer)))))))
  10700. (org-map-continue-from nil)
  10701. lspos tags tags-list
  10702. (tags-alist (list (cons 0 org-file-tags)))
  10703. (llast 0) rtn rtn1 level category i txt
  10704. todo marker entry priority
  10705. ts-date ts-date-type ts-date-pair)
  10706. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  10707. (setq action (list 'lambda nil action)))
  10708. (save-excursion
  10709. (goto-char (point-min))
  10710. (when (eq action 'sparse-tree)
  10711. (org-overview)
  10712. (org-remove-occur-highlights))
  10713. (while (let (case-fold-search)
  10714. (re-search-forward re nil t))
  10715. (setq org-map-continue-from nil)
  10716. (catch :skip
  10717. ;; Ignore closing parts of inline tasks.
  10718. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  10719. (throw :skip t))
  10720. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  10721. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  10722. (goto-char (setq lspos (match-beginning 0)))
  10723. (setq level (org-reduced-level (org-outline-level))
  10724. category (org-get-category))
  10725. (when (eq action 'agenda)
  10726. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  10727. ts-date (car ts-date-pair)
  10728. ts-date-type (cdr ts-date-pair)))
  10729. (setq i llast llast level)
  10730. ;; remove tag lists from same and sublevels
  10731. (while (>= i level)
  10732. (when (setq entry (assoc i tags-alist))
  10733. (setq tags-alist (delete entry tags-alist)))
  10734. (setq i (1- i)))
  10735. ;; add the next tags
  10736. (when tags
  10737. (setq tags (org-split-string tags ":")
  10738. tags-alist
  10739. (cons (cons level tags) tags-alist)))
  10740. ;; compile tags for current headline
  10741. (setq tags-list
  10742. (if org-use-tag-inheritance
  10743. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10744. tags)
  10745. org-scanner-tags tags-list)
  10746. (when org-use-tag-inheritance
  10747. (setcdr (car tags-alist)
  10748. (mapcar (lambda (x)
  10749. (setq x (copy-sequence x))
  10750. (org-add-prop-inherited x))
  10751. (cdar tags-alist))))
  10752. (when (and tags org-use-tag-inheritance
  10753. (or (not (eq t org-use-tag-inheritance))
  10754. org-tags-exclude-from-inheritance))
  10755. ;; Selective inheritance, remove uninherited ones.
  10756. (setcdr (car tags-alist)
  10757. (org-remove-uninherited-tags (cdar tags-alist))))
  10758. (when (and
  10759. ;; eval matcher only when the todo condition is OK
  10760. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10761. (if (functionp matcher)
  10762. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10763. (funcall matcher todo tags-list level))
  10764. matcher))
  10765. ;; Call the skipper, but return t if it does not
  10766. ;; skip, so that the `and' form continues evaluating.
  10767. (progn
  10768. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10769. t)
  10770. ;; Check if timestamps are deselecting this entry
  10771. (or (not todo-only)
  10772. (and (member todo org-todo-keywords-1)
  10773. (or (not org-agenda-tags-todo-honor-ignore-options)
  10774. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10775. ;; select this headline
  10776. (cond
  10777. ((eq action 'sparse-tree)
  10778. (and org-highlight-sparse-tree-matches
  10779. (org-get-heading) (match-end 0)
  10780. (org-highlight-new-match
  10781. (match-beginning 1) (match-end 1)))
  10782. (org-show-context 'tags-tree))
  10783. ((eq action 'agenda)
  10784. (setq txt (org-agenda-format-item
  10785. ""
  10786. (concat
  10787. (if (eq org-tags-match-list-sublevels 'indented)
  10788. (make-string (1- level) ?.) "")
  10789. (org-get-heading))
  10790. (make-string level ?\s)
  10791. category
  10792. tags-list)
  10793. priority (org-get-priority txt))
  10794. (goto-char lspos)
  10795. (setq marker (org-agenda-new-marker))
  10796. (org-add-props txt props
  10797. 'org-marker marker 'org-hd-marker marker 'org-category category
  10798. 'todo-state todo
  10799. 'ts-date ts-date
  10800. 'priority priority
  10801. 'type (concat "tagsmatch" ts-date-type))
  10802. (push txt rtn))
  10803. ((functionp action)
  10804. (setq org-map-continue-from nil)
  10805. (save-excursion
  10806. (setq rtn1 (funcall action))
  10807. (push rtn1 rtn)))
  10808. (t (user-error "Invalid action")))
  10809. ;; if we are to skip sublevels, jump to end of subtree
  10810. (unless org-tags-match-list-sublevels
  10811. (org-end-of-subtree t)
  10812. (backward-char 1))))
  10813. ;; Get the correct position from where to continue
  10814. (if org-map-continue-from
  10815. (goto-char org-map-continue-from)
  10816. (and (= (point) lspos) (end-of-line 1)))))
  10817. (when (and (eq action 'sparse-tree)
  10818. (not org-sparse-tree-open-archived-trees))
  10819. (org-hide-archived-subtrees (point-min) (point-max)))
  10820. (nreverse rtn)))
  10821. (defun org-remove-uninherited-tags (tags)
  10822. "Remove all tags that are not inherited from the list TAGS."
  10823. (cond
  10824. ((eq org-use-tag-inheritance t)
  10825. (if org-tags-exclude-from-inheritance
  10826. (org-delete-all org-tags-exclude-from-inheritance tags)
  10827. tags))
  10828. ((not org-use-tag-inheritance) nil)
  10829. ((stringp org-use-tag-inheritance)
  10830. (delq nil (mapcar
  10831. (lambda (x)
  10832. (if (and (string-match org-use-tag-inheritance x)
  10833. (not (member x org-tags-exclude-from-inheritance)))
  10834. x nil))
  10835. tags)))
  10836. ((listp org-use-tag-inheritance)
  10837. (delq nil (mapcar
  10838. (lambda (x)
  10839. (if (member x org-use-tag-inheritance) x nil))
  10840. tags)))))
  10841. (defun org-match-sparse-tree (&optional todo-only match)
  10842. "Create a sparse tree according to tags string MATCH.
  10843. MATCH is a string with match syntax. It can contain a selection
  10844. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10845. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10846. those. See the manual for details.
  10847. If optional argument TODO-ONLY is non-nil, only select lines that
  10848. are also TODO tasks."
  10849. (interactive "P")
  10850. (org-agenda-prepare-buffers (list (current-buffer)))
  10851. (let ((org--matcher-tags-todo-only todo-only))
  10852. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  10853. org--matcher-tags-todo-only)))
  10854. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10855. (defvar org-cached-props nil)
  10856. (defun org-cached-entry-get (pom property)
  10857. (if (or (eq t org-use-property-inheritance)
  10858. (and (stringp org-use-property-inheritance)
  10859. (let ((case-fold-search t))
  10860. (string-match-p org-use-property-inheritance property)))
  10861. (and (listp org-use-property-inheritance)
  10862. (member-ignore-case property org-use-property-inheritance)))
  10863. ;; Caching is not possible, check it directly.
  10864. (org-entry-get pom property 'inherit)
  10865. ;; Get all properties, so we can do complicated checks easily.
  10866. (cdr (assoc-string property
  10867. (or org-cached-props
  10868. (setq org-cached-props (org-entry-properties pom)))
  10869. t))))
  10870. (defun org-global-tags-completion-table (&optional files)
  10871. "Return the list of all tags in all agenda buffer/files.
  10872. Optional FILES argument is a list of files which can be used
  10873. instead of the agenda files."
  10874. (save-excursion
  10875. (org-uniquify
  10876. (delq nil
  10877. (apply #'append
  10878. (mapcar
  10879. (lambda (file)
  10880. (set-buffer (find-file-noselect file))
  10881. (org--tag-add-to-alist
  10882. (org-get-buffer-tags)
  10883. (mapcar (lambda (x)
  10884. (and (stringp (car-safe x))
  10885. (list (car-safe x))))
  10886. org-current-tag-alist)))
  10887. (if (car-safe files) files
  10888. (org-agenda-files))))))))
  10889. (defun org-make-tags-matcher (match)
  10890. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10891. Returns a cons of the selection string MATCH and a function
  10892. implementing the matcher.
  10893. The matcher is to be called at an Org entry, with point on the
  10894. headline, and returns non-nil if the entry matches the selection
  10895. string MATCH. It must be called with three arguments: the TODO
  10896. keyword at the entry (or nil if none), the list of all tags at
  10897. the entry including inherited ones and the reduced level of the
  10898. headline. Additionally, the category of the entry, if any, must
  10899. be specified as the text property `org-category' on the headline.
  10900. This function sets the variable `org--matcher-tags-todo-only' to
  10901. a non-nil value if the matcher restricts matching to TODO
  10902. entries, otherwise it is not touched.
  10903. See also `org-scan-tags'."
  10904. (unless match
  10905. ;; Get a new match request, with completion against the global
  10906. ;; tags table and the local tags in current buffer.
  10907. (let ((org-last-tags-completion-table
  10908. (org--tag-add-to-alist
  10909. (org-get-buffer-tags)
  10910. (org-global-tags-completion-table))))
  10911. (setq match
  10912. (completing-read
  10913. "Match: "
  10914. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10915. (let ((match0 match)
  10916. (re (concat
  10917. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10918. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10919. "\\([<>=]\\{1,2\\}\\)"
  10920. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10921. "\\|" org-tag-re "\\)"))
  10922. (start 0)
  10923. tagsmatch todomatch tagsmatcher todomatcher)
  10924. ;; Expand group tags.
  10925. (setq match (org-tags-expand match))
  10926. ;; Check if there is a TODO part of this match, which would be the
  10927. ;; part after a "/". To make sure that this slash is not part of
  10928. ;; a property value to be matched against, we also check that
  10929. ;; there is no / after that slash. First, find the last slash.
  10930. (let ((s 0))
  10931. (while (string-match "/+" match s)
  10932. (setq start (match-beginning 0))
  10933. (setq s (match-end 0))))
  10934. (if (and (string-match "/+" match start)
  10935. (not (string-match-p "\"" match start)))
  10936. ;; Match contains also a TODO-matching request.
  10937. (progn
  10938. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10939. (setq todomatch (substring match (match-end 0)))
  10940. (when (string-prefix-p "!" todomatch)
  10941. (setq org--matcher-tags-todo-only t)
  10942. (setq todomatch (substring todomatch 1)))
  10943. (when (string-match "\\`\\s-*\\'" todomatch)
  10944. (setq todomatch nil)))
  10945. ;; Only matching tags.
  10946. (setq tagsmatch match)
  10947. (setq todomatch nil))
  10948. ;; Make the tags matcher.
  10949. (when (org-string-nw-p tagsmatch)
  10950. (let ((orlist nil)
  10951. (orterms (org-split-string tagsmatch "|"))
  10952. term)
  10953. (while (setq term (pop orterms))
  10954. (while (and (equal (substring term -1) "\\") orterms)
  10955. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10956. (while (string-match re term)
  10957. (let* ((rest (substring term (match-end 0)))
  10958. (minus (and (match-end 1)
  10959. (equal (match-string 1 term) "-")))
  10960. (tag (save-match-data
  10961. (replace-regexp-in-string
  10962. "\\\\-" "-" (match-string 2 term))))
  10963. (regexp (eq (string-to-char tag) ?{))
  10964. (levelp (match-end 4))
  10965. (propp (match-end 5))
  10966. (mm
  10967. (cond
  10968. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10969. (levelp
  10970. `(,(org-op-to-function (match-string 3 term))
  10971. level
  10972. ,(string-to-number (match-string 4 term))))
  10973. (propp
  10974. (let* ((gv (pcase (upcase (match-string 5 term))
  10975. ("CATEGORY"
  10976. '(get-text-property (point) 'org-category))
  10977. ("TODO" 'todo)
  10978. (p `(org-cached-entry-get nil ,p))))
  10979. (pv (match-string 7 term))
  10980. (regexp (eq (string-to-char pv) ?{))
  10981. (strp (eq (string-to-char pv) ?\"))
  10982. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10983. (po (org-op-to-function (match-string 6 term)
  10984. (if timep 'time strp))))
  10985. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10986. (when timep (setq pv (org-matcher-time pv)))
  10987. (cond ((and regexp (eq po '/=))
  10988. `(not (string-match ,pv (or ,gv ""))))
  10989. (regexp `(string-match ,pv (or ,gv "")))
  10990. (strp `(,po (or ,gv "") ,pv))
  10991. (t
  10992. `(,po
  10993. (string-to-number (or ,gv ""))
  10994. ,(string-to-number pv))))))
  10995. (t `(member ,tag tags-list)))))
  10996. (push (if minus `(not ,mm) mm) tagsmatcher)
  10997. (setq term rest)))
  10998. (push `(and ,@tagsmatcher) orlist)
  10999. (setq tagsmatcher nil))
  11000. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  11001. ;; Make the TODO matcher.
  11002. (when (org-string-nw-p todomatch)
  11003. (let ((orlist nil))
  11004. (dolist (term (org-split-string todomatch "|"))
  11005. (while (string-match re term)
  11006. (let* ((minus (and (match-end 1)
  11007. (equal (match-string 1 term) "-")))
  11008. (kwd (match-string 2 term))
  11009. (regexp (eq (string-to-char kwd) ?{))
  11010. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  11011. `(equal todo ,kwd))))
  11012. (push (if minus `(not ,mm) mm) todomatcher))
  11013. (setq term (substring term (match-end 0))))
  11014. (push (if (> (length todomatcher) 1)
  11015. (cons 'and todomatcher)
  11016. (car todomatcher))
  11017. orlist)
  11018. (setq todomatcher nil))
  11019. (setq todomatcher (cons 'or orlist))))
  11020. ;; Return the string and function of the matcher. If no
  11021. ;; tags-specific or todo-specific matcher exists, match
  11022. ;; everything.
  11023. (let ((matcher (if (and tagsmatcher todomatcher)
  11024. `(and ,tagsmatcher ,todomatcher)
  11025. (or tagsmatcher todomatcher t))))
  11026. (when org--matcher-tags-todo-only
  11027. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  11028. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  11029. (defun org--tags-expand-group (group tag-groups expanded)
  11030. "Recursively Expand all tags in GROUP, according to TAG-GROUPS.
  11031. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  11032. an accumulator used in recursive calls."
  11033. (dolist (tag group)
  11034. (unless (member tag expanded)
  11035. (let ((group (assoc tag tag-groups)))
  11036. (push tag expanded)
  11037. (when group
  11038. (setq expanded
  11039. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  11040. expanded)
  11041. (defun org-tags-expand (match &optional single-as-list downcased)
  11042. "Expand group tags in MATCH.
  11043. This replaces every group tag in MATCH with a regexp tag search.
  11044. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  11045. will be replaced like this:
  11046. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  11047. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  11048. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  11049. Replacing by a regexp preserves the structure of the match.
  11050. E.g., this expansion
  11051. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  11052. will match anything tagged with \"Lab\" and \"Home\", or tagged
  11053. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  11054. A group tag in MATCH can contain regular expressions of its own.
  11055. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  11056. will be replaced like this:
  11057. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  11058. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  11059. assumed to be a single group tag, and the function will return
  11060. the list of tags in this group.
  11061. When DOWNCASED is non-nil, expand downcased TAGS."
  11062. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  11063. (let ((tag-groups
  11064. (let ((g (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  11065. (if (not downcased) g
  11066. (mapcar (lambda (s) (mapcar #'downcase s)) g)))))
  11067. (cond
  11068. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  11069. (org-group-tags
  11070. (let* ((case-fold-search t)
  11071. (tag-syntax org-mode-syntax-table)
  11072. (group-keys (mapcar #'car tag-groups))
  11073. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  11074. (return-match (if downcased (downcase match) match)))
  11075. ;; Mark regexp-expressions in the match-expression so that we
  11076. ;; do not replace them later on.
  11077. (let ((s 0))
  11078. (while (string-match "{.+?}" return-match s)
  11079. (setq s (match-end 0))
  11080. (add-text-properties
  11081. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  11082. ;; @ and _ are allowed as word-components in tags.
  11083. (modify-syntax-entry ?@ "w" tag-syntax)
  11084. (modify-syntax-entry ?_ "w" tag-syntax)
  11085. ;; For each tag token found in MATCH, compute a regexp and it
  11086. (with-syntax-table tag-syntax
  11087. (replace-regexp-in-string
  11088. key-regexp
  11089. (lambda (m)
  11090. (if (get-text-property (match-beginning 2) 'regexp m)
  11091. m ;regexp tag: ignore
  11092. (let* ((operator (match-string 1 m))
  11093. (tag-token (let ((tag (match-string 2 m)))
  11094. (list (if downcased (downcase tag) tag))))
  11095. regexp-tags regular-tags)
  11096. ;; Partition tags between regexp and regular tags.
  11097. ;; Remove curly bracket syntax from regexp tags.
  11098. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  11099. (save-match-data
  11100. (if (string-match "{\\(.+?\\)}" tag)
  11101. (push (match-string 1 tag) regexp-tags)
  11102. (push tag regular-tags))))
  11103. ;; Replace tag token by the appropriate regexp.
  11104. ;; Regular tags need to be regexp-quoted, whereas
  11105. ;; regexp-tags are inserted as-is.
  11106. (let ((regular (regexp-opt regular-tags))
  11107. (regexp (mapconcat #'identity regexp-tags "\\|")))
  11108. (concat operator
  11109. (cond
  11110. ((null regular-tags) (format "{%s}" regexp))
  11111. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  11112. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  11113. return-match
  11114. t t))))
  11115. (t match))))
  11116. (defun org-op-to-function (op &optional stringp)
  11117. "Turn an operator into the appropriate function."
  11118. (setq op
  11119. (cond
  11120. ((equal op "<" ) '(< org-string< org-time<))
  11121. ((equal op ">" ) '(> org-string> org-time>))
  11122. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  11123. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  11124. ((member op '("=" "==")) '(= string= org-time=))
  11125. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  11126. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  11127. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  11128. (defvar org-tags-overlay (make-overlay 1 1))
  11129. (delete-overlay org-tags-overlay)
  11130. (defun org-add-prop-inherited (s)
  11131. (add-text-properties 0 (length s) '(inherited t) s)
  11132. s)
  11133. (defun org-toggle-tag (tag &optional onoff)
  11134. "Toggle the tag TAG for the current line.
  11135. If ONOFF is `on' or `off', don't toggle but set to this state."
  11136. (save-excursion
  11137. (org-back-to-heading t)
  11138. (let ((current
  11139. ;; Reverse the tags list so any new tag is appended to the
  11140. ;; current list of tags.
  11141. (nreverse (org-get-tags nil t)))
  11142. res)
  11143. (pcase onoff
  11144. (`off (setq current (delete tag current)))
  11145. ((or `on (guard (not (member tag current))))
  11146. (setq res t)
  11147. (cl-pushnew tag current :test #'equal))
  11148. (_ (setq current (delete tag current))))
  11149. (org-set-tags (nreverse current))
  11150. res)))
  11151. (defun org--align-tags-here (to-col)
  11152. "Align tags on the current headline to TO-COL.
  11153. Assume point is on a headline. Preserve point when aligning
  11154. tags."
  11155. (when (org-match-line org-tag-line-re)
  11156. (let* ((tags-start (match-beginning 1))
  11157. (blank-start (save-excursion
  11158. (goto-char tags-start)
  11159. (skip-chars-backward " \t")
  11160. (point)))
  11161. (new (max (if (>= to-col 0) to-col
  11162. (- (abs to-col) (string-width (match-string 1))))
  11163. ;; Introduce at least one space after the heading
  11164. ;; or the stars.
  11165. (save-excursion
  11166. (goto-char blank-start)
  11167. (1+ (current-column)))))
  11168. (current
  11169. (save-excursion (goto-char tags-start) (current-column)))
  11170. (origin (point-marker))
  11171. (column (current-column))
  11172. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  11173. (when (/= new current)
  11174. (delete-region blank-start tags-start)
  11175. (goto-char blank-start)
  11176. (let ((indent-tabs-mode nil)) (indent-to new))
  11177. ;; Try to move back to original position. If point was in the
  11178. ;; blanks before the tags, ORIGIN marker is of no use because
  11179. ;; it now points to BLANK-START. Use COLUMN instead.
  11180. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  11181. (defun org-set-tags-command (&optional arg)
  11182. "Set the tags for the current visible entry.
  11183. When called with `\\[universal-argument]' prefix argument ARG, \
  11184. realign all tags
  11185. in the current buffer.
  11186. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  11187. unconditionally do not
  11188. offer the fast tag selection interface.
  11189. If a region is active, set tags in the region according to the
  11190. setting of `org-loop-over-headlines-in-active-region'.
  11191. This function is for interactive use only;
  11192. in Lisp code use `org-set-tags' instead."
  11193. (interactive "P")
  11194. (let ((org-use-fast-tag-selection
  11195. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  11196. (cond
  11197. ((equal '(4) arg) (org-align-tags t))
  11198. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11199. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  11200. (org-map-entries
  11201. #'org-set-tags-command
  11202. nil
  11203. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11204. 'region-start-level
  11205. 'region)
  11206. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  11207. (t
  11208. (save-excursion
  11209. (org-back-to-heading)
  11210. (let* ((all-tags (org-get-tags))
  11211. (table (setq org-last-tags-completion-table
  11212. (org--tag-add-to-alist
  11213. (and org-complete-tags-always-offer-all-agenda-tags
  11214. (org-global-tags-completion-table
  11215. (org-agenda-files)))
  11216. (or org-current-tag-alist (org-get-buffer-tags)))))
  11217. (current-tags
  11218. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  11219. all-tags))
  11220. (inherited-tags
  11221. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  11222. all-tags))
  11223. (tags
  11224. (replace-regexp-in-string
  11225. ;; Ignore all forbidden characters in tags.
  11226. "[^[:alnum:]_@#%]+" ":"
  11227. (if (or (eq t org-use-fast-tag-selection)
  11228. (and org-use-fast-tag-selection
  11229. (delq nil (mapcar #'cdr table))))
  11230. (org-fast-tag-selection
  11231. current-tags
  11232. inherited-tags
  11233. table
  11234. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  11235. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  11236. (org-trim (completing-read
  11237. "Tags: "
  11238. #'org-tags-completion-function
  11239. nil nil (org-make-tag-string current-tags)
  11240. 'org-tags-history)))))))
  11241. (org-set-tags tags)))))))
  11242. (defun org-align-tags (&optional all)
  11243. "Align tags in current entry.
  11244. When optional argument ALL is non-nil, align all tags in the
  11245. visible part of the buffer."
  11246. (let ((get-indent-column
  11247. (lambda ()
  11248. (let ((offset (if (bound-and-true-p org-indent-mode)
  11249. (* (1- org-indent-indentation-per-level)
  11250. (1- (org-current-level)))
  11251. 0)))
  11252. (+ org-tags-column
  11253. (if (> org-tags-column 0) (- offset) offset))))))
  11254. (if (and (not all) (org-at-heading-p))
  11255. (org--align-tags-here (funcall get-indent-column))
  11256. (save-excursion
  11257. (if all
  11258. (progn
  11259. (goto-char (point-min))
  11260. (while (re-search-forward org-tag-line-re nil t)
  11261. (org--align-tags-here (funcall get-indent-column))))
  11262. (org-back-to-heading t)
  11263. (org--align-tags-here (funcall get-indent-column)))))))
  11264. (defun org-set-tags (tags)
  11265. "Set the tags of the current entry to TAGS, replacing current tags.
  11266. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  11267. If TAGS is nil or the empty string, all tags are removed.
  11268. This function assumes point is on a headline."
  11269. (org-with-wide-buffer
  11270. (let ((tags (pcase tags
  11271. ((pred listp) tags)
  11272. ((pred stringp) (split-string (org-trim tags) ":" t))
  11273. (_ (error "Invalid tag specification: %S" tags))))
  11274. (old-tags (org-get-tags nil t))
  11275. (tags-change? nil))
  11276. (when (functionp org-tags-sort-function)
  11277. (setq tags (sort tags org-tags-sort-function)))
  11278. (setq tags-change? (not (equal tags old-tags)))
  11279. (when tags-change?
  11280. ;; Delete previous tags and any trailing white space.
  11281. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  11282. (line-end-position)))
  11283. (skip-chars-backward " \t")
  11284. (delete-region (point) (line-end-position))
  11285. ;; Deleting white spaces may break an otherwise empty headline.
  11286. ;; Re-introduce one space in this case.
  11287. (unless (org-at-heading-p) (insert " "))
  11288. (when tags
  11289. (save-excursion (insert " " (org-make-tag-string tags)))
  11290. ;; When text is being inserted on an invisible region
  11291. ;; boundary, it can be inadvertently sucked into
  11292. ;; invisibility.
  11293. (unless (org-invisible-p (line-beginning-position))
  11294. (org-flag-region (point) (line-end-position) nil 'outline))))
  11295. ;; Align tags, if any.
  11296. (when tags (org-align-tags))
  11297. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  11298. (defun org-change-tag-in-region (beg end tag off)
  11299. "Add or remove TAG for each entry in the region.
  11300. This works in the agenda, and also in an Org buffer."
  11301. (interactive
  11302. (list (region-beginning) (region-end)
  11303. (let ((org-last-tags-completion-table
  11304. (if (derived-mode-p 'org-mode)
  11305. (org--tag-add-to-alist
  11306. (org-get-buffer-tags)
  11307. (org-global-tags-completion-table))
  11308. (org-global-tags-completion-table))))
  11309. (completing-read
  11310. "Tag: " 'org-tags-completion-function nil nil nil
  11311. 'org-tags-history))
  11312. (progn
  11313. (message "[s]et or [r]emove? ")
  11314. (equal (read-char-exclusive) ?r))))
  11315. (when (fboundp 'deactivate-mark) (deactivate-mark))
  11316. (let ((agendap (equal major-mode 'org-agenda-mode))
  11317. l1 l2 m buf pos newhead (cnt 0))
  11318. (goto-char end)
  11319. (setq l2 (1- (org-current-line)))
  11320. (goto-char beg)
  11321. (setq l1 (org-current-line))
  11322. (cl-loop for l from l1 to l2 do
  11323. (org-goto-line l)
  11324. (setq m (get-text-property (point) 'org-hd-marker))
  11325. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  11326. (and agendap m))
  11327. (setq buf (if agendap (marker-buffer m) (current-buffer))
  11328. pos (if agendap m (point)))
  11329. (with-current-buffer buf
  11330. (save-excursion
  11331. (save-restriction
  11332. (goto-char pos)
  11333. (setq cnt (1+ cnt))
  11334. (org-toggle-tag tag (if off 'off 'on))
  11335. (setq newhead (org-get-heading)))))
  11336. (and agendap (org-agenda-change-all-lines newhead m))))
  11337. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  11338. (defun org-tags-completion-function (string _predicate &optional flag)
  11339. "Complete tag STRING.
  11340. FLAG specifies the type of completion operation to perform. This
  11341. function is passed as a collection function to `completing-read',
  11342. which see."
  11343. (let ((completion-ignore-case nil) ;tags are case-sensitive
  11344. (confirm (lambda (x) (stringp (car x))))
  11345. (prefix ""))
  11346. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  11347. (setq prefix (match-string 1 string))
  11348. (setq string (match-string 2 string)))
  11349. (pcase flag
  11350. (`t (all-completions string org-last-tags-completion-table confirm))
  11351. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  11352. (`nil
  11353. (pcase (try-completion string org-last-tags-completion-table confirm)
  11354. ((and completion (pred stringp))
  11355. (concat prefix
  11356. completion
  11357. (if (and org-add-colon-after-tag-completion
  11358. (assoc completion org-last-tags-completion-table))
  11359. ":"
  11360. "")))
  11361. (completion completion)))
  11362. (_ nil))))
  11363. (defun org-fast-tag-insert (kwd tags face &optional end)
  11364. "Insert KWD, and the TAGS, the latter with face FACE.
  11365. Also insert END."
  11366. (insert (format "%-12s" (concat kwd ":"))
  11367. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  11368. (or end "")))
  11369. (defun org-fast-tag-show-exit (flag)
  11370. (save-excursion
  11371. (org-goto-line 3)
  11372. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  11373. (replace-match ""))
  11374. (when flag
  11375. (end-of-line 1)
  11376. (org-move-to-column (- (window-width) 19) t)
  11377. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  11378. (defun org-set-current-tags-overlay (current prefix)
  11379. "Add an overlay to CURRENT tag with PREFIX."
  11380. (let ((s (org-make-tag-string current)))
  11381. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  11382. (org-overlay-display org-tags-overlay (concat prefix s))))
  11383. (defvar org-last-tag-selection-key nil)
  11384. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  11385. "Fast tag selection with single keys.
  11386. CURRENT is the current list of tags in the headline, INHERITED is the
  11387. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  11388. possibly with grouping information. TODO-TABLE is a similar table with
  11389. TODO keywords, should these have keys assigned to them.
  11390. If the keys are nil, a-z are automatically assigned.
  11391. Returns the new tags string, or nil to not change the current settings."
  11392. (let* ((fulltable (append table todo-table))
  11393. (maxlen (if (null fulltable) 0
  11394. (apply #'max
  11395. (mapcar (lambda (x)
  11396. (if (stringp (car x)) (string-width (car x))
  11397. 0))
  11398. fulltable))))
  11399. (buf (current-buffer))
  11400. (expert (eq org-fast-tag-selection-single-key 'expert))
  11401. (buffer-tags nil)
  11402. (fwidth (+ maxlen 3 1 3))
  11403. (ncol (/ (- (window-width) 4) fwidth))
  11404. (i-face 'org-done)
  11405. (c-face 'org-todo)
  11406. tg cnt e c char c1 c2 ntable tbl rtn
  11407. ov-start ov-end ov-prefix
  11408. (exit-after-next org-fast-tag-selection-single-key)
  11409. (done-keywords org-done-keywords)
  11410. groups ingroup intaggroup)
  11411. (save-excursion
  11412. (beginning-of-line)
  11413. (if (looking-at org-tag-line-re)
  11414. (setq ov-start (match-beginning 1)
  11415. ov-end (match-end 1)
  11416. ov-prefix "")
  11417. (setq ov-start (1- (point-at-eol))
  11418. ov-end (1+ ov-start))
  11419. (skip-chars-forward "^\n\r")
  11420. (setq ov-prefix
  11421. (concat
  11422. (buffer-substring (1- (point)) (point))
  11423. (if (> (current-column) org-tags-column)
  11424. " "
  11425. (make-string (- org-tags-column (current-column)) ?\ ))))))
  11426. (move-overlay org-tags-overlay ov-start ov-end)
  11427. (save-window-excursion
  11428. (if expert
  11429. (set-buffer (get-buffer-create " *Org tags*"))
  11430. (delete-other-windows)
  11431. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  11432. (org-switch-to-buffer-other-window " *Org tags*"))
  11433. (erase-buffer)
  11434. (setq-local org-done-keywords done-keywords)
  11435. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  11436. (org-fast-tag-insert "Current" current c-face "\n\n")
  11437. (org-fast-tag-show-exit exit-after-next)
  11438. (org-set-current-tags-overlay current ov-prefix)
  11439. (setq tbl fulltable char ?a cnt 0)
  11440. (while (setq e (pop tbl))
  11441. (cond
  11442. ((eq (car e) :startgroup)
  11443. (push '() groups) (setq ingroup t)
  11444. (unless (zerop cnt)
  11445. (setq cnt 0)
  11446. (insert "\n"))
  11447. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  11448. ((eq (car e) :endgroup)
  11449. (setq ingroup nil cnt 0)
  11450. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  11451. ((eq (car e) :startgrouptag)
  11452. (setq intaggroup t)
  11453. (unless (zerop cnt)
  11454. (setq cnt 0)
  11455. (insert "\n"))
  11456. (insert "[ "))
  11457. ((eq (car e) :endgrouptag)
  11458. (setq intaggroup nil cnt 0)
  11459. (insert "]\n"))
  11460. ((equal e '(:newline))
  11461. (unless (zerop cnt)
  11462. (setq cnt 0)
  11463. (insert "\n")
  11464. (setq e (car tbl))
  11465. (while (equal (car tbl) '(:newline))
  11466. (insert "\n")
  11467. (setq tbl (cdr tbl)))))
  11468. ((equal e '(:grouptags)) (insert " : "))
  11469. (t
  11470. (setq tg (copy-sequence (car e)) c2 nil)
  11471. (if (cdr e)
  11472. (setq c (cdr e))
  11473. ;; automatically assign a character.
  11474. (setq c1 (string-to-char
  11475. (downcase (substring
  11476. tg (if (= (string-to-char tg) ?@) 1 0)))))
  11477. (if (or (rassoc c1 ntable) (rassoc c1 table))
  11478. (while (or (rassoc char ntable) (rassoc char table))
  11479. (setq char (1+ char)))
  11480. (setq c2 c1))
  11481. (setq c (or c2 char)))
  11482. (when ingroup (push tg (car groups)))
  11483. (setq tg (org-add-props tg nil 'face
  11484. (cond
  11485. ((not (assoc tg table))
  11486. (org-get-todo-face tg))
  11487. ((member tg current) c-face)
  11488. ((member tg inherited) i-face))))
  11489. (when (equal (caar tbl) :grouptags)
  11490. (org-add-props tg nil 'face 'org-tag-group))
  11491. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  11492. (insert "[" c "] " tg (make-string
  11493. (- fwidth 4 (length tg)) ?\ ))
  11494. (push (cons tg c) ntable)
  11495. (when (= (cl-incf cnt) ncol)
  11496. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  11497. (insert "\n")
  11498. (when (or ingroup intaggroup) (insert " ")))
  11499. (setq cnt 0)))))
  11500. (setq ntable (nreverse ntable))
  11501. (insert "\n")
  11502. (goto-char (point-min))
  11503. (unless expert (org-fit-window-to-buffer))
  11504. (setq rtn
  11505. (catch 'exit
  11506. (while t
  11507. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  11508. (if (not groups) "no " "")
  11509. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  11510. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11511. (setq org-last-tag-selection-key c)
  11512. (cond
  11513. ((= c ?\r) (throw 'exit t))
  11514. ((= c ?!)
  11515. (setq groups (not groups))
  11516. (goto-char (point-min))
  11517. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  11518. ((= c ?\C-c)
  11519. (if (not expert)
  11520. (org-fast-tag-show-exit
  11521. (setq exit-after-next (not exit-after-next)))
  11522. (setq expert nil)
  11523. (delete-other-windows)
  11524. (set-window-buffer (split-window-vertically) " *Org tags*")
  11525. (org-switch-to-buffer-other-window " *Org tags*")
  11526. (org-fit-window-to-buffer)))
  11527. ((or (= c ?\C-g)
  11528. (and (= c ?q) (not (rassoc c ntable))))
  11529. (delete-overlay org-tags-overlay)
  11530. (setq quit-flag t))
  11531. ((= c ?\ )
  11532. (setq current nil)
  11533. (when exit-after-next (setq exit-after-next 'now)))
  11534. ((= c ?\t)
  11535. (condition-case nil
  11536. (setq tg (completing-read
  11537. "Tag: "
  11538. (or buffer-tags
  11539. (with-current-buffer buf
  11540. (setq buffer-tags
  11541. (org-get-buffer-tags))))))
  11542. (quit (setq tg "")))
  11543. (when (string-match "\\S-" tg)
  11544. (cl-pushnew (list tg) buffer-tags :test #'equal)
  11545. (if (member tg current)
  11546. (setq current (delete tg current))
  11547. (push tg current)))
  11548. (when exit-after-next (setq exit-after-next 'now)))
  11549. ((setq e (rassoc c todo-table) tg (car e))
  11550. (with-current-buffer buf
  11551. (save-excursion (org-todo tg)))
  11552. (when exit-after-next (setq exit-after-next 'now)))
  11553. ((setq e (rassoc c ntable) tg (car e))
  11554. (if (member tg current)
  11555. (setq current (delete tg current))
  11556. (cl-loop for g in groups do
  11557. (when (member tg g)
  11558. (dolist (x g) (setq current (delete x current)))))
  11559. (push tg current))
  11560. (when exit-after-next (setq exit-after-next 'now))))
  11561. ;; Create a sorted list
  11562. (setq current
  11563. (sort current
  11564. (lambda (a b)
  11565. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  11566. (when (eq exit-after-next 'now) (throw 'exit t))
  11567. (goto-char (point-min))
  11568. (beginning-of-line 2)
  11569. (delete-region (point) (point-at-eol))
  11570. (org-fast-tag-insert "Current" current c-face)
  11571. (org-set-current-tags-overlay current ov-prefix)
  11572. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  11573. (while (re-search-forward tag-re nil t)
  11574. (let ((tag (match-string 1)))
  11575. (add-text-properties
  11576. (match-beginning 1) (match-end 1)
  11577. (list 'face
  11578. (cond
  11579. ((member tag current) c-face)
  11580. ((member tag inherited) i-face)
  11581. (t (get-text-property (match-beginning 1) '
  11582. face))))))))
  11583. (goto-char (point-min)))))
  11584. (delete-overlay org-tags-overlay)
  11585. (if rtn
  11586. (mapconcat 'identity current ":")
  11587. nil))))
  11588. (defun org-make-tag-string (tags)
  11589. "Return string associated to TAGS.
  11590. TAGS is a list of strings."
  11591. (if (null tags) ""
  11592. (format ":%s:" (mapconcat #'identity tags ":"))))
  11593. (defun org--get-local-tags ()
  11594. "Return list of tags for the current headline.
  11595. Assume point is at the beginning of the headline."
  11596. (and (looking-at org-tag-line-re)
  11597. (split-string (match-string-no-properties 2) ":" t)))
  11598. (defun org-get-tags (&optional pos local)
  11599. "Get the list of tags specified in the current headline.
  11600. When argument POS is non-nil, retrieve tags for headline at POS.
  11601. According to `org-use-tag-inheritance', tags may be inherited
  11602. from parent headlines, and from the whole document, through
  11603. `org-file-tags'. In this case, the returned list of tags
  11604. contains tags in this order: file tags, tags inherited from
  11605. parent headlines, local tags.
  11606. However, when optional argument LOCAL is non-nil, only return
  11607. tags specified at the headline.
  11608. Inherited tags have the `inherited' text property."
  11609. (if (and org-trust-scanner-tags
  11610. (or (not pos) (eq pos (point)))
  11611. (not local))
  11612. org-scanner-tags
  11613. (org-with-point-at (or pos (point))
  11614. (unless (org-before-first-heading-p)
  11615. (org-back-to-heading t)
  11616. (let ((ltags (org--get-local-tags)) itags)
  11617. (if (or local (not org-use-tag-inheritance)) ltags
  11618. (while (org-up-heading-safe)
  11619. (setq itags (append (mapcar #'org-add-prop-inherited
  11620. (org--get-local-tags))
  11621. itags)))
  11622. (setq itags (append org-file-tags itags))
  11623. (delete-dups
  11624. (append (org-remove-uninherited-tags itags) ltags))))))))
  11625. (defun org-get-buffer-tags ()
  11626. "Get a table of all tags used in the buffer, for completion."
  11627. (org-with-point-at 1
  11628. (let (tags)
  11629. (while (re-search-forward org-tag-line-re nil t)
  11630. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  11631. tags)))
  11632. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  11633. ;;;; The mapping API
  11634. (defvar org-agenda-skip-comment-trees)
  11635. (defvar org-agenda-skip-function)
  11636. (defun org-map-entries (func &optional match scope &rest skip)
  11637. "Call FUNC at each headline selected by MATCH in SCOPE.
  11638. FUNC is a function or a lisp form. The function will be called without
  11639. arguments, with the cursor positioned at the beginning of the headline.
  11640. The return values of all calls to the function will be collected and
  11641. returned as a list.
  11642. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  11643. does not need to preserve point. After evaluation, the cursor will be
  11644. moved to the end of the line (presumably of the headline of the
  11645. processed entry) and search continues from there. Under some
  11646. circumstances, this may not produce the wanted results. For example,
  11647. if you have removed (e.g. archived) the current (sub)tree it could
  11648. mean that the next entry will be skipped entirely. In such cases, you
  11649. can specify the position from where search should continue by making
  11650. FUNC set the variable `org-map-continue-from' to the desired buffer
  11651. position.
  11652. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  11653. Only headlines that are matched by this query will be considered during
  11654. the iteration. When MATCH is nil or t, all headlines will be
  11655. visited by the iteration.
  11656. SCOPE determines the scope of this command. It can be any of:
  11657. nil The current buffer, respecting the restriction if any
  11658. tree The subtree started with the entry at point
  11659. region The entries within the active region, if any
  11660. region-start-level
  11661. The entries within the active region, but only those at
  11662. the same level than the first one.
  11663. file The current buffer, without restriction
  11664. file-with-archives
  11665. The current buffer, and any archives associated with it
  11666. agenda All agenda files
  11667. agenda-with-archives
  11668. All agenda files with any archive files associated with them
  11669. \(file1 file2 ...)
  11670. If this is a list, all files in the list will be scanned
  11671. The remaining args are treated as settings for the skipping facilities of
  11672. the scanner. The following items can be given here:
  11673. archive skip trees with the archive tag
  11674. comment skip trees with the COMMENT keyword
  11675. function or Emacs Lisp form:
  11676. will be used as value for `org-agenda-skip-function', so
  11677. whenever the function returns a position, FUNC will not be
  11678. called for that entry and search will continue from the
  11679. position returned
  11680. If your function needs to retrieve the tags including inherited tags
  11681. at the *current* entry, you can use the value of the variable
  11682. `org-scanner-tags' which will be much faster than getting the value
  11683. with `org-get-tags'. If your function gets properties with
  11684. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  11685. to t around the call to `org-entry-properties' to get the same speedup.
  11686. Note that if your function moves around to retrieve tags and properties at
  11687. a *different* entry, you cannot use these techniques."
  11688. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  11689. (not (org-region-active-p)))
  11690. (let* ((org-agenda-archives-mode nil) ; just to make sure
  11691. (org-agenda-skip-archived-trees (memq 'archive skip))
  11692. (org-agenda-skip-comment-trees (memq 'comment skip))
  11693. (org-agenda-skip-function
  11694. (car (org-delete-all '(comment archive) skip)))
  11695. (org-tags-match-list-sublevels t)
  11696. (start-level (eq scope 'region-start-level))
  11697. matcher res
  11698. org-todo-keywords-for-agenda
  11699. org-done-keywords-for-agenda
  11700. org-todo-keyword-alist-for-agenda
  11701. org-tag-alist-for-agenda
  11702. org--matcher-tags-todo-only)
  11703. (cond
  11704. ((eq match t) (setq matcher t))
  11705. ((eq match nil) (setq matcher t))
  11706. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  11707. (save-excursion
  11708. (save-restriction
  11709. (cond ((eq scope 'tree)
  11710. (org-back-to-heading t)
  11711. (org-narrow-to-subtree)
  11712. (setq scope nil))
  11713. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11714. (org-region-active-p))
  11715. ;; If needed, set start-level to a string like "2"
  11716. (when start-level
  11717. (save-excursion
  11718. (goto-char (region-beginning))
  11719. (unless (org-at-heading-p) (outline-next-heading))
  11720. (setq start-level (org-current-level))))
  11721. (narrow-to-region (region-beginning)
  11722. (save-excursion
  11723. (goto-char (region-end))
  11724. (unless (and (bolp) (org-at-heading-p))
  11725. (outline-next-heading))
  11726. (point)))
  11727. (setq scope nil)))
  11728. (if (not scope)
  11729. (progn
  11730. (org-agenda-prepare-buffers
  11731. (and buffer-file-name (list buffer-file-name)))
  11732. (setq res
  11733. (org-scan-tags
  11734. func matcher org--matcher-tags-todo-only start-level)))
  11735. ;; Get the right scope
  11736. (cond
  11737. ((and scope (listp scope) (symbolp (car scope)))
  11738. (setq scope (eval scope)))
  11739. ((eq scope 'agenda)
  11740. (setq scope (org-agenda-files t)))
  11741. ((eq scope 'agenda-with-archives)
  11742. (setq scope (org-agenda-files t))
  11743. (setq scope (org-add-archive-files scope)))
  11744. ((eq scope 'file)
  11745. (setq scope (and buffer-file-name (list buffer-file-name))))
  11746. ((eq scope 'file-with-archives)
  11747. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11748. (org-agenda-prepare-buffers scope)
  11749. (dolist (file scope)
  11750. (with-current-buffer (org-find-base-buffer-visiting file)
  11751. (org-with-wide-buffer
  11752. (goto-char (point-min))
  11753. (setq res
  11754. (append
  11755. res
  11756. (org-scan-tags
  11757. func matcher org--matcher-tags-todo-only)))))))))
  11758. res)))
  11759. ;;; Properties API
  11760. (defconst org-special-properties
  11761. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11762. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11763. "The special properties valid in Org mode.
  11764. These are properties that are not defined in the property drawer,
  11765. but in some other way.")
  11766. (defconst org-default-properties
  11767. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11768. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11769. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11770. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11771. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11772. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11773. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  11774. "Some properties that are used by Org mode for various purposes.
  11775. Being in this list makes sure that they are offered for completion.")
  11776. (defun org--valid-property-p (property)
  11777. "Non nil when string PROPERTY is a valid property name."
  11778. (not
  11779. (or (equal property "")
  11780. (string-match-p "\\s-" property))))
  11781. (defun org--update-property-plist (key val props)
  11782. "Associate KEY to VAL in alist PROPS.
  11783. Modifications are made by side-effect. Return new alist."
  11784. (let* ((appending (string= (substring key -1) "+"))
  11785. (key (if appending (substring key 0 -1) key))
  11786. (old (assoc-string key props t)))
  11787. (if (not old) (cons (cons key val) props)
  11788. (setcdr old (if appending (concat (cdr old) " " val) val))
  11789. props)))
  11790. (defun org-get-property-block (&optional beg force)
  11791. "Return the (beg . end) range of the body of the property drawer.
  11792. BEG is the beginning of the current subtree, or of the part
  11793. before the first headline. If it is not given, it will be found.
  11794. If the drawer does not exist, create it if FORCE is non-nil, or
  11795. return nil."
  11796. (org-with-wide-buffer
  11797. (when beg (goto-char beg))
  11798. (unless (org-before-first-heading-p)
  11799. (let ((beg (cond (beg)
  11800. ((or (not (featurep 'org-inlinetask))
  11801. (org-inlinetask-in-task-p))
  11802. (org-back-to-heading t))
  11803. (t (org-with-limited-levels (org-back-to-heading t))))))
  11804. (forward-line)
  11805. (when (looking-at-p org-planning-line-re) (forward-line))
  11806. (cond ((looking-at org-property-drawer-re)
  11807. (forward-line)
  11808. (cons (point) (progn (goto-char (match-end 0))
  11809. (line-beginning-position))))
  11810. (force
  11811. (goto-char beg)
  11812. (org-insert-property-drawer)
  11813. (let ((pos (save-excursion (search-forward ":END:")
  11814. (line-beginning-position))))
  11815. (cons pos pos))))))))
  11816. (defun org-at-property-p ()
  11817. "Non-nil when point is inside a property drawer.
  11818. See `org-property-re' for match data, if applicable."
  11819. (save-excursion
  11820. (beginning-of-line)
  11821. (and (looking-at org-property-re)
  11822. (let ((property-drawer (save-match-data (org-get-property-block))))
  11823. (and property-drawer
  11824. (>= (point) (car property-drawer))
  11825. (< (point) (cdr property-drawer)))))))
  11826. (defun org-property-action ()
  11827. "Do an action on properties."
  11828. (interactive)
  11829. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11830. (let ((c (read-char-exclusive)))
  11831. (cl-case c
  11832. (?s (call-interactively #'org-set-property))
  11833. (?d (call-interactively #'org-delete-property))
  11834. (?D (call-interactively #'org-delete-property-globally))
  11835. (?c (call-interactively #'org-compute-property-at-point))
  11836. (otherwise (user-error "No such property action %c" c)))))
  11837. (defun org-inc-effort ()
  11838. "Increment the value of the effort property in the current entry."
  11839. (interactive)
  11840. (org-set-effort t))
  11841. (defvar org-clock-effort) ; Defined in org-clock.el.
  11842. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11843. (defun org-set-effort (&optional increment value)
  11844. "Set the effort property of the current entry.
  11845. If INCREMENT is non-nil, set the property to the next allowed
  11846. value. Otherwise, if optional argument VALUE is provided, use
  11847. it. Eventually, prompt for the new value if none of the previous
  11848. variables is set."
  11849. (interactive "P")
  11850. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11851. (current (org-entry-get nil org-effort-property))
  11852. (value
  11853. (cond
  11854. (increment
  11855. (unless allowed (user-error "Allowed effort values are not set"))
  11856. (or (cl-caadr (member (list current) allowed))
  11857. (user-error "Unknown value %S among allowed values" current)))
  11858. (value
  11859. (if (stringp value) value
  11860. (error "Invalid effort value: %S" value)))
  11861. (t
  11862. (let ((must-match
  11863. (and allowed
  11864. (not (get-text-property 0 'org-unrestricted
  11865. (caar allowed))))))
  11866. (completing-read "Effort: " allowed nil must-match))))))
  11867. (unless (equal current value)
  11868. (org-entry-put nil org-effort-property value))
  11869. (org-refresh-property '((effort . identity)
  11870. (effort-minutes . org-duration-to-minutes))
  11871. value)
  11872. (when (equal (org-get-heading t t t t)
  11873. (bound-and-true-p org-clock-current-task))
  11874. (setq org-clock-effort value)
  11875. (org-clock-update-mode-line))
  11876. (message "%s is now %s" org-effort-property value)))
  11877. (defun org-entry-properties (&optional pom which)
  11878. "Get all properties of the current entry.
  11879. When POM is a buffer position, get all properties from the entry
  11880. there instead.
  11881. This includes the TODO keyword, the tags, time strings for
  11882. deadline, scheduled, and clocking, and any additional properties
  11883. defined in the entry.
  11884. If WHICH is nil or `all', get all properties. If WHICH is
  11885. `special' or `standard', only get that subclass. If WHICH is
  11886. a string, only get that property.
  11887. Return value is an alist. Keys are properties, as upcased
  11888. strings."
  11889. (org-with-point-at pom
  11890. (when (and (derived-mode-p 'org-mode)
  11891. (ignore-errors (org-back-to-heading t)))
  11892. (catch 'exit
  11893. (let* ((beg (point))
  11894. (specific (and (stringp which) (upcase which)))
  11895. (which (cond ((not specific) which)
  11896. ((member specific org-special-properties) 'special)
  11897. (t 'standard)))
  11898. props)
  11899. ;; Get the special properties, like TODO and TAGS.
  11900. (when (memq which '(nil all special))
  11901. (when (or (not specific) (string= specific "CLOCKSUM"))
  11902. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11903. (when clocksum
  11904. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11905. props)))
  11906. (when specific (throw 'exit props)))
  11907. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11908. (let ((clocksumt (get-text-property (point)
  11909. :org-clock-minutes-today)))
  11910. (when clocksumt
  11911. (push (cons "CLOCKSUM_T"
  11912. (org-duration-from-minutes clocksumt))
  11913. props)))
  11914. (when specific (throw 'exit props)))
  11915. (when (or (not specific) (string= specific "ITEM"))
  11916. (let ((case-fold-search nil))
  11917. (when (looking-at org-complex-heading-regexp)
  11918. (push (cons "ITEM"
  11919. (let ((title (match-string-no-properties 4)))
  11920. (if (org-string-nw-p title)
  11921. (org-remove-tabs title)
  11922. "")))
  11923. props)))
  11924. (when specific (throw 'exit props)))
  11925. (when (or (not specific) (string= specific "TODO"))
  11926. (let ((case-fold-search nil))
  11927. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11928. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11929. (when specific (throw 'exit props)))
  11930. (when (or (not specific) (string= specific "PRIORITY"))
  11931. (push (cons "PRIORITY"
  11932. (if (looking-at org-priority-regexp)
  11933. (match-string-no-properties 2)
  11934. (char-to-string org-default-priority)))
  11935. props)
  11936. (when specific (throw 'exit props)))
  11937. (when (or (not specific) (string= specific "FILE"))
  11938. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11939. props)
  11940. (when specific (throw 'exit props)))
  11941. (when (or (not specific) (string= specific "TAGS"))
  11942. (let ((tags (org-get-tags nil t)))
  11943. (when tags
  11944. (push (cons "TAGS" (org-make-tag-string tags))
  11945. props)))
  11946. (when specific (throw 'exit props)))
  11947. (when (or (not specific) (string= specific "ALLTAGS"))
  11948. (let ((tags (org-get-tags)))
  11949. (when tags
  11950. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11951. props)))
  11952. (when specific (throw 'exit props)))
  11953. (when (or (not specific) (string= specific "BLOCKED"))
  11954. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11955. (when specific (throw 'exit props)))
  11956. (when (or (not specific)
  11957. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11958. (forward-line)
  11959. (when (looking-at-p org-planning-line-re)
  11960. (end-of-line)
  11961. (let ((bol (line-beginning-position))
  11962. ;; Backward compatibility: time keywords used to
  11963. ;; be configurable (before 8.3). Make sure we
  11964. ;; get the correct keyword.
  11965. (key-assoc `(("CLOSED" . ,org-closed-string)
  11966. ("DEADLINE" . ,org-deadline-string)
  11967. ("SCHEDULED" . ,org-scheduled-string))))
  11968. (dolist (pair (if specific (list (assoc specific key-assoc))
  11969. key-assoc))
  11970. (save-excursion
  11971. (when (search-backward (cdr pair) bol t)
  11972. (goto-char (match-end 0))
  11973. (skip-chars-forward " \t")
  11974. (and (looking-at org-ts-regexp-both)
  11975. (push (cons (car pair)
  11976. (match-string-no-properties 0))
  11977. props)))))))
  11978. (when specific (throw 'exit props)))
  11979. (when (or (not specific)
  11980. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11981. (let ((find-ts
  11982. (lambda (end ts)
  11983. ;; Fix next time-stamp before END. TS is the
  11984. ;; list of time-stamps found so far.
  11985. (let ((ts ts)
  11986. (regexp (cond
  11987. ((string= specific "TIMESTAMP")
  11988. org-ts-regexp)
  11989. ((string= specific "TIMESTAMP_IA")
  11990. org-ts-regexp-inactive)
  11991. ((assoc "TIMESTAMP_IA" ts)
  11992. org-ts-regexp)
  11993. ((assoc "TIMESTAMP" ts)
  11994. org-ts-regexp-inactive)
  11995. (t org-ts-regexp-both))))
  11996. (catch 'next
  11997. (while (re-search-forward regexp end t)
  11998. (backward-char)
  11999. (let ((object (org-element-context)))
  12000. ;; Accept to match timestamps in node
  12001. ;; properties, too.
  12002. (when (memq (org-element-type object)
  12003. '(node-property timestamp))
  12004. (let ((type
  12005. (org-element-property :type object)))
  12006. (cond
  12007. ((and (memq type '(active active-range))
  12008. (not (equal specific "TIMESTAMP_IA")))
  12009. (unless (assoc "TIMESTAMP" ts)
  12010. (push (cons "TIMESTAMP"
  12011. (org-element-property
  12012. :raw-value object))
  12013. ts)
  12014. (when specific (throw 'exit ts))))
  12015. ((and (memq type '(inactive inactive-range))
  12016. (not (string= specific "TIMESTAMP")))
  12017. (unless (assoc "TIMESTAMP_IA" ts)
  12018. (push (cons "TIMESTAMP_IA"
  12019. (org-element-property
  12020. :raw-value object))
  12021. ts)
  12022. (when specific (throw 'exit ts))))))
  12023. ;; Both timestamp types are found,
  12024. ;; move to next part.
  12025. (when (= (length ts) 2) (throw 'next ts)))))
  12026. ts)))))
  12027. (goto-char beg)
  12028. ;; First look for timestamps within headline.
  12029. (let ((ts (funcall find-ts (line-end-position) nil)))
  12030. (if (= (length ts) 2) (setq props (nconc ts props))
  12031. ;; Then find timestamps in the section, skipping
  12032. ;; planning line.
  12033. (let ((end (save-excursion (outline-next-heading))))
  12034. (forward-line)
  12035. (when (looking-at-p org-planning-line-re) (forward-line))
  12036. (setq props (nconc (funcall find-ts end ts) props))))))))
  12037. ;; Get the standard properties, like :PROP:.
  12038. (when (memq which '(nil all standard))
  12039. ;; If we are looking after a specific property, delegate
  12040. ;; to `org-entry-get', which is faster. However, make an
  12041. ;; exception for "CATEGORY", since it can be also set
  12042. ;; through keywords (i.e. #+CATEGORY).
  12043. (if (and specific (not (equal specific "CATEGORY")))
  12044. (let ((value (org-entry-get beg specific nil t)))
  12045. (throw 'exit (and value (list (cons specific value)))))
  12046. (let ((range (org-get-property-block beg)))
  12047. (when range
  12048. (let ((end (cdr range)) seen-base)
  12049. (goto-char (car range))
  12050. ;; Unlike to `org--update-property-plist', we
  12051. ;; handle the case where base values is found
  12052. ;; after its extension. We also forbid standard
  12053. ;; properties to be named as special properties.
  12054. (while (re-search-forward org-property-re end t)
  12055. (let* ((key (upcase (match-string-no-properties 2)))
  12056. (extendp (string-match-p "\\+\\'" key))
  12057. (key-base (if extendp (substring key 0 -1) key))
  12058. (value (match-string-no-properties 3)))
  12059. (cond
  12060. ((member-ignore-case key-base org-special-properties))
  12061. (extendp
  12062. (setq props
  12063. (org--update-property-plist key value props)))
  12064. ((member key seen-base))
  12065. (t (push key seen-base)
  12066. (let ((p (assoc-string key props t)))
  12067. (if p (setcdr p (concat value " " (cdr p)))
  12068. (push (cons key value) props))))))))))))
  12069. (unless (assoc "CATEGORY" props)
  12070. (push (cons "CATEGORY" (org-get-category beg)) props)
  12071. (when (string= specific "CATEGORY") (throw 'exit props)))
  12072. ;; Return value.
  12073. props)))))
  12074. (defun org--property-local-values (property literal-nil)
  12075. "Return value for PROPERTY in current entry.
  12076. Value is a list whose car is the base value for PROPERTY and cdr
  12077. a list of accumulated values. Return nil if neither is found in
  12078. the entry. Also return nil when PROPERTY is set to \"nil\",
  12079. unless LITERAL-NIL is non-nil."
  12080. (let ((range (org-get-property-block)))
  12081. (when range
  12082. (goto-char (car range))
  12083. (let* ((case-fold-search t)
  12084. (end (cdr range))
  12085. (value
  12086. ;; Base value.
  12087. (save-excursion
  12088. (let ((v (and (re-search-forward
  12089. (org-re-property property nil t) end t)
  12090. (match-string-no-properties 3))))
  12091. (list (if literal-nil v (org-not-nil v)))))))
  12092. ;; Find additional values.
  12093. (let* ((property+ (org-re-property (concat property "+") nil t)))
  12094. (while (re-search-forward property+ end t)
  12095. (push (match-string-no-properties 3) value)))
  12096. ;; Return final values.
  12097. (and (not (equal value '(nil))) (nreverse value))))))
  12098. (defun org--property-global-value (property literal-nil)
  12099. "Return value for PROPERTY in current buffer.
  12100. Return value is a string. Return nil if property is not set
  12101. globally. Also return nil when PROPERTY is set to \"nil\",
  12102. unless LITERAL-NIL is non-nil."
  12103. (let ((global
  12104. (cdr (or (assoc-string property org-file-properties t)
  12105. (assoc-string property org-global-properties t)
  12106. (assoc-string property org-global-properties-fixed t)))))
  12107. (if literal-nil global (org-not-nil global))))
  12108. (defun org-entry-get (pom property &optional inherit literal-nil)
  12109. "Get value of PROPERTY for entry or content at point-or-marker POM.
  12110. If INHERIT is non-nil and the entry does not have the property,
  12111. then also check higher levels of the hierarchy. If INHERIT is
  12112. the symbol `selective', use inheritance only if the setting in
  12113. `org-use-property-inheritance' selects PROPERTY for inheritance.
  12114. If the property is present but empty, the return value is the
  12115. empty string. If the property is not present at all, nil is
  12116. returned. In any other case, return the value as a string.
  12117. Search is case-insensitive.
  12118. If LITERAL-NIL is set, return the string value \"nil\" as
  12119. a string, do not interpret it as the list atom nil. This is used
  12120. for inheritance when a \"nil\" value can supersede a non-nil
  12121. value higher up the hierarchy."
  12122. (org-with-point-at pom
  12123. (cond
  12124. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  12125. ;; We need a special property. Use `org-entry-properties' to
  12126. ;; retrieve it, but specify the wanted property.
  12127. (cdr (assoc-string property (org-entry-properties nil property))))
  12128. ((and inherit
  12129. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  12130. (org-entry-get-with-inheritance property literal-nil))
  12131. (t
  12132. (let* ((local (org--property-local-values property literal-nil))
  12133. (value (and local (mapconcat #'identity (delq nil local) " "))))
  12134. (if literal-nil value (org-not-nil value)))))))
  12135. (defun org-property-or-variable-value (var &optional inherit)
  12136. "Check if there is a property fixing the value of VAR.
  12137. If yes, return this value. If not, return the current value of the variable."
  12138. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  12139. (if (and prop (stringp prop) (string-match "\\S-" prop))
  12140. (read prop)
  12141. (symbol-value var))))
  12142. (defun org-entry-delete (pom property)
  12143. "Delete PROPERTY from entry at point-or-marker POM.
  12144. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  12145. non-nil when a property was removed."
  12146. (org-with-point-at pom
  12147. (pcase (org-get-property-block)
  12148. (`(,begin . ,origin)
  12149. (let* ((end (copy-marker origin))
  12150. (re (org-re-property
  12151. (concat (regexp-quote property) "\\+?") t t)))
  12152. (goto-char begin)
  12153. (while (re-search-forward re end t)
  12154. (delete-region (match-beginning 0) (line-beginning-position 2)))
  12155. ;; If drawer is empty, remove it altogether.
  12156. (when (= begin end)
  12157. (delete-region (line-beginning-position 0)
  12158. (line-beginning-position 2)))
  12159. ;; Return non-nil if some property was removed.
  12160. (prog1 (/= end origin) (set-marker end nil))))
  12161. (_ nil))))
  12162. ;; Multi-values properties are properties that contain multiple values
  12163. ;; These values are assumed to be single words, separated by whitespace.
  12164. (defun org-entry-add-to-multivalued-property (pom property value)
  12165. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  12166. (let* ((old (org-entry-get pom property))
  12167. (values (and old (split-string old))))
  12168. (setq value (org-entry-protect-space value))
  12169. (unless (member value values)
  12170. (setq values (append values (list value)))
  12171. (org-entry-put pom property (mapconcat #'identity values " ")))))
  12172. (defun org-entry-remove-from-multivalued-property (pom property value)
  12173. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  12174. (let* ((old (org-entry-get pom property))
  12175. (values (and old (split-string old))))
  12176. (setq value (org-entry-protect-space value))
  12177. (when (member value values)
  12178. (setq values (delete value values))
  12179. (org-entry-put pom property (mapconcat #'identity values " ")))))
  12180. (defun org-entry-member-in-multivalued-property (pom property value)
  12181. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  12182. (let* ((old (org-entry-get pom property))
  12183. (values (and old (split-string old))))
  12184. (setq value (org-entry-protect-space value))
  12185. (member value values)))
  12186. (defun org-entry-get-multivalued-property (pom property)
  12187. "Return a list of values in a multivalued property."
  12188. (let* ((value (org-entry-get pom property))
  12189. (values (and value (split-string value))))
  12190. (mapcar #'org-entry-restore-space values)))
  12191. (defun org-entry-put-multivalued-property (pom property &rest values)
  12192. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  12193. VALUES should be a list of strings. Spaces will be protected."
  12194. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  12195. (let* ((value (org-entry-get pom property))
  12196. (values (and value (split-string value))))
  12197. (mapcar #'org-entry-restore-space values)))
  12198. (defun org-entry-protect-space (s)
  12199. "Protect spaces and newline in string S."
  12200. (while (string-match " " s)
  12201. (setq s (replace-match "%20" t t s)))
  12202. (while (string-match "\n" s)
  12203. (setq s (replace-match "%0A" t t s)))
  12204. s)
  12205. (defun org-entry-restore-space (s)
  12206. "Restore spaces and newline in string S."
  12207. (while (string-match "%20" s)
  12208. (setq s (replace-match " " t t s)))
  12209. (while (string-match "%0A" s)
  12210. (setq s (replace-match "\n" t t s)))
  12211. s)
  12212. (defvar org-entry-property-inherited-from (make-marker)
  12213. "Marker pointing to the entry from where a property was inherited.
  12214. Each call to `org-entry-get-with-inheritance' will set this marker to the
  12215. location of the entry where the inheritance search matched. If there was
  12216. no match, the marker will point nowhere.
  12217. Note that also `org-entry-get' calls this function, if the INHERIT flag
  12218. is set.")
  12219. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  12220. "Get PROPERTY of entry or content at point, search higher levels if needed.
  12221. The search will stop at the first ancestor which has the property defined.
  12222. If the value found is \"nil\", return nil to show that the property
  12223. should be considered as undefined (this is the meaning of nil here).
  12224. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  12225. (move-marker org-entry-property-inherited-from nil)
  12226. (org-with-wide-buffer
  12227. (let (value)
  12228. (catch 'exit
  12229. (while t
  12230. (let ((v (org--property-local-values property literal-nil)))
  12231. (when v
  12232. (setq value
  12233. (concat (mapconcat #'identity (delq nil v) " ")
  12234. (and value " ")
  12235. value)))
  12236. (cond
  12237. ((car v)
  12238. (org-back-to-heading t)
  12239. (move-marker org-entry-property-inherited-from (point))
  12240. (throw 'exit nil))
  12241. ((org-up-heading-safe))
  12242. (t
  12243. (let ((global (org--property-global-value property literal-nil)))
  12244. (cond ((not global))
  12245. (value (setq value (concat global " " value)))
  12246. (t (setq value global))))
  12247. (throw 'exit nil))))))
  12248. (if literal-nil value (org-not-nil value)))))
  12249. (defvar org-property-changed-functions nil
  12250. "Hook called when the value of a property has changed.
  12251. Each hook function should accept two arguments, the name of the property
  12252. and the new value.")
  12253. (defun org-entry-put (pom property value)
  12254. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  12255. If the value is nil, it is converted to the empty string. If it
  12256. is not a string, an error is raised. Also raise an error on
  12257. invalid property names.
  12258. PROPERTY can be any regular property (see
  12259. `org-special-properties'). It can also be \"TODO\",
  12260. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  12261. For the last two properties, VALUE may have any of the special
  12262. values \"earlier\" and \"later\". The function then increases or
  12263. decreases scheduled or deadline date by one day."
  12264. (cond ((null value) (setq value ""))
  12265. ((not (stringp value)) (error "Properties values should be strings"))
  12266. ((not (org--valid-property-p property))
  12267. (user-error "Invalid property name: \"%s\"" property)))
  12268. (org-with-point-at pom
  12269. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12270. (org-back-to-heading t)
  12271. (org-with-limited-levels (org-back-to-heading t)))
  12272. (let ((beg (point)))
  12273. (cond
  12274. ((equal property "TODO")
  12275. (cond ((not (org-string-nw-p value)) (setq value 'none))
  12276. ((not (member value org-todo-keywords-1))
  12277. (user-error "\"%s\" is not a valid TODO state" value)))
  12278. (org-todo value)
  12279. (org-align-tags))
  12280. ((equal property "PRIORITY")
  12281. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  12282. (org-align-tags))
  12283. ((equal property "SCHEDULED")
  12284. (forward-line)
  12285. (if (and (looking-at-p org-planning-line-re)
  12286. (re-search-forward
  12287. org-scheduled-time-regexp (line-end-position) t))
  12288. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12289. ((string= value "later") (org-timestamp-change 1 'day))
  12290. ((string= value "") (org-schedule '(4)))
  12291. (t (org-schedule nil value)))
  12292. (if (member value '("earlier" "later" ""))
  12293. (call-interactively #'org-schedule)
  12294. (org-schedule nil value))))
  12295. ((equal property "DEADLINE")
  12296. (forward-line)
  12297. (if (and (looking-at-p org-planning-line-re)
  12298. (re-search-forward
  12299. org-deadline-time-regexp (line-end-position) t))
  12300. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12301. ((string= value "later") (org-timestamp-change 1 'day))
  12302. ((string= value "") (org-deadline '(4)))
  12303. (t (org-deadline nil value)))
  12304. (if (member value '("earlier" "later" ""))
  12305. (call-interactively #'org-deadline)
  12306. (org-deadline nil value))))
  12307. ((member property org-special-properties)
  12308. (error "The %s property cannot be set with `org-entry-put'" property))
  12309. (t
  12310. (let* ((range (org-get-property-block beg 'force))
  12311. (end (cdr range))
  12312. (case-fold-search t))
  12313. (goto-char (car range))
  12314. (if (re-search-forward (org-re-property property nil t) end t)
  12315. (progn (delete-region (match-beginning 0) (match-end 0))
  12316. (goto-char (match-beginning 0)))
  12317. (goto-char end)
  12318. (insert "\n")
  12319. (backward-char))
  12320. (insert ":" property ":")
  12321. (when value (insert " " value))
  12322. (org-indent-line)))))
  12323. (run-hook-with-args 'org-property-changed-functions property value)))
  12324. (defun org-buffer-property-keys (&optional specials defaults columns)
  12325. "Get all property keys in the current buffer.
  12326. When SPECIALS is non-nil, also list the special properties that
  12327. reflect things like tags and TODO state.
  12328. When DEFAULTS is non-nil, also include properties that has
  12329. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  12330. DESCRIPTION, LOCATION, and LOGGING and others.
  12331. When COLUMNS in non-nil, also include property names given in
  12332. COLUMN formats in the current buffer."
  12333. (let ((case-fold-search t)
  12334. (props (append
  12335. (and specials org-special-properties)
  12336. (and defaults (cons org-effort-property org-default-properties))
  12337. nil)))
  12338. (org-with-wide-buffer
  12339. (goto-char (point-min))
  12340. (while (re-search-forward org-property-start-re nil t)
  12341. (catch :skip
  12342. (let ((range (org-get-property-block)))
  12343. (unless range (throw :skip nil))
  12344. (goto-char (car range))
  12345. (let ((begin (car range))
  12346. (end (cdr range)))
  12347. ;; Make sure that found property block is not located
  12348. ;; before current point, as it would generate an infloop.
  12349. ;; It can happen, for example, in the following
  12350. ;; situation:
  12351. ;;
  12352. ;; * Headline
  12353. ;; :PROPERTIES:
  12354. ;; ...
  12355. ;; :END:
  12356. ;; *************** Inlinetask
  12357. ;; #+BEGIN_EXAMPLE
  12358. ;; :PROPERTIES:
  12359. ;; #+END_EXAMPLE
  12360. ;;
  12361. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  12362. (while (< (point) end)
  12363. (let ((p (progn (looking-at org-property-re)
  12364. (match-string-no-properties 2))))
  12365. ;; Only add true property name, not extension symbol.
  12366. (push (if (not (string-match-p "\\+\\'" p)) p
  12367. (substring p 0 -1))
  12368. props))
  12369. (forward-line))))
  12370. (outline-next-heading)))
  12371. (when columns
  12372. (goto-char (point-min))
  12373. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  12374. (let ((element (org-element-at-point)))
  12375. (when (memq (org-element-type element) '(keyword node-property))
  12376. (let ((value (org-element-property :value element))
  12377. (start 0))
  12378. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  12379. \\(?:{[^}]+}\\)?"
  12380. value start)
  12381. (setq start (match-end 0))
  12382. (let ((p (match-string-no-properties 1 value)))
  12383. (unless (member-ignore-case p org-special-properties)
  12384. (push p props))))))))))
  12385. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  12386. (defun org-property-values (key)
  12387. "List all non-nil values of property KEY in current buffer."
  12388. (org-with-wide-buffer
  12389. (goto-char (point-min))
  12390. (let ((case-fold-search t)
  12391. (re (org-re-property key))
  12392. values)
  12393. (while (re-search-forward re nil t)
  12394. (push (org-entry-get (point) key) values))
  12395. (delete-dups values))))
  12396. (defun org-insert-property-drawer ()
  12397. "Insert a property drawer into the current entry."
  12398. (org-with-wide-buffer
  12399. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12400. (org-back-to-heading t)
  12401. (org-with-limited-levels (org-back-to-heading t)))
  12402. (forward-line)
  12403. (when (looking-at-p org-planning-line-re) (forward-line))
  12404. (unless (looking-at-p org-property-drawer-re)
  12405. ;; Make sure we start editing a line from current entry, not from
  12406. ;; next one. It prevents extending text properties or overlays
  12407. ;; belonging to the latter.
  12408. (when (bolp) (backward-char))
  12409. (let ((begin (1+ (point)))
  12410. (inhibit-read-only t))
  12411. (insert "\n:PROPERTIES:\n:END:")
  12412. (when (eobp) (insert "\n"))
  12413. (org-indent-region begin (point))))))
  12414. (defun org-insert-drawer (&optional arg drawer)
  12415. "Insert a drawer at point.
  12416. When optional argument ARG is non-nil, insert a property drawer.
  12417. Optional argument DRAWER, when non-nil, is a string representing
  12418. drawer's name. Otherwise, the user is prompted for a name.
  12419. If a region is active, insert the drawer around that region
  12420. instead.
  12421. Point is left between drawer's boundaries."
  12422. (interactive "P")
  12423. (let* ((drawer (if arg "PROPERTIES"
  12424. (or drawer (read-from-minibuffer "Drawer: ")))))
  12425. (cond
  12426. ;; With C-u, fall back on `org-insert-property-drawer'
  12427. (arg (org-insert-property-drawer))
  12428. ;; Check validity of suggested drawer's name.
  12429. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  12430. (user-error "Invalid drawer name"))
  12431. ;; With an active region, insert a drawer at point.
  12432. ((not (org-region-active-p))
  12433. (progn
  12434. (unless (bolp) (insert "\n"))
  12435. (insert (format ":%s:\n\n:END:\n" drawer))
  12436. (forward-line -2)))
  12437. ;; Otherwise, insert the drawer at point
  12438. (t
  12439. (let ((rbeg (region-beginning))
  12440. (rend (copy-marker (region-end))))
  12441. (unwind-protect
  12442. (progn
  12443. (goto-char rbeg)
  12444. (beginning-of-line)
  12445. (when (save-excursion
  12446. (re-search-forward org-outline-regexp-bol rend t))
  12447. (user-error "Drawers cannot contain headlines"))
  12448. ;; Position point at the beginning of the first
  12449. ;; non-blank line in region. Insert drawer's opening
  12450. ;; there, then indent it.
  12451. (org-skip-whitespace)
  12452. (beginning-of-line)
  12453. (insert ":" drawer ":\n")
  12454. (forward-line -1)
  12455. (indent-for-tab-command)
  12456. ;; Move point to the beginning of the first blank line
  12457. ;; after the last non-blank line in region. Insert
  12458. ;; drawer's closing, then indent it.
  12459. (goto-char rend)
  12460. (skip-chars-backward " \r\t\n")
  12461. (insert "\n:END:")
  12462. (deactivate-mark t)
  12463. (indent-for-tab-command)
  12464. (unless (eolp) (insert "\n")))
  12465. ;; Clear marker, whatever the outcome of insertion is.
  12466. (set-marker rend nil)))))))
  12467. (defvar org-property-set-functions-alist nil
  12468. "Property set function alist.
  12469. Each entry should have the following format:
  12470. (PROPERTY . READ-FUNCTION)
  12471. The read function will be called with the same argument as
  12472. `org-completing-read'.")
  12473. (defun org-set-property-function (property)
  12474. "Get the function that should be used to set PROPERTY.
  12475. This is computed according to `org-property-set-functions-alist'."
  12476. (or (cdr (assoc property org-property-set-functions-alist))
  12477. 'org-completing-read))
  12478. (defun org-read-property-value (property &optional pom)
  12479. "Read value for PROPERTY, as a string.
  12480. When optional argument POM is non-nil, completion uses additional
  12481. information, i.e., allowed or existing values at point or marker
  12482. POM."
  12483. (let* ((completion-ignore-case t)
  12484. (allowed
  12485. (or (org-property-get-allowed-values nil property 'table)
  12486. (and pom (org-property-get-allowed-values pom property 'table))))
  12487. (current (org-entry-get nil property))
  12488. (prompt (format "%s value%s: "
  12489. property
  12490. (if (org-string-nw-p current)
  12491. (format " [%s]" current)
  12492. "")))
  12493. (set-function (org-set-property-function property)))
  12494. (org-trim
  12495. (if allowed
  12496. (funcall set-function
  12497. prompt allowed nil
  12498. (not (get-text-property 0 'org-unrestricted (caar allowed))))
  12499. (let ((all (mapcar #'list
  12500. (append (org-property-values property)
  12501. (and pom
  12502. (org-with-point-at pom
  12503. (org-property-values property)))))))
  12504. (funcall set-function prompt all nil nil "" nil current))))))
  12505. (defvar org-last-set-property nil)
  12506. (defvar org-last-set-property-value nil)
  12507. (defun org-read-property-name ()
  12508. "Read a property name."
  12509. (let ((completion-ignore-case t)
  12510. (default-prop (or (and (org-at-property-p)
  12511. (match-string-no-properties 2))
  12512. org-last-set-property)))
  12513. (org-completing-read
  12514. (concat "Property"
  12515. (if default-prop (concat " [" default-prop "]") "")
  12516. ": ")
  12517. (mapcar #'list (org-buffer-property-keys nil t t))
  12518. nil nil nil nil default-prop)))
  12519. (defun org-set-property-and-value (use-last)
  12520. "Allow to set [PROPERTY]: [value] direction from prompt.
  12521. When use-default, don't even ask, just use the last
  12522. \"[PROPERTY]: [value]\" string from the history."
  12523. (interactive "P")
  12524. (let* ((completion-ignore-case t)
  12525. (pv (or (and use-last org-last-set-property-value)
  12526. (org-completing-read
  12527. "Enter a \"[Property]: [value]\" pair: "
  12528. nil nil nil nil nil
  12529. org-last-set-property-value)))
  12530. prop val)
  12531. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  12532. (setq prop (match-string 1 pv)
  12533. val (match-string 2 pv))
  12534. (org-set-property prop val))))
  12535. (defun org-set-property (property value)
  12536. "In the current entry, set PROPERTY to VALUE.
  12537. When called interactively, this will prompt for a property name, offering
  12538. completion on existing and default properties. And then it will prompt
  12539. for a value, offering completion either on allowed values (via an inherited
  12540. xxx_ALL property) or on existing values in other instances of this property
  12541. in the current file.
  12542. Throw an error when trying to set a property with an invalid name."
  12543. (interactive (list nil nil))
  12544. (let ((property (or property (org-read-property-name))))
  12545. ;; `org-entry-put' also makes the following check, but this one
  12546. ;; avoids polluting `org-last-set-property' and
  12547. ;; `org-last-set-property-value' needlessly.
  12548. (unless (org--valid-property-p property)
  12549. (user-error "Invalid property name: \"%s\"" property))
  12550. (let ((value (or value (org-read-property-value property)))
  12551. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  12552. (setq org-last-set-property property)
  12553. (setq org-last-set-property-value (concat property ": " value))
  12554. ;; Possibly postprocess the inserted value:
  12555. (when fn (setq value (funcall fn value)))
  12556. (unless (equal (org-entry-get nil property) value)
  12557. (org-entry-put nil property value)))))
  12558. (defun org-find-property (property &optional value)
  12559. "Find first entry in buffer that sets PROPERTY.
  12560. When optional argument VALUE is non-nil, only consider an entry
  12561. if it contains PROPERTY set to this value. If PROPERTY should be
  12562. explicitly set to nil, use string \"nil\" for VALUE.
  12563. Return position where the entry begins, or nil if there is no
  12564. such entry. If narrowing is in effect, only search the visible
  12565. part of the buffer."
  12566. (save-excursion
  12567. (goto-char (point-min))
  12568. (let ((case-fold-search t)
  12569. (re (org-re-property property nil (not value) value)))
  12570. (catch 'exit
  12571. (while (re-search-forward re nil t)
  12572. (when (if value (org-at-property-p)
  12573. (org-entry-get (point) property nil t))
  12574. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  12575. (defun org-delete-property (property)
  12576. "In the current entry, delete PROPERTY."
  12577. (interactive
  12578. (let* ((completion-ignore-case t)
  12579. (cat (org-entry-get (point) "CATEGORY"))
  12580. (props0 (org-entry-properties nil 'standard))
  12581. (props (if cat props0
  12582. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  12583. (prop (if (< 1 (length props))
  12584. (completing-read "Property: " props nil t)
  12585. (caar props))))
  12586. (list prop)))
  12587. (if (not property)
  12588. (message "No property to delete in this entry")
  12589. (org-entry-delete nil property)
  12590. (message "Property \"%s\" deleted" property)))
  12591. (defun org-delete-property-globally (property)
  12592. "Remove PROPERTY globally, from all entries.
  12593. This function ignores narrowing, if any."
  12594. (interactive
  12595. (let* ((completion-ignore-case t)
  12596. (prop (completing-read
  12597. "Globally remove property: "
  12598. (mapcar #'list (org-buffer-property-keys)))))
  12599. (list prop)))
  12600. (org-with-wide-buffer
  12601. (goto-char (point-min))
  12602. (let ((count 0)
  12603. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  12604. (while (re-search-forward re nil t)
  12605. (when (org-entry-delete (point) property) (cl-incf count)))
  12606. (message "Property \"%s\" removed from %d entries" property count))))
  12607. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  12608. (defun org-compute-property-at-point ()
  12609. "Compute the property at point.
  12610. This looks for an enclosing column format, extracts the operator and
  12611. then applies it to the property in the column format's scope."
  12612. (interactive)
  12613. (unless (org-at-property-p)
  12614. (user-error "Not at a property"))
  12615. (let ((prop (match-string-no-properties 2)))
  12616. (org-columns-get-format-and-top-level)
  12617. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  12618. (user-error "No operator defined for property %s" prop))
  12619. (org-columns-compute prop)))
  12620. (defvar org-property-allowed-value-functions nil
  12621. "Hook for functions supplying allowed values for a specific property.
  12622. The functions must take a single argument, the name of the property, and
  12623. return a flat list of allowed values. If \":ETC\" is one of
  12624. the values, this means that these values are intended as defaults for
  12625. completion, but that other values should be allowed too.
  12626. The functions must return nil if they are not responsible for this
  12627. property.")
  12628. (defun org-property-get-allowed-values (pom property &optional table)
  12629. "Get allowed values for the property PROPERTY.
  12630. When TABLE is non-nil, return an alist that can directly be used for
  12631. completion."
  12632. (let (vals)
  12633. (cond
  12634. ((equal property "TODO")
  12635. (setq vals (org-with-point-at pom
  12636. (append org-todo-keywords-1 '("")))))
  12637. ((equal property "PRIORITY")
  12638. (let ((n org-lowest-priority))
  12639. (while (>= n org-highest-priority)
  12640. (push (char-to-string n) vals)
  12641. (setq n (1- n)))))
  12642. ((equal property "CATEGORY"))
  12643. ((member property org-special-properties))
  12644. ((setq vals (run-hook-with-args-until-success
  12645. 'org-property-allowed-value-functions property)))
  12646. (t
  12647. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  12648. (when (and vals (string-match "\\S-" vals))
  12649. (setq vals (car (read-from-string (concat "(" vals ")"))))
  12650. (setq vals (mapcar (lambda (x)
  12651. (cond ((stringp x) x)
  12652. ((numberp x) (number-to-string x))
  12653. ((symbolp x) (symbol-name x))
  12654. (t "???")))
  12655. vals)))))
  12656. (when (member ":ETC" vals)
  12657. (setq vals (remove ":ETC" vals))
  12658. (org-add-props (car vals) '(org-unrestricted t)))
  12659. (if table (mapcar 'list vals) vals)))
  12660. (defun org-property-previous-allowed-value (&optional _previous)
  12661. "Switch to the next allowed value for this property."
  12662. (interactive)
  12663. (org-property-next-allowed-value t))
  12664. (defun org-property-next-allowed-value (&optional previous)
  12665. "Switch to the next allowed value for this property."
  12666. (interactive)
  12667. (unless (org-at-property-p)
  12668. (user-error "Not at a property"))
  12669. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  12670. (key (match-string 2))
  12671. (value (match-string 3))
  12672. (allowed (or (org-property-get-allowed-values (point) key)
  12673. (and (member value '("[ ]" "[-]" "[X]"))
  12674. '("[ ]" "[X]"))))
  12675. (heading (save-match-data (nth 4 (org-heading-components))))
  12676. nval)
  12677. (unless allowed
  12678. (user-error "Allowed values for this property have not been defined"))
  12679. (when previous (setq allowed (reverse allowed)))
  12680. (when (member value allowed)
  12681. (setq nval (car (cdr (member value allowed)))))
  12682. (setq nval (or nval (car allowed)))
  12683. (when (equal nval value)
  12684. (user-error "Only one allowed value for this property"))
  12685. (org-at-property-p)
  12686. (replace-match (concat " :" key ": " nval) t t)
  12687. (org-indent-line)
  12688. (beginning-of-line 1)
  12689. (skip-chars-forward " \t")
  12690. (when (equal prop org-effort-property)
  12691. (org-refresh-property
  12692. '((effort . identity)
  12693. (effort-minutes . org-duration-to-minutes))
  12694. nval)
  12695. (when (string= org-clock-current-task heading)
  12696. (setq org-clock-effort nval)
  12697. (org-clock-update-mode-line)))
  12698. (run-hook-with-args 'org-property-changed-functions key nval)))
  12699. (defun org-find-olp (path &optional this-buffer)
  12700. "Return a marker pointing to the entry at outline path OLP.
  12701. If anything goes wrong, throw an error.
  12702. You can wrap this call to catch the error like this:
  12703. (condition-case msg
  12704. (org-mobile-locate-entry (match-string 4))
  12705. (error (nth 1 msg)))
  12706. The return value will then be either a string with the error message,
  12707. or a marker if everything is OK.
  12708. If THIS-BUFFER is set, the outline path does not contain a file,
  12709. only headings."
  12710. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12711. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12712. (level 1)
  12713. (lmin 1)
  12714. (lmax 1)
  12715. end found flevel)
  12716. (unless buffer (error "File not found :%s" file))
  12717. (with-current-buffer buffer
  12718. (unless (derived-mode-p 'org-mode)
  12719. (error "Buffer %s needs to be in Org mode" buffer))
  12720. (org-with-wide-buffer
  12721. (goto-char (point-min))
  12722. (dolist (heading path)
  12723. (let ((re (format org-complex-heading-regexp-format
  12724. (regexp-quote heading)))
  12725. (cnt 0))
  12726. (while (re-search-forward re end t)
  12727. (setq level (- (match-end 1) (match-beginning 1)))
  12728. (when (and (>= level lmin) (<= level lmax))
  12729. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12730. (when (= cnt 0)
  12731. (error "Heading not found on level %d: %s" lmax heading))
  12732. (when (> cnt 1)
  12733. (error "Heading not unique on level %d: %s" lmax heading))
  12734. (goto-char found)
  12735. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12736. (setq end (save-excursion (org-end-of-subtree t t)))))
  12737. (when (org-at-heading-p)
  12738. (point-marker))))))
  12739. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12740. "Find node HEADING in BUFFER.
  12741. Return a marker to the heading if it was found, or nil if not.
  12742. If POS-ONLY is set, return just the position instead of a marker.
  12743. The heading text must match exact, but it may have a TODO keyword,
  12744. a priority cookie and tags in the standard locations."
  12745. (with-current-buffer (or buffer (current-buffer))
  12746. (org-with-wide-buffer
  12747. (goto-char (point-min))
  12748. (let (case-fold-search)
  12749. (when (re-search-forward
  12750. (format org-complex-heading-regexp-format
  12751. (regexp-quote heading)) nil t)
  12752. (if pos-only
  12753. (match-beginning 0)
  12754. (move-marker (make-marker) (match-beginning 0))))))))
  12755. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12756. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12757. When the target headline is found, return a marker to this location."
  12758. (let ((files (directory-files (or dir default-directory)
  12759. t "\\`[^.#].*\\.org\\'"))
  12760. visiting m buffer)
  12761. (catch 'found
  12762. (dolist (file files)
  12763. (message "trying %s" file)
  12764. (setq visiting (org-find-base-buffer-visiting file))
  12765. (setq buffer (or visiting (find-file-noselect file)))
  12766. (setq m (org-find-exact-headline-in-buffer
  12767. heading buffer))
  12768. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12769. (and m (throw 'found m))))))
  12770. (defun org-find-entry-with-id (ident)
  12771. "Locate the entry that contains the ID property with exact value IDENT.
  12772. IDENT can be a string, a symbol or a number, this function will search for
  12773. the string representation of it.
  12774. Return the position where this entry starts, or nil if there is no such entry."
  12775. (interactive "sID: ")
  12776. (let ((id (cond
  12777. ((stringp ident) ident)
  12778. ((symbolp ident) (symbol-name ident))
  12779. ((numberp ident) (number-to-string ident))
  12780. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12781. (org-with-wide-buffer (org-find-property "ID" id))))
  12782. ;;;; Timestamps
  12783. (defvar org-last-changed-timestamp nil)
  12784. (defvar org-last-inserted-timestamp nil
  12785. "The last time stamp inserted with `org-insert-time-stamp'.")
  12786. (defun org-time-stamp (arg &optional inactive)
  12787. "Prompt for a date/time and insert a time stamp.
  12788. If the user specifies a time like HH:MM or if this command is
  12789. called with at least one prefix argument, the time stamp contains
  12790. the date and the time. Otherwise, only the date is included.
  12791. All parts of a date not specified by the user are filled in from
  12792. the timestamp at point, if any, or the current date/time
  12793. otherwise.
  12794. If there is already a timestamp at the cursor, it is replaced.
  12795. With two universal prefix arguments, insert an active timestamp
  12796. with the current time without prompting the user.
  12797. When called from lisp, the timestamp is inactive if INACTIVE is
  12798. non-nil."
  12799. (interactive "P")
  12800. (let* ((ts (cond
  12801. ((org-at-date-range-p t)
  12802. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12803. ((org-at-timestamp-p 'lax) (match-string 0))))
  12804. ;; Default time is either the timestamp at point or today.
  12805. ;; When entering a range, only the range start is considered.
  12806. (default-time (and ts
  12807. (apply #'encode-time (org-parse-time-string ts))))
  12808. (default-input (and ts (org-get-compact-tod ts)))
  12809. (repeater (and ts
  12810. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12811. (match-string 0 ts)))
  12812. org-time-was-given
  12813. org-end-time-was-given
  12814. (time
  12815. (if (equal arg '(16)) (current-time)
  12816. ;; Preserve `this-command' and `last-command'.
  12817. (let ((this-command this-command)
  12818. (last-command last-command))
  12819. (org-read-date
  12820. arg 'totime nil nil default-time default-input
  12821. inactive)))))
  12822. (cond
  12823. ((and ts
  12824. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12825. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12826. (insert "--")
  12827. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12828. (ts
  12829. ;; Make sure we're on a timestamp. When in the middle of a date
  12830. ;; range, move arbitrarily to range end.
  12831. (unless (org-at-timestamp-p 'lax)
  12832. (skip-chars-forward "-")
  12833. (org-at-timestamp-p 'lax))
  12834. (replace-match "")
  12835. (setq org-last-changed-timestamp
  12836. (org-insert-time-stamp
  12837. time (or org-time-was-given arg)
  12838. inactive nil nil (list org-end-time-was-given)))
  12839. (when repeater
  12840. (backward-char)
  12841. (insert " " repeater)
  12842. (setq org-last-changed-timestamp
  12843. (concat (substring org-last-inserted-timestamp 0 -1)
  12844. " " repeater ">")))
  12845. (message "Timestamp updated"))
  12846. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12847. (t (org-insert-time-stamp
  12848. time (or org-time-was-given arg) inactive nil nil
  12849. (list org-end-time-was-given))))))
  12850. ;; FIXME: can we use this for something else, like computing time differences?
  12851. (defun org-get-compact-tod (s)
  12852. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12853. (let* ((t1 (match-string 1 s))
  12854. (h1 (string-to-number (match-string 2 s)))
  12855. (m1 (string-to-number (match-string 3 s)))
  12856. (t2 (and (match-end 4) (match-string 5 s)))
  12857. (h2 (and t2 (string-to-number (match-string 6 s))))
  12858. (m2 (and t2 (string-to-number (match-string 7 s))))
  12859. dh dm)
  12860. (if (not t2)
  12861. t1
  12862. (setq dh (- h2 h1) dm (- m2 m1))
  12863. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12864. (concat t1 "+" (number-to-string dh)
  12865. (and (/= 0 dm) (format ":%02d" dm)))))))
  12866. (defun org-time-stamp-inactive (&optional arg)
  12867. "Insert an inactive time stamp.
  12868. An inactive time stamp is enclosed in square brackets instead of angle
  12869. brackets. It is inactive in the sense that it does not trigger agenda entries,
  12870. does not link to the calendar and cannot be changed with the S-cursor keys.
  12871. So these are more for recording a certain time/date.
  12872. If the user specifies a time like HH:MM or if this command is called with
  12873. at least one prefix argument, the time stamp contains the date and the time.
  12874. Otherwise, only the date is included.
  12875. When called with two universal prefix arguments, insert an active time stamp
  12876. with the current time without prompting the user."
  12877. (interactive "P")
  12878. (org-time-stamp arg 'inactive))
  12879. (defvar org-date-ovl (make-overlay 1 1))
  12880. (overlay-put org-date-ovl 'face 'org-date-selected)
  12881. (delete-overlay org-date-ovl)
  12882. (defvar org-ans1) ; dynamically scoped parameter
  12883. (defvar org-ans2) ; dynamically scoped parameter
  12884. (defvar org-plain-time-of-day-regexp) ; defined below
  12885. (defvar org-overriding-default-time nil) ; dynamically scoped
  12886. (defvar org-read-date-overlay nil)
  12887. (defvar org-dcst nil) ; dynamically scoped
  12888. (defvar org-read-date-history nil)
  12889. (defvar org-read-date-final-answer nil)
  12890. (defvar org-read-date-analyze-futurep nil)
  12891. (defvar org-read-date-analyze-forced-year nil)
  12892. (defvar org-read-date-inactive)
  12893. (defvar org-def)
  12894. (defvar org-defdecode)
  12895. (defvar org-with-time)
  12896. (defvar calendar-setup) ; Dynamically scoped.
  12897. (defun org-read-date (&optional with-time to-time from-string prompt
  12898. default-time default-input inactive)
  12899. "Read a date, possibly a time, and make things smooth for the user.
  12900. The prompt will suggest to enter an ISO date, but you can also enter anything
  12901. which will at least partially be understood by `parse-time-string'.
  12902. Unrecognized parts of the date will default to the current day, month, year,
  12903. hour and minute. If this command is called to replace a timestamp at point,
  12904. or to enter the second timestamp of a range, the default time is taken
  12905. from the existing stamp. Furthermore, the command prefers the future,
  12906. so if you are giving a date where the year is not given, and the day-month
  12907. combination is already past in the current year, it will assume you
  12908. mean next year. For details, see the manual. A few examples:
  12909. 3-2-5 --> 2003-02-05
  12910. feb 15 --> currentyear-02-15
  12911. 2/15 --> currentyear-02-15
  12912. sep 12 9 --> 2009-09-12
  12913. 12:45 --> today 12:45
  12914. 22 sept 0:34 --> currentyear-09-22 0:34
  12915. 12 --> currentyear-currentmonth-12
  12916. Fri --> nearest Friday after today
  12917. -Tue --> last Tuesday
  12918. etc.
  12919. Furthermore you can specify a relative date by giving, as the *first* thing
  12920. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12921. change in days weeks, months, years.
  12922. With a single plus or minus, the date is relative to today. With a double
  12923. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12924. +4d --> four days from today
  12925. +4 --> same as above
  12926. +2w --> two weeks from today
  12927. ++5 --> five days from default date
  12928. The function understands only English month and weekday abbreviations.
  12929. While prompting, a calendar is popped up - you can also select the
  12930. date with the mouse (button 1). The calendar shows a period of three
  12931. months. To scroll it to other months, use the keys `>' and `<'.
  12932. If you don't like the calendar, turn it off with
  12933. (setq org-read-date-popup-calendar nil)
  12934. With optional argument TO-TIME, the date will immediately be converted
  12935. to an internal time.
  12936. With an optional argument WITH-TIME, the prompt will suggest to
  12937. also insert a time. Note that when WITH-TIME is not set, you can
  12938. still enter a time, and this function will inform the calling routine
  12939. about this change. The calling routine may then choose to change the
  12940. format used to insert the time stamp into the buffer to include the time.
  12941. With optional argument FROM-STRING, read from this string instead from
  12942. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12943. the time/date that is used for everything that is not specified by the
  12944. user."
  12945. (require 'parse-time)
  12946. (let* ((org-with-time with-time)
  12947. (org-time-stamp-rounding-minutes
  12948. (if (equal org-with-time '(16))
  12949. '(0 0)
  12950. org-time-stamp-rounding-minutes))
  12951. (org-dcst org-display-custom-times)
  12952. (ct (org-current-time))
  12953. (org-def (or org-overriding-default-time default-time ct))
  12954. (org-defdecode (decode-time org-def))
  12955. (cur-frame (selected-frame))
  12956. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12957. (calendar-setup
  12958. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12959. (calendar-move-hook nil)
  12960. (calendar-view-diary-initially-flag nil)
  12961. (calendar-view-holidays-initially-flag nil)
  12962. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12963. ;; Rationalize `org-def' and `org-defdecode', if required.
  12964. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12965. (setf (nth 2 org-defdecode) -1)
  12966. (setf (nth 1 org-defdecode) 59)
  12967. (setq org-def (apply #'encode-time org-defdecode))
  12968. (setq org-defdecode (decode-time org-def)))
  12969. (let* ((timestr (format-time-string
  12970. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12971. org-def))
  12972. (prompt (concat (if prompt (concat prompt " ") "")
  12973. (format "Date+time [%s]: " timestr))))
  12974. (cond
  12975. (from-string (setq ans from-string))
  12976. (org-read-date-popup-calendar
  12977. (save-excursion
  12978. (save-window-excursion
  12979. (calendar)
  12980. (when (eq calendar-setup 'calendar-only)
  12981. (setq cal-frame
  12982. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12983. (select-frame cal-frame))
  12984. (org-eval-in-calendar '(setq cursor-type nil) t)
  12985. (unwind-protect
  12986. (progn
  12987. (calendar-forward-day (- (time-to-days org-def)
  12988. (calendar-absolute-from-gregorian
  12989. (calendar-current-date))))
  12990. (org-eval-in-calendar nil t)
  12991. (let* ((old-map (current-local-map))
  12992. (map (copy-keymap calendar-mode-map))
  12993. (minibuffer-local-map
  12994. (copy-keymap org-read-date-minibuffer-local-map)))
  12995. (org-defkey map (kbd "RET") 'org-calendar-select)
  12996. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12997. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12998. (unwind-protect
  12999. (progn
  13000. (use-local-map map)
  13001. (setq org-read-date-inactive inactive)
  13002. (add-hook 'post-command-hook 'org-read-date-display)
  13003. (setq org-ans0
  13004. (read-string prompt
  13005. default-input
  13006. 'org-read-date-history
  13007. nil))
  13008. ;; org-ans0: from prompt
  13009. ;; org-ans1: from mouse click
  13010. ;; org-ans2: from calendar motion
  13011. (setq ans
  13012. (concat org-ans0 " " (or org-ans1 org-ans2))))
  13013. (remove-hook 'post-command-hook 'org-read-date-display)
  13014. (use-local-map old-map)
  13015. (when org-read-date-overlay
  13016. (delete-overlay org-read-date-overlay)
  13017. (setq org-read-date-overlay nil)))))
  13018. (bury-buffer "*Calendar*")
  13019. (when cal-frame
  13020. (delete-frame cal-frame)
  13021. (select-frame-set-input-focus cur-frame))))))
  13022. (t ; Naked prompt only
  13023. (unwind-protect
  13024. (setq ans (read-string prompt default-input
  13025. 'org-read-date-history timestr))
  13026. (when org-read-date-overlay
  13027. (delete-overlay org-read-date-overlay)
  13028. (setq org-read-date-overlay nil))))))
  13029. (setq final (org-read-date-analyze ans org-def org-defdecode))
  13030. (when org-read-date-analyze-forced-year
  13031. (message "Year was forced into %s"
  13032. (if org-read-date-force-compatible-dates
  13033. "compatible range (1970-2037)"
  13034. "range representable on this machine"))
  13035. (ding))
  13036. ;; One round trip to get rid of 34th of August and stuff like that....
  13037. (setq final (decode-time (apply 'encode-time final)))
  13038. (setq org-read-date-final-answer ans)
  13039. (if to-time
  13040. (apply 'encode-time final)
  13041. (if (and (boundp 'org-time-was-given) org-time-was-given)
  13042. (format "%04d-%02d-%02d %02d:%02d"
  13043. (nth 5 final) (nth 4 final) (nth 3 final)
  13044. (nth 2 final) (nth 1 final))
  13045. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  13046. (defun org-read-date-display ()
  13047. "Display the current date prompt interpretation in the minibuffer."
  13048. (when org-read-date-display-live
  13049. (when org-read-date-overlay
  13050. (delete-overlay org-read-date-overlay))
  13051. (when (minibufferp (current-buffer))
  13052. (save-excursion
  13053. (end-of-line 1)
  13054. (while (not (equal (buffer-substring
  13055. (max (point-min) (- (point) 4)) (point))
  13056. " "))
  13057. (insert " ")))
  13058. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  13059. " " (or org-ans1 org-ans2)))
  13060. (org-end-time-was-given nil)
  13061. (f (org-read-date-analyze ans org-def org-defdecode))
  13062. (fmts (if org-dcst
  13063. org-time-stamp-custom-formats
  13064. org-time-stamp-formats))
  13065. (fmt (if (or org-with-time
  13066. (and (boundp 'org-time-was-given) org-time-was-given))
  13067. (cdr fmts)
  13068. (car fmts)))
  13069. (txt (format-time-string fmt (apply 'encode-time f)))
  13070. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  13071. (txt (concat "=> " txt)))
  13072. (when (and org-end-time-was-given
  13073. (string-match org-plain-time-of-day-regexp txt))
  13074. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  13075. org-end-time-was-given
  13076. (substring txt (match-end 0)))))
  13077. (when org-read-date-analyze-futurep
  13078. (setq txt (concat txt " (=>F)")))
  13079. (setq org-read-date-overlay
  13080. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  13081. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  13082. (defun org-read-date-analyze (ans def defdecode)
  13083. "Analyze the combined answer of the date prompt."
  13084. ;; FIXME: cleanup and comment
  13085. (let ((org-def def)
  13086. (org-defdecode defdecode)
  13087. (nowdecode (decode-time))
  13088. delta deltan deltaw deltadef year month day
  13089. hour minute second wday pm h2 m2 tl wday1
  13090. iso-year iso-weekday iso-week iso-date futurep kill-year)
  13091. (setq org-read-date-analyze-futurep nil
  13092. org-read-date-analyze-forced-year nil)
  13093. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  13094. (setq ans "+0"))
  13095. (when (setq delta (org-read-date-get-relative ans nil org-def))
  13096. (setq ans (replace-match "" t t ans)
  13097. deltan (car delta)
  13098. deltaw (nth 1 delta)
  13099. deltadef (nth 2 delta)))
  13100. ;; Check if there is an iso week date in there. If yes, store the
  13101. ;; info and postpone interpreting it until the rest of the parsing
  13102. ;; is done.
  13103. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  13104. (setq iso-year (when (match-end 1)
  13105. (org-small-year-to-year
  13106. (string-to-number (match-string 1 ans))))
  13107. iso-weekday (when (match-end 3)
  13108. (string-to-number (match-string 3 ans)))
  13109. iso-week (string-to-number (match-string 2 ans)))
  13110. (setq ans (replace-match "" t t ans)))
  13111. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  13112. (when (string-match
  13113. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  13114. (setq year (if (match-end 2)
  13115. (string-to-number (match-string 2 ans))
  13116. (progn (setq kill-year t)
  13117. (string-to-number (format-time-string "%Y"))))
  13118. month (string-to-number (match-string 3 ans))
  13119. day (string-to-number (match-string 4 ans)))
  13120. (setq year (org-small-year-to-year year))
  13121. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  13122. t nil ans)))
  13123. ;; Help matching dotted european dates
  13124. (when (string-match
  13125. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  13126. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  13127. (setq kill-year t)
  13128. (string-to-number (format-time-string "%Y")))
  13129. day (string-to-number (match-string 1 ans))
  13130. month (string-to-number (match-string 2 ans))
  13131. ans (replace-match (format "%04d-%02d-%02d" year month day)
  13132. t nil ans)))
  13133. ;; Help matching american dates, like 5/30 or 5/30/7
  13134. (when (string-match
  13135. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  13136. (setq year (if (match-end 4)
  13137. (string-to-number (match-string 4 ans))
  13138. (progn (setq kill-year t)
  13139. (string-to-number (format-time-string "%Y"))))
  13140. month (string-to-number (match-string 1 ans))
  13141. day (string-to-number (match-string 2 ans)))
  13142. (setq year (org-small-year-to-year year))
  13143. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  13144. t nil ans)))
  13145. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  13146. ;; If there is a time with am/pm, and *no* time without it, we convert
  13147. ;; so that matching will be successful.
  13148. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  13149. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  13150. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  13151. (setq hour (string-to-number (match-string 1 ans))
  13152. minute (if (match-end 3)
  13153. (string-to-number (match-string 3 ans))
  13154. 0)
  13155. pm (equal ?p
  13156. (string-to-char (downcase (match-string 4 ans)))))
  13157. (if (and (= hour 12) (not pm))
  13158. (setq hour 0)
  13159. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  13160. (setq ans (replace-match (format "%02d:%02d" hour minute)
  13161. t t ans))))
  13162. ;; Check if a time range is given as a duration
  13163. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  13164. (setq hour (string-to-number (match-string 1 ans))
  13165. h2 (+ hour (string-to-number (match-string 3 ans)))
  13166. minute (string-to-number (match-string 2 ans))
  13167. m2 (+ minute (if (match-end 5) (string-to-number
  13168. (match-string 5 ans))0)))
  13169. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  13170. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  13171. t t ans)))
  13172. ;; Check if there is a time range
  13173. (when (boundp 'org-end-time-was-given)
  13174. (setq org-time-was-given nil)
  13175. (when (and (string-match org-plain-time-of-day-regexp ans)
  13176. (match-end 8))
  13177. (setq org-end-time-was-given (match-string 8 ans))
  13178. (setq ans (concat (substring ans 0 (match-beginning 7))
  13179. (substring ans (match-end 7))))))
  13180. (setq tl (parse-time-string ans)
  13181. day (or (nth 3 tl) (nth 3 org-defdecode))
  13182. month
  13183. (cond ((nth 4 tl))
  13184. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  13185. ;; Day was specified. Make sure DAY+MONTH
  13186. ;; combination happens in the future.
  13187. ((nth 3 tl)
  13188. (setq futurep t)
  13189. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  13190. (nth 4 nowdecode)))
  13191. (t (nth 4 org-defdecode)))
  13192. year
  13193. (cond ((and (not kill-year) (nth 5 tl)))
  13194. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  13195. ;; Month was guessed in the future and is at least
  13196. ;; equal to NOWDECODE's. Fix year accordingly.
  13197. (futurep
  13198. (if (or (> month (nth 4 nowdecode))
  13199. (>= day (nth 3 nowdecode)))
  13200. (nth 5 nowdecode)
  13201. (1+ (nth 5 nowdecode))))
  13202. ;; Month was specified. Make sure MONTH+YEAR
  13203. ;; combination happens in the future.
  13204. ((nth 4 tl)
  13205. (setq futurep t)
  13206. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  13207. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  13208. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  13209. (t (nth 5 nowdecode))))
  13210. (t (nth 5 org-defdecode)))
  13211. hour (or (nth 2 tl) (nth 2 org-defdecode))
  13212. minute (or (nth 1 tl) (nth 1 org-defdecode))
  13213. second (or (nth 0 tl) 0)
  13214. wday (nth 6 tl))
  13215. (when (and (eq org-read-date-prefer-future 'time)
  13216. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  13217. (equal day (nth 3 nowdecode))
  13218. (equal month (nth 4 nowdecode))
  13219. (equal year (nth 5 nowdecode))
  13220. (nth 2 tl)
  13221. (or (< (nth 2 tl) (nth 2 nowdecode))
  13222. (and (= (nth 2 tl) (nth 2 nowdecode))
  13223. (nth 1 tl)
  13224. (< (nth 1 tl) (nth 1 nowdecode)))))
  13225. (setq day (1+ day)
  13226. futurep t))
  13227. ;; Special date definitions below
  13228. (cond
  13229. (iso-week
  13230. ;; There was an iso week
  13231. (require 'cal-iso)
  13232. (setq futurep nil)
  13233. (setq year (or iso-year year)
  13234. day (or iso-weekday wday 1)
  13235. wday nil ; to make sure that the trigger below does not match
  13236. iso-date (calendar-gregorian-from-absolute
  13237. (calendar-iso-to-absolute
  13238. (list iso-week day year))))
  13239. ; FIXME: Should we also push ISO weeks into the future?
  13240. ; (when (and org-read-date-prefer-future
  13241. ; (not iso-year)
  13242. ; (< (calendar-absolute-from-gregorian iso-date)
  13243. ; (time-to-days nil)))
  13244. ; (setq year (1+ year)
  13245. ; iso-date (calendar-gregorian-from-absolute
  13246. ; (calendar-iso-to-absolute
  13247. ; (list iso-week day year)))))
  13248. (setq month (car iso-date)
  13249. year (nth 2 iso-date)
  13250. day (nth 1 iso-date)))
  13251. (deltan
  13252. (setq futurep nil)
  13253. (unless deltadef
  13254. (let ((now (decode-time)))
  13255. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  13256. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  13257. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  13258. ((equal deltaw "m") (setq month (+ month deltan)))
  13259. ((equal deltaw "y") (setq year (+ year deltan)))))
  13260. ((and wday (not (nth 3 tl)))
  13261. ;; Weekday was given, but no day, so pick that day in the week
  13262. ;; on or after the derived date.
  13263. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  13264. (unless (equal wday wday1)
  13265. (setq day (+ day (% (- wday wday1 -7) 7))))))
  13266. (when (and (boundp 'org-time-was-given)
  13267. (nth 2 tl))
  13268. (setq org-time-was-given t))
  13269. (when (< year 100) (setq year (+ 2000 year)))
  13270. ;; Check of the date is representable
  13271. (if org-read-date-force-compatible-dates
  13272. (progn
  13273. (when (< year 1970)
  13274. (setq year 1970 org-read-date-analyze-forced-year t))
  13275. (when (> year 2037)
  13276. (setq year 2037 org-read-date-analyze-forced-year t)))
  13277. (condition-case nil
  13278. (ignore (encode-time second minute hour day month year))
  13279. (error
  13280. (setq year (nth 5 org-defdecode))
  13281. (setq org-read-date-analyze-forced-year t))))
  13282. (setq org-read-date-analyze-futurep futurep)
  13283. (list second minute hour day month year)))
  13284. (defvar parse-time-weekdays)
  13285. (defun org-read-date-get-relative (s today default)
  13286. "Check string S for special relative date string.
  13287. TODAY and DEFAULT are internal times, for today and for a default.
  13288. Return shift list (N what def-flag)
  13289. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  13290. N is the number of WHATs to shift.
  13291. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  13292. the DEFAULT date rather than TODAY."
  13293. (require 'parse-time)
  13294. (when (and
  13295. (string-match
  13296. (concat
  13297. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  13298. "\\([0-9]+\\)?"
  13299. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  13300. "\\([ \t]\\|$\\)") s)
  13301. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  13302. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  13303. (string-to-char (substring (match-string 1 s) -1))
  13304. ?+))
  13305. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  13306. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  13307. (what (if (match-end 3) (match-string 3 s) "d"))
  13308. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  13309. (date (if rel default today))
  13310. (wday (nth 6 (decode-time date)))
  13311. delta)
  13312. (if wday1
  13313. (progn
  13314. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  13315. (when (= delta 0) (setq delta 7))
  13316. (when (= dir ?-)
  13317. (setq delta (- delta 7))
  13318. (when (= delta 0) (setq delta -7)))
  13319. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  13320. (list delta "d" rel))
  13321. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  13322. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  13323. "Turn a user-specified date into the internal representation.
  13324. The internal representation needed by the calendar is (month day year).
  13325. This is a wrapper to handle the brain-dead convention in calendar that
  13326. user function argument order change dependent on argument order."
  13327. (pcase calendar-date-style
  13328. (`american (list arg1 arg2 arg3))
  13329. (`european (list arg2 arg1 arg3))
  13330. (`iso (list arg2 arg3 arg1))))
  13331. (defun org-eval-in-calendar (form &optional keepdate)
  13332. "Eval FORM in the calendar window and return to current window.
  13333. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  13334. (let ((sf (selected-frame))
  13335. (sw (selected-window)))
  13336. (select-window (get-buffer-window "*Calendar*" t))
  13337. (eval form)
  13338. (when (and (not keepdate) (calendar-cursor-to-date))
  13339. (let* ((date (calendar-cursor-to-date))
  13340. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13341. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  13342. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  13343. (select-window sw)
  13344. (select-frame-set-input-focus sf)))
  13345. (defun org-calendar-select ()
  13346. "Return to `org-read-date' with the date currently selected.
  13347. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13348. (interactive)
  13349. (when (calendar-cursor-to-date)
  13350. (let* ((date (calendar-cursor-to-date))
  13351. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13352. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13353. (when (active-minibuffer-window) (exit-minibuffer))))
  13354. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  13355. "Insert a date stamp for the date given by the internal TIME.
  13356. See `format-time-string' for the format of TIME.
  13357. WITH-HM means use the stamp format that includes the time of the day.
  13358. INACTIVE means use square brackets instead of angular ones, so that the
  13359. stamp will not contribute to the agenda.
  13360. PRE and POST are optional strings to be inserted before and after the
  13361. stamp.
  13362. The command returns the inserted time stamp."
  13363. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  13364. stamp)
  13365. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  13366. (insert-before-markers (or pre ""))
  13367. (when (listp extra)
  13368. (setq extra (car extra))
  13369. (if (and (stringp extra)
  13370. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  13371. (setq extra (format "-%02d:%02d"
  13372. (string-to-number (match-string 1 extra))
  13373. (string-to-number (match-string 2 extra))))
  13374. (setq extra nil)))
  13375. (when extra
  13376. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  13377. (insert-before-markers (setq stamp (format-time-string fmt time)))
  13378. (insert-before-markers (or post ""))
  13379. (setq org-last-inserted-timestamp stamp)))
  13380. (defun org-toggle-time-stamp-overlays ()
  13381. "Toggle the use of custom time stamp formats."
  13382. (interactive)
  13383. (setq org-display-custom-times (not org-display-custom-times))
  13384. (unless org-display-custom-times
  13385. (let ((p (point-min)) (bmp (buffer-modified-p)))
  13386. (while (setq p (next-single-property-change p 'display))
  13387. (when (and (get-text-property p 'display)
  13388. (eq (get-text-property p 'face) 'org-date))
  13389. (remove-text-properties
  13390. p (setq p (next-single-property-change p 'display))
  13391. '(display t))))
  13392. (set-buffer-modified-p bmp)))
  13393. (org-restart-font-lock)
  13394. (setq org-table-may-need-update t)
  13395. (if org-display-custom-times
  13396. (message "Time stamps are overlaid with custom format")
  13397. (message "Time stamp overlays removed")))
  13398. (defun org-display-custom-time (beg end)
  13399. "Overlay modified time stamp format over timestamp between BEG and END."
  13400. (let* ((ts (buffer-substring beg end))
  13401. t1 with-hm tf time str (off 0))
  13402. (save-match-data
  13403. (setq t1 (org-parse-time-string ts t))
  13404. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  13405. (setq off (- (match-end 0) (match-beginning 0)))))
  13406. (setq end (- end off))
  13407. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  13408. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  13409. time (org-fix-decoded-time t1)
  13410. str (org-add-props
  13411. (format-time-string
  13412. (substring tf 1 -1) (apply 'encode-time time))
  13413. nil 'mouse-face 'highlight))
  13414. (put-text-property beg end 'display str)))
  13415. (defun org-fix-decoded-time (time)
  13416. "Set 0 instead of nil for the first 6 elements of time.
  13417. Don't touch the rest."
  13418. (let ((n 0))
  13419. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  13420. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  13421. "Difference between TIMESTAMP-STRING and now in days.
  13422. If SECONDS is non-nil, return the difference in seconds."
  13423. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  13424. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  13425. (funcall fdiff nil))))
  13426. (defun org-deadline-close-p (timestamp-string &optional ndays)
  13427. "Is the time in TIMESTAMP-STRING close to the current date?"
  13428. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  13429. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  13430. (not (org-entry-is-done-p))))
  13431. (defun org-get-wdays (ts &optional delay zero-delay)
  13432. "Get the deadline lead time appropriate for timestring TS.
  13433. When DELAY is non-nil, get the delay time for scheduled items
  13434. instead of the deadline lead time. When ZERO-DELAY is non-nil
  13435. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  13436. don't try to find the delay cookie in the scheduled timestamp."
  13437. (let ((tv (if delay org-scheduled-delay-days
  13438. org-deadline-warning-days)))
  13439. (cond
  13440. ((or (and delay (< tv 0))
  13441. (and delay zero-delay (<= tv 0))
  13442. (and (not delay) (<= tv 0)))
  13443. ;; Enforce this value no matter what
  13444. (- tv))
  13445. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  13446. ;; lead time is specified.
  13447. (floor (* (string-to-number (match-string 1 ts))
  13448. (cdr (assoc (match-string 2 ts)
  13449. '(("d" . 1) ("w" . 7)
  13450. ("m" . 30.4) ("y" . 365.25)
  13451. ("h" . 0.041667)))))))
  13452. ;; go for the default.
  13453. (t tv))))
  13454. (defun org-calendar-select-mouse (ev)
  13455. "Return to `org-read-date' with the date currently selected.
  13456. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13457. (interactive "e")
  13458. (mouse-set-point ev)
  13459. (when (calendar-cursor-to-date)
  13460. (let* ((date (calendar-cursor-to-date))
  13461. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13462. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13463. (when (active-minibuffer-window) (exit-minibuffer))))
  13464. (defun org-check-deadlines (ndays)
  13465. "Check if there are any deadlines due or past due.
  13466. A deadline is considered due if it happens within `org-deadline-warning-days'
  13467. days from today's date. If the deadline appears in an entry marked DONE,
  13468. it is not shown. A numeric prefix argument NDAYS can be used to test that
  13469. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  13470. are shown."
  13471. (interactive "P")
  13472. (let* ((org-warn-days
  13473. (cond
  13474. ((equal ndays '(4)) 100000)
  13475. (ndays (prefix-numeric-value ndays))
  13476. (t (abs org-deadline-warning-days))))
  13477. (case-fold-search nil)
  13478. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  13479. (callback
  13480. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  13481. (message "%d deadlines past-due or due within %d days"
  13482. (org-occur regexp nil callback)
  13483. org-warn-days)))
  13484. (defsubst org-re-timestamp (type)
  13485. "Return a regexp for timestamp TYPE.
  13486. Allowed values for TYPE are:
  13487. all: all timestamps
  13488. active: only active timestamps (<...>)
  13489. inactive: only inactive timestamps ([...])
  13490. scheduled: only scheduled timestamps
  13491. deadline: only deadline timestamps
  13492. closed: only closed time-stamps
  13493. When TYPE is nil, fall back on returning a regexp that matches
  13494. both scheduled and deadline timestamps."
  13495. (cl-case type
  13496. (all org-ts-regexp-both)
  13497. (active org-ts-regexp)
  13498. (inactive org-ts-regexp-inactive)
  13499. (scheduled org-scheduled-time-regexp)
  13500. (deadline org-deadline-time-regexp)
  13501. (closed org-closed-time-regexp)
  13502. (otherwise
  13503. (concat "\\<"
  13504. (regexp-opt (list org-deadline-string org-scheduled-string))
  13505. " *<\\([^>]+\\)>"))))
  13506. (defun org-check-before-date (d)
  13507. "Check if there are deadlines or scheduled entries before date D."
  13508. (interactive (list (org-read-date)))
  13509. (let* ((case-fold-search nil)
  13510. (regexp (org-re-timestamp org-ts-type))
  13511. (ts-type org-ts-type)
  13512. (callback
  13513. (lambda ()
  13514. (let ((match (match-string 1)))
  13515. (and (if (memq ts-type '(active inactive all))
  13516. (eq (org-element-type (save-excursion
  13517. (backward-char)
  13518. (org-element-context)))
  13519. 'timestamp)
  13520. (org-at-planning-p))
  13521. (time-less-p
  13522. (org-time-string-to-time match)
  13523. (org-time-string-to-time d)))))))
  13524. (message "%d entries before %s"
  13525. (org-occur regexp nil callback)
  13526. d)))
  13527. (defun org-check-after-date (d)
  13528. "Check if there are deadlines or scheduled entries after date D."
  13529. (interactive (list (org-read-date)))
  13530. (let* ((case-fold-search nil)
  13531. (regexp (org-re-timestamp org-ts-type))
  13532. (ts-type org-ts-type)
  13533. (callback
  13534. (lambda ()
  13535. (let ((match (match-string 1)))
  13536. (and (if (memq ts-type '(active inactive all))
  13537. (eq (org-element-type (save-excursion
  13538. (backward-char)
  13539. (org-element-context)))
  13540. 'timestamp)
  13541. (org-at-planning-p))
  13542. (not (time-less-p
  13543. (org-time-string-to-time match)
  13544. (org-time-string-to-time d))))))))
  13545. (message "%d entries after %s"
  13546. (org-occur regexp nil callback)
  13547. d)))
  13548. (defun org-check-dates-range (start-date end-date)
  13549. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  13550. (interactive (list (org-read-date nil nil nil "Range starts")
  13551. (org-read-date nil nil nil "Range end")))
  13552. (let ((case-fold-search nil)
  13553. (regexp (org-re-timestamp org-ts-type))
  13554. (callback
  13555. (let ((type org-ts-type))
  13556. (lambda ()
  13557. (let ((match (match-string 1)))
  13558. (and
  13559. (if (memq type '(active inactive all))
  13560. (eq (org-element-type (save-excursion
  13561. (backward-char)
  13562. (org-element-context)))
  13563. 'timestamp)
  13564. (org-at-planning-p))
  13565. (not (time-less-p
  13566. (org-time-string-to-time match)
  13567. (org-time-string-to-time start-date)))
  13568. (time-less-p
  13569. (org-time-string-to-time match)
  13570. (org-time-string-to-time end-date))))))))
  13571. (message "%d entries between %s and %s"
  13572. (org-occur regexp nil callback) start-date end-date)))
  13573. (defun org-evaluate-time-range (&optional to-buffer)
  13574. "Evaluate a time range by computing the difference between start and end.
  13575. Normally the result is just printed in the echo area, but with prefix arg
  13576. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  13577. If the time range is actually in a table, the result is inserted into the
  13578. next column.
  13579. For time difference computation, a year is assumed to be exactly 365
  13580. days in order to avoid rounding problems."
  13581. (interactive "P")
  13582. (or
  13583. (org-clock-update-time-maybe)
  13584. (save-excursion
  13585. (unless (org-at-date-range-p t)
  13586. (goto-char (point-at-bol))
  13587. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  13588. (unless (org-at-date-range-p t)
  13589. (user-error "Not at a time-stamp range, and none found in current line")))
  13590. (let* ((ts1 (match-string 1))
  13591. (ts2 (match-string 2))
  13592. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  13593. (match-end (match-end 0))
  13594. (time1 (org-time-string-to-time ts1))
  13595. (time2 (org-time-string-to-time ts2))
  13596. (diff (abs (float-time (time-subtract time2 time1))))
  13597. (negative (time-less-p time2 time1))
  13598. ;; (ys (floor (* 365 24 60 60)))
  13599. (ds (* 24 60 60))
  13600. (hs (* 60 60))
  13601. (fy "%dy %dd %02d:%02d")
  13602. (fy1 "%dy %dd")
  13603. (fd "%dd %02d:%02d")
  13604. (fd1 "%dd")
  13605. (fh "%02d:%02d")
  13606. y d h m align)
  13607. (if havetime
  13608. (setq ; y (floor diff ys) diff (mod diff ys)
  13609. y 0
  13610. d (floor diff ds) diff (mod diff ds)
  13611. h (floor diff hs) diff (mod diff hs)
  13612. m (floor diff 60))
  13613. (setq ; y (floor diff ys) diff (mod diff ys)
  13614. y 0
  13615. d (round diff ds)
  13616. h 0 m 0))
  13617. (if (not to-buffer)
  13618. (message "%s" (org-make-tdiff-string y d h m))
  13619. (if (org-at-table-p)
  13620. (progn
  13621. (goto-char match-end)
  13622. (setq align t)
  13623. (and (looking-at " *|") (goto-char (match-end 0))))
  13624. (goto-char match-end))
  13625. (when (looking-at
  13626. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  13627. (replace-match ""))
  13628. (when negative (insert " -"))
  13629. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  13630. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  13631. (insert " " (format fh h m))))
  13632. (when align (org-table-align))
  13633. (message "Time difference inserted")))))
  13634. (defun org-make-tdiff-string (y d h m)
  13635. (let ((fmt "")
  13636. (l nil))
  13637. (when (> y 0)
  13638. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  13639. (push y l))
  13640. (when (> d 0)
  13641. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  13642. (push d l))
  13643. (when (> h 0)
  13644. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  13645. (push h l))
  13646. (when (> m 0)
  13647. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  13648. (push m l))
  13649. (apply 'format fmt (nreverse l))))
  13650. (defun org-time-string-to-time (s)
  13651. "Convert timestamp string S into internal time."
  13652. (apply #'encode-time (org-parse-time-string s)))
  13653. (defun org-time-string-to-seconds (s)
  13654. "Convert a timestamp string S into a number of seconds."
  13655. (float-time (org-time-string-to-time s)))
  13656. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  13657. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  13658. "Convert time stamp S to an absolute day number.
  13659. If DAYNR in non-nil, and there is a specifier for a cyclic time
  13660. stamp, get the closest date to DAYNR. If PREFER is
  13661. `past' (respectively `future') return a date past (respectively
  13662. after) or equal to DAYNR.
  13663. POS is the location of time stamp S, as a buffer position in
  13664. BUFFER.
  13665. Diary sexp timestamps are matched against DAYNR, when non-nil.
  13666. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  13667. signaled."
  13668. (cond
  13669. ((string-match "\\`%%\\((.*)\\)" s)
  13670. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13671. ;; only able to match individual dates. If it fails, raise an
  13672. ;; error.
  13673. (if (and daynr
  13674. (org-diary-sexp-entry
  13675. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13676. daynr
  13677. (signal 'org-diary-sexp-no-match (list s))))
  13678. (daynr (org-closest-date s daynr prefer))
  13679. (t (time-to-days
  13680. (condition-case errdata
  13681. (apply #'encode-time (org-parse-time-string s))
  13682. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13683. s
  13684. (if (not (and buffer pos)) ""
  13685. (format-message " at %d in buffer `%s'" pos buffer))
  13686. (cdr errdata))))))))
  13687. (defun org-days-to-iso-week (days)
  13688. "Return the iso week number."
  13689. (require 'cal-iso)
  13690. (car (calendar-iso-from-absolute days)))
  13691. (defun org-small-year-to-year (year)
  13692. "Convert 2-digit years into 4-digit years.
  13693. YEAR is expanded into one of the 30 next years, if possible, or
  13694. into a past one. Any year larger than 99 is returned unchanged."
  13695. (if (>= year 100) year
  13696. (let* ((current (string-to-number (format-time-string "%Y")))
  13697. (century (/ current 100))
  13698. (offset (- year (% current 100))))
  13699. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13700. ((> offset -70) (+ (* century 100) year))
  13701. (t (+ (* (1+ century) 100) year))))))
  13702. (defun org-time-from-absolute (d)
  13703. "Return the time corresponding to date D.
  13704. D may be an absolute day number, or a calendar-type list (month day year)."
  13705. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13706. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13707. (defvar org-agenda-current-date)
  13708. (defun org-calendar-holiday ()
  13709. "List of holidays, for Diary display in Org mode."
  13710. (require 'holidays)
  13711. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13712. (and hl (mapconcat #'identity hl "; "))))
  13713. (defun org-diary-sexp-entry (sexp entry d)
  13714. "Process a SEXP diary ENTRY for date D."
  13715. (require 'diary-lib)
  13716. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13717. ;; dynamically.
  13718. (let* ((sexp `(let ((entry ,entry)
  13719. (date ',d))
  13720. ,(car (read-from-string sexp))))
  13721. (result (if calendar-debug-sexp (eval sexp)
  13722. (condition-case nil
  13723. (eval sexp)
  13724. (error
  13725. (beep)
  13726. (message "Bad sexp at line %d in %s: %s"
  13727. (org-current-line)
  13728. (buffer-file-name) sexp)
  13729. (sleep-for 2))))))
  13730. (cond ((stringp result) (split-string result "; "))
  13731. ((and (consp result)
  13732. (not (consp (cdr result)))
  13733. (stringp (cdr result))) (cdr result))
  13734. ((and (consp result)
  13735. (stringp (car result))) result)
  13736. (result entry))))
  13737. (defun org-diary-to-ical-string (frombuf)
  13738. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13739. This uses the icalendar.el library."
  13740. (let* ((tmpdir temporary-file-directory)
  13741. (tmpfile (make-temp-name
  13742. (expand-file-name "orgics" tmpdir)))
  13743. buf rtn b e)
  13744. (with-current-buffer frombuf
  13745. (icalendar-export-region (point-min) (point-max) tmpfile)
  13746. (setq buf (find-buffer-visiting tmpfile))
  13747. (set-buffer buf)
  13748. (goto-char (point-min))
  13749. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13750. (setq b (match-beginning 0)))
  13751. (goto-char (point-max))
  13752. (when (re-search-backward "^END:VEVENT" nil t)
  13753. (setq e (match-end 0)))
  13754. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13755. (kill-buffer buf)
  13756. (delete-file tmpfile)
  13757. rtn))
  13758. (defun org-closest-date (start current prefer)
  13759. "Return closest date to CURRENT starting from START.
  13760. CURRENT and START are both time stamps.
  13761. When PREFER is `past', return a date that is either CURRENT or
  13762. past. When PREFER is `future', return a date that is either
  13763. CURRENT or future.
  13764. Only time stamps with a repeater are modified. Any other time
  13765. stamp stay unchanged. In any case, return value is an absolute
  13766. day number."
  13767. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13768. ;; No repeater. Do not shift time stamp.
  13769. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  13770. (let ((value (string-to-number (match-string 1 start)))
  13771. (type (match-string 2 start)))
  13772. (if (= 0 value)
  13773. ;; Repeater with a 0-value is considered as void.
  13774. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  13775. (let* ((base (org-date-to-gregorian start))
  13776. (target (org-date-to-gregorian current))
  13777. (sday (calendar-absolute-from-gregorian base))
  13778. (cday (calendar-absolute-from-gregorian target))
  13779. n1 n2)
  13780. ;; If START is already past CURRENT, just return START.
  13781. (if (<= cday sday) sday
  13782. ;; Compute closest date before (N1) and closest date past
  13783. ;; (N2) CURRENT.
  13784. (pcase type
  13785. ("h"
  13786. (let ((missing-hours
  13787. (mod (+ (- (* 24 (- cday sday))
  13788. (nth 2 (org-parse-time-string start)))
  13789. org-extend-today-until)
  13790. value)))
  13791. (setf n1 (if (= missing-hours 0) cday
  13792. (- cday (1+ (/ missing-hours 24)))))
  13793. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13794. ((or "d" "w")
  13795. (let ((value (if (equal type "w") (* 7 value) value)))
  13796. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13797. (setf n2 (+ n1 value))))
  13798. ("m"
  13799. (let* ((add-months
  13800. (lambda (d n)
  13801. ;; Add N months to gregorian date D, i.e.,
  13802. ;; a list (MONTH DAY YEAR). Return a valid
  13803. ;; gregorian date.
  13804. (let ((m (+ (nth 0 d) n)))
  13805. (list (mod m 12)
  13806. (nth 1 d)
  13807. (+ (/ m 12) (nth 2 d))))))
  13808. (months ; Complete months to TARGET.
  13809. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13810. (- (nth 0 target) (nth 0 base))
  13811. ;; If START's day is greater than
  13812. ;; TARGET's, remove incomplete month.
  13813. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13814. value)
  13815. value))
  13816. (before (funcall add-months base months)))
  13817. (setf n1 (calendar-absolute-from-gregorian before))
  13818. (setf n2
  13819. (calendar-absolute-from-gregorian
  13820. (funcall add-months before value)))))
  13821. (_
  13822. (let* ((d (nth 1 base))
  13823. (m (nth 0 base))
  13824. (y (nth 2 base))
  13825. (years ; Complete years to TARGET.
  13826. (* (/ (- (nth 2 target)
  13827. y
  13828. ;; If START's month and day are
  13829. ;; greater than TARGET's, remove
  13830. ;; incomplete year.
  13831. (if (or (> (nth 0 target) m)
  13832. (and (= (nth 0 target) m)
  13833. (> (nth 1 target) d)))
  13834. 0
  13835. 1))
  13836. value)
  13837. value))
  13838. (before (list m d (+ y years))))
  13839. (setf n1 (calendar-absolute-from-gregorian before))
  13840. (setf n2 (calendar-absolute-from-gregorian
  13841. (list m d (+ (nth 2 before) value)))))))
  13842. ;; Handle PREFER parameter, if any.
  13843. (cond
  13844. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13845. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13846. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13847. (defun org-date-to-gregorian (d)
  13848. "Turn any specification of date D into a Gregorian date for the calendar."
  13849. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13850. ((and (listp d) (= (length d) 3)) d)
  13851. ((stringp d)
  13852. (let ((d (org-parse-time-string d)))
  13853. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13854. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13855. (defun org-timestamp-up (&optional arg)
  13856. "Increase the date item at the cursor by one.
  13857. If the cursor is on the year, change the year. If it is on the month,
  13858. the day or the time, change that. If the cursor is on the enclosing
  13859. bracket, change the timestamp type.
  13860. With prefix ARG, change by that many units."
  13861. (interactive "p")
  13862. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13863. (defun org-timestamp-down (&optional arg)
  13864. "Decrease the date item at the cursor by one.
  13865. If the cursor is on the year, change the year. If it is on the month,
  13866. the day or the time, change that. If the cursor is on the enclosing
  13867. bracket, change the timestamp type.
  13868. With prefix ARG, change by that many units."
  13869. (interactive "p")
  13870. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13871. (defun org-timestamp-up-day (&optional arg)
  13872. "Increase the date in the time stamp by one day.
  13873. With prefix ARG, change that many days."
  13874. (interactive "p")
  13875. (if (and (not (org-at-timestamp-p 'lax))
  13876. (org-at-heading-p))
  13877. (org-todo 'up)
  13878. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13879. (defun org-timestamp-down-day (&optional arg)
  13880. "Decrease the date in the time stamp by one day.
  13881. With prefix ARG, change that many days."
  13882. (interactive "p")
  13883. (if (and (not (org-at-timestamp-p 'lax))
  13884. (org-at-heading-p))
  13885. (org-todo 'down)
  13886. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13887. (defun org-at-timestamp-p (&optional extended)
  13888. "Non-nil if point is inside a timestamp.
  13889. By default, the function only consider syntactically valid active
  13890. timestamps. However, the caller may have a broader definition
  13891. for timestamps. As a consequence, optional argument EXTENDED can
  13892. be set to the following values
  13893. `inactive'
  13894. Include also syntactically valid inactive timestamps.
  13895. `agenda'
  13896. Include timestamps allowed in Agenda, i.e., those in
  13897. properties drawers, planning lines and clock lines.
  13898. `lax'
  13899. Ignore context. The function matches any part of the
  13900. document looking like a timestamp. This includes comments,
  13901. example blocks...
  13902. For backward-compatibility with Org 9.0, every other non-nil
  13903. value is equivalent to `inactive'.
  13904. When at a timestamp, return the position of the point as a symbol
  13905. among `bracket', `after', `year', `month', `hour', `minute',
  13906. `day' or a number of character from the last know part of the
  13907. time stamp.
  13908. When matching, the match groups are the following:
  13909. group 1: year
  13910. group 2: month
  13911. group 3: day number
  13912. group 4: day name
  13913. group 5: hours, if any
  13914. group 6: minutes, if any"
  13915. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  13916. (pos (point))
  13917. (match?
  13918. (let ((boundaries (org-in-regexp regexp)))
  13919. (save-match-data
  13920. (cond ((null boundaries) nil)
  13921. ((eq extended 'lax) t)
  13922. (t
  13923. (or (and (eq extended 'agenda)
  13924. (or (org-at-planning-p)
  13925. (org-at-property-p)
  13926. (and (bound-and-true-p
  13927. org-agenda-include-inactive-timestamps)
  13928. (org-at-clock-log-p))))
  13929. (eq 'timestamp
  13930. (save-excursion
  13931. (when (= pos (cdr boundaries)) (forward-char -1))
  13932. (org-element-type (org-element-context)))))))))))
  13933. (cond
  13934. ((not match?) nil)
  13935. ((= pos (match-beginning 0)) 'bracket)
  13936. ;; Distinguish location right before the closing bracket from
  13937. ;; right after it.
  13938. ((= pos (1- (match-end 0))) 'bracket)
  13939. ((= pos (match-end 0)) 'after)
  13940. ((org-pos-in-match-range pos 2) 'year)
  13941. ((org-pos-in-match-range pos 3) 'month)
  13942. ((org-pos-in-match-range pos 7) 'hour)
  13943. ((org-pos-in-match-range pos 8) 'minute)
  13944. ((or (org-pos-in-match-range pos 4)
  13945. (org-pos-in-match-range pos 5)) 'day)
  13946. ((and (> pos (or (match-end 8) (match-end 5)))
  13947. (< pos (match-end 0)))
  13948. (- pos (or (match-end 8) (match-end 5))))
  13949. (t 'day))))
  13950. (defun org-toggle-timestamp-type ()
  13951. "Toggle the type (<active> or [inactive]) of a time stamp."
  13952. (interactive)
  13953. (when (org-at-timestamp-p 'lax)
  13954. (let ((beg (match-beginning 0)) (end (match-end 0))
  13955. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13956. (save-excursion
  13957. (goto-char beg)
  13958. (while (re-search-forward "[][<>]" end t)
  13959. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13960. t t)))
  13961. (message "Timestamp is now %sactive"
  13962. (if (equal (char-after beg) ?<) "" "in")))))
  13963. (defun org-at-clock-log-p ()
  13964. "Non-nil if point is on a clock log line."
  13965. (and (org-match-line org-clock-line-re)
  13966. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13967. (defvar org-clock-history) ; defined in org-clock.el
  13968. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13969. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13970. "Change the date in the time stamp at point.
  13971. The date will be changed by N times WHAT. WHAT can be `day', `month',
  13972. `year', `minute', `second'. If WHAT is not given, the cursor position
  13973. in the timestamp determines what will be changed.
  13974. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  13975. (let ((origin (point))
  13976. (timestamp? (org-at-timestamp-p 'lax))
  13977. origin-cat
  13978. with-hm inactive
  13979. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13980. extra rem
  13981. ts time time0 fixnext clrgx)
  13982. (unless timestamp? (user-error "Not at a timestamp"))
  13983. (if (and (not what) (eq timestamp? 'bracket))
  13984. (org-toggle-timestamp-type)
  13985. ;; Point isn't on brackets. Remember the part of the time-stamp
  13986. ;; the point was in. Indeed, size of time-stamps may change,
  13987. ;; but point must be kept in the same category nonetheless.
  13988. (setq origin-cat timestamp?)
  13989. (when (and (not what) (not (eq timestamp? 'day))
  13990. org-display-custom-times
  13991. (get-text-property (point) 'display)
  13992. (not (get-text-property (1- (point)) 'display)))
  13993. (setq timestamp? 'day))
  13994. (setq timestamp? (or what timestamp?)
  13995. inactive (= (char-after (match-beginning 0)) ?\[)
  13996. ts (match-string 0))
  13997. (replace-match "")
  13998. (when (string-match
  13999. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  14000. ts)
  14001. (setq extra (match-string 1 ts))
  14002. (when suppress-tmp-delay
  14003. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  14004. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  14005. (setq with-hm t))
  14006. (setq time0 (org-parse-time-string ts))
  14007. (when (and updown
  14008. (eq timestamp? 'minute)
  14009. (not current-prefix-arg))
  14010. ;; This looks like s-up and s-down. Change by one rounding step.
  14011. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  14012. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  14013. (setcar (cdr time0) (+ (nth 1 time0)
  14014. (if (> n 0) (- rem) (- dm rem))))))
  14015. (setq time
  14016. (apply #'encode-time
  14017. (or (car time0) 0)
  14018. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  14019. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  14020. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  14021. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  14022. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  14023. (nthcdr 6 time0)))
  14024. (when (and (memq timestamp? '(hour minute))
  14025. extra
  14026. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  14027. (setq extra (org-modify-ts-extra
  14028. extra
  14029. (if (eq timestamp? 'hour) 2 5)
  14030. n dm)))
  14031. (when (integerp timestamp?)
  14032. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  14033. (when (eq what 'calendar)
  14034. (let ((cal-date (org-get-date-from-calendar)))
  14035. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  14036. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  14037. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  14038. (setcar time0 (or (car time0) 0))
  14039. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  14040. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  14041. (setq time (apply 'encode-time time0))))
  14042. ;; Insert the new time-stamp, and ensure point stays in the same
  14043. ;; category as before (i.e. not after the last position in that
  14044. ;; category).
  14045. (let ((pos (point)))
  14046. ;; Stay before inserted string. `save-excursion' is of no use.
  14047. (setq org-last-changed-timestamp
  14048. (org-insert-time-stamp time with-hm inactive nil nil extra))
  14049. (goto-char pos))
  14050. (save-match-data
  14051. (looking-at org-ts-regexp3)
  14052. (goto-char
  14053. (pcase origin-cat
  14054. ;; `day' category ends before `hour' if any, or at the end
  14055. ;; of the day name.
  14056. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  14057. (`hour (min (match-end 7) origin))
  14058. (`minute (min (1- (match-end 8)) origin))
  14059. ((pred integerp) (min (1- (match-end 0)) origin))
  14060. ;; Point was right after the time-stamp. However, the
  14061. ;; time-stamp length might have changed, so refer to
  14062. ;; (match-end 0) instead.
  14063. (`after (match-end 0))
  14064. ;; `year' and `month' have both fixed size: point couldn't
  14065. ;; have moved into another part.
  14066. (_ origin))))
  14067. ;; Update clock if on a CLOCK line.
  14068. (org-clock-update-time-maybe)
  14069. ;; Maybe adjust the closest clock in `org-clock-history'
  14070. (when org-clock-adjust-closest
  14071. (if (not (and (org-at-clock-log-p)
  14072. (< 1 (length (delq nil (mapcar 'marker-position
  14073. org-clock-history))))))
  14074. (message "No clock to adjust")
  14075. (cond ((save-excursion ; fix previous clock?
  14076. (re-search-backward org-ts-regexp0 nil t)
  14077. (looking-back (concat org-clock-string " \\[")
  14078. (line-beginning-position)))
  14079. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  14080. ((save-excursion ; fix next clock?
  14081. (re-search-backward org-ts-regexp0 nil t)
  14082. (looking-at (concat org-ts-regexp0 "\\] =>")))
  14083. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  14084. (save-window-excursion
  14085. ;; Find closest clock to point, adjust the previous/next one in history
  14086. (let* ((p (save-excursion (org-back-to-heading t)))
  14087. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  14088. (clfixnth
  14089. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  14090. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  14091. (if (not clfixpos)
  14092. (message "No clock to adjust")
  14093. (save-excursion
  14094. (org-goto-marker-or-bmk clfixpos)
  14095. (org-show-subtree)
  14096. (when (re-search-forward clrgx nil t)
  14097. (goto-char (match-beginning 1))
  14098. (let (org-clock-adjust-closest)
  14099. (org-timestamp-change n timestamp? updown))
  14100. (message "Clock adjusted in %s for heading: %s"
  14101. (file-name-nondirectory (buffer-file-name))
  14102. (org-get-heading t t)))))))))
  14103. ;; Try to recenter the calendar window, if any.
  14104. (when (and org-calendar-follow-timestamp-change
  14105. (get-buffer-window "*Calendar*" t)
  14106. (memq timestamp? '(day month year)))
  14107. (org-recenter-calendar (time-to-days time))))))
  14108. (defun org-modify-ts-extra (s pos n dm)
  14109. "Change the different parts of the lead-time and repeat fields in timestamp."
  14110. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  14111. ng h m new rem)
  14112. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  14113. (cond
  14114. ((or (org-pos-in-match-range pos 2)
  14115. (org-pos-in-match-range pos 3))
  14116. (setq m (string-to-number (match-string 3 s))
  14117. h (string-to-number (match-string 2 s)))
  14118. (if (org-pos-in-match-range pos 2)
  14119. (setq h (+ h n))
  14120. (setq n (* dm (with-no-warnings (cl-signum n))))
  14121. (unless (= 0 (setq rem (% m dm)))
  14122. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  14123. (setq m (+ m n)))
  14124. (when (< m 0) (setq m (+ m 60) h (1- h)))
  14125. (when (> m 59) (setq m (- m 60) h (1+ h)))
  14126. (setq h (mod h 24))
  14127. (setq ng 1 new (format "-%02d:%02d" h m)))
  14128. ((org-pos-in-match-range pos 6)
  14129. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  14130. ((org-pos-in-match-range pos 5)
  14131. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  14132. ((org-pos-in-match-range pos 9)
  14133. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  14134. ((org-pos-in-match-range pos 8)
  14135. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  14136. (when ng
  14137. (setq s (concat
  14138. (substring s 0 (match-beginning ng))
  14139. new
  14140. (substring s (match-end ng))))))
  14141. s))
  14142. (defun org-recenter-calendar (d)
  14143. "If the calendar is visible, recenter it to date D."
  14144. (let ((cwin (get-buffer-window "*Calendar*" t)))
  14145. (when cwin
  14146. (let ((calendar-move-hook nil))
  14147. (with-selected-window cwin
  14148. (calendar-goto-date
  14149. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  14150. (defun org-goto-calendar (&optional arg)
  14151. "Go to the Emacs calendar at the current date.
  14152. If there is a time stamp in the current line, go to that date.
  14153. A prefix ARG can be used to force the current date."
  14154. (interactive "P")
  14155. (let ((calendar-move-hook nil)
  14156. (calendar-view-holidays-initially-flag nil)
  14157. (calendar-view-diary-initially-flag nil)
  14158. diff)
  14159. (when (or (org-at-timestamp-p 'lax)
  14160. (org-match-line (concat ".*" org-ts-regexp)))
  14161. (let ((d1 (time-to-days nil))
  14162. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  14163. (setq diff (- d2 d1))))
  14164. (calendar)
  14165. (calendar-goto-today)
  14166. (when (and diff (not arg)) (calendar-forward-day diff))))
  14167. (defun org-get-date-from-calendar ()
  14168. "Return a list (month day year) of date at point in calendar."
  14169. (with-current-buffer "*Calendar*"
  14170. (save-match-data
  14171. (calendar-cursor-to-date))))
  14172. (defun org-date-from-calendar ()
  14173. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  14174. If there is already a time stamp at the cursor position, update it."
  14175. (interactive)
  14176. (if (org-at-timestamp-p 'lax)
  14177. (org-timestamp-change 0 'calendar)
  14178. (let ((cal-date (org-get-date-from-calendar)))
  14179. (org-insert-time-stamp
  14180. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  14181. (defcustom org-image-actual-width t
  14182. "Should we use the actual width of images when inlining them?
  14183. When set to t, always use the image width.
  14184. When set to a number, use imagemagick (when available) to set
  14185. the image's width to this value.
  14186. When set to a number in a list, try to get the width from any
  14187. #+ATTR.* keyword if it matches a width specification like
  14188. #+ATTR_HTML: :width 300px
  14189. and fall back on that number if none is found.
  14190. When set to nil, try to get the width from an #+ATTR.* keyword
  14191. and fall back on the original width if none is found.
  14192. This requires Emacs >= 24.1, build with imagemagick support."
  14193. :group 'org-appearance
  14194. :version "24.4"
  14195. :package-version '(Org . "8.0")
  14196. :type '(choice
  14197. (const :tag "Use the image width" t)
  14198. (integer :tag "Use a number of pixels")
  14199. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  14200. (const :tag "Use #+ATTR* or don't resize" nil)))
  14201. (defcustom org-agenda-inhibit-startup nil
  14202. "Inhibit startup when preparing agenda buffers.
  14203. When this variable is t, the initialization of the Org agenda
  14204. buffers is inhibited: e.g. the visibility state is not set, the
  14205. tables are not re-aligned, etc."
  14206. :type 'boolean
  14207. :version "24.3"
  14208. :group 'org-agenda)
  14209. (defcustom org-agenda-ignore-properties nil
  14210. "Avoid updating text properties when building the agenda.
  14211. Properties are used to prepare buffers for effort estimates,
  14212. appointments, statistics and subtree-local categories.
  14213. If you don't use these in the agenda, you can add them to this
  14214. list and agenda building will be a bit faster.
  14215. The value is a list, with zero or more of the symbols `effort', `appt',
  14216. `stats' or `category'."
  14217. :type '(set :greedy t
  14218. (const effort)
  14219. (const appt)
  14220. (const stats)
  14221. (const category))
  14222. :version "26.1"
  14223. :package-version '(Org . "8.3")
  14224. :group 'org-agenda)
  14225. ;;;; Files
  14226. (defun org-save-all-org-buffers ()
  14227. "Save all Org buffers without user confirmation."
  14228. (interactive)
  14229. (message "Saving all Org buffers...")
  14230. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  14231. (when (featurep 'org-id) (org-id-locations-save))
  14232. (message "Saving all Org buffers... done"))
  14233. (defun org-revert-all-org-buffers ()
  14234. "Revert all Org buffers.
  14235. Prompt for confirmation when there are unsaved changes.
  14236. Be sure you know what you are doing before letting this function
  14237. overwrite your changes.
  14238. This function is useful in a setup where one tracks Org files
  14239. with a version control system, to revert on one machine after pulling
  14240. changes from another. I believe the procedure must be like this:
  14241. 1. M-x org-save-all-org-buffers
  14242. 2. Pull changes from the other machine, resolve conflicts
  14243. 3. M-x org-revert-all-org-buffers"
  14244. (interactive)
  14245. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  14246. (user-error "Abort"))
  14247. (save-excursion
  14248. (save-window-excursion
  14249. (dolist (b (buffer-list))
  14250. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  14251. (with-current-buffer b buffer-file-name))
  14252. (pop-to-buffer-same-window b)
  14253. (revert-buffer t 'no-confirm)))
  14254. (when (and (featurep 'org-id) org-id-track-globally)
  14255. (org-id-locations-load)))))
  14256. ;;;; Agenda files
  14257. ;;;###autoload
  14258. (defun org-switchb (&optional arg)
  14259. "Switch between Org buffers.
  14260. With `\\[universal-argument]' prefix, restrict available buffers to files.
  14261. With `\\[universal-argument] \\[universal-argument]' \
  14262. prefix, restrict available buffers to agenda files."
  14263. (interactive "P")
  14264. (let ((blist (org-buffer-list
  14265. (cond ((equal arg '(4)) 'files)
  14266. ((equal arg '(16)) 'agenda)))))
  14267. (pop-to-buffer-same-window
  14268. (completing-read "Org buffer: "
  14269. (mapcar #'list (mapcar #'buffer-name blist))
  14270. nil t))))
  14271. (defun org-buffer-list (&optional predicate exclude-tmp)
  14272. "Return a list of Org buffers.
  14273. PREDICATE can be `export', `files' or `agenda'.
  14274. export restrict the list to Export buffers.
  14275. files restrict the list to buffers visiting Org files.
  14276. agenda restrict the list to buffers visiting agenda files.
  14277. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  14278. (let* ((bfn nil)
  14279. (agenda-files (and (eq predicate 'agenda)
  14280. (mapcar 'file-truename (org-agenda-files t))))
  14281. (filter
  14282. (cond
  14283. ((eq predicate 'files)
  14284. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  14285. ((eq predicate 'export)
  14286. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  14287. ((eq predicate 'agenda)
  14288. (lambda (b)
  14289. (with-current-buffer b
  14290. (and (derived-mode-p 'org-mode)
  14291. (setq bfn (buffer-file-name b))
  14292. (member (file-truename bfn) agenda-files)))))
  14293. (t (lambda (b) (with-current-buffer b
  14294. (or (derived-mode-p 'org-mode)
  14295. (string-match "\\*Org .*Export"
  14296. (buffer-name b)))))))))
  14297. (delq nil
  14298. (mapcar
  14299. (lambda(b)
  14300. (if (and (funcall filter b)
  14301. (or (not exclude-tmp)
  14302. (not (string-match "tmp" (buffer-name b)))))
  14303. b
  14304. nil))
  14305. (buffer-list)))))
  14306. (defun org-agenda-files (&optional unrestricted archives)
  14307. "Get the list of agenda files.
  14308. Optional UNRESTRICTED means return the full list even if a restriction
  14309. is currently in place.
  14310. When ARCHIVES is t, include all archive files that are really being
  14311. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  14312. `org-agenda-archives-mode' is t."
  14313. (let ((files
  14314. (cond
  14315. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  14316. ((stringp org-agenda-files) (org-read-agenda-file-list))
  14317. ((listp org-agenda-files) org-agenda-files)
  14318. (t (error "Invalid value of `org-agenda-files'")))))
  14319. (setq files (apply 'append
  14320. (mapcar (lambda (f)
  14321. (if (file-directory-p f)
  14322. (directory-files
  14323. f t org-agenda-file-regexp)
  14324. (list f)))
  14325. files)))
  14326. (when org-agenda-skip-unavailable-files
  14327. (setq files (delq nil
  14328. (mapcar (function
  14329. (lambda (file)
  14330. (and (file-readable-p file) file)))
  14331. files))))
  14332. (when (or (eq archives t)
  14333. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  14334. (setq files (org-add-archive-files files)))
  14335. files))
  14336. (defun org-agenda-file-p (&optional file)
  14337. "Return non-nil, if FILE is an agenda file.
  14338. If FILE is omitted, use the file associated with the current
  14339. buffer."
  14340. (let ((fname (or file (buffer-file-name))))
  14341. (and fname
  14342. (member (file-truename fname)
  14343. (mapcar #'file-truename (org-agenda-files t))))))
  14344. (defun org-edit-agenda-file-list ()
  14345. "Edit the list of agenda files.
  14346. Depending on setup, this either uses customize to edit the variable
  14347. `org-agenda-files', or it visits the file that is holding the list. In the
  14348. latter case, the buffer is set up in a way that saving it automatically kills
  14349. the buffer and restores the previous window configuration."
  14350. (interactive)
  14351. (if (stringp org-agenda-files)
  14352. (let ((cw (current-window-configuration)))
  14353. (find-file org-agenda-files)
  14354. (setq-local org-window-configuration cw)
  14355. (add-hook 'after-save-hook
  14356. (lambda ()
  14357. (set-window-configuration
  14358. (prog1 org-window-configuration
  14359. (kill-buffer (current-buffer))))
  14360. (org-install-agenda-files-menu)
  14361. (message "New agenda file list installed"))
  14362. nil 'local)
  14363. (message "%s" (substitute-command-keys
  14364. "Edit list and finish with \\[save-buffer]")))
  14365. (customize-variable 'org-agenda-files)))
  14366. (defun org-store-new-agenda-file-list (list)
  14367. "Set new value for the agenda file list and save it correctly."
  14368. (if (stringp org-agenda-files)
  14369. (let ((fe (org-read-agenda-file-list t)) b u)
  14370. (while (setq b (find-buffer-visiting org-agenda-files))
  14371. (kill-buffer b))
  14372. (with-temp-file org-agenda-files
  14373. (insert
  14374. (mapconcat
  14375. (lambda (f) ;; Keep un-expanded entries.
  14376. (if (setq u (assoc f fe))
  14377. (cdr u)
  14378. f))
  14379. list "\n")
  14380. "\n")))
  14381. (let ((org-mode-hook nil) (org-inhibit-startup t)
  14382. (org-insert-mode-line-in-empty-file nil))
  14383. (setq org-agenda-files list)
  14384. (customize-save-variable 'org-agenda-files org-agenda-files))))
  14385. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  14386. "Read the list of agenda files from a file.
  14387. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  14388. filenames, used by `org-store-new-agenda-file-list' to write back
  14389. un-expanded file names."
  14390. (when (file-directory-p org-agenda-files)
  14391. (error "`org-agenda-files' cannot be a single directory"))
  14392. (when (stringp org-agenda-files)
  14393. (with-temp-buffer
  14394. (insert-file-contents org-agenda-files)
  14395. (mapcar
  14396. (lambda (f)
  14397. (let ((e (expand-file-name (substitute-in-file-name f)
  14398. org-directory)))
  14399. (if pair-with-expansion
  14400. (cons e f)
  14401. e)))
  14402. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  14403. ;;;###autoload
  14404. (defun org-cycle-agenda-files ()
  14405. "Cycle through the files in `org-agenda-files'.
  14406. If the current buffer visits an agenda file, find the next one in the list.
  14407. If the current buffer does not, find the first agenda file."
  14408. (interactive)
  14409. (let* ((fs (or (org-agenda-files t)
  14410. (user-error "No agenda files")))
  14411. (files (copy-sequence fs))
  14412. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  14413. file)
  14414. (when tcf
  14415. (while (and (setq file (pop files))
  14416. (not (equal (file-truename file) tcf)))))
  14417. (find-file (car (or files fs)))
  14418. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  14419. (defun org-agenda-file-to-front (&optional to-end)
  14420. "Move/add the current file to the top of the agenda file list.
  14421. If the file is not present in the list, it is added to the front. If it is
  14422. present, it is moved there. With optional argument TO-END, add/move to the
  14423. end of the list."
  14424. (interactive "P")
  14425. (let ((org-agenda-skip-unavailable-files nil)
  14426. (file-alist (mapcar (lambda (x)
  14427. (cons (file-truename x) x))
  14428. (org-agenda-files t)))
  14429. (ctf (file-truename
  14430. (or buffer-file-name
  14431. (user-error "Please save the current buffer to a file"))))
  14432. x had)
  14433. (setq x (assoc ctf file-alist) had x)
  14434. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  14435. (if to-end
  14436. (setq file-alist (append (delq x file-alist) (list x)))
  14437. (setq file-alist (cons x (delq x file-alist))))
  14438. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  14439. (org-install-agenda-files-menu)
  14440. (message "File %s to %s of agenda file list"
  14441. (if had "moved" "added") (if to-end "end" "front"))))
  14442. (defun org-remove-file (&optional file)
  14443. "Remove current file from the list of files in variable `org-agenda-files'.
  14444. These are the files which are being checked for agenda entries.
  14445. Optional argument FILE means use this file instead of the current."
  14446. (interactive)
  14447. (let* ((org-agenda-skip-unavailable-files nil)
  14448. (file (or file buffer-file-name
  14449. (user-error "Current buffer does not visit a file")))
  14450. (true-file (file-truename file))
  14451. (afile (abbreviate-file-name file))
  14452. (files (delq nil (mapcar
  14453. (lambda (x)
  14454. (unless (equal true-file
  14455. (file-truename x))
  14456. x))
  14457. (org-agenda-files t)))))
  14458. (if (not (= (length files) (length (org-agenda-files t))))
  14459. (progn
  14460. (org-store-new-agenda-file-list files)
  14461. (org-install-agenda-files-menu)
  14462. (message "Removed from Org Agenda list: %s" afile))
  14463. (message "File was not in list: %s (not removed)" afile))))
  14464. (defun org-file-menu-entry (file)
  14465. (vector file (list 'find-file file) t))
  14466. (defun org-check-agenda-file (file)
  14467. "Make sure FILE exists. If not, ask user what to do."
  14468. (unless (file-exists-p file)
  14469. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  14470. (abbreviate-file-name file))
  14471. (let ((r (downcase (read-char-exclusive))))
  14472. (cond
  14473. ((equal r ?r)
  14474. (org-remove-file file)
  14475. (throw 'nextfile t))
  14476. (t (user-error "Abort"))))))
  14477. (defun org-get-agenda-file-buffer (file)
  14478. "Get an agenda buffer visiting FILE.
  14479. If the buffer needs to be created, add it to the list of buffers
  14480. which might be released later."
  14481. (let ((buf (org-find-base-buffer-visiting file)))
  14482. (if buf
  14483. buf ; just return it
  14484. ;; Make a new buffer and remember it
  14485. (setq buf (find-file-noselect file))
  14486. (when buf (push buf org-agenda-new-buffers))
  14487. buf)))
  14488. (defun org-release-buffers (blist)
  14489. "Release all buffers in list, asking the user for confirmation when needed.
  14490. When a buffer is unmodified, it is just killed. When modified, it is saved
  14491. \(if the user agrees) and then killed."
  14492. (let (file)
  14493. (dolist (buf blist)
  14494. (setq file (buffer-file-name buf))
  14495. (when (and (buffer-modified-p buf)
  14496. file
  14497. (y-or-n-p (format "Save file %s? " file)))
  14498. (with-current-buffer buf (save-buffer)))
  14499. (kill-buffer buf))))
  14500. (defun org-agenda-prepare-buffers (files)
  14501. "Create buffers for all agenda files, protect archived trees and comments."
  14502. (interactive)
  14503. (let ((pa '(:org-archived t))
  14504. (pc '(:org-comment t))
  14505. (pall '(:org-archived t :org-comment t))
  14506. (inhibit-read-only t)
  14507. (org-inhibit-startup org-agenda-inhibit-startup)
  14508. (rea (org-make-tag-string (list org-archive-tag)))
  14509. re pos)
  14510. (setq org-tag-alist-for-agenda nil
  14511. org-tag-groups-alist-for-agenda nil)
  14512. (save-excursion
  14513. (save-restriction
  14514. (dolist (file files)
  14515. (catch 'nextfile
  14516. (if (bufferp file)
  14517. (set-buffer file)
  14518. (org-check-agenda-file file)
  14519. (set-buffer (org-get-agenda-file-buffer file)))
  14520. (widen)
  14521. (org-set-regexps-and-options 'tags-only)
  14522. (setq pos (point))
  14523. (or (memq 'category org-agenda-ignore-properties)
  14524. (org-refresh-category-properties))
  14525. (or (memq 'stats org-agenda-ignore-properties)
  14526. (org-refresh-stats-properties))
  14527. (or (memq 'effort org-agenda-ignore-properties)
  14528. (org-refresh-effort-properties))
  14529. (or (memq 'appt org-agenda-ignore-properties)
  14530. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  14531. (setq org-todo-keywords-for-agenda
  14532. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  14533. (setq org-done-keywords-for-agenda
  14534. (append org-done-keywords-for-agenda org-done-keywords))
  14535. (setq org-todo-keyword-alist-for-agenda
  14536. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  14537. (setq org-tag-alist-for-agenda
  14538. (org--tag-add-to-alist
  14539. org-tag-alist-for-agenda
  14540. org-current-tag-alist))
  14541. ;; Merge current file's tag groups into global
  14542. ;; `org-tag-groups-alist-for-agenda'.
  14543. (when org-group-tags
  14544. (dolist (alist org-tag-groups-alist)
  14545. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  14546. (if old
  14547. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  14548. (push alist org-tag-groups-alist-for-agenda)))))
  14549. (with-silent-modifications
  14550. (save-excursion
  14551. (remove-text-properties (point-min) (point-max) pall)
  14552. (when org-agenda-skip-archived-trees
  14553. (goto-char (point-min))
  14554. (while (re-search-forward rea nil t)
  14555. (when (org-at-heading-p t)
  14556. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  14557. (goto-char (point-min))
  14558. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  14559. (while (re-search-forward re nil t)
  14560. (when (save-match-data (org-in-commented-heading-p t))
  14561. (add-text-properties
  14562. (match-beginning 0) (org-end-of-subtree t) pc)))))
  14563. (goto-char pos)))))
  14564. (setq org-todo-keywords-for-agenda
  14565. (org-uniquify org-todo-keywords-for-agenda))
  14566. (setq org-todo-keyword-alist-for-agenda
  14567. (org-uniquify org-todo-keyword-alist-for-agenda))))
  14568. ;;;; CDLaTeX minor mode
  14569. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  14570. "Keymap for the minor `org-cdlatex-mode'.")
  14571. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  14572. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  14573. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  14574. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  14575. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  14576. (defvar org-cdlatex-texmathp-advice-is-done nil
  14577. "Flag remembering if we have applied the advice to texmathp already.")
  14578. (define-minor-mode org-cdlatex-mode
  14579. "Toggle the minor `org-cdlatex-mode'.
  14580. This mode supports entering LaTeX environment and math in LaTeX fragments
  14581. in Org mode.
  14582. \\{org-cdlatex-mode-map}"
  14583. nil " OCDL" nil
  14584. (when org-cdlatex-mode
  14585. (require 'cdlatex)
  14586. (run-hooks 'cdlatex-mode-hook)
  14587. (cdlatex-compute-tables))
  14588. (unless org-cdlatex-texmathp-advice-is-done
  14589. (setq org-cdlatex-texmathp-advice-is-done t)
  14590. (defadvice texmathp (around org-math-always-on activate)
  14591. "Always return t in Org buffers.
  14592. This is because we want to insert math symbols without dollars even outside
  14593. the LaTeX math segments. If Org mode thinks that point is actually inside
  14594. an embedded LaTeX fragment, let `texmathp' do its job.
  14595. `\\[org-cdlatex-mode-map]'"
  14596. (interactive)
  14597. (let (p)
  14598. (cond
  14599. ((not (derived-mode-p 'org-mode)) ad-do-it)
  14600. ((eq this-command 'cdlatex-math-symbol)
  14601. (setq ad-return-value t
  14602. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  14603. (t
  14604. (let ((p (org-inside-LaTeX-fragment-p)))
  14605. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  14606. (setq ad-return-value t
  14607. texmathp-why '("Org mode embedded math" . 0))
  14608. (when p ad-do-it)))))))))
  14609. (defun turn-on-org-cdlatex ()
  14610. "Unconditionally turn on `org-cdlatex-mode'."
  14611. (org-cdlatex-mode 1))
  14612. (defun org-try-cdlatex-tab ()
  14613. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  14614. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  14615. - inside a LaTeX fragment, or
  14616. - after the first word in a line, where an abbreviation expansion could
  14617. insert a LaTeX environment."
  14618. (when org-cdlatex-mode
  14619. (cond
  14620. ;; Before any word on the line: No expansion possible.
  14621. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  14622. ;; Just after first word on the line: Expand it. Make sure it
  14623. ;; cannot happen on headlines, though.
  14624. ((save-excursion
  14625. (skip-chars-backward "a-zA-Z0-9*")
  14626. (skip-chars-backward " \t")
  14627. (and (bolp) (not (org-at-heading-p))))
  14628. (cdlatex-tab) t)
  14629. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  14630. (defun org-cdlatex-underscore-caret (&optional _arg)
  14631. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  14632. Revert to the normal definition outside of these fragments."
  14633. (interactive "P")
  14634. (if (org-inside-LaTeX-fragment-p)
  14635. (call-interactively 'cdlatex-sub-superscript)
  14636. (let (org-cdlatex-mode)
  14637. (call-interactively (key-binding (vector last-input-event))))))
  14638. (defun org-cdlatex-math-modify (&optional _arg)
  14639. "Execute `cdlatex-math-modify' in LaTeX fragments.
  14640. Revert to the normal definition outside of these fragments."
  14641. (interactive "P")
  14642. (if (org-inside-LaTeX-fragment-p)
  14643. (call-interactively 'cdlatex-math-modify)
  14644. (let (org-cdlatex-mode)
  14645. (call-interactively (key-binding (vector last-input-event))))))
  14646. (defun org-cdlatex-environment-indent (&optional environment item)
  14647. "Execute `cdlatex-environment' and indent the inserted environment.
  14648. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  14649. The inserted environment is indented to current indentation
  14650. unless point is at the beginning of the line, in which the
  14651. environment remains unintended."
  14652. (interactive)
  14653. ;; cdlatex-environment always return nil. Therefore, capture output
  14654. ;; first and determine if an environment was selected.
  14655. (let* ((beg (point-marker))
  14656. (end (copy-marker (point) t))
  14657. (inserted (progn
  14658. (ignore-errors (cdlatex-environment environment item))
  14659. (< beg end)))
  14660. ;; Figure out how many lines to move forward after the
  14661. ;; environment has been inserted.
  14662. (lines (when inserted
  14663. (save-excursion
  14664. (- (cl-loop while (< beg (point))
  14665. with x = 0
  14666. do (forward-line -1)
  14667. (cl-incf x)
  14668. finally return x)
  14669. (if (progn (goto-char beg)
  14670. (and (progn (skip-chars-forward " \t") (eolp))
  14671. (progn (skip-chars-backward " \t") (bolp))))
  14672. 1 0)))))
  14673. (env (org-trim (delete-and-extract-region beg end))))
  14674. (when inserted
  14675. ;; Get indentation of next line unless at column 0.
  14676. (let ((ind (if (bolp) 0
  14677. (save-excursion
  14678. (org-return-indent)
  14679. (prog1 (current-indentation)
  14680. (when (progn (skip-chars-forward " \t") (eolp))
  14681. (delete-region beg (point)))))))
  14682. (bol (progn (skip-chars-backward " \t") (bolp))))
  14683. ;; Insert a newline before environment unless at column zero
  14684. ;; to "escape" the current line. Insert a newline if
  14685. ;; something is one the same line as \end{ENVIRONMENT}.
  14686. (insert
  14687. (concat (unless bol "\n") env
  14688. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14689. (unless (zerop ind)
  14690. (save-excursion
  14691. (goto-char beg)
  14692. (while (< (point) end)
  14693. (unless (eolp) (indent-line-to ind))
  14694. (forward-line))))
  14695. (goto-char beg)
  14696. (forward-line lines)
  14697. (indent-line-to ind)))
  14698. (set-marker beg nil)
  14699. (set-marker end nil)))
  14700. ;;;; LaTeX fragments
  14701. (defun org-inside-LaTeX-fragment-p ()
  14702. "Test if point is inside a LaTeX fragment.
  14703. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14704. sequence appearing also before point.
  14705. Even though the matchers for math are configurable, this function assumes
  14706. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14707. delimiters are skipped when they have been removed by customization.
  14708. The return value is nil, or a cons cell with the delimiter and the
  14709. position of this delimiter.
  14710. This function does a reasonably good job, but can locally be fooled by
  14711. for example currency specifications. For example it will assume being in
  14712. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14713. fragments that are properly closed, but during editing, we have to live
  14714. with the uncertainty caused by missing closing delimiters. This function
  14715. looks only before point, not after."
  14716. (catch 'exit
  14717. (let ((pos (point))
  14718. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14719. (lim (save-excursion (org-backward-paragraph) (point)))
  14720. dd-on str (start 0) m re)
  14721. (goto-char pos)
  14722. (when dodollar
  14723. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14724. re (nth 1 (assoc "$" org-latex-regexps)))
  14725. (while (string-match re str start)
  14726. (cond
  14727. ((= (match-end 0) (length str))
  14728. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14729. ((= (match-end 0) (- (length str) 5))
  14730. (throw 'exit nil))
  14731. (t (setq start (match-end 0))))))
  14732. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14733. (goto-char pos)
  14734. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14735. (and (match-beginning 2) (throw 'exit nil))
  14736. ;; count $$
  14737. (while (re-search-backward "\\$\\$" lim t)
  14738. (setq dd-on (not dd-on)))
  14739. (goto-char pos)
  14740. (when dd-on (cons "$$" m))))))
  14741. (defun org-inside-latex-macro-p ()
  14742. "Is point inside a LaTeX macro or its arguments?"
  14743. (save-match-data
  14744. (org-in-regexp
  14745. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14746. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14747. "Build an overlay between BEG and END using IMAGE file.
  14748. Argument IMAGETYPE is the extension of the displayed image,
  14749. as a string. It defaults to \"png\"."
  14750. (let ((ov (make-overlay beg end))
  14751. (imagetype (or (intern imagetype) 'png)))
  14752. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14753. (overlay-put ov 'evaporate t)
  14754. (overlay-put ov
  14755. 'modification-hooks
  14756. (list (lambda (o _flag _beg _end &optional _l)
  14757. (delete-overlay o))))
  14758. (overlay-put ov
  14759. 'display
  14760. (list 'image :type imagetype :file image :ascent 'center))))
  14761. (defun org-clear-latex-preview (&optional beg end)
  14762. "Remove all overlays with LaTeX fragment images in current buffer.
  14763. When optional arguments BEG and END are non-nil, remove all
  14764. overlays between them instead. Return a non-nil value when some
  14765. overlays were removed, nil otherwise."
  14766. (let ((overlays
  14767. (cl-remove-if-not
  14768. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14769. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14770. (mapc #'delete-overlay overlays)
  14771. overlays))
  14772. (defun org--latex-preview-region (beg end)
  14773. "Preview LaTeX fragments between BEG and END.
  14774. BEG and END are buffer positions."
  14775. (let ((file (buffer-file-name (buffer-base-buffer))))
  14776. (save-excursion
  14777. (org-format-latex
  14778. (concat org-preview-latex-image-directory "org-ltximg")
  14779. beg end
  14780. ;; Emacs cannot overlay images from remote hosts. Create it in
  14781. ;; `temporary-file-directory' instead.
  14782. (if (or (not file) (file-remote-p file))
  14783. temporary-file-directory
  14784. default-directory)
  14785. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14786. (defun org-latex-preview (&optional arg)
  14787. "Toggle preview of the LaTeX fragment at point.
  14788. If the cursor is on a LaTeX fragment, create the image and
  14789. overlay it over the source code, if there is none. Remove it
  14790. otherwise. If there is no fragment at point, display images for
  14791. all fragments in the current section.
  14792. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14793. for all fragments
  14794. in the current section.
  14795. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14796. argument ARG, display image for all
  14797. fragments in the buffer.
  14798. With a `\\[universal-argument] \\[universal-argument] \
  14799. \\[universal-argument]' prefix argument ARG, clear image for all
  14800. fragments in the buffer."
  14801. (interactive "P")
  14802. (cond
  14803. ((not (display-graphic-p)) nil)
  14804. ;; Clear whole buffer.
  14805. ((equal arg '(64))
  14806. (org-clear-latex-preview (point-min) (point-max))
  14807. (message "LaTeX previews removed from buffer"))
  14808. ;; Preview whole buffer.
  14809. ((equal arg '(16))
  14810. (message "Creating LaTeX previews in buffer...")
  14811. (org--latex-preview-region (point-min) (point-max))
  14812. (message "Creating LaTeX previews in buffer... done."))
  14813. ;; Clear current section.
  14814. ((equal arg '(4))
  14815. (org-clear-latex-preview
  14816. (if (org-before-first-heading-p) (point-min)
  14817. (save-excursion
  14818. (org-with-limited-levels (org-back-to-heading t) (point))))
  14819. (org-with-limited-levels (org-entry-end-position))))
  14820. ;; Toggle preview on LaTeX code at point.
  14821. ((let ((datum (org-element-context)))
  14822. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14823. (let ((beg (org-element-property :begin datum))
  14824. (end (org-element-property :end datum)))
  14825. (if (org-clear-latex-preview beg end)
  14826. (message "LaTeX preview removed")
  14827. (message "Creating LaTeX preview...")
  14828. (org--latex-preview-region beg end)
  14829. (message "Creating LaTeX preview... done."))
  14830. t))))
  14831. ;; Preview current section.
  14832. (t
  14833. (let ((beg (if (org-before-first-heading-p) (point-min)
  14834. (save-excursion
  14835. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14836. (end (org-with-limited-levels (org-entry-end-position))))
  14837. (message "Creating LaTeX previews in section...")
  14838. (org--latex-preview-region beg end)
  14839. (message "Creating LaTeX previews in section... done.")))))
  14840. (defun org-format-latex
  14841. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14842. "Replace LaTeX fragments with links to an image.
  14843. The function takes care of creating the replacement image.
  14844. Only consider fragments between BEG and END when those are
  14845. provided.
  14846. When optional argument OVERLAYS is non-nil, display the image on
  14847. top of the fragment instead of replacing it.
  14848. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14849. Some of the options can be changed using the variable
  14850. `org-format-latex-options', which see."
  14851. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14852. (unless (eq processing-type 'verbatim)
  14853. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14854. (cnt 0)
  14855. checkdir-flag)
  14856. (goto-char (or beg (point-min)))
  14857. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14858. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14859. (overlay-recenter (or end (point-max))))
  14860. (while (re-search-forward math-regexp end t)
  14861. (unless (and overlays
  14862. (eq (get-char-property (point) 'org-overlay-type)
  14863. 'org-latex-overlay))
  14864. (let* ((context (org-element-context))
  14865. (type (org-element-type context)))
  14866. (when (memq type '(latex-environment latex-fragment))
  14867. (let ((block-type (eq type 'latex-environment))
  14868. (value (org-element-property :value context))
  14869. (beg (org-element-property :begin context))
  14870. (end (save-excursion
  14871. (goto-char (org-element-property :end context))
  14872. (skip-chars-backward " \r\t\n")
  14873. (point))))
  14874. (cond
  14875. ((eq processing-type 'mathjax)
  14876. ;; Prepare for MathJax processing.
  14877. (if (not (string-match "\\`\\$\\$?" value))
  14878. (goto-char end)
  14879. (delete-region beg end)
  14880. (if (string= (match-string 0 value) "$$")
  14881. (insert "\\[" (substring value 2 -2) "\\]")
  14882. (insert "\\(" (substring value 1 -1) "\\)"))))
  14883. ((assq processing-type org-preview-latex-process-alist)
  14884. ;; Process to an image.
  14885. (cl-incf cnt)
  14886. (goto-char beg)
  14887. (let* ((processing-info
  14888. (cdr (assq processing-type org-preview-latex-process-alist)))
  14889. (face (face-at-point))
  14890. ;; Get the colors from the face at point.
  14891. (fg
  14892. (let ((color (plist-get org-format-latex-options
  14893. :foreground)))
  14894. (if (and forbuffer (eq color 'auto))
  14895. (face-attribute face :foreground nil 'default)
  14896. color)))
  14897. (bg
  14898. (let ((color (plist-get org-format-latex-options
  14899. :background)))
  14900. (if (and forbuffer (eq color 'auto))
  14901. (face-attribute face :background nil 'default)
  14902. color)))
  14903. (hash (sha1 (prin1-to-string
  14904. (list org-format-latex-header
  14905. org-latex-default-packages-alist
  14906. org-latex-packages-alist
  14907. org-format-latex-options
  14908. forbuffer value fg bg))))
  14909. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14910. (absprefix (expand-file-name prefix dir))
  14911. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14912. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14913. (sep (and block-type "\n\n"))
  14914. (link (concat sep "[[file:" linkfile "]]" sep))
  14915. (options
  14916. (org-combine-plists
  14917. org-format-latex-options
  14918. `(:foreground ,fg :background ,bg))))
  14919. (when msg (message msg cnt))
  14920. (unless checkdir-flag ; Ensure the directory exists.
  14921. (setq checkdir-flag t)
  14922. (let ((todir (file-name-directory absprefix)))
  14923. (unless (file-directory-p todir)
  14924. (make-directory todir t))))
  14925. (unless (file-exists-p movefile)
  14926. (org-create-formula-image
  14927. value movefile options forbuffer processing-type))
  14928. (if overlays
  14929. (progn
  14930. (dolist (o (overlays-in beg end))
  14931. (when (eq (overlay-get o 'org-overlay-type)
  14932. 'org-latex-overlay)
  14933. (delete-overlay o)))
  14934. (org--make-preview-overlay beg end movefile imagetype)
  14935. (goto-char end))
  14936. (delete-region beg end)
  14937. (insert
  14938. (org-add-props link
  14939. (list 'org-latex-src
  14940. (replace-regexp-in-string "\"" "" value)
  14941. 'org-latex-src-embed-type
  14942. (if block-type 'paragraph 'character)))))))
  14943. ((eq processing-type 'mathml)
  14944. ;; Process to MathML.
  14945. (unless (org-format-latex-mathml-available-p)
  14946. (user-error "LaTeX to MathML converter not configured"))
  14947. (cl-incf cnt)
  14948. (when msg (message msg cnt))
  14949. (goto-char beg)
  14950. (delete-region beg end)
  14951. (insert (org-format-latex-as-mathml
  14952. value block-type prefix dir)))
  14953. (t
  14954. (error "Unknown conversion process %s for LaTeX fragments"
  14955. processing-type)))))))))))
  14956. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14957. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14958. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14959. sucessful, return the portion between \"<math...> </math>\"
  14960. elements otherwise return nil. When MATHML-FILE is specified,
  14961. write the results in to that file. When invoked as an
  14962. interactive command, prompt for LATEX-FRAG, with initial value
  14963. set to the current active region and echo the results for user
  14964. inspection."
  14965. (interactive (list (let ((frag (when (org-region-active-p)
  14966. (buffer-substring-no-properties
  14967. (region-beginning) (region-end)))))
  14968. (read-string "LaTeX Fragment: " frag nil frag))))
  14969. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14970. (let* ((tmp-in-file
  14971. (let ((file (file-relative-name
  14972. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14973. (write-region latex-frag nil file)
  14974. file))
  14975. (tmp-out-file (file-relative-name
  14976. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14977. (cmd (format-spec
  14978. org-latex-to-mathml-convert-command
  14979. `((?j . ,(and org-latex-to-mathml-jar-file
  14980. (shell-quote-argument
  14981. (expand-file-name
  14982. org-latex-to-mathml-jar-file))))
  14983. (?I . ,(shell-quote-argument tmp-in-file))
  14984. (?i . ,latex-frag)
  14985. (?o . ,(shell-quote-argument tmp-out-file)))))
  14986. mathml shell-command-output)
  14987. (when (called-interactively-p 'any)
  14988. (unless (org-format-latex-mathml-available-p)
  14989. (user-error "LaTeX to MathML converter not configured")))
  14990. (message "Running %s" cmd)
  14991. (setq shell-command-output (shell-command-to-string cmd))
  14992. (setq mathml
  14993. (when (file-readable-p tmp-out-file)
  14994. (with-current-buffer (find-file-noselect tmp-out-file t)
  14995. (goto-char (point-min))
  14996. (when (re-search-forward
  14997. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14998. (regexp-quote
  14999. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  15000. nil t)
  15001. (prog1 (match-string 0) (kill-buffer))))))
  15002. (cond
  15003. (mathml
  15004. (setq mathml
  15005. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  15006. (when mathml-file
  15007. (write-region mathml nil mathml-file))
  15008. (when (called-interactively-p 'any)
  15009. (message mathml)))
  15010. ((message "LaTeX to MathML conversion failed")
  15011. (message shell-command-output)))
  15012. (delete-file tmp-in-file)
  15013. (when (file-exists-p tmp-out-file)
  15014. (delete-file tmp-out-file))
  15015. mathml))
  15016. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  15017. prefix &optional dir)
  15018. "Use `org-create-math-formula' but check local cache first."
  15019. (let* ((absprefix (expand-file-name prefix dir))
  15020. (print-length nil) (print-level nil)
  15021. (formula-id (concat
  15022. "formula-"
  15023. (sha1
  15024. (prin1-to-string
  15025. (list latex-frag
  15026. org-latex-to-mathml-convert-command)))))
  15027. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  15028. (formula-cache-dir (file-name-directory formula-cache)))
  15029. (unless (file-directory-p formula-cache-dir)
  15030. (make-directory formula-cache-dir t))
  15031. (unless (file-exists-p formula-cache)
  15032. (org-create-math-formula latex-frag formula-cache))
  15033. (if (file-exists-p formula-cache)
  15034. ;; Successful conversion. Return the link to MathML file.
  15035. (org-add-props
  15036. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  15037. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  15038. 'org-latex-src-embed-type (if latex-frag-type
  15039. 'paragraph 'character)))
  15040. ;; Failed conversion. Return the LaTeX fragment verbatim
  15041. latex-frag)))
  15042. (defun org--get-display-dpi ()
  15043. "Get the DPI of the display.
  15044. The function assumes that the display has the same pixel width in
  15045. the horizontal and vertical directions."
  15046. (if (display-graphic-p)
  15047. (round (/ (display-pixel-height)
  15048. (/ (display-mm-height) 25.4)))
  15049. (error "Attempt to calculate the dpi of a non-graphic display")))
  15050. (defun org-create-formula-image
  15051. (string tofile options buffer &optional processing-type)
  15052. "Create an image from LaTeX source using external processes.
  15053. The LaTeX STRING is saved to a temporary LaTeX file, then
  15054. converted to an image file by process PROCESSING-TYPE defined in
  15055. `org-preview-latex-process-alist'. A nil value defaults to
  15056. `org-preview-latex-default-process'.
  15057. The generated image file is eventually moved to TOFILE.
  15058. The OPTIONS argument controls the size, foreground color and
  15059. background color of the generated image.
  15060. When BUFFER non-nil, this function is used for LaTeX previewing.
  15061. Otherwise, it is used to deal with LaTeX snippets showed in
  15062. a HTML file."
  15063. (let* ((processing-type (or processing-type
  15064. org-preview-latex-default-process))
  15065. (processing-info
  15066. (cdr (assq processing-type org-preview-latex-process-alist)))
  15067. (programs (plist-get processing-info :programs))
  15068. (error-message (or (plist-get processing-info :message) ""))
  15069. (image-input-type (plist-get processing-info :image-input-type))
  15070. (image-output-type (plist-get processing-info :image-output-type))
  15071. (post-clean (or (plist-get processing-info :post-clean)
  15072. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  15073. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  15074. (latex-header
  15075. (or (plist-get processing-info :latex-header)
  15076. (org-latex-make-preamble
  15077. (org-export-get-environment (org-export-get-backend 'latex))
  15078. org-format-latex-header
  15079. 'snippet)))
  15080. (latex-compiler (plist-get processing-info :latex-compiler))
  15081. (image-converter (plist-get processing-info :image-converter))
  15082. (tmpdir temporary-file-directory)
  15083. (texfilebase (make-temp-name
  15084. (expand-file-name "orgtex" tmpdir)))
  15085. (texfile (concat texfilebase ".tex"))
  15086. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  15087. '(1.0 . 1.0)))
  15088. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  15089. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  15090. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  15091. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  15092. "Black"))
  15093. (bg (or (plist-get options (if buffer :background :html-background))
  15094. "Transparent"))
  15095. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  15096. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  15097. (dolist (program programs)
  15098. (org-check-external-command program error-message))
  15099. (if (eq fg 'default)
  15100. (setq fg (org-latex-color :foreground))
  15101. (setq fg (org-latex-color-format fg)))
  15102. (if (eq bg 'default)
  15103. (setq bg (org-latex-color :background))
  15104. (setq bg (org-latex-color-format
  15105. (if (string= bg "Transparent") "white" bg))))
  15106. (with-temp-file texfile
  15107. (insert latex-header)
  15108. (insert "\n\\begin{document}\n"
  15109. "\\definecolor{fg}{rgb}{" fg "}\n"
  15110. "\\definecolor{bg}{rgb}{" bg "}\n"
  15111. "\n\\pagecolor{bg}\n"
  15112. "\n{\\color{fg}\n"
  15113. string
  15114. "\n}\n"
  15115. "\n\\end{document}\n"))
  15116. (let* ((err-msg (format "Please adjust `%s' part of \
  15117. `org-preview-latex-process-alist'."
  15118. processing-type))
  15119. (image-input-file
  15120. (org-compile-file
  15121. texfile latex-compiler image-input-type err-msg log-buf))
  15122. (image-output-file
  15123. (org-compile-file
  15124. image-input-file image-converter image-output-type err-msg log-buf
  15125. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  15126. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  15127. (copy-file image-output-file tofile 'replace)
  15128. (dolist (e post-clean)
  15129. (when (file-exists-p (concat texfilebase e))
  15130. (delete-file (concat texfilebase e))))
  15131. image-output-file)))
  15132. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  15133. "Fill a LaTeX header template TPL.
  15134. In the template, the following place holders will be recognized:
  15135. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  15136. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  15137. [PACKAGES] \\usepackage statements for PKG
  15138. [NO-PACKAGES] do not include PKG
  15139. [EXTRA] the string EXTRA
  15140. [NO-EXTRA] do not include EXTRA
  15141. For backward compatibility, if both the positive and the negative place
  15142. holder is missing, the positive one (without the \"NO-\") will be
  15143. assumed to be present at the end of the template.
  15144. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  15145. EXTRA is a string.
  15146. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  15147. (let (rpl (end ""))
  15148. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  15149. (setq rpl (if (or (match-end 1) (not def-pkg))
  15150. "" (org-latex-packages-to-string def-pkg snippets-p t))
  15151. tpl (replace-match rpl t t tpl))
  15152. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  15153. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  15154. (setq rpl (if (or (match-end 1) (not pkg))
  15155. "" (org-latex-packages-to-string pkg snippets-p t))
  15156. tpl (replace-match rpl t t tpl))
  15157. (when pkg (setq end
  15158. (concat end "\n"
  15159. (org-latex-packages-to-string pkg snippets-p)))))
  15160. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  15161. (setq rpl (if (or (match-end 1) (not extra))
  15162. "" (concat extra "\n"))
  15163. tpl (replace-match rpl t t tpl))
  15164. (when (and extra (string-match "\\S-" extra))
  15165. (setq end (concat end "\n" extra))))
  15166. (if (string-match "\\S-" end)
  15167. (concat tpl "\n" end)
  15168. tpl)))
  15169. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  15170. "Turn an alist of packages into a string with the \\usepackage macros."
  15171. (setq pkg (mapconcat (lambda(p)
  15172. (cond
  15173. ((stringp p) p)
  15174. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  15175. (format "%% Package %s omitted" (cadr p)))
  15176. ((equal "" (car p))
  15177. (format "\\usepackage{%s}" (cadr p)))
  15178. (t
  15179. (format "\\usepackage[%s]{%s}"
  15180. (car p) (cadr p)))))
  15181. pkg
  15182. "\n"))
  15183. (if newline (concat pkg "\n") pkg))
  15184. (defun org-dvipng-color (attr)
  15185. "Return a RGB color specification for dvipng."
  15186. (org-dvipng-color-format (face-attribute 'default attr nil)))
  15187. (defun org-dvipng-color-format (color-name)
  15188. "Convert COLOR-NAME to a RGB color value for dvipng."
  15189. (apply #'format "rgb %s %s %s"
  15190. (mapcar 'org-normalize-color
  15191. (color-values color-name))))
  15192. (defun org-latex-color (attr)
  15193. "Return a RGB color for the LaTeX color package."
  15194. (org-latex-color-format (face-attribute 'default attr nil)))
  15195. (defun org-latex-color-format (color-name)
  15196. "Convert COLOR-NAME to a RGB color value."
  15197. (apply #'format "%s,%s,%s"
  15198. (mapcar 'org-normalize-color
  15199. (color-values color-name))))
  15200. (defun org-normalize-color (value)
  15201. "Return string to be used as color value for an RGB component."
  15202. (format "%g" (/ value 65535.0)))
  15203. ;; Image display
  15204. (defvar-local org-inline-image-overlays nil)
  15205. (defun org-toggle-inline-images (&optional include-linked)
  15206. "Toggle the display of inline images.
  15207. INCLUDE-LINKED is passed to `org-display-inline-images'."
  15208. (interactive "P")
  15209. (if org-inline-image-overlays
  15210. (progn
  15211. (org-remove-inline-images)
  15212. (when (called-interactively-p 'interactive)
  15213. (message "Inline image display turned off")))
  15214. (org-display-inline-images include-linked)
  15215. (when (called-interactively-p 'interactive)
  15216. (message (if org-inline-image-overlays
  15217. (format "%d images displayed inline"
  15218. (length org-inline-image-overlays))
  15219. "No images to display inline")))))
  15220. (defun org-redisplay-inline-images ()
  15221. "Refresh the display of inline images."
  15222. (interactive)
  15223. (if (not org-inline-image-overlays)
  15224. (org-toggle-inline-images)
  15225. (org-toggle-inline-images)
  15226. (org-toggle-inline-images)))
  15227. ;; For without-x builds.
  15228. (declare-function image-refresh "image" (spec &optional frame))
  15229. (defun org-display-inline-images (&optional include-linked refresh beg end)
  15230. "Display inline images.
  15231. An inline image is a link which follows either of these
  15232. conventions:
  15233. 1. Its path is a file with an extension matching return value
  15234. from `image-file-name-regexp' and it has no contents.
  15235. 2. Its description consists in a single link of the previous
  15236. type. In this case, that link must be a well-formed plain
  15237. or angle link, i.e., it must have an explicit \"file\" type.
  15238. When optional argument INCLUDE-LINKED is non-nil, also links with
  15239. a text description part will be inlined. This can be nice for
  15240. a quick look at those images, but it does not reflect what
  15241. exported files will look like.
  15242. When optional argument REFRESH is non-nil, refresh existing
  15243. images between BEG and END. This will create new image displays
  15244. only if necessary. BEG and END default to the buffer
  15245. boundaries."
  15246. (interactive "P")
  15247. (when (display-graphic-p)
  15248. (unless refresh
  15249. (org-remove-inline-images)
  15250. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  15251. (org-with-point-at (or beg 1)
  15252. (let* ((case-fold-search t)
  15253. (file-extension-re (image-file-name-regexp))
  15254. (link-abbrevs (mapcar #'car
  15255. (append org-link-abbrev-alist-local
  15256. org-link-abbrev-alist)))
  15257. ;; Check absolute, relative file names and explicit
  15258. ;; "file:" links. Also check link abbreviations since
  15259. ;; some might expand to "file" links.
  15260. (file-types-re
  15261. (format "\\[\\[\\(?:file%s:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  15262. (if (not link-abbrevs) ""
  15263. (concat "\\|" (regexp-opt link-abbrevs))))))
  15264. (while (re-search-forward file-types-re end t)
  15265. (let* ((link (org-element-lineage
  15266. (save-match-data (org-element-context))
  15267. '(link) t))
  15268. (inner-start (match-beginning 1))
  15269. (path
  15270. (cond
  15271. ;; No link at point; no inline image.
  15272. ((not link) nil)
  15273. ;; File link without a description. Also handle
  15274. ;; INCLUDE-LINKED here since it should have
  15275. ;; precedence over the next case. I.e., if link
  15276. ;; contains filenames in both the path and the
  15277. ;; description, prioritize the path only when
  15278. ;; INCLUDE-LINKED is non-nil.
  15279. ((or (not (org-element-property :contents-begin link))
  15280. include-linked)
  15281. (and (equal "file" (org-element-property :type link))
  15282. (org-element-property :path link)))
  15283. ;; Link with a description. Check if description
  15284. ;; is a filename. Even if Org doesn't have syntax
  15285. ;; for those -- clickable image -- constructs, fake
  15286. ;; them, as in `org-export-insert-image-links'.
  15287. ((not inner-start) nil)
  15288. (t
  15289. (org-with-point-at inner-start
  15290. (and (looking-at
  15291. (if (char-equal ?< (char-after inner-start))
  15292. org-link-angle-re
  15293. org-link-plain-re))
  15294. ;; File name must fill the whole
  15295. ;; description.
  15296. (= (org-element-property :contents-end link)
  15297. (match-end 0))
  15298. (match-string 2)))))))
  15299. (when (and path (string-match-p file-extension-re path))
  15300. (let ((file (expand-file-name path)))
  15301. (when (file-exists-p file)
  15302. (let ((width
  15303. ;; Apply `org-image-actual-width' specifications.
  15304. (cond
  15305. ((not (image-type-available-p 'imagemagick)) nil)
  15306. ((eq org-image-actual-width t) nil)
  15307. ((listp org-image-actual-width)
  15308. (or
  15309. ;; First try to find a width among
  15310. ;; attributes associated to the paragraph
  15311. ;; containing link.
  15312. (let ((paragraph
  15313. (let ((e link))
  15314. (while (and (setq e (org-element-property
  15315. :parent e))
  15316. (not (eq (org-element-type e)
  15317. 'paragraph))))
  15318. e)))
  15319. (when paragraph
  15320. (save-excursion
  15321. (goto-char (org-element-property :begin paragraph))
  15322. (when
  15323. (re-search-forward
  15324. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  15325. (org-element-property
  15326. :post-affiliated paragraph)
  15327. t)
  15328. (string-to-number (match-string 1))))))
  15329. ;; Otherwise, fall-back to provided number.
  15330. (car org-image-actual-width)))
  15331. ((numberp org-image-actual-width)
  15332. org-image-actual-width)))
  15333. (old (get-char-property-and-overlay
  15334. (org-element-property :begin link)
  15335. 'org-image-overlay)))
  15336. (if (and (car-safe old) refresh)
  15337. (image-refresh (overlay-get (cdr old) 'display))
  15338. (let ((image (create-image file
  15339. (and width 'imagemagick)
  15340. nil
  15341. :width width)))
  15342. (when image
  15343. (let ((ov (make-overlay
  15344. (org-element-property :begin link)
  15345. (progn
  15346. (goto-char
  15347. (org-element-property :end link))
  15348. (skip-chars-backward " \t")
  15349. (point)))))
  15350. (overlay-put ov 'display image)
  15351. (overlay-put ov 'face 'default)
  15352. (overlay-put ov 'org-image-overlay t)
  15353. (overlay-put
  15354. ov 'modification-hooks
  15355. (list 'org-display-inline-remove-overlay))
  15356. (push ov org-inline-image-overlays)))))))))))))))
  15357. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  15358. "Remove inline-display overlay if a corresponding region is modified."
  15359. (let ((inhibit-modification-hooks t))
  15360. (when (and ov after)
  15361. (delete ov org-inline-image-overlays)
  15362. (delete-overlay ov))))
  15363. (defun org-remove-inline-images ()
  15364. "Remove inline display of images."
  15365. (interactive)
  15366. (mapc #'delete-overlay org-inline-image-overlays)
  15367. (setq org-inline-image-overlays nil))
  15368. (defvar org-self-insert-command-undo-counter 0)
  15369. (defvar org-speed-command nil)
  15370. (defun org-self-insert-command (N)
  15371. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  15372. If the cursor is in a table looking at whitespace, the whitespace is
  15373. overwritten, and the table is not marked as requiring realignment."
  15374. (interactive "p")
  15375. (org-check-before-invisible-edit 'insert)
  15376. (cond
  15377. ((and org-use-speed-commands
  15378. (let ((kv (this-command-keys-vector)))
  15379. (setq org-speed-command
  15380. (run-hook-with-args-until-success
  15381. 'org-speed-command-hook
  15382. (make-string 1 (aref kv (1- (length kv))))))))
  15383. (cond
  15384. ((commandp org-speed-command)
  15385. (setq this-command org-speed-command)
  15386. (call-interactively org-speed-command))
  15387. ((functionp org-speed-command)
  15388. (funcall org-speed-command))
  15389. ((and org-speed-command (listp org-speed-command))
  15390. (eval org-speed-command))
  15391. (t (let (org-use-speed-commands)
  15392. (call-interactively 'org-self-insert-command)))))
  15393. ((and
  15394. (= N 1)
  15395. (not (org-region-active-p))
  15396. (org-at-table-p)
  15397. (progn
  15398. ;; Check if we blank the field, and if that triggers align.
  15399. (and (featurep 'org-table)
  15400. org-table-auto-blank-field
  15401. (memq last-command
  15402. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  15403. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  15404. ;; Got extra space, this field does not determine
  15405. ;; column width.
  15406. (let (org-table-may-need-update) (org-table-blank-field))
  15407. ;; No extra space, this field may determine column
  15408. ;; width.
  15409. (org-table-blank-field)))
  15410. t)
  15411. (looking-at "[^|\n]* |"))
  15412. ;; There is room for insertion without re-aligning the table.
  15413. (self-insert-command N)
  15414. (org-table-with-shrunk-field
  15415. (save-excursion
  15416. (skip-chars-forward "^|")
  15417. ;; Do not delete last space, which is
  15418. ;; `org-table-separator-space', but the regular space before
  15419. ;; it.
  15420. (delete-region (- (point) 2) (1- (point))))))
  15421. (t
  15422. (setq org-table-may-need-update t)
  15423. (self-insert-command N)
  15424. (org-fix-tags-on-the-fly)
  15425. (when org-self-insert-cluster-for-undo
  15426. (if (not (eq last-command 'org-self-insert-command))
  15427. (setq org-self-insert-command-undo-counter 1)
  15428. (if (>= org-self-insert-command-undo-counter 20)
  15429. (setq org-self-insert-command-undo-counter 1)
  15430. (and (> org-self-insert-command-undo-counter 0)
  15431. buffer-undo-list (listp buffer-undo-list)
  15432. (not (cadr buffer-undo-list)) ; remove nil entry
  15433. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  15434. (setq org-self-insert-command-undo-counter
  15435. (1+ org-self-insert-command-undo-counter))))))))
  15436. (defun org-check-before-invisible-edit (kind)
  15437. "Check is editing if kind KIND would be dangerous with invisible text around.
  15438. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  15439. ;; First, try to get out of here as quickly as possible, to reduce overhead
  15440. (when (and org-catch-invisible-edits
  15441. (or (not (boundp 'visible-mode)) (not visible-mode))
  15442. (or (get-char-property (point) 'invisible)
  15443. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  15444. ;; OK, we need to take a closer look. Do not consider
  15445. ;; invisibility obtained through text properties (e.g., link
  15446. ;; fontification), as it cannot be toggled.
  15447. (let* ((invisible-at-point
  15448. (pcase (get-char-property-and-overlay (point) 'invisible)
  15449. (`(,_ . ,(and (pred overlayp) o)) o)))
  15450. ;; Assume that point cannot land in the middle of an
  15451. ;; overlay, or between two overlays.
  15452. (invisible-before-point
  15453. (and (not invisible-at-point)
  15454. (not (bobp))
  15455. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  15456. (`(,_ . ,(and (pred overlayp) o)) o))))
  15457. (border-and-ok-direction
  15458. (or
  15459. ;; Check if we are acting predictably before invisible
  15460. ;; text.
  15461. (and invisible-at-point
  15462. (memq kind '(insert delete-backward)))
  15463. ;; Check if we are acting predictably after invisible text
  15464. ;; This works not well, and I have turned it off. It seems
  15465. ;; better to always show and stop after invisible text.
  15466. ;; (and (not invisible-at-point) invisible-before-point
  15467. ;; (memq kind '(insert delete)))
  15468. )))
  15469. (when (or invisible-at-point invisible-before-point)
  15470. (when (eq org-catch-invisible-edits 'error)
  15471. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  15472. (if (and org-custom-properties-overlays
  15473. (y-or-n-p "Display invisible properties in this buffer? "))
  15474. (org-toggle-custom-properties-visibility)
  15475. ;; Make the area visible
  15476. (save-excursion
  15477. (when invisible-before-point
  15478. (goto-char
  15479. (previous-single-char-property-change (point) 'invisible)))
  15480. ;; Remove whatever overlay is currently making yet-to-be
  15481. ;; edited text invisible. Also remove nested invisibility
  15482. ;; related overlays.
  15483. (delete-overlay (or invisible-at-point invisible-before-point))
  15484. (let ((origin (if invisible-at-point (point) (1- (point)))))
  15485. (while (pcase (get-char-property-and-overlay origin 'invisible)
  15486. (`(,_ . ,(and (pred overlayp) o))
  15487. (delete-overlay o)
  15488. t)))))
  15489. (cond
  15490. ((eq org-catch-invisible-edits 'show)
  15491. ;; That's it, we do the edit after showing
  15492. (message
  15493. "Unfolding invisible region around point before editing")
  15494. (sit-for 1))
  15495. ((and (eq org-catch-invisible-edits 'smart)
  15496. border-and-ok-direction)
  15497. (message "Unfolding invisible region around point before editing"))
  15498. (t
  15499. ;; Don't do the edit, make the user repeat it in full visibility
  15500. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  15501. (defun org-fix-tags-on-the-fly ()
  15502. "Align tags in headline at point.
  15503. Unlike `org-align-tags', this function does nothing if point is
  15504. either not currently on a tagged headline or on a tag."
  15505. (when (and (org-match-line org-tag-line-re)
  15506. (< (point) (match-beginning 1)))
  15507. (org-align-tags)))
  15508. (defun org-delete-backward-char (N)
  15509. "Like `delete-backward-char', insert whitespace at field end in tables.
  15510. When deleting backwards, in tables this function will insert whitespace in
  15511. front of the next \"|\" separator, to keep the table aligned. The table will
  15512. still be marked for re-alignment if the field did fill the entire column,
  15513. because, in this case the deletion might narrow the column."
  15514. (interactive "p")
  15515. (save-match-data
  15516. (org-check-before-invisible-edit 'delete-backward)
  15517. (if (and (= N 1)
  15518. (not overwrite-mode)
  15519. (not (org-region-active-p))
  15520. (not (eq (char-before) ?|))
  15521. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  15522. (looking-at-p ".*?|")
  15523. (org-at-table-p))
  15524. (progn (forward-char -1) (org-delete-char 1))
  15525. (backward-delete-char N)
  15526. (org-fix-tags-on-the-fly))))
  15527. (defun org-delete-char (N)
  15528. "Like `delete-char', but insert whitespace at field end in tables.
  15529. When deleting characters, in tables this function will insert whitespace in
  15530. front of the next \"|\" separator, to keep the table aligned. The table will
  15531. still be marked for re-alignment if the field did fill the entire column,
  15532. because, in this case the deletion might narrow the column."
  15533. (interactive "p")
  15534. (save-match-data
  15535. (org-check-before-invisible-edit 'delete)
  15536. (cond
  15537. ((or (/= N 1)
  15538. (eq (char-after) ?|)
  15539. (save-excursion (skip-chars-backward " \t") (bolp))
  15540. (not (org-at-table-p)))
  15541. (delete-char N)
  15542. (org-fix-tags-on-the-fly))
  15543. ((looking-at ".\\(.*?\\)|")
  15544. (let* ((update? org-table-may-need-update)
  15545. (noalign (looking-at-p ".*? |")))
  15546. (delete-char 1)
  15547. (org-table-with-shrunk-field
  15548. (save-excursion
  15549. ;; Last space is `org-table-separator-space', so insert
  15550. ;; a regular one before it instead.
  15551. (goto-char (- (match-end 0) 2))
  15552. (insert " ")))
  15553. ;; If there were two spaces at the end, this field does not
  15554. ;; determine the width of the column.
  15555. (when noalign (setq org-table-may-need-update update?))))
  15556. (t
  15557. (delete-char N)))))
  15558. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  15559. (put 'org-self-insert-command 'delete-selection
  15560. (lambda ()
  15561. (not (run-hook-with-args-until-success
  15562. 'self-insert-uses-region-functions))))
  15563. (put 'orgtbl-self-insert-command 'delete-selection
  15564. (lambda ()
  15565. (not (run-hook-with-args-until-success
  15566. 'self-insert-uses-region-functions))))
  15567. (put 'org-delete-char 'delete-selection 'supersede)
  15568. (put 'org-delete-backward-char 'delete-selection 'supersede)
  15569. (put 'org-yank 'delete-selection 'yank)
  15570. ;; Make `flyspell-mode' delay after some commands
  15571. (put 'org-self-insert-command 'flyspell-delayed t)
  15572. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  15573. (put 'org-delete-char 'flyspell-delayed t)
  15574. (put 'org-delete-backward-char 'flyspell-delayed t)
  15575. ;; Make pabbrev-mode expand after Org mode commands
  15576. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  15577. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  15578. (defun org-transpose-words ()
  15579. "Transpose words for Org.
  15580. This uses the `org-mode-transpose-word-syntax-table' syntax
  15581. table, which interprets characters in `org-emphasis-alist' as
  15582. word constituents."
  15583. (interactive)
  15584. (with-syntax-table org-mode-transpose-word-syntax-table
  15585. (call-interactively 'transpose-words)))
  15586. (defvar org-ctrl-c-ctrl-c-hook nil
  15587. "Hook for functions attaching themselves to `C-c C-c'.
  15588. This can be used to add additional functionality to the C-c C-c
  15589. key which executes context-dependent commands. This hook is run
  15590. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  15591. run after the last test.
  15592. Each function will be called with no arguments. The function
  15593. must check if the context is appropriate for it to act. If yes,
  15594. it should do its thing and then return a non-nil value. If the
  15595. context is wrong, just do nothing and return nil.")
  15596. (defvar org-ctrl-c-ctrl-c-final-hook nil
  15597. "Hook for functions attaching themselves to `C-c C-c'.
  15598. This can be used to add additional functionality to the C-c C-c
  15599. key which executes context-dependent commands. This hook is run
  15600. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  15601. before the first test.
  15602. Each function will be called with no arguments. The function
  15603. must check if the context is appropriate for it to act. If yes,
  15604. it should do its thing and then return a non-nil value. If the
  15605. context is wrong, just do nothing and return nil.")
  15606. (defvar org-tab-first-hook nil
  15607. "Hook for functions to attach themselves to TAB.
  15608. See `org-ctrl-c-ctrl-c-hook' for more information.
  15609. This hook runs as the first action when TAB is pressed, even before
  15610. `org-cycle' messes around with the `outline-regexp' to cater for
  15611. inline tasks and plain list item folding.
  15612. If any function in this hook returns t, any other actions that
  15613. would have been caused by TAB (such as table field motion or visibility
  15614. cycling) will not occur.")
  15615. (defvar org-tab-after-check-for-table-hook nil
  15616. "Hook for functions to attach themselves to TAB.
  15617. See `org-ctrl-c-ctrl-c-hook' for more information.
  15618. This hook runs after it has been established that the cursor is not in a
  15619. table, but before checking if the cursor is in a headline or if global cycling
  15620. should be done.
  15621. If any function in this hook returns t, not other actions like visibility
  15622. cycling will be done.")
  15623. (defvar org-tab-after-check-for-cycling-hook nil
  15624. "Hook for functions to attach themselves to TAB.
  15625. See `org-ctrl-c-ctrl-c-hook' for more information.
  15626. This hook runs after it has been established that not table field motion and
  15627. not visibility should be done because of current context. This is probably
  15628. the place where a package like yasnippets can hook in.")
  15629. (defvar org-tab-before-tab-emulation-hook nil
  15630. "Hook for functions to attach themselves to TAB.
  15631. See `org-ctrl-c-ctrl-c-hook' for more information.
  15632. This hook runs after every other options for TAB have been exhausted, but
  15633. before indentation and \t insertion takes place.")
  15634. (defvar org-metaleft-hook nil
  15635. "Hook for functions attaching themselves to `M-left'.
  15636. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15637. (defvar org-metaright-hook nil
  15638. "Hook for functions attaching themselves to `M-right'.
  15639. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15640. (defvar org-metaup-hook nil
  15641. "Hook for functions attaching themselves to `M-up'.
  15642. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15643. (defvar org-metadown-hook nil
  15644. "Hook for functions attaching themselves to `M-down'.
  15645. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15646. (defvar org-shiftmetaleft-hook nil
  15647. "Hook for functions attaching themselves to `M-S-left'.
  15648. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15649. (defvar org-shiftmetaright-hook nil
  15650. "Hook for functions attaching themselves to `M-S-right'.
  15651. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15652. (defvar org-shiftmetaup-hook nil
  15653. "Hook for functions attaching themselves to `M-S-up'.
  15654. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15655. (defvar org-shiftmetadown-hook nil
  15656. "Hook for functions attaching themselves to `M-S-down'.
  15657. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15658. (defvar org-metareturn-hook nil
  15659. "Hook for functions attaching themselves to `M-RET'.
  15660. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15661. (defvar org-shiftup-hook nil
  15662. "Hook for functions attaching themselves to `S-up'.
  15663. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15664. (defvar org-shiftup-final-hook nil
  15665. "Hook for functions attaching themselves to `S-up'.
  15666. This one runs after all other options except shift-select have been excluded.
  15667. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15668. (defvar org-shiftdown-hook nil
  15669. "Hook for functions attaching themselves to `S-down'.
  15670. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15671. (defvar org-shiftdown-final-hook nil
  15672. "Hook for functions attaching themselves to `S-down'.
  15673. This one runs after all other options except shift-select have been excluded.
  15674. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15675. (defvar org-shiftleft-hook nil
  15676. "Hook for functions attaching themselves to `S-left'.
  15677. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15678. (defvar org-shiftleft-final-hook nil
  15679. "Hook for functions attaching themselves to `S-left'.
  15680. This one runs after all other options except shift-select have been excluded.
  15681. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15682. (defvar org-shiftright-hook nil
  15683. "Hook for functions attaching themselves to `S-right'.
  15684. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15685. (defvar org-shiftright-final-hook nil
  15686. "Hook for functions attaching themselves to `S-right'.
  15687. This one runs after all other options except shift-select have been excluded.
  15688. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15689. (defun org-modifier-cursor-error ()
  15690. "Throw an error, a modified cursor command was applied in wrong context."
  15691. (user-error "This command is active in special context like tables, headlines or items"))
  15692. (defun org-shiftselect-error ()
  15693. "Throw an error because Shift-Cursor command was applied in wrong context."
  15694. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15695. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15696. (user-error "This command works only in special context like headlines or timestamps")))
  15697. (defun org-call-for-shift-select (cmd)
  15698. (let ((this-command-keys-shift-translated t))
  15699. (call-interactively cmd)))
  15700. (defun org-shifttab (&optional arg)
  15701. "Global visibility cycling or move to previous table field.
  15702. Call `org-table-previous-field' within a table.
  15703. When ARG is nil, cycle globally through visibility states.
  15704. When ARG is a numeric prefix, show contents of this level."
  15705. (interactive "P")
  15706. (cond
  15707. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15708. ((integerp arg)
  15709. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15710. (message "Content view to level: %d" arg)
  15711. (org-content (prefix-numeric-value arg2))
  15712. (org-cycle-show-empty-lines t)
  15713. (setq org-cycle-global-status 'overview)))
  15714. (t (call-interactively 'org-global-cycle))))
  15715. (defun org-shiftmetaleft ()
  15716. "Promote subtree or delete table column.
  15717. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15718. `org-table-delete-column', depending on context. See the
  15719. individual commands for more information."
  15720. (interactive)
  15721. (cond
  15722. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15723. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15724. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15725. ((if (not (org-region-active-p)) (org-at-item-p)
  15726. (save-excursion (goto-char (region-beginning))
  15727. (org-at-item-p)))
  15728. (call-interactively 'org-outdent-item-tree))
  15729. (t (org-modifier-cursor-error))))
  15730. (defun org-shiftmetaright ()
  15731. "Demote subtree or insert table column.
  15732. Calls `org-demote-subtree', `org-indent-item-tree', or
  15733. `org-table-insert-column', depending on context. See the
  15734. individual commands for more information."
  15735. (interactive)
  15736. (cond
  15737. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15738. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15739. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15740. ((if (not (org-region-active-p)) (org-at-item-p)
  15741. (save-excursion (goto-char (region-beginning))
  15742. (org-at-item-p)))
  15743. (call-interactively 'org-indent-item-tree))
  15744. (t (org-modifier-cursor-error))))
  15745. (defun org-shiftmetaup (&optional _arg)
  15746. "Drag the line at point up.
  15747. In a table, kill the current row.
  15748. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15749. but also adjust the previous clocked item in the clock history.
  15750. Everywhere else, drag the line at point up."
  15751. (interactive "P")
  15752. (cond
  15753. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15754. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15755. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15756. (call-interactively 'org-timestamp-up)))
  15757. (t (call-interactively 'org-drag-line-backward))))
  15758. (defun org-shiftmetadown (&optional _arg)
  15759. "Drag the line at point down.
  15760. In a table, insert an empty row at the current line.
  15761. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15762. but also adjust the previous clocked item in the clock history.
  15763. Everywhere else, drag the line at point down."
  15764. (interactive "P")
  15765. (cond
  15766. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15767. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15768. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15769. (call-interactively 'org-timestamp-down)))
  15770. (t (call-interactively 'org-drag-line-forward))))
  15771. (defsubst org-hidden-tree-error ()
  15772. (user-error
  15773. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15774. (defun org-metaleft (&optional _arg)
  15775. "Promote heading, list item at point or move table column left.
  15776. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15777. depending on context. With no specific context, calls the Emacs
  15778. default `backward-word'. See the individual commands for more
  15779. information.
  15780. This function runs the hook `org-metaleft-hook' as a first step,
  15781. and returns at first non-nil value."
  15782. (interactive "P")
  15783. (cond
  15784. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15785. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15786. ((org-with-limited-levels
  15787. (or (org-at-heading-p)
  15788. (and (org-region-active-p)
  15789. (save-excursion
  15790. (goto-char (region-beginning))
  15791. (org-at-heading-p)))))
  15792. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15793. (call-interactively 'org-do-promote))
  15794. ;; At an inline task.
  15795. ((org-at-heading-p)
  15796. (call-interactively 'org-inlinetask-promote))
  15797. ((or (org-at-item-p)
  15798. (and (org-region-active-p)
  15799. (save-excursion
  15800. (goto-char (region-beginning))
  15801. (org-at-item-p))))
  15802. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15803. (call-interactively 'org-outdent-item))
  15804. (t (call-interactively 'backward-word))))
  15805. (defun org-metaright (&optional _arg)
  15806. "Demote heading, list item at point or move table column right.
  15807. In front of a drawer or a block keyword, indent it correctly.
  15808. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15809. `org-indent-drawer' or `org-indent-block' depending on context.
  15810. With no specific context, calls the Emacs default `forward-word'.
  15811. See the individual commands for more information.
  15812. This function runs the hook `org-metaright-hook' as a first step,
  15813. and returns at first non-nil value."
  15814. (interactive "P")
  15815. (cond
  15816. ((run-hook-with-args-until-success 'org-metaright-hook))
  15817. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15818. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15819. ((org-at-block-p) (call-interactively 'org-indent-block))
  15820. ((org-with-limited-levels
  15821. (or (org-at-heading-p)
  15822. (and (org-region-active-p)
  15823. (save-excursion
  15824. (goto-char (region-beginning))
  15825. (org-at-heading-p)))))
  15826. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15827. (call-interactively 'org-do-demote))
  15828. ;; At an inline task.
  15829. ((org-at-heading-p)
  15830. (call-interactively 'org-inlinetask-demote))
  15831. ((or (org-at-item-p)
  15832. (and (org-region-active-p)
  15833. (save-excursion
  15834. (goto-char (region-beginning))
  15835. (org-at-item-p))))
  15836. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15837. (call-interactively 'org-indent-item))
  15838. (t (call-interactively 'forward-word))))
  15839. (defun org-check-for-hidden (what)
  15840. "Check if there are hidden headlines/items in the current visual line.
  15841. WHAT can be either `headlines' or `items'. If the current line is
  15842. an outline or item heading and it has a folded subtree below it,
  15843. this function returns t, nil otherwise."
  15844. (let ((re (cond
  15845. ((eq what 'headlines) org-outline-regexp-bol)
  15846. ((eq what 'items) (org-item-beginning-re))
  15847. (t (error "This should not happen"))))
  15848. beg end)
  15849. (save-excursion
  15850. (catch 'exit
  15851. (unless (org-region-active-p)
  15852. (setq beg (point-at-bol))
  15853. (beginning-of-line 2)
  15854. (while (and (not (eobp)) ;; this is like `next-line'
  15855. (get-char-property (1- (point)) 'invisible))
  15856. (beginning-of-line 2))
  15857. (setq end (point))
  15858. (goto-char beg)
  15859. (goto-char (point-at-eol))
  15860. (setq end (max end (point)))
  15861. (while (re-search-forward re end t)
  15862. (when (get-char-property (match-beginning 0) 'invisible)
  15863. (throw 'exit t))))
  15864. nil))))
  15865. (defun org-metaup (&optional _arg)
  15866. "Move subtree up or move table row up.
  15867. Calls `org-move-subtree-up' or `org-table-move-row' or
  15868. `org-move-item-up', depending on context. See the individual commands
  15869. for more information."
  15870. (interactive "P")
  15871. (cond
  15872. ((run-hook-with-args-until-success 'org-metaup-hook))
  15873. ((org-region-active-p)
  15874. (let* ((a (save-excursion
  15875. (goto-char (min (region-beginning) (region-end)))
  15876. (line-beginning-position)))
  15877. (b (save-excursion
  15878. (goto-char (max (region-beginning) (region-end)))
  15879. (if (bolp) (1- (point)) (line-end-position))))
  15880. (c (save-excursion
  15881. (goto-char a)
  15882. (move-beginning-of-line 0)
  15883. (point)))
  15884. (d (save-excursion
  15885. (goto-char a)
  15886. (move-end-of-line 0)
  15887. (point))))
  15888. (transpose-regions a b c d)
  15889. (goto-char c)))
  15890. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15891. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15892. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15893. (t (org-drag-element-backward))))
  15894. (defun org-metadown (&optional _arg)
  15895. "Move subtree down or move table row down.
  15896. Calls `org-move-subtree-down' or `org-table-move-row' or
  15897. `org-move-item-down', depending on context. See the individual
  15898. commands for more information."
  15899. (interactive "P")
  15900. (cond
  15901. ((run-hook-with-args-until-success 'org-metadown-hook))
  15902. ((org-region-active-p)
  15903. (let* ((a (save-excursion
  15904. (goto-char (min (region-beginning) (region-end)))
  15905. (line-beginning-position)))
  15906. (b (save-excursion
  15907. (goto-char (max (region-beginning) (region-end)))
  15908. (if (bolp) (1- (point)) (line-end-position))))
  15909. (c (save-excursion
  15910. (goto-char b)
  15911. (move-beginning-of-line (if (bolp) 1 2))
  15912. (point)))
  15913. (d (save-excursion
  15914. (goto-char b)
  15915. (move-end-of-line (if (bolp) 1 2))
  15916. (point))))
  15917. (transpose-regions a b c d)
  15918. (goto-char d)))
  15919. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15920. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15921. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15922. (t (org-drag-element-forward))))
  15923. (defun org-shiftup (&optional arg)
  15924. "Act on current element according to context.
  15925. Call `org-timestamp-up' or `org-priority-up', or
  15926. `org-previous-item', or `org-table-move-cell-up'. See the
  15927. individual commands for more information."
  15928. (interactive "P")
  15929. (cond
  15930. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15931. ((and org-support-shift-select (org-region-active-p))
  15932. (org-call-for-shift-select 'previous-line))
  15933. ((org-at-timestamp-p 'lax)
  15934. (call-interactively (if org-edit-timestamp-down-means-later
  15935. 'org-timestamp-down 'org-timestamp-up)))
  15936. ((and (not (eq org-support-shift-select 'always))
  15937. org-enable-priority-commands
  15938. (org-at-heading-p))
  15939. (call-interactively 'org-priority-up))
  15940. ((and (not org-support-shift-select) (org-at-item-p))
  15941. (call-interactively 'org-previous-item))
  15942. ((org-clocktable-try-shift 'up arg))
  15943. ((org-at-table-p) (org-table-move-cell-up))
  15944. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15945. (org-support-shift-select
  15946. (org-call-for-shift-select 'previous-line))
  15947. (t (org-shiftselect-error))))
  15948. (defun org-shiftdown (&optional arg)
  15949. "Act on current element according to context.
  15950. Call `org-timestamp-down' or `org-priority-down', or
  15951. `org-next-item', or `org-table-move-cell-down'. See the
  15952. individual commands for more information."
  15953. (interactive "P")
  15954. (cond
  15955. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15956. ((and org-support-shift-select (org-region-active-p))
  15957. (org-call-for-shift-select 'next-line))
  15958. ((org-at-timestamp-p 'lax)
  15959. (call-interactively (if org-edit-timestamp-down-means-later
  15960. 'org-timestamp-up 'org-timestamp-down)))
  15961. ((and (not (eq org-support-shift-select 'always))
  15962. org-enable-priority-commands
  15963. (org-at-heading-p))
  15964. (call-interactively 'org-priority-down))
  15965. ((and (not org-support-shift-select) (org-at-item-p))
  15966. (call-interactively 'org-next-item))
  15967. ((org-clocktable-try-shift 'down arg))
  15968. ((org-at-table-p) (org-table-move-cell-down))
  15969. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15970. (org-support-shift-select
  15971. (org-call-for-shift-select 'next-line))
  15972. (t (org-shiftselect-error))))
  15973. (defun org-shiftright (&optional arg)
  15974. "Act on the current element according to context.
  15975. This does one of the following:
  15976. - switch a timestamp at point one day into the future
  15977. - on a headline, switch to the next TODO keyword.
  15978. - on an item, switch entire list to the next bullet type
  15979. - on a property line, switch to the next allowed value
  15980. - on a clocktable definition line, move time block into the future
  15981. - in a table, move a single cell right"
  15982. (interactive "P")
  15983. (cond
  15984. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15985. ((and org-support-shift-select (org-region-active-p))
  15986. (org-call-for-shift-select 'forward-char))
  15987. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15988. ((and (not (eq org-support-shift-select 'always))
  15989. (org-at-heading-p))
  15990. (let ((org-inhibit-logging
  15991. (not org-treat-S-cursor-todo-selection-as-state-change))
  15992. (org-inhibit-blocking
  15993. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15994. (org-call-with-arg 'org-todo 'right)))
  15995. ((or (and org-support-shift-select
  15996. (not (eq org-support-shift-select 'always))
  15997. (org-at-item-bullet-p))
  15998. (and (not org-support-shift-select) (org-at-item-p)))
  15999. (org-call-with-arg 'org-cycle-list-bullet nil))
  16000. ((and (not (eq org-support-shift-select 'always))
  16001. (org-at-property-p))
  16002. (call-interactively 'org-property-next-allowed-value))
  16003. ((org-clocktable-try-shift 'right arg))
  16004. ((org-at-table-p) (org-table-move-cell-right))
  16005. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  16006. (org-support-shift-select
  16007. (org-call-for-shift-select 'forward-char))
  16008. (t (org-shiftselect-error))))
  16009. (defun org-shiftleft (&optional arg)
  16010. "Act on current element according to context.
  16011. This does one of the following:
  16012. - switch a timestamp at point one day into the past
  16013. - on a headline, switch to the previous TODO keyword.
  16014. - on an item, switch entire list to the previous bullet type
  16015. - on a property line, switch to the previous allowed value
  16016. - on a clocktable definition line, move time block into the past
  16017. - in a table, move a single cell left"
  16018. (interactive "P")
  16019. (cond
  16020. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  16021. ((and org-support-shift-select (org-region-active-p))
  16022. (org-call-for-shift-select 'backward-char))
  16023. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  16024. ((and (not (eq org-support-shift-select 'always))
  16025. (org-at-heading-p))
  16026. (let ((org-inhibit-logging
  16027. (not org-treat-S-cursor-todo-selection-as-state-change))
  16028. (org-inhibit-blocking
  16029. (not org-treat-S-cursor-todo-selection-as-state-change)))
  16030. (org-call-with-arg 'org-todo 'left)))
  16031. ((or (and org-support-shift-select
  16032. (not (eq org-support-shift-select 'always))
  16033. (org-at-item-bullet-p))
  16034. (and (not org-support-shift-select) (org-at-item-p)))
  16035. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  16036. ((and (not (eq org-support-shift-select 'always))
  16037. (org-at-property-p))
  16038. (call-interactively 'org-property-previous-allowed-value))
  16039. ((org-clocktable-try-shift 'left arg))
  16040. ((org-at-table-p) (org-table-move-cell-left))
  16041. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  16042. (org-support-shift-select
  16043. (org-call-for-shift-select 'backward-char))
  16044. (t (org-shiftselect-error))))
  16045. (defun org-shiftcontrolright ()
  16046. "Switch to next TODO set."
  16047. (interactive)
  16048. (cond
  16049. ((and org-support-shift-select (org-region-active-p))
  16050. (org-call-for-shift-select 'forward-word))
  16051. ((and (not (eq org-support-shift-select 'always))
  16052. (org-at-heading-p))
  16053. (org-call-with-arg 'org-todo 'nextset))
  16054. (org-support-shift-select
  16055. (org-call-for-shift-select 'forward-word))
  16056. (t (org-shiftselect-error))))
  16057. (defun org-shiftcontrolleft ()
  16058. "Switch to previous TODO set."
  16059. (interactive)
  16060. (cond
  16061. ((and org-support-shift-select (org-region-active-p))
  16062. (org-call-for-shift-select 'backward-word))
  16063. ((and (not (eq org-support-shift-select 'always))
  16064. (org-at-heading-p))
  16065. (org-call-with-arg 'org-todo 'previousset))
  16066. (org-support-shift-select
  16067. (org-call-for-shift-select 'backward-word))
  16068. (t (org-shiftselect-error))))
  16069. (defun org-shiftcontrolup (&optional n)
  16070. "Change timestamps synchronously up in CLOCK log lines.
  16071. Optional argument N tells to change by that many units."
  16072. (interactive "P")
  16073. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  16074. (let (org-support-shift-select)
  16075. (org-clock-timestamps-up n))
  16076. (user-error "Not at a clock log")))
  16077. (defun org-shiftcontroldown (&optional n)
  16078. "Change timestamps synchronously down in CLOCK log lines.
  16079. Optional argument N tells to change by that many units."
  16080. (interactive "P")
  16081. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  16082. (let (org-support-shift-select)
  16083. (org-clock-timestamps-down n))
  16084. (user-error "Not at a clock log")))
  16085. (defun org-increase-number-at-point (&optional inc)
  16086. "Increment the number at point.
  16087. With an optional prefix numeric argument INC, increment using
  16088. this numeric value."
  16089. (interactive "p")
  16090. (if (not (number-at-point))
  16091. (user-error "Not on a number")
  16092. (unless inc (setq inc 1))
  16093. (let ((pos (point))
  16094. (beg (skip-chars-backward "-+^/*0-9eE."))
  16095. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  16096. (setq nap (buffer-substring-no-properties
  16097. (+ pos beg) (+ pos beg end)))
  16098. (delete-region (+ pos beg) (+ pos beg end))
  16099. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  16100. (when (org-at-table-p)
  16101. (org-table-align)
  16102. (org-table-end-of-field 1))))
  16103. (defun org-decrease-number-at-point (&optional inc)
  16104. "Decrement the number at point.
  16105. With an optional prefix numeric argument INC, decrement using
  16106. this numeric value."
  16107. (interactive "p")
  16108. (org-increase-number-at-point (- (or inc 1))))
  16109. (defun org-ctrl-c-ret ()
  16110. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  16111. (interactive)
  16112. (cond
  16113. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  16114. (t (call-interactively 'org-insert-heading))))
  16115. (defun org-find-visible ()
  16116. (let ((s (point)))
  16117. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  16118. (get-char-property s 'invisible)))
  16119. s))
  16120. (defun org-find-invisible ()
  16121. (let ((s (point)))
  16122. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  16123. (not (get-char-property s 'invisible))))
  16124. s))
  16125. (defun org-copy-visible (beg end)
  16126. "Copy the visible parts of the region."
  16127. (interactive "r")
  16128. (let ((result ""))
  16129. (while (/= beg end)
  16130. (when (get-char-property beg 'invisible)
  16131. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  16132. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  16133. (setq result (concat result (buffer-substring beg next)))
  16134. (setq beg next)))
  16135. (setq deactivate-mark t)
  16136. (kill-new result)
  16137. (message "Visible strings have been copied to the kill ring.")))
  16138. (defun org-copy-special ()
  16139. "Copy region in table or copy current subtree.
  16140. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  16141. context. See the individual commands for more information."
  16142. (interactive)
  16143. (call-interactively
  16144. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  16145. (defun org-cut-special ()
  16146. "Cut region in table or cut current subtree.
  16147. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  16148. context. See the individual commands for more information."
  16149. (interactive)
  16150. (call-interactively
  16151. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  16152. (defun org-paste-special (arg)
  16153. "Paste rectangular region into table, or past subtree relative to level.
  16154. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  16155. See the individual commands for more information."
  16156. (interactive "P")
  16157. (if (org-at-table-p)
  16158. (org-table-paste-rectangle)
  16159. (org-paste-subtree arg)))
  16160. (defun org-edit-special (&optional arg)
  16161. "Call a special editor for the element at point.
  16162. When at a table, call the formula editor with `org-table-edit-formulas'.
  16163. When in a source code block, call `org-edit-src-code'.
  16164. When in a fixed-width region, call `org-edit-fixed-width-region'.
  16165. When in an export block, call `org-edit-export-block'.
  16166. When in a LaTeX environment, call `org-edit-latex-environment'.
  16167. When at an #+INCLUDE keyword, visit the included file.
  16168. When at a footnote reference, call `org-edit-footnote-reference'.
  16169. When at a planning line call, `org-deadline' and/or `org-schedule'.
  16170. When at an active timestamp, call `org-time-stamp'.
  16171. When at an inactive timestamp, call `org-time-stamp-inactive'.
  16172. On a link, call `ffap' to visit the link at point.
  16173. Otherwise, return a user error."
  16174. (interactive "P")
  16175. (let ((element (org-element-at-point)))
  16176. (barf-if-buffer-read-only)
  16177. (pcase (org-element-type element)
  16178. (`src-block
  16179. (if (not arg) (org-edit-src-code)
  16180. (let* ((info (org-babel-get-src-block-info))
  16181. (lang (nth 0 info))
  16182. (params (nth 2 info))
  16183. (session (cdr (assq :session params))))
  16184. (if (not session) (org-edit-src-code)
  16185. ;; At a source block with a session and function called
  16186. ;; with an ARG: switch to the buffer related to the
  16187. ;; inferior process.
  16188. (switch-to-buffer
  16189. (funcall (intern (concat "org-babel-prep-session:" lang))
  16190. session params))))))
  16191. (`keyword
  16192. (unless (member (org-element-property :key element)
  16193. '("INCLUDE" "SETUPFILE"))
  16194. (user-error "No special environment to edit here"))
  16195. (let ((value (org-element-property :value element)))
  16196. (unless (org-string-nw-p value) (user-error "No file to edit"))
  16197. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  16198. (or (match-string 1 value)
  16199. (match-string 0 value)))))
  16200. (when (org-file-url-p file)
  16201. (user-error "Files located with a URL cannot be edited"))
  16202. (org-link-open-from-string
  16203. (format "[[%s]]" (expand-file-name file))))))
  16204. (`table
  16205. (if (eq (org-element-property :type element) 'table.el)
  16206. (org-edit-table.el)
  16207. (call-interactively 'org-table-edit-formulas)))
  16208. ;; Only Org tables contain `table-row' type elements.
  16209. (`table-row (call-interactively 'org-table-edit-formulas))
  16210. (`example-block (org-edit-src-code))
  16211. (`export-block (org-edit-export-block))
  16212. (`fixed-width (org-edit-fixed-width-region))
  16213. (`latex-environment (org-edit-latex-environment))
  16214. (`planning
  16215. (let ((proplist (cadr element)))
  16216. (mapc #'call-interactively
  16217. (remq nil
  16218. (list
  16219. (when (plist-get proplist :deadline) #'org-deadline)
  16220. (when (plist-get proplist :scheduled) #'org-schedule))))))
  16221. (_
  16222. ;; No notable element at point. Though, we may be at a link or
  16223. ;; a footnote reference, which are objects. Thus, scan deeper.
  16224. (let ((context (org-element-context element)))
  16225. (pcase (org-element-type context)
  16226. (`footnote-reference (org-edit-footnote-reference))
  16227. (`inline-src-block (org-edit-inline-src-code))
  16228. (`timestamp (if (eq 'inactive (org-element-property :type context))
  16229. (call-interactively #'org-time-stamp-inactive)
  16230. (call-interactively #'org-time-stamp)))
  16231. (`link (call-interactively #'ffap))
  16232. (_ (user-error "No special environment to edit here"))))))))
  16233. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  16234. (defun org-ctrl-c-ctrl-c (&optional arg)
  16235. "Set tags in headline, or update according to changed information at point.
  16236. This command does many different things, depending on context:
  16237. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  16238. this is what we do.
  16239. - If the cursor is on a statistics cookie, update it.
  16240. - If the cursor is in a headline, prompt for tags and insert them
  16241. into the current line, aligned to `org-tags-column'. When called
  16242. with prefix arg, realign all tags in the current buffer.
  16243. - If the cursor is in one of the special #+KEYWORD lines, this
  16244. triggers scanning the buffer for these lines and updating the
  16245. information.
  16246. - If the cursor is inside a table, realign the table. This command
  16247. works even if the automatic table editor has been turned off.
  16248. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  16249. the entire table.
  16250. - If the cursor is at a footnote reference or definition, jump to
  16251. the corresponding definition or references, respectively.
  16252. - If the cursor is a the beginning of a dynamic block, update it.
  16253. - If the current buffer is a capture buffer, close note and file it.
  16254. - If the cursor is on a <<<target>>>, update radio targets and
  16255. corresponding links in this buffer.
  16256. - If the cursor is on a numbered item in a plain list, renumber the
  16257. ordered list.
  16258. - If the cursor is on a checkbox, toggle it.
  16259. - If the cursor is on a code block, evaluate it. The variable
  16260. `org-confirm-babel-evaluate' can be used to control prompting
  16261. before code block evaluation, by default every code block
  16262. evaluation requires confirmation. Code block evaluation can be
  16263. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  16264. (interactive "P")
  16265. (cond
  16266. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  16267. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  16268. (org-remove-occur-highlights)
  16269. (message "Temporary highlights/overlays removed from current buffer"))
  16270. ((and (local-variable-p 'org-finish-function)
  16271. (fboundp org-finish-function))
  16272. (funcall org-finish-function))
  16273. ((org-babel-hash-at-point))
  16274. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  16275. (t
  16276. (let* ((context
  16277. (org-element-lineage
  16278. (org-element-context)
  16279. ;; Limit to supported contexts.
  16280. '(babel-call clock dynamic-block footnote-definition
  16281. footnote-reference inline-babel-call inline-src-block
  16282. inlinetask item keyword node-property paragraph
  16283. plain-list planning property-drawer radio-target
  16284. src-block statistics-cookie table table-cell table-row
  16285. timestamp)
  16286. t))
  16287. (type (org-element-type context)))
  16288. ;; For convenience: at the first line of a paragraph on the same
  16289. ;; line as an item, apply function on that item instead.
  16290. (when (eq type 'paragraph)
  16291. (let ((parent (org-element-property :parent context)))
  16292. (when (and (eq (org-element-type parent) 'item)
  16293. (= (line-beginning-position)
  16294. (org-element-property :begin parent)))
  16295. (setq context parent)
  16296. (setq type 'item))))
  16297. ;; Act according to type of element or object at point.
  16298. ;;
  16299. ;; Do nothing on a blank line, except if it is contained in
  16300. ;; a source block. Hence, we first check if point is in such
  16301. ;; a block and then if it is at a blank line.
  16302. (pcase type
  16303. ((or `inline-src-block `src-block)
  16304. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  16305. (org-babel-eval-wipe-error-buffer)
  16306. (org-babel-execute-src-block
  16307. current-prefix-arg (org-babel-get-src-block-info nil context))))
  16308. ((guard (org-match-line "[ \t]*$"))
  16309. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  16310. (user-error
  16311. (substitute-command-keys
  16312. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  16313. ((or `babel-call `inline-babel-call)
  16314. (let ((info (org-babel-lob-get-info context)))
  16315. (when info (org-babel-execute-src-block nil info))))
  16316. (`clock (org-clock-update-time-maybe))
  16317. (`dynamic-block
  16318. (save-excursion
  16319. (goto-char (org-element-property :post-affiliated context))
  16320. (org-update-dblock)))
  16321. (`footnote-definition
  16322. (goto-char (org-element-property :post-affiliated context))
  16323. (call-interactively 'org-footnote-action))
  16324. (`footnote-reference (call-interactively #'org-footnote-action))
  16325. ((or `headline `inlinetask)
  16326. (save-excursion (goto-char (org-element-property :begin context))
  16327. (call-interactively #'org-set-tags-command)))
  16328. (`item
  16329. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  16330. ;; unconditionally, whereas `C-u' will toggle its presence.
  16331. ;; Without a universal argument, if the item has a checkbox,
  16332. ;; toggle it. Otherwise repair the list.
  16333. (let* ((box (org-element-property :checkbox context))
  16334. (struct (org-element-property :structure context))
  16335. (old-struct (copy-tree struct))
  16336. (parents (org-list-parents-alist struct))
  16337. (prevs (org-list-prevs-alist struct))
  16338. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  16339. (org-list-set-checkbox
  16340. (org-element-property :begin context) struct
  16341. (cond ((equal arg '(16)) "[-]")
  16342. ((and (not box) (equal arg '(4))) "[ ]")
  16343. ((or (not box) (equal arg '(4))) nil)
  16344. ((eq box 'on) "[ ]")
  16345. (t "[X]")))
  16346. ;; Mimic `org-list-write-struct' but with grabbing a return
  16347. ;; value from `org-list-struct-fix-box'.
  16348. (org-list-struct-fix-ind struct parents 2)
  16349. (org-list-struct-fix-item-end struct)
  16350. (org-list-struct-fix-bul struct prevs)
  16351. (org-list-struct-fix-ind struct parents)
  16352. (let ((block-item
  16353. (org-list-struct-fix-box struct parents prevs orderedp)))
  16354. (if (and box (equal struct old-struct))
  16355. (if (equal arg '(16))
  16356. (message "Checkboxes already reset")
  16357. (user-error "Cannot toggle this checkbox: %s"
  16358. (if (eq box 'on)
  16359. "all subitems checked"
  16360. "unchecked subitems")))
  16361. (org-list-struct-apply-struct struct old-struct)
  16362. (org-update-checkbox-count-maybe))
  16363. (when block-item
  16364. (message "Checkboxes were removed due to empty box at line %d"
  16365. (org-current-line block-item))))))
  16366. (`keyword
  16367. (let ((org-inhibit-startup-visibility-stuff t)
  16368. (org-startup-align-all-tables nil))
  16369. (when (boundp 'org-table-coordinate-overlays)
  16370. (mapc #'delete-overlay org-table-coordinate-overlays)
  16371. (setq org-table-coordinate-overlays nil))
  16372. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  16373. (message "Local setup has been refreshed"))
  16374. (`plain-list
  16375. ;; At a plain list, with a double C-u argument, set
  16376. ;; checkboxes of each item to "[-]", whereas a single one
  16377. ;; will toggle their presence according to the state of the
  16378. ;; first item in the list. Without an argument, repair the
  16379. ;; list.
  16380. (let* ((begin (org-element-property :contents-begin context))
  16381. (struct (org-element-property :structure context))
  16382. (old-struct (copy-tree struct))
  16383. (first-box (save-excursion
  16384. (goto-char begin)
  16385. (looking-at org-list-full-item-re)
  16386. (match-string-no-properties 3)))
  16387. (new-box (cond ((equal arg '(16)) "[-]")
  16388. ((equal arg '(4)) (unless first-box "[ ]"))
  16389. ((equal first-box "[X]") "[ ]")
  16390. (t "[X]"))))
  16391. (cond
  16392. (arg
  16393. (dolist (pos
  16394. (org-list-get-all-items
  16395. begin struct (org-list-prevs-alist struct)))
  16396. (org-list-set-checkbox pos struct new-box)))
  16397. ((and first-box (eq (point) begin))
  16398. ;; For convenience, when point is at bol on the first
  16399. ;; item of the list and no argument is provided, simply
  16400. ;; toggle checkbox of that item, if any.
  16401. (org-list-set-checkbox begin struct new-box)))
  16402. (when (equal
  16403. (org-list-write-struct
  16404. struct (org-list-parents-alist struct) old-struct)
  16405. old-struct)
  16406. (message "Cannot update this checkbox"))
  16407. (org-update-checkbox-count-maybe)))
  16408. ((or `property-drawer `node-property)
  16409. (call-interactively #'org-property-action))
  16410. (`radio-target
  16411. (call-interactively #'org-update-radio-target-regexp))
  16412. (`statistics-cookie
  16413. (call-interactively #'org-update-statistics-cookies))
  16414. ((or `table `table-cell `table-row)
  16415. ;; At a table, recalculate every field and align it. Also
  16416. ;; send the table if necessary. If the table has
  16417. ;; a `table.el' type, just give up. At a table row or cell,
  16418. ;; maybe recalculate line but always align table.
  16419. (if (eq (org-element-property :type context) 'table.el)
  16420. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  16421. Use `\\[org-edit-special]' to edit table.el tables"))
  16422. (if (or (eq type 'table)
  16423. ;; Check if point is at a TBLFM line.
  16424. (and (eq type 'table-row)
  16425. (= (point) (org-element-property :end context))))
  16426. (save-excursion
  16427. (if (org-at-TBLFM-p)
  16428. (progn (require 'org-table)
  16429. (org-table-calc-current-TBLFM))
  16430. (goto-char (org-element-property :contents-begin context))
  16431. (org-call-with-arg 'org-table-recalculate (or arg t))
  16432. (orgtbl-send-table 'maybe)))
  16433. (org-table-maybe-eval-formula)
  16434. (cond (arg (call-interactively #'org-table-recalculate))
  16435. ((org-table-maybe-recalculate-line))
  16436. (t (org-table-align))))))
  16437. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  16438. (org-timestamp-change 0 'day))
  16439. ((and `nil (guard (org-at-heading-p)))
  16440. ;; When point is on an unsupported object type, we can miss
  16441. ;; the fact that it also is at a heading. Handle it here.
  16442. (call-interactively #'org-set-tags-command))
  16443. ((guard
  16444. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  16445. (_
  16446. (user-error
  16447. (substitute-command-keys
  16448. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  16449. (defun org-mode-restart ()
  16450. (interactive)
  16451. (let ((indent-status (bound-and-true-p org-indent-mode)))
  16452. (funcall major-mode)
  16453. (hack-local-variables)
  16454. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  16455. (org-indent-mode -1))
  16456. (org-reset-file-cache))
  16457. (message "%s restarted" major-mode))
  16458. (defun org-kill-note-or-show-branches ()
  16459. "Abort storing current note, or call `outline-show-branches'."
  16460. (interactive)
  16461. (if (not org-finish-function)
  16462. (save-excursion
  16463. (save-restriction
  16464. (org-narrow-to-subtree)
  16465. (org-flag-subtree t)
  16466. (call-interactively 'outline-show-branches)
  16467. (org-hide-archived-subtrees (point-min) (point-max))))
  16468. (let ((org-note-abort t))
  16469. (funcall org-finish-function))))
  16470. (defun org-delete-indentation (&optional arg)
  16471. "Join current line to previous and fix whitespace at join.
  16472. If previous line is a headline add to headline title. Otherwise
  16473. the function calls `delete-indentation'.
  16474. With a non-nil optional argument, join it to the following one."
  16475. (interactive "*P")
  16476. (if (save-excursion
  16477. (beginning-of-line (if arg 1 0))
  16478. (let ((case-fold-search nil))
  16479. (looking-at org-complex-heading-regexp)))
  16480. ;; At headline.
  16481. (let ((tags-column (when (match-beginning 5)
  16482. (save-excursion (goto-char (match-beginning 5))
  16483. (current-column))))
  16484. (string (concat " " (progn (when arg (forward-line 1))
  16485. (org-trim (delete-and-extract-region
  16486. (line-beginning-position)
  16487. (line-end-position)))))))
  16488. (unless (bobp) (delete-region (point) (1- (point))))
  16489. (goto-char (or (match-end 4)
  16490. (match-beginning 5)
  16491. (match-end 0)))
  16492. (skip-chars-backward " \t")
  16493. (save-excursion (insert string))
  16494. ;; Adjust alignment of tags.
  16495. (cond
  16496. ((not tags-column)) ;no tags
  16497. (org-auto-align-tags (org-align-tags))
  16498. (t (org--align-tags-here tags-column)))) ;preserve tags column
  16499. (delete-indentation arg)))
  16500. (defun org-open-line (n)
  16501. "Insert a new row in tables, call `open-line' elsewhere.
  16502. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  16503. As a special case, when a document starts with a table, allow to
  16504. call `open-line' on the very first character."
  16505. (interactive "*p")
  16506. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  16507. (org-table-insert-row)
  16508. (open-line n)))
  16509. (defun org-return (&optional indent)
  16510. "Goto next table row or insert a newline.
  16511. Calls `org-table-next-row' or `newline', depending on context.
  16512. When optional INDENT argument is non-nil, call
  16513. `newline-and-indent' instead of `newline'.
  16514. When `org-return-follows-link' is non-nil and point is on
  16515. a timestamp or a link, call `org-open-at-point'. However, it
  16516. will not happen if point is in a table or on a \"dead\"
  16517. object (e.g., within a comment). In these case, you need to use
  16518. `org-open-at-point' directly."
  16519. (interactive)
  16520. (let ((context (if org-return-follows-link (org-element-context)
  16521. (org-element-at-point))))
  16522. (cond
  16523. ;; In a table, call `org-table-next-row'. However, before first
  16524. ;; column or after last one, split the table.
  16525. ((or (and (eq 'table (org-element-type context))
  16526. (not (eq 'table.el (org-element-property :type context)))
  16527. (>= (point) (org-element-property :contents-begin context))
  16528. (< (point) (org-element-property :contents-end context)))
  16529. (org-element-lineage context '(table-row table-cell) t))
  16530. (if (or (looking-at-p "[ \t]*$")
  16531. (save-excursion (skip-chars-backward " \t") (bolp)))
  16532. (insert "\n")
  16533. (org-table-justify-field-maybe)
  16534. (call-interactively #'org-table-next-row)))
  16535. ;; On a link or a timestamp, call `org-open-at-point' if
  16536. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  16537. ;; locations, e.g., in a comment, as `org-open-at-point'.
  16538. ((and org-return-follows-link
  16539. (or (and (eq 'link (org-element-type context))
  16540. ;; Ensure point is not on the white spaces after
  16541. ;; the link.
  16542. (let ((origin (point)))
  16543. (org-with-point-at (org-element-property :end context)
  16544. (skip-chars-backward " \t")
  16545. (> (point) origin))))
  16546. (org-in-regexp org-ts-regexp-both nil t)
  16547. (org-in-regexp org-tsr-regexp-both nil t)
  16548. (org-in-regexp org-link-any-re nil t)))
  16549. (call-interactively #'org-open-at-point))
  16550. ;; Insert newline in heading, but preserve tags.
  16551. ((and (not (bolp))
  16552. (let ((case-fold-search nil))
  16553. (org-match-line org-complex-heading-regexp)))
  16554. ;; At headline. Split line. However, if point is on keyword,
  16555. ;; priority cookie or tags, do not break any of them: add
  16556. ;; a newline after the headline instead.
  16557. (let ((tags-column (and (match-beginning 5)
  16558. (save-excursion (goto-char (match-beginning 5))
  16559. (current-column))))
  16560. (string
  16561. (when (and (match-end 4) (org-point-in-group (point) 4))
  16562. (delete-and-extract-region (point) (match-end 4)))))
  16563. ;; Adjust tag alignment.
  16564. (cond
  16565. ((not (and tags-column string)))
  16566. (org-auto-align-tags (org-align-tags))
  16567. (t (org--align-tags-here tags-column))) ;preserve tags column
  16568. (end-of-line)
  16569. (org-show-entry)
  16570. (if indent (newline-and-indent) (newline))
  16571. (when string (save-excursion (insert (org-trim string))))))
  16572. ;; In a list, make sure indenting keeps trailing text within.
  16573. ((and indent
  16574. (not (eolp))
  16575. (org-element-lineage context '(item)))
  16576. (let ((trailing-data
  16577. (delete-and-extract-region (point) (line-end-position))))
  16578. (newline-and-indent)
  16579. (save-excursion (insert trailing-data))))
  16580. (t
  16581. ;; Do not auto-fill when point is in an Org property drawer.
  16582. (let ((auto-fill-function (and (not (org-at-property-p))
  16583. auto-fill-function)))
  16584. (if indent
  16585. (newline-and-indent)
  16586. (newline)))))))
  16587. (defun org-return-indent ()
  16588. "Goto next table row or insert a newline and indent.
  16589. Calls `org-table-next-row' or `newline-and-indent', depending on
  16590. context. See the individual commands for more information."
  16591. (interactive)
  16592. (org-return t))
  16593. (defun org-ctrl-c-tab (&optional _arg)
  16594. "Toggle columns width in a table, or show children.
  16595. Call `org-table-toggle-column-width' if point is in a table.
  16596. Otherwise, call `org-show-children'."
  16597. (interactive "p")
  16598. (call-interactively
  16599. (if (org-at-table-p) #'org-table-toggle-column-width
  16600. #'org-show-children)))
  16601. (defun org-ctrl-c-star ()
  16602. "Compute table, or change heading status of lines.
  16603. Calls `org-table-recalculate' or `org-toggle-heading',
  16604. depending on context."
  16605. (interactive)
  16606. (cond
  16607. ((org-at-table-p)
  16608. (call-interactively 'org-table-recalculate))
  16609. (t
  16610. ;; Convert all lines in region to list items
  16611. (call-interactively 'org-toggle-heading))))
  16612. (defun org-ctrl-c-minus ()
  16613. "Insert separator line in table or modify bullet status of line.
  16614. Also turns a plain line or a region of lines into list items.
  16615. Calls `org-table-insert-hline', `org-toggle-item', or
  16616. `org-cycle-list-bullet', depending on context."
  16617. (interactive)
  16618. (cond
  16619. ((org-at-table-p)
  16620. (call-interactively 'org-table-insert-hline))
  16621. ((org-region-active-p)
  16622. (call-interactively 'org-toggle-item))
  16623. ((org-in-item-p)
  16624. (call-interactively 'org-cycle-list-bullet))
  16625. (t
  16626. (call-interactively 'org-toggle-item))))
  16627. (defun org-toggle-heading (&optional nstars)
  16628. "Convert headings to normal text, or items or text to headings.
  16629. If there is no active region, only convert the current line.
  16630. With a `\\[universal-argument]' prefix, convert the whole list at
  16631. point into heading.
  16632. In a region:
  16633. - If the first non blank line is a headline, remove the stars
  16634. from all headlines in the region.
  16635. - If it is a normal line, turn each and every normal line (i.e.,
  16636. not an heading or an item) in the region into headings. If you
  16637. want to convert only the first line of this region, use one
  16638. universal prefix argument.
  16639. - If it is a plain list item, turn all plain list items into headings.
  16640. When converting a line into a heading, the number of stars is chosen
  16641. such that the lines become children of the current entry. However,
  16642. when a numeric prefix argument is given, its value determines the
  16643. number of stars to add."
  16644. (interactive "P")
  16645. (let ((skip-blanks
  16646. (function
  16647. ;; Return beginning of first non-blank line, starting from
  16648. ;; line at POS.
  16649. (lambda (pos)
  16650. (save-excursion
  16651. (goto-char pos)
  16652. (while (org-at-comment-p) (forward-line))
  16653. (skip-chars-forward " \r\t\n")
  16654. (point-at-bol)))))
  16655. beg end toggled)
  16656. ;; Determine boundaries of changes. If a universal prefix has
  16657. ;; been given, put the list in a region. If region ends at a bol,
  16658. ;; do not consider the last line to be in the region.
  16659. (when (and current-prefix-arg (org-at-item-p))
  16660. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16661. (org-mark-element))
  16662. (if (org-region-active-p)
  16663. (setq beg (funcall skip-blanks (region-beginning))
  16664. end (copy-marker (save-excursion
  16665. (goto-char (region-end))
  16666. (if (bolp) (point) (point-at-eol)))))
  16667. (setq beg (funcall skip-blanks (point-at-bol))
  16668. end (copy-marker (point-at-eol))))
  16669. ;; Ensure inline tasks don't count as headings.
  16670. (org-with-limited-levels
  16671. (save-excursion
  16672. (goto-char beg)
  16673. (cond
  16674. ;; Case 1. Started at an heading: de-star headings.
  16675. ((org-at-heading-p)
  16676. (while (< (point) end)
  16677. (when (org-at-heading-p t)
  16678. (looking-at org-outline-regexp) (replace-match "")
  16679. (setq toggled t))
  16680. (forward-line)))
  16681. ;; Case 2. Started at an item: change items into headlines.
  16682. ;; One star will be added by `org-list-to-subtree'.
  16683. ((org-at-item-p)
  16684. (while (< (point) end)
  16685. (when (org-at-item-p)
  16686. ;; Pay attention to cases when region ends before list.
  16687. (let* ((struct (org-list-struct))
  16688. (list-end
  16689. (min (org-list-get-bottom-point struct) (1+ end))))
  16690. (save-restriction
  16691. (narrow-to-region (point) list-end)
  16692. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  16693. (setq toggled t))
  16694. (forward-line)))
  16695. ;; Case 3. Started at normal text: make every line an heading,
  16696. ;; skipping headlines and items.
  16697. (t (let* ((stars
  16698. (make-string
  16699. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16700. (add-stars
  16701. (cond (nstars "") ; stars from prefix only
  16702. ((equal stars "") "*") ; before first heading
  16703. (org-odd-levels-only "**") ; inside heading, odd
  16704. (t "*"))) ; inside heading, oddeven
  16705. (rpl (concat stars add-stars " "))
  16706. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16707. (while (< (point) (if (equal nstars '(4)) lend end))
  16708. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16709. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16710. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16711. (forward-line)))))))
  16712. (unless toggled (message "Cannot toggle heading from here"))))
  16713. (defun org-meta-return (&optional arg)
  16714. "Insert a new heading or wrap a region in a table.
  16715. Calls `org-insert-heading', `org-insert-item' or
  16716. `org-table-wrap-region', depending on context. When called with
  16717. an argument, unconditionally call `org-insert-heading'."
  16718. (interactive "P")
  16719. (org-check-before-invisible-edit 'insert)
  16720. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16721. (call-interactively (cond (arg #'org-insert-heading)
  16722. ((org-at-table-p) #'org-table-wrap-region)
  16723. ((org-in-item-p) #'org-insert-item)
  16724. (t #'org-insert-heading)))))
  16725. ;;; Menu entries
  16726. (defsubst org-in-subtree-not-table-p ()
  16727. "Are we in a subtree and not in a table?"
  16728. (and (not (org-before-first-heading-p))
  16729. (not (org-at-table-p))))
  16730. ;; Define the Org mode menus
  16731. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  16732. '("Tbl"
  16733. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16734. ["Next Field" org-cycle (org-at-table-p)]
  16735. ["Previous Field" org-shifttab (org-at-table-p)]
  16736. ["Next Row" org-return (org-at-table-p)]
  16737. "--"
  16738. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16739. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16740. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16741. "--"
  16742. ("Column"
  16743. ["Move Column Left" org-metaleft (org-at-table-p)]
  16744. ["Move Column Right" org-metaright (org-at-table-p)]
  16745. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16746. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16747. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16748. ("Row"
  16749. ["Move Row Up" org-metaup (org-at-table-p)]
  16750. ["Move Row Down" org-metadown (org-at-table-p)]
  16751. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16752. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16753. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16754. "--"
  16755. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16756. ("Rectangle"
  16757. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16758. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16759. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16760. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16761. "--"
  16762. ("Calculate"
  16763. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16764. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16765. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16766. "--"
  16767. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16768. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16769. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16770. "--"
  16771. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16772. "--"
  16773. ["Sum Column/Rectangle" org-table-sum
  16774. (or (org-at-table-p) (org-region-active-p))]
  16775. ["Which Column?" org-table-current-column (org-at-table-p)])
  16776. ["Debug Formulas"
  16777. org-table-toggle-formula-debugger
  16778. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16779. ["Show Col/Row Numbers"
  16780. org-table-toggle-coordinate-overlays
  16781. :style toggle
  16782. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16783. "--"
  16784. ["Create" org-table-create (not (org-at-table-p))]
  16785. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16786. ["Import from File" org-table-import (not (org-at-table-p))]
  16787. ["Export to File" org-table-export (org-at-table-p)]
  16788. "--"
  16789. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16790. "--"
  16791. ("Plot"
  16792. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16793. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16794. (easy-menu-define org-org-menu org-mode-map "Org menu"
  16795. '("Org"
  16796. ("Show/Hide"
  16797. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16798. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16799. ["Sparse Tree..." org-sparse-tree t]
  16800. ["Reveal Context" org-reveal t]
  16801. ["Show All" org-show-all t]
  16802. "--"
  16803. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16804. "--"
  16805. ["New Heading" org-insert-heading t]
  16806. ("Navigate Headings"
  16807. ["Up" outline-up-heading t]
  16808. ["Next" outline-next-visible-heading t]
  16809. ["Previous" outline-previous-visible-heading t]
  16810. ["Next Same Level" outline-forward-same-level t]
  16811. ["Previous Same Level" outline-backward-same-level t]
  16812. "--"
  16813. ["Jump" org-goto t])
  16814. ("Edit Structure"
  16815. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  16816. "--"
  16817. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16818. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16819. "--"
  16820. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16821. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16822. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16823. "--"
  16824. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16825. "--"
  16826. ["Copy visible text" org-copy-visible t]
  16827. "--"
  16828. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16829. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16830. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16831. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16832. "--"
  16833. ["Sort Region/Children" org-sort t]
  16834. "--"
  16835. ["Convert to odd levels" org-convert-to-odd-levels t]
  16836. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16837. ("Editing"
  16838. ["Emphasis..." org-emphasize t]
  16839. ["Edit Source Example" org-edit-special t]
  16840. "--"
  16841. ["Footnote new/jump" org-footnote-action t]
  16842. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16843. ("Archive"
  16844. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16845. "--"
  16846. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16847. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16848. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  16849. )
  16850. "--"
  16851. ("Hyperlinks"
  16852. ["Store Link (Global)" org-store-link t]
  16853. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16854. ["Insert Link" org-insert-link t]
  16855. ["Follow Link" org-open-at-point t]
  16856. "--"
  16857. ["Next link" org-next-link t]
  16858. ["Previous link" org-previous-link t]
  16859. "--"
  16860. ["Descriptive Links"
  16861. org-toggle-link-display
  16862. :style radio
  16863. :selected org-descriptive-links
  16864. ]
  16865. ["Literal Links"
  16866. org-toggle-link-display
  16867. :style radio
  16868. :selected (not org-descriptive-links)])
  16869. "--"
  16870. ("TODO Lists"
  16871. ["TODO/DONE/-" org-todo t]
  16872. ("Select keyword"
  16873. ["Next keyword" org-shiftright (org-at-heading-p)]
  16874. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16875. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16876. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16877. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16878. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16879. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16880. "--"
  16881. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16882. :selected org-enforce-todo-dependencies :style toggle :active t]
  16883. "Settings for tree at point"
  16884. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16885. :selected (org-entry-get nil "ORDERED")
  16886. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16887. ["Do Children parallel" org-toggle-ordered-property :style radio
  16888. :selected (not (org-entry-get nil "ORDERED"))
  16889. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16890. "--"
  16891. ["Set Priority" org-priority t]
  16892. ["Priority Up" org-shiftup t]
  16893. ["Priority Down" org-shiftdown t]
  16894. "--"
  16895. ["Get news from all feeds" org-feed-update-all t]
  16896. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16897. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16898. ("TAGS and Properties"
  16899. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16900. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16901. "--"
  16902. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16903. ["Column view of properties" org-columns t]
  16904. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16905. ("Dates and Scheduling"
  16906. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16907. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16908. ("Change Date"
  16909. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16910. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16911. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16912. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16913. ["Compute Time Range" org-evaluate-time-range t]
  16914. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16915. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16916. "--"
  16917. ["Custom time format" org-toggle-time-stamp-overlays
  16918. :style radio :selected org-display-custom-times]
  16919. "--"
  16920. ["Goto Calendar" org-goto-calendar t]
  16921. ["Date from Calendar" org-date-from-calendar t]
  16922. "--"
  16923. ["Start/Restart Timer" org-timer-start t]
  16924. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16925. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16926. ["Insert Timer String" org-timer t]
  16927. ["Insert Timer Item" org-timer-item t])
  16928. ("Logging work"
  16929. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16930. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16931. ["Clock out" org-clock-out t]
  16932. ["Clock cancel" org-clock-cancel t]
  16933. "--"
  16934. ["Mark as default task" org-clock-mark-default-task t]
  16935. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16936. ["Goto running clock" org-clock-goto t]
  16937. "--"
  16938. ["Display times" org-clock-display t]
  16939. ["Create clock table" org-clock-report t]
  16940. "--"
  16941. ["Record DONE time"
  16942. (progn (setq org-log-done (not org-log-done))
  16943. (message "Switching to %s will %s record a timestamp"
  16944. (car org-done-keywords)
  16945. (if org-log-done "automatically" "not")))
  16946. :style toggle :selected org-log-done])
  16947. "--"
  16948. ["Agenda Command..." org-agenda t]
  16949. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16950. ("File List for Agenda")
  16951. ("Special views current file"
  16952. ["TODO Tree" org-show-todo-tree t]
  16953. ["Check Deadlines" org-check-deadlines t]
  16954. ["Tags/Property tree" org-match-sparse-tree t])
  16955. "--"
  16956. ["Export/Publish..." org-export-dispatch t]
  16957. ("LaTeX"
  16958. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16959. :style toggle :selected org-cdlatex-mode]
  16960. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16961. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16962. ["Modify math symbol" org-cdlatex-math-modify
  16963. (org-inside-LaTeX-fragment-p)]
  16964. ["Insert citation" org-reftex-citation t])
  16965. "--"
  16966. ("MobileOrg"
  16967. ["Push Files and Views" org-mobile-push t]
  16968. ["Get Captured and Flagged" org-mobile-pull t]
  16969. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
  16970. "--"
  16971. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  16972. "--"
  16973. ("Documentation"
  16974. ["Show Version" org-version t]
  16975. ["Info Documentation" org-info t]
  16976. ["Browse Org News" org-browse-news t])
  16977. ("Customize"
  16978. ["Browse Org Group" org-customize t]
  16979. "--"
  16980. ["Expand This Menu" org-create-customize-menu
  16981. (fboundp 'customize-menu-create)])
  16982. ["Send bug report" org-submit-bug-report t]
  16983. "--"
  16984. ("Refresh/Reload"
  16985. ["Refresh setup current buffer" org-mode-restart t]
  16986. ["Reload Org (after update)" org-reload t]
  16987. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16988. (defun org-info (&optional node)
  16989. "Read documentation for Org in the info system.
  16990. With optional NODE, go directly to that node."
  16991. (interactive)
  16992. (info (format "(org)%s" (or node ""))))
  16993. (defun org-browse-news ()
  16994. "Browse the news for the latest major release."
  16995. (interactive)
  16996. (browse-url "https://orgmode.org/Changes.html"))
  16997. ;;;###autoload
  16998. (defun org-submit-bug-report ()
  16999. "Submit a bug report on Org via mail.
  17000. Don't hesitate to report any problems or inaccurate documentation.
  17001. If you don't have setup sending mail from (X)Emacs, please copy the
  17002. output buffer into your mail program, as it gives us important
  17003. information about your Org version and configuration."
  17004. (interactive)
  17005. (require 'reporter)
  17006. (defvar reporter-prompt-for-summary-p)
  17007. (org-load-modules-maybe)
  17008. (org-require-autoloaded-modules)
  17009. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  17010. (reporter-submit-bug-report
  17011. "emacs-orgmode@gnu.org"
  17012. (org-version nil 'full)
  17013. (let (list)
  17014. (save-window-excursion
  17015. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  17016. (delete-other-windows)
  17017. (erase-buffer)
  17018. (insert "You are about to submit a bug report to the Org mailing list.
  17019. We would like to add your full Org and Outline configuration to the
  17020. bug report. This greatly simplifies the work of the maintainer and
  17021. other experts on the mailing list.
  17022. HOWEVER, some variables you have customized may contain private
  17023. information. The names of customers, colleagues, or friends, might
  17024. appear in the form of file names, tags, todo states, or search strings.
  17025. If you answer yes to the prompt, you might want to check and remove
  17026. such private information before sending the email.")
  17027. (add-text-properties (point-min) (point-max) '(face org-warning))
  17028. (when (yes-or-no-p "Include your Org configuration ")
  17029. (mapatoms
  17030. (lambda (v)
  17031. (and (boundp v)
  17032. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  17033. (or (and (symbol-value v)
  17034. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  17035. (and
  17036. (get v 'custom-type) (get v 'standard-value)
  17037. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  17038. (push v list)))))
  17039. (kill-buffer (get-buffer "*Warn about privacy*"))
  17040. list))
  17041. nil nil
  17042. "Remember to cover the basics, that is, what you expected to happen and
  17043. what in fact did happen. You don't know how to make a good report? See
  17044. https://orgmode.org/manual/Feedback.html#Feedback
  17045. Your bug report will be posted to the Org mailing list.
  17046. ------------------------------------------------------------------------")
  17047. (save-excursion
  17048. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  17049. (replace-match "\\1Bug: \\3 [\\2]")))))
  17050. (defun org-install-agenda-files-menu ()
  17051. (let ((bl (buffer-list)))
  17052. (save-excursion
  17053. (while bl
  17054. (set-buffer (pop bl))
  17055. (when (derived-mode-p 'org-mode) (setq bl nil)))
  17056. (when (derived-mode-p 'org-mode)
  17057. (easy-menu-change
  17058. '("Org") "File List for Agenda"
  17059. (append
  17060. (list
  17061. ["Edit File List" (org-edit-agenda-file-list) t]
  17062. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  17063. ["Remove Current File from List" org-remove-file t]
  17064. ["Cycle through agenda files" org-cycle-agenda-files t]
  17065. ["Occur in all agenda files" org-occur-in-agenda-files t]
  17066. "--")
  17067. (mapcar 'org-file-menu-entry
  17068. ;; Prevent initialization from failing.
  17069. (ignore-errors (org-agenda-files t)))))))))
  17070. ;;;; Documentation
  17071. (defun org-require-autoloaded-modules ()
  17072. (interactive)
  17073. (mapc #'require
  17074. '(org-agenda org-archive org-attach org-clock org-colview org-id
  17075. org-table org-timer)))
  17076. ;;;###autoload
  17077. (defun org-reload (&optional uncompiled)
  17078. "Reload all Org Lisp files.
  17079. With prefix arg UNCOMPILED, load the uncompiled versions."
  17080. (interactive "P")
  17081. (require 'loadhist)
  17082. (let* ((org-dir (org-find-library-dir "org"))
  17083. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  17084. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  17085. (remove-re (format "\\`%s\\'"
  17086. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  17087. (feats (delete-dups
  17088. (mapcar 'file-name-sans-extension
  17089. (mapcar 'file-name-nondirectory
  17090. (delq nil
  17091. (mapcar 'feature-file
  17092. features))))))
  17093. (lfeat (append
  17094. (sort
  17095. (setq feats
  17096. (delq nil (mapcar
  17097. (lambda (f)
  17098. (if (and (string-match feature-re f)
  17099. (not (string-match remove-re f)))
  17100. f nil))
  17101. feats)))
  17102. 'string-lessp)
  17103. (list "org-version" "org")))
  17104. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  17105. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  17106. load-uncore load-misses)
  17107. (setq load-misses
  17108. (delq 't
  17109. (mapcar (lambda (f)
  17110. (or (org-load-noerror-mustsuffix (concat org-dir f))
  17111. (and (string= org-dir contrib-dir)
  17112. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  17113. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  17114. (add-to-list 'load-uncore f 'append)
  17115. 't)
  17116. f))
  17117. lfeat)))
  17118. (when load-uncore
  17119. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  17120. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  17121. (if load-misses
  17122. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  17123. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  17124. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  17125. ;;;###autoload
  17126. (defun org-customize ()
  17127. "Call the customize function with org as argument."
  17128. (interactive)
  17129. (org-load-modules-maybe)
  17130. (org-require-autoloaded-modules)
  17131. (customize-browse 'org))
  17132. (defun org-create-customize-menu ()
  17133. "Create a full customization menu for Org mode, insert it into the menu."
  17134. (interactive)
  17135. (org-load-modules-maybe)
  17136. (org-require-autoloaded-modules)
  17137. (if (fboundp 'customize-menu-create)
  17138. (progn
  17139. (easy-menu-change
  17140. '("Org") "Customize"
  17141. `(["Browse Org group" org-customize t]
  17142. "--"
  17143. ,(customize-menu-create 'org)
  17144. ["Set" Custom-set t]
  17145. ["Save" Custom-save t]
  17146. ["Reset to Current" Custom-reset-current t]
  17147. ["Reset to Saved" Custom-reset-saved t]
  17148. ["Reset to Standard Settings" Custom-reset-standard t]))
  17149. (message "\"Org\"-menu now contains full customization menu"))
  17150. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  17151. ;;;; Miscellaneous stuff
  17152. ;;; Generally useful functions
  17153. (defun org-in-clocktable-p ()
  17154. "Check if the cursor is in a clocktable."
  17155. (let ((pos (point)) start)
  17156. (save-excursion
  17157. (end-of-line 1)
  17158. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  17159. (setq start (match-beginning 0))
  17160. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  17161. (>= (match-end 0) pos)
  17162. start))))
  17163. (defun org-in-verbatim-emphasis ()
  17164. (save-match-data
  17165. (and (org-in-regexp org-verbatim-re 2)
  17166. (>= (point) (match-beginning 3))
  17167. (<= (point) (match-end 4)))))
  17168. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  17169. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  17170. (if (and marker (marker-buffer marker)
  17171. (buffer-live-p (marker-buffer marker)))
  17172. (progn
  17173. (pop-to-buffer-same-window (marker-buffer marker))
  17174. (when (or (> marker (point-max)) (< marker (point-min)))
  17175. (widen))
  17176. (goto-char marker)
  17177. (org-show-context 'org-goto))
  17178. (if bookmark
  17179. (bookmark-jump bookmark)
  17180. (error "Cannot find location"))))
  17181. (defun org-quote-csv-field (s)
  17182. "Quote field for inclusion in CSV material."
  17183. (if (string-match "[\",]" s)
  17184. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  17185. s))
  17186. (defun org-force-self-insert (N)
  17187. "Needed to enforce self-insert under remapping."
  17188. (interactive "p")
  17189. (self-insert-command N))
  17190. (defun org-quote-vert (s)
  17191. "Replace \"|\" with \"\\vert\"."
  17192. (while (string-match "|" s)
  17193. (setq s (replace-match "\\vert" t t s)))
  17194. s)
  17195. (defun org-uuidgen-p (s)
  17196. "Is S an ID created by UUIDGEN?"
  17197. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  17198. (defun org-in-src-block-p (&optional inside)
  17199. "Whether point is in a code source block.
  17200. When INSIDE is non-nil, don't consider we are within a source
  17201. block when point is at #+BEGIN_SRC or #+END_SRC."
  17202. (let ((case-fold-search t))
  17203. (or (and (eq (get-char-property (point) 'src-block) t))
  17204. (and (not inside)
  17205. (save-match-data
  17206. (save-excursion
  17207. (beginning-of-line)
  17208. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  17209. (defun org-context ()
  17210. "Return a list of contexts of the current cursor position.
  17211. If several contexts apply, all are returned.
  17212. Each context entry is a list with a symbol naming the context, and
  17213. two positions indicating start and end of the context. Possible
  17214. contexts are:
  17215. :headline anywhere in a headline
  17216. :headline-stars on the leading stars in a headline
  17217. :todo-keyword on a TODO keyword (including DONE) in a headline
  17218. :tags on the TAGS in a headline
  17219. :priority on the priority cookie in a headline
  17220. :item on the first line of a plain list item
  17221. :item-bullet on the bullet/number of a plain list item
  17222. :checkbox on the checkbox in a plain list item
  17223. :table in an Org table
  17224. :table-special on a special filed in a table
  17225. :table-table in a table.el table
  17226. :clocktable in a clocktable
  17227. :src-block in a source block
  17228. :link on a hyperlink
  17229. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  17230. :latex-fragment on a LaTeX fragment
  17231. :latex-preview on a LaTeX fragment with overlaid preview image
  17232. This function expects the position to be visible because it uses font-lock
  17233. faces as a help to recognize the following contexts: :table-special, :link,
  17234. and :keyword."
  17235. (let* ((f (get-text-property (point) 'face))
  17236. (faces (if (listp f) f (list f)))
  17237. (case-fold-search t)
  17238. (p (point)) clist o)
  17239. ;; First the large context
  17240. (cond
  17241. ((org-at-heading-p t)
  17242. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  17243. (when (progn
  17244. (beginning-of-line 1)
  17245. (looking-at org-todo-line-tags-regexp))
  17246. (push (org-point-in-group p 1 :headline-stars) clist)
  17247. (push (org-point-in-group p 2 :todo-keyword) clist)
  17248. (push (org-point-in-group p 4 :tags) clist))
  17249. (goto-char p)
  17250. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  17251. (when (looking-at "\\[#[A-Z0-9]\\]")
  17252. (push (org-point-in-group p 0 :priority) clist)))
  17253. ((org-at-item-p)
  17254. (push (org-point-in-group p 2 :item-bullet) clist)
  17255. (push (list :item (point-at-bol)
  17256. (save-excursion (org-end-of-item) (point)))
  17257. clist)
  17258. (and (org-at-item-checkbox-p)
  17259. (push (org-point-in-group p 0 :checkbox) clist)))
  17260. ((org-at-table-p)
  17261. (push (list :table (org-table-begin) (org-table-end)) clist)
  17262. (when (memq 'org-formula faces)
  17263. (push (list :table-special
  17264. (previous-single-property-change p 'face)
  17265. (next-single-property-change p 'face)) clist)))
  17266. ((org-at-table-p 'any)
  17267. (push (list :table-table) clist)))
  17268. (goto-char p)
  17269. (let ((case-fold-search t))
  17270. ;; New the "medium" contexts: clocktables, source blocks
  17271. (cond ((org-in-clocktable-p)
  17272. (push (list :clocktable
  17273. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  17274. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  17275. (match-beginning 1))
  17276. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  17277. (match-end 0))) clist))
  17278. ((org-in-src-block-p)
  17279. (push (list :src-block
  17280. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  17281. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  17282. (match-beginning 1))
  17283. (and (search-forward "#+END_SRC" nil t)
  17284. (match-beginning 0))) clist))))
  17285. (goto-char p)
  17286. ;; Now the small context
  17287. (cond
  17288. ((org-at-timestamp-p)
  17289. (push (org-point-in-group p 0 :timestamp) clist))
  17290. ((memq 'org-link faces)
  17291. (push (list :link
  17292. (previous-single-property-change p 'face)
  17293. (next-single-property-change p 'face)) clist))
  17294. ((memq 'org-special-keyword faces)
  17295. (push (list :keyword
  17296. (previous-single-property-change p 'face)
  17297. (next-single-property-change p 'face)) clist))
  17298. ((setq o (cl-some
  17299. (lambda (o)
  17300. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  17301. o))
  17302. (overlays-at (point))))
  17303. (push (list :latex-fragment
  17304. (overlay-start o) (overlay-end o)) clist)
  17305. (push (list :latex-preview
  17306. (overlay-start o) (overlay-end o)) clist))
  17307. ((org-inside-LaTeX-fragment-p)
  17308. ;; FIXME: positions wrong.
  17309. (push (list :latex-fragment (point) (point)) clist)))
  17310. (setq clist (nreverse (delq nil clist)))
  17311. clist))
  17312. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  17313. "Non-nil when point is between matches of START-RE and END-RE.
  17314. Also return a non-nil value when point is on one of the matches.
  17315. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  17316. buffer positions. Default values are the positions of headlines
  17317. surrounding the point.
  17318. The functions returns a cons cell whose car (resp. cdr) is the
  17319. position before START-RE (resp. after END-RE)."
  17320. (save-match-data
  17321. (let ((pos (point))
  17322. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  17323. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  17324. beg end)
  17325. (save-excursion
  17326. ;; Point is on a block when on START-RE or if START-RE can be
  17327. ;; found before it...
  17328. (and (or (org-in-regexp start-re)
  17329. (re-search-backward start-re limit-up t))
  17330. (setq beg (match-beginning 0))
  17331. ;; ... and END-RE after it...
  17332. (goto-char (match-end 0))
  17333. (re-search-forward end-re limit-down t)
  17334. (> (setq end (match-end 0)) pos)
  17335. ;; ... without another START-RE in-between.
  17336. (goto-char (match-beginning 0))
  17337. (not (re-search-backward start-re (1+ beg) t))
  17338. ;; Return value.
  17339. (cons beg end))))))
  17340. (defun org-in-block-p (names)
  17341. "Non-nil when point belongs to a block whose name belongs to NAMES.
  17342. NAMES is a list of strings containing names of blocks.
  17343. Return first block name matched, or nil. Beware that in case of
  17344. nested blocks, the returned name may not belong to the closest
  17345. block from point."
  17346. (save-match-data
  17347. (catch 'exit
  17348. (let ((case-fold-search t)
  17349. (lim-up (save-excursion (outline-previous-heading)))
  17350. (lim-down (save-excursion (outline-next-heading))))
  17351. (dolist (name names)
  17352. (let ((n (regexp-quote name)))
  17353. (when (org-between-regexps-p
  17354. (concat "^[ \t]*#\\+begin_" n)
  17355. (concat "^[ \t]*#\\+end_" n)
  17356. lim-up lim-down)
  17357. (throw 'exit n)))))
  17358. nil)))
  17359. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  17360. "Call `multi-occur' with buffers for all agenda files."
  17361. (interactive "sOrg-files matching: ")
  17362. (let* ((files (org-agenda-files))
  17363. (tnames (mapcar #'file-truename files))
  17364. (extra org-agenda-text-search-extra-files))
  17365. (when (eq (car extra) 'agenda-archives)
  17366. (setq extra (cdr extra))
  17367. (setq files (org-add-archive-files files)))
  17368. (dolist (f extra)
  17369. (unless (member (file-truename f) tnames)
  17370. (unless (member f files) (setq files (append files (list f))))
  17371. (setq tnames (append tnames (list (file-truename f))))))
  17372. (multi-occur
  17373. (mapcar (lambda (x)
  17374. (with-current-buffer
  17375. ;; FIXME: Why not just (find-file-noselect x)?
  17376. ;; Is it to avoid the "revert buffer" prompt?
  17377. (or (get-file-buffer x) (find-file-noselect x))
  17378. (widen)
  17379. (current-buffer)))
  17380. files)
  17381. regexp)))
  17382. (add-hook 'occur-mode-find-occurrence-hook
  17383. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  17384. (defun org-occur-link-in-agenda-files ()
  17385. "Create a link and search for it in the agendas.
  17386. The link is not stored in `org-stored-links', it is just created
  17387. for the search purpose."
  17388. (interactive)
  17389. (let ((link (condition-case nil
  17390. (org-store-link nil)
  17391. (error "Unable to create a link to here"))))
  17392. (org-occur-in-agenda-files (regexp-quote link))))
  17393. (defun org-back-over-empty-lines ()
  17394. "Move backwards over whitespace, to the beginning of the first empty line.
  17395. Returns the number of empty lines passed."
  17396. (let ((pos (point)))
  17397. (if (cdr (assq 'heading org-blank-before-new-entry))
  17398. (skip-chars-backward " \t\n\r")
  17399. (unless (eobp)
  17400. (forward-line -1)))
  17401. (beginning-of-line 2)
  17402. (goto-char (min (point) pos))
  17403. (count-lines (point) pos)))
  17404. ;;; TODO: Only called once, from ox-odt which should probably use
  17405. ;;; org-export-inline-image-p or something.
  17406. (defun org-file-image-p (file)
  17407. "Return non-nil if FILE is an image."
  17408. (save-match-data
  17409. (string-match (image-file-name-regexp) file)))
  17410. (defun org-get-cursor-date (&optional with-time)
  17411. "Return the date at cursor in as a time.
  17412. This works in the calendar and in the agenda, anywhere else it just
  17413. returns the current time.
  17414. If WITH-TIME is non-nil, returns the time of the event at point (in
  17415. the agenda) or the current time of the day."
  17416. (let (date day defd tp hod mod)
  17417. (when with-time
  17418. (setq tp (get-text-property (point) 'time))
  17419. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  17420. (setq hod (string-to-number (match-string 1 tp))
  17421. mod (string-to-number (match-string 2 tp))))
  17422. (or tp (let ((now (decode-time)))
  17423. (setq hod (nth 2 now)
  17424. mod (nth 1 now)))))
  17425. (cond
  17426. ((eq major-mode 'calendar-mode)
  17427. (setq date (calendar-cursor-to-date)
  17428. defd (encode-time 0 (or mod 0) (or hod 0)
  17429. (nth 1 date) (nth 0 date) (nth 2 date))))
  17430. ((eq major-mode 'org-agenda-mode)
  17431. (setq day (get-text-property (point) 'day))
  17432. (when day
  17433. (setq date (calendar-gregorian-from-absolute day)
  17434. defd (encode-time 0 (or mod 0) (or hod 0)
  17435. (nth 1 date) (nth 0 date) (nth 2 date))))))
  17436. (or defd (current-time))))
  17437. (defun org-mark-subtree (&optional up)
  17438. "Mark the current subtree.
  17439. This puts point at the start of the current subtree, and mark at
  17440. the end. If a numeric prefix UP is given, move up into the
  17441. hierarchy of headlines by UP levels before marking the subtree."
  17442. (interactive "P")
  17443. (org-with-limited-levels
  17444. (cond ((org-at-heading-p) (beginning-of-line))
  17445. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  17446. (t (outline-previous-visible-heading 1))))
  17447. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  17448. (if (called-interactively-p 'any)
  17449. (call-interactively 'org-mark-element)
  17450. (org-mark-element)))
  17451. ;;; Indentation
  17452. (defvar org-element-greater-elements)
  17453. (defun org--get-expected-indentation (element contentsp)
  17454. "Expected indentation column for current line, according to ELEMENT.
  17455. ELEMENT is an element containing point. CONTENTSP is non-nil
  17456. when indentation is to be computed according to contents of
  17457. ELEMENT."
  17458. (let ((type (org-element-type element))
  17459. (start (org-element-property :begin element))
  17460. (post-affiliated (org-element-property :post-affiliated element)))
  17461. (org-with-wide-buffer
  17462. (cond
  17463. (contentsp
  17464. (cl-case type
  17465. ((diary-sexp footnote-definition) 0)
  17466. ((headline inlinetask nil)
  17467. (if (not org-adapt-indentation) 0
  17468. (let ((level (org-current-level)))
  17469. (if level (1+ level) 0))))
  17470. ((item plain-list) (org-list-item-body-column post-affiliated))
  17471. (t
  17472. (goto-char start)
  17473. (current-indentation))))
  17474. ((memq type '(headline inlinetask nil))
  17475. (if (org-match-line "[ \t]*$")
  17476. (org--get-expected-indentation element t)
  17477. 0))
  17478. ((memq type '(diary-sexp footnote-definition)) 0)
  17479. ;; First paragraph of a footnote definition or an item.
  17480. ;; Indent like parent.
  17481. ((< (line-beginning-position) start)
  17482. (org--get-expected-indentation
  17483. (org-element-property :parent element) t))
  17484. ;; At first line: indent according to previous sibling, if any,
  17485. ;; ignoring footnote definitions and inline tasks, or parent's
  17486. ;; contents.
  17487. ((= (line-beginning-position) start)
  17488. (catch 'exit
  17489. (while t
  17490. (if (= (point-min) start) (throw 'exit 0)
  17491. (goto-char (1- start))
  17492. (let* ((previous (org-element-at-point))
  17493. (parent previous))
  17494. (while (and parent (<= (org-element-property :end parent) start))
  17495. (setq previous parent
  17496. parent (org-element-property :parent parent)))
  17497. (cond
  17498. ((not previous) (throw 'exit 0))
  17499. ((> (org-element-property :end previous) start)
  17500. (throw 'exit (org--get-expected-indentation previous t)))
  17501. ((memq (org-element-type previous)
  17502. '(footnote-definition inlinetask))
  17503. (setq start (org-element-property :begin previous)))
  17504. (t (goto-char (org-element-property :begin previous))
  17505. (throw 'exit
  17506. (if (bolp) (current-indentation)
  17507. ;; At first paragraph in an item or
  17508. ;; a footnote definition.
  17509. (org--get-expected-indentation
  17510. (org-element-property :parent previous) t))))))))))
  17511. ;; Otherwise, move to the first non-blank line above.
  17512. (t
  17513. (beginning-of-line)
  17514. (let ((pos (point)))
  17515. (skip-chars-backward " \r\t\n")
  17516. (cond
  17517. ;; Two blank lines end a footnote definition or a plain
  17518. ;; list. When we indent an empty line after them, the
  17519. ;; containing list or footnote definition is over, so it
  17520. ;; qualifies as a previous sibling. Therefore, we indent
  17521. ;; like its first line.
  17522. ((and (memq type '(footnote-definition plain-list))
  17523. (> (count-lines (point) pos) 2))
  17524. (goto-char start)
  17525. (current-indentation))
  17526. ;; Line above is the first one of a paragraph at the
  17527. ;; beginning of an item or a footnote definition. Indent
  17528. ;; like parent.
  17529. ((< (line-beginning-position) start)
  17530. (org--get-expected-indentation
  17531. (org-element-property :parent element) t))
  17532. ;; Line above is the beginning of an element, i.e., point
  17533. ;; was originally on the blank lines between element's start
  17534. ;; and contents.
  17535. ((= (line-beginning-position) post-affiliated)
  17536. (org--get-expected-indentation element t))
  17537. ;; POS is after contents in a greater element. Indent like
  17538. ;; the beginning of the element.
  17539. ((and (memq type org-element-greater-elements)
  17540. (let ((cend (org-element-property :contents-end element)))
  17541. (and cend (<= cend pos))))
  17542. ;; As a special case, if point is at the end of a footnote
  17543. ;; definition or an item, indent like the very last element
  17544. ;; within. If that last element is an item, indent like
  17545. ;; its contents.
  17546. (if (memq type '(footnote-definition item plain-list))
  17547. (let ((last (org-element-at-point)))
  17548. (goto-char pos)
  17549. (org--get-expected-indentation
  17550. last (eq (org-element-type last) 'item)))
  17551. (goto-char start)
  17552. (current-indentation)))
  17553. ;; In any other case, indent like the current line.
  17554. (t (current-indentation)))))))))
  17555. (defun org--align-node-property ()
  17556. "Align node property at point.
  17557. Alignment is done according to `org-property-format', which see."
  17558. (when (save-excursion
  17559. (beginning-of-line)
  17560. (looking-at org-property-re))
  17561. (replace-match
  17562. (concat (match-string 4)
  17563. (org-trim
  17564. (format org-property-format (match-string 1) (match-string 3))))
  17565. t t)))
  17566. (defun org-indent-line ()
  17567. "Indent line depending on context.
  17568. Indentation is done according to the following rules:
  17569. - Footnote definitions, diary sexps, headlines and inline tasks
  17570. have to start at column 0.
  17571. - On the very first line of an element, consider, in order, the
  17572. next rules until one matches:
  17573. 1. If there's a sibling element before, ignoring footnote
  17574. definitions and inline tasks, indent like its first line.
  17575. 2. If element has a parent, indent like its contents. More
  17576. precisely, if parent is an item, indent after the bullet.
  17577. Else, indent like parent's first line.
  17578. 3. Otherwise, indent relatively to current level, if
  17579. `org-adapt-indentation' is non-nil, or to left margin.
  17580. - On a blank line at the end of an element, indent according to
  17581. the type of the element. More precisely
  17582. 1. If element is a plain list, an item, or a footnote
  17583. definition, indent like the very last element within.
  17584. 2. If element is a paragraph, indent like its last non blank
  17585. line.
  17586. 3. Otherwise, indent like its very first line.
  17587. - In the code part of a source block, use language major mode
  17588. to indent current line if `org-src-tab-acts-natively' is
  17589. non-nil. If it is nil, do nothing.
  17590. - Otherwise, indent like the first non-blank line above.
  17591. The function doesn't indent an item as it could break the whole
  17592. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17593. `\\[org-shiftmetaright]'.
  17594. Also align node properties according to `org-property-format'."
  17595. (interactive)
  17596. (cond
  17597. ((org-at-heading-p) 'noindent)
  17598. (t
  17599. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  17600. (type (org-element-type element)))
  17601. (cond ((and (memq type '(plain-list item))
  17602. (= (line-beginning-position)
  17603. (org-element-property :post-affiliated element)))
  17604. 'noindent)
  17605. ((and (eq type 'latex-environment)
  17606. (>= (point) (org-element-property :post-affiliated element))
  17607. (< (point) (org-with-wide-buffer
  17608. (goto-char (org-element-property :end element))
  17609. (skip-chars-backward " \r\t\n")
  17610. (line-beginning-position 2))))
  17611. 'noindent)
  17612. ((and (eq type 'src-block)
  17613. org-src-tab-acts-natively
  17614. (> (line-beginning-position)
  17615. (org-element-property :post-affiliated element))
  17616. (< (line-beginning-position)
  17617. (org-with-wide-buffer
  17618. (goto-char (org-element-property :end element))
  17619. (skip-chars-backward " \r\t\n")
  17620. (line-beginning-position))))
  17621. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17622. (t
  17623. (let ((column (org--get-expected-indentation element nil)))
  17624. ;; Preserve current column.
  17625. (if (<= (current-column) (current-indentation))
  17626. (indent-line-to column)
  17627. (save-excursion (indent-line-to column))))
  17628. ;; Align node property. Also preserve current column.
  17629. (when (eq type 'node-property)
  17630. (let ((column (current-column)))
  17631. (org--align-node-property)
  17632. (org-move-to-column column)))))))))
  17633. (defun org-indent-region (start end)
  17634. "Indent each non-blank line in the region.
  17635. Called from a program, START and END specify the region to
  17636. indent. The function will not indent contents of example blocks,
  17637. verse blocks and export blocks as leading white spaces are
  17638. assumed to be significant there."
  17639. (interactive "r")
  17640. (save-excursion
  17641. (goto-char start)
  17642. (skip-chars-forward " \r\t\n")
  17643. (unless (eobp) (beginning-of-line))
  17644. (let ((indent-to
  17645. (lambda (ind pos)
  17646. ;; Set IND as indentation for all lines between point and
  17647. ;; POS. Blank lines are ignored. Leave point after POS
  17648. ;; once done.
  17649. (let ((limit (copy-marker pos)))
  17650. (while (< (point) limit)
  17651. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17652. (forward-line))
  17653. (set-marker limit nil))))
  17654. (end (copy-marker end)))
  17655. (while (< (point) end)
  17656. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17657. (let* ((element (org-element-at-point))
  17658. (type (org-element-type element))
  17659. (element-end (copy-marker (org-element-property :end element)))
  17660. (ind (org--get-expected-indentation element nil)))
  17661. (cond
  17662. ;; Element indented as a single block. Example blocks
  17663. ;; preserving indentation are a special case since the
  17664. ;; "contents" must not be indented whereas the block
  17665. ;; boundaries can.
  17666. ((or (memq type '(export-block latex-environment))
  17667. (and (eq type 'example-block)
  17668. (not
  17669. (or org-src-preserve-indentation
  17670. (org-element-property :preserve-indent element)))))
  17671. (let ((offset (- ind (current-indentation))))
  17672. (unless (zerop offset)
  17673. (indent-rigidly (org-element-property :begin element)
  17674. (org-element-property :end element)
  17675. offset)))
  17676. (goto-char element-end))
  17677. ;; Elements indented line wise. Be sure to exclude
  17678. ;; example blocks (preserving indentation) and source
  17679. ;; blocks from this category as they are treated
  17680. ;; specially later.
  17681. ((or (memq type '(paragraph table table-row))
  17682. (not (or (org-element-property :contents-begin element)
  17683. (memq type '(example-block src-block)))))
  17684. (when (eq type 'node-property)
  17685. (org--align-node-property)
  17686. (beginning-of-line))
  17687. (funcall indent-to ind (min element-end end)))
  17688. ;; Elements consisting of three parts: before the
  17689. ;; contents, the contents, and after the contents. The
  17690. ;; contents are treated specially, according to the
  17691. ;; element type, or not indented at all. Other parts are
  17692. ;; indented as a single block.
  17693. (t
  17694. (let* ((post (copy-marker
  17695. (org-element-property :post-affiliated element)))
  17696. (cbeg
  17697. (copy-marker
  17698. (cond
  17699. ((not (org-element-property :contents-begin element))
  17700. ;; Fake contents for source blocks.
  17701. (org-with-wide-buffer
  17702. (goto-char post)
  17703. (line-beginning-position 2)))
  17704. ((memq type '(footnote-definition item plain-list))
  17705. ;; Contents in these elements could start on
  17706. ;; the same line as the beginning of the
  17707. ;; element. Make sure we start indenting
  17708. ;; from the second line.
  17709. (org-with-wide-buffer
  17710. (goto-char post)
  17711. (end-of-line)
  17712. (skip-chars-forward " \r\t\n")
  17713. (if (eobp) (point) (line-beginning-position))))
  17714. (t (org-element-property :contents-begin element)))))
  17715. (cend (copy-marker
  17716. (or (org-element-property :contents-end element)
  17717. ;; Fake contents for source blocks.
  17718. (org-with-wide-buffer
  17719. (goto-char element-end)
  17720. (skip-chars-backward " \r\t\n")
  17721. (line-beginning-position)))
  17722. t)))
  17723. ;; Do not change items indentation individually as it
  17724. ;; might break the list as a whole. On the other
  17725. ;; hand, when at a plain list, indent it as a whole.
  17726. (cond ((eq type 'plain-list)
  17727. (let ((offset (- ind (current-indentation))))
  17728. (unless (zerop offset)
  17729. (indent-rigidly (org-element-property :begin element)
  17730. (org-element-property :end element)
  17731. offset))
  17732. (goto-char cbeg)))
  17733. ((eq type 'item) (goto-char cbeg))
  17734. (t (funcall indent-to ind (min cbeg end))))
  17735. (when (< (point) end)
  17736. (cl-case type
  17737. ((example-block verse-block))
  17738. (src-block
  17739. ;; In a source block, indent source code
  17740. ;; according to language major mode, but only if
  17741. ;; `org-src-tab-acts-natively' is non-nil.
  17742. (when (and (< (point) end) org-src-tab-acts-natively)
  17743. (ignore-errors
  17744. (org-babel-do-in-edit-buffer
  17745. (indent-region (point-min) (point-max))))))
  17746. (t (org-indent-region (point) (min cend end))))
  17747. (goto-char (min cend end))
  17748. (when (< (point) end)
  17749. (funcall indent-to ind (min element-end end))))
  17750. (set-marker post nil)
  17751. (set-marker cbeg nil)
  17752. (set-marker cend nil))))
  17753. (set-marker element-end nil))))
  17754. (set-marker end nil))))
  17755. (defun org-indent-drawer ()
  17756. "Indent the drawer at point."
  17757. (interactive)
  17758. (unless (save-excursion
  17759. (beginning-of-line)
  17760. (looking-at-p org-drawer-regexp))
  17761. (user-error "Not at a drawer"))
  17762. (let ((element (org-element-at-point)))
  17763. (unless (memq (org-element-type element) '(drawer property-drawer))
  17764. (user-error "Not at a drawer"))
  17765. (org-with-wide-buffer
  17766. (org-indent-region (org-element-property :begin element)
  17767. (org-element-property :end element))))
  17768. (message "Drawer at point indented"))
  17769. (defun org-indent-block ()
  17770. "Indent the block at point."
  17771. (interactive)
  17772. (unless (save-excursion
  17773. (beginning-of-line)
  17774. (let ((case-fold-search t))
  17775. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17776. (user-error "Not at a block"))
  17777. (let ((element (org-element-at-point)))
  17778. (unless (memq (org-element-type element)
  17779. '(comment-block center-block dynamic-block example-block
  17780. export-block quote-block special-block
  17781. src-block verse-block))
  17782. (user-error "Not at a block"))
  17783. (org-with-wide-buffer
  17784. (org-indent-region (org-element-property :begin element)
  17785. (org-element-property :end element))))
  17786. (message "Block at point indented"))
  17787. ;;; Filling
  17788. ;; We use our own fill-paragraph and auto-fill functions.
  17789. ;; `org-fill-paragraph' relies on adaptive filling and context
  17790. ;; checking. Appropriate `fill-prefix' is computed with
  17791. ;; `org-adaptive-fill-function'.
  17792. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17793. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17794. ;; `org-adaptive-fill-function' value. Internally,
  17795. ;; `org-comment-line-break-function' breaks the line.
  17796. ;; `org-setup-filling' installs filling and auto-filling related
  17797. ;; variables during `org-mode' initialization.
  17798. (defun org-setup-filling ()
  17799. (require 'org-element)
  17800. ;; Prevent auto-fill from inserting unwanted new items.
  17801. (when (boundp 'fill-nobreak-predicate)
  17802. (setq-local
  17803. fill-nobreak-predicate
  17804. (org-uniquify
  17805. (append fill-nobreak-predicate
  17806. '(org-fill-line-break-nobreak-p
  17807. org-fill-n-macro-as-item-nobreak-p
  17808. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17809. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17810. (setq-local paragraph-start paragraph-ending)
  17811. (setq-local paragraph-separate paragraph-ending))
  17812. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17813. (setq-local auto-fill-inhibit-regexp nil)
  17814. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17815. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17816. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17817. (defun org-fill-line-break-nobreak-p ()
  17818. "Non-nil when a new line at point would create an Org line break."
  17819. (save-excursion
  17820. (skip-chars-backward "[ \t]")
  17821. (skip-chars-backward "\\\\")
  17822. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  17823. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17824. "Non-nil when a new line at point would split a timestamp."
  17825. (and (org-at-timestamp-p 'lax)
  17826. (not (looking-at org-ts-regexp-both))))
  17827. (defun org-fill-n-macro-as-item-nobreak-p ()
  17828. "Non-nil when a new line at point would create a new list."
  17829. ;; During export, a "n" macro followed by a dot or a closing
  17830. ;; parenthesis can end up being parsed as a new list item.
  17831. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17832. (defvar orgtbl-line-start-regexp) ; From org-table.el
  17833. (defun org-adaptive-fill-function ()
  17834. "Compute a fill prefix for the current line.
  17835. Return fill prefix, as a string, or nil if current line isn't
  17836. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17837. matches in paragraphs or comments, use it."
  17838. (org-with-wide-buffer
  17839. (unless (org-at-heading-p)
  17840. (let* ((p (line-beginning-position))
  17841. (element (save-excursion
  17842. (beginning-of-line)
  17843. (org-element-at-point)))
  17844. (type (org-element-type element))
  17845. (post-affiliated (org-element-property :post-affiliated element)))
  17846. (unless (< p post-affiliated)
  17847. (cl-case type
  17848. (comment
  17849. (save-excursion
  17850. (beginning-of-line)
  17851. (looking-at "[ \t]*")
  17852. (concat (match-string 0) "# ")))
  17853. (footnote-definition "")
  17854. ((item plain-list)
  17855. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17856. (paragraph
  17857. ;; Fill prefix is usually the same as the current line,
  17858. ;; unless the paragraph is at the beginning of an item.
  17859. (let ((parent (org-element-property :parent element)))
  17860. (save-excursion
  17861. (beginning-of-line)
  17862. (cond ((eq (org-element-type parent) 'item)
  17863. (make-string (org-list-item-body-column
  17864. (org-element-property :begin parent))
  17865. ?\s))
  17866. ((and adaptive-fill-regexp
  17867. ;; Locally disable
  17868. ;; `adaptive-fill-function' to let
  17869. ;; `fill-context-prefix' handle
  17870. ;; `adaptive-fill-regexp' variable.
  17871. (let (adaptive-fill-function)
  17872. (fill-context-prefix
  17873. post-affiliated
  17874. (org-element-property :end element)))))
  17875. ((looking-at "[ \t]+") (match-string 0))
  17876. (t "")))))
  17877. (comment-block
  17878. ;; Only fill contents if P is within block boundaries.
  17879. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17880. (forward-line)
  17881. (point)))
  17882. (cend (save-excursion
  17883. (goto-char (org-element-property :end element))
  17884. (skip-chars-backward " \r\t\n")
  17885. (line-beginning-position))))
  17886. (when (and (>= p cbeg) (< p cend))
  17887. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17888. (match-string 0)
  17889. ""))))))))))
  17890. (defun org-fill-element (&optional justify)
  17891. "Fill element at point, when applicable.
  17892. This function only applies to comment blocks, comments, example
  17893. blocks and paragraphs. Also, as a special case, re-align table
  17894. when point is at one.
  17895. If JUSTIFY is non-nil (interactively, with prefix argument),
  17896. justify as well. If `sentence-end-double-space' is non-nil, then
  17897. period followed by one space does not end a sentence, so don't
  17898. break a line there. The variable `fill-column' controls the
  17899. width for filling.
  17900. For convenience, when point is at a plain list, an item or
  17901. a footnote definition, try to fill the first paragraph within."
  17902. (with-syntax-table org-mode-transpose-word-syntax-table
  17903. ;; Move to end of line in order to get the first paragraph within
  17904. ;; a plain list or a footnote definition.
  17905. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17906. ;; First check if point is in a blank line at the beginning of
  17907. ;; the buffer. In that case, ignore filling.
  17908. (cl-case (org-element-type element)
  17909. ;; Use major mode filling function is source blocks.
  17910. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  17911. ;; Align Org tables, leave table.el tables as-is.
  17912. (table-row (org-table-align) t)
  17913. (table
  17914. (when (eq (org-element-property :type element) 'org)
  17915. (save-excursion
  17916. (goto-char (org-element-property :post-affiliated element))
  17917. (org-table-align)))
  17918. t)
  17919. (paragraph
  17920. ;; Paragraphs may contain `line-break' type objects.
  17921. (let ((beg (max (point-min)
  17922. (org-element-property :contents-begin element)))
  17923. (end (min (point-max)
  17924. (org-element-property :contents-end element))))
  17925. ;; Do nothing if point is at an affiliated keyword.
  17926. (if (< (line-end-position) beg) t
  17927. ;; Fill paragraph, taking line breaks into account.
  17928. (save-excursion
  17929. (goto-char beg)
  17930. (let ((cuts (list beg)))
  17931. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17932. (when (eq 'line-break
  17933. (org-element-type
  17934. (save-excursion (backward-char)
  17935. (org-element-context))))
  17936. (push (point) cuts)))
  17937. (dolist (c (delq end cuts))
  17938. (fill-region-as-paragraph c end justify)
  17939. (setq end c))))
  17940. t)))
  17941. ;; Contents of `comment-block' type elements should be
  17942. ;; filled as plain text, but only if point is within block
  17943. ;; markers.
  17944. (comment-block
  17945. (let* ((case-fold-search t)
  17946. (beg (save-excursion
  17947. (goto-char (org-element-property :begin element))
  17948. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17949. (forward-line)
  17950. (point)))
  17951. (end (save-excursion
  17952. (goto-char (org-element-property :end element))
  17953. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17954. (line-beginning-position))))
  17955. (if (or (< (point) beg) (> (point) end)) t
  17956. (fill-region-as-paragraph
  17957. (save-excursion (end-of-line)
  17958. (re-search-backward "^[ \t]*$" beg 'move)
  17959. (line-beginning-position))
  17960. (save-excursion (beginning-of-line)
  17961. (re-search-forward "^[ \t]*$" end 'move)
  17962. (line-beginning-position))
  17963. justify))))
  17964. ;; Fill comments.
  17965. (comment
  17966. (let ((begin (org-element-property :post-affiliated element))
  17967. (end (org-element-property :end element)))
  17968. (when (and (>= (point) begin) (<= (point) end))
  17969. (let ((begin (save-excursion
  17970. (end-of-line)
  17971. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17972. (progn (forward-line) (point))
  17973. begin)))
  17974. (end (save-excursion
  17975. (end-of-line)
  17976. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17977. (1- (line-beginning-position))
  17978. (skip-chars-backward " \r\t\n")
  17979. (line-end-position)))))
  17980. ;; Do not fill comments when at a blank line.
  17981. (when (> end begin)
  17982. (let ((fill-prefix
  17983. (save-excursion
  17984. (beginning-of-line)
  17985. (looking-at "[ \t]*#")
  17986. (let ((comment-prefix (match-string 0)))
  17987. (goto-char (match-end 0))
  17988. (if (looking-at adaptive-fill-regexp)
  17989. (concat comment-prefix (match-string 0))
  17990. (concat comment-prefix " "))))))
  17991. (save-excursion
  17992. (fill-region-as-paragraph begin end justify))))))
  17993. t))
  17994. ;; Ignore every other element.
  17995. (otherwise t)))))
  17996. (defun org-fill-paragraph (&optional justify region)
  17997. "Fill element at point, when applicable.
  17998. This function only applies to comment blocks, comments, example
  17999. blocks and paragraphs. Also, as a special case, re-align table
  18000. when point is at one.
  18001. For convenience, when point is at a plain list, an item or
  18002. a footnote definition, try to fill the first paragraph within.
  18003. If JUSTIFY is non-nil (interactively, with prefix argument),
  18004. justify as well. If `sentence-end-double-space' is non-nil, then
  18005. period followed by one space does not end a sentence, so don't
  18006. break a line there. The variable `fill-column' controls the
  18007. width for filling.
  18008. The REGION argument is non-nil if called interactively; in that
  18009. case, if Transient Mark mode is enabled and the mark is active,
  18010. fill each of the elements in the active region, instead of just
  18011. filling the current element."
  18012. (interactive (progn
  18013. (barf-if-buffer-read-only)
  18014. (list (when current-prefix-arg 'full) t)))
  18015. (let ((hash (and (not (buffer-modified-p))
  18016. (org-buffer-hash))))
  18017. (cond
  18018. ((and region transient-mark-mode mark-active
  18019. (not (eq (region-beginning) (region-end))))
  18020. (let ((origin (point-marker))
  18021. (start (region-beginning)))
  18022. (unwind-protect
  18023. (progn
  18024. (goto-char (region-end))
  18025. (while (> (point) start)
  18026. (org-backward-paragraph)
  18027. (org-fill-element justify)))
  18028. (goto-char origin)
  18029. (set-marker origin nil))))
  18030. (t (org-fill-element justify)))
  18031. ;; If we didn't change anything in the buffer (and the buffer was
  18032. ;; previously unmodified), then flip the modification status back
  18033. ;; to "unchanged".
  18034. (when (and hash (equal hash (org-buffer-hash)))
  18035. (set-buffer-modified-p nil))))
  18036. (defun org-auto-fill-function ()
  18037. "Auto-fill function."
  18038. ;; Check if auto-filling is meaningful.
  18039. (let ((fc (current-fill-column)))
  18040. (when (and fc (> (current-column) fc))
  18041. (let* ((fill-prefix (org-adaptive-fill-function))
  18042. ;; Enforce empty fill prefix, if required. Otherwise, it
  18043. ;; will be computed again.
  18044. (adaptive-fill-mode (not (equal fill-prefix ""))))
  18045. (when fill-prefix (do-auto-fill))))))
  18046. (defun org-comment-line-break-function (&optional soft)
  18047. "Break line at point and indent, continuing comment if within one.
  18048. The inserted newline is marked hard if variable
  18049. `use-hard-newlines' is true, unless optional argument SOFT is
  18050. non-nil."
  18051. (if soft (insert-and-inherit ?\n) (newline 1))
  18052. (save-excursion (forward-char -1) (delete-horizontal-space))
  18053. (delete-horizontal-space)
  18054. (indent-to-left-margin)
  18055. (insert-before-markers-and-inherit fill-prefix))
  18056. ;;; Fixed Width Areas
  18057. (defun org-toggle-fixed-width ()
  18058. "Toggle fixed-width markup.
  18059. Add or remove fixed-width markup on current line, whenever it
  18060. makes sense. Return an error otherwise.
  18061. If a region is active and if it contains only fixed-width areas
  18062. or blank lines, remove all fixed-width markup in it. If the
  18063. region contains anything else, convert all non-fixed-width lines
  18064. to fixed-width ones.
  18065. Blank lines at the end of the region are ignored unless the
  18066. region only contains such lines."
  18067. (interactive)
  18068. (if (not (org-region-active-p))
  18069. ;; No region:
  18070. ;;
  18071. ;; Remove fixed width marker only in a fixed-with element.
  18072. ;;
  18073. ;; Add fixed width maker in paragraphs, in blank lines after
  18074. ;; elements or at the beginning of a headline or an inlinetask,
  18075. ;; and before any one-line elements (e.g., a clock).
  18076. (progn
  18077. (beginning-of-line)
  18078. (let* ((element (org-element-at-point))
  18079. (type (org-element-type element)))
  18080. (cond
  18081. ((and (eq type 'fixed-width)
  18082. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  18083. (replace-match
  18084. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  18085. ((and (memq type '(babel-call clock comment diary-sexp headline
  18086. horizontal-rule keyword paragraph
  18087. planning))
  18088. (<= (org-element-property :post-affiliated element) (point)))
  18089. (skip-chars-forward " \t")
  18090. (insert ": "))
  18091. ((and (looking-at-p "[ \t]*$")
  18092. (or (eq type 'inlinetask)
  18093. (save-excursion
  18094. (skip-chars-forward " \r\t\n")
  18095. (<= (org-element-property :end element) (point)))))
  18096. (delete-region (point) (line-end-position))
  18097. (org-indent-line)
  18098. (insert ": "))
  18099. (t (user-error "Cannot insert a fixed-width line here")))))
  18100. ;; Region active.
  18101. (let* ((begin (save-excursion
  18102. (goto-char (region-beginning))
  18103. (line-beginning-position)))
  18104. (end (copy-marker
  18105. (save-excursion
  18106. (goto-char (region-end))
  18107. (unless (eolp) (beginning-of-line))
  18108. (if (save-excursion (re-search-backward "\\S-" begin t))
  18109. (progn (skip-chars-backward " \r\t\n") (point))
  18110. (point)))))
  18111. (all-fixed-width-p
  18112. (catch 'not-all-p
  18113. (save-excursion
  18114. (goto-char begin)
  18115. (skip-chars-forward " \r\t\n")
  18116. (when (eobp) (throw 'not-all-p nil))
  18117. (while (< (point) end)
  18118. (let ((element (org-element-at-point)))
  18119. (if (eq (org-element-type element) 'fixed-width)
  18120. (goto-char (org-element-property :end element))
  18121. (throw 'not-all-p nil))))
  18122. t))))
  18123. (if all-fixed-width-p
  18124. (save-excursion
  18125. (goto-char begin)
  18126. (while (< (point) end)
  18127. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  18128. (replace-match
  18129. "" nil nil nil
  18130. (if (= (line-end-position) (match-end 0)) 0 1)))
  18131. (forward-line)))
  18132. (let ((min-ind (point-max)))
  18133. ;; Find minimum indentation across all lines.
  18134. (save-excursion
  18135. (goto-char begin)
  18136. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  18137. (setq min-ind 0)
  18138. (catch 'zerop
  18139. (while (< (point) end)
  18140. (unless (looking-at-p "[ \t]*$")
  18141. (let ((ind (current-indentation)))
  18142. (setq min-ind (min min-ind ind))
  18143. (when (zerop ind) (throw 'zerop t))))
  18144. (forward-line)))))
  18145. ;; Loop over all lines and add fixed-width markup everywhere
  18146. ;; but in fixed-width lines.
  18147. (save-excursion
  18148. (goto-char begin)
  18149. (while (< (point) end)
  18150. (cond
  18151. ((org-at-heading-p)
  18152. (insert ": ")
  18153. (forward-line)
  18154. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  18155. (insert ":")
  18156. (forward-line)))
  18157. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  18158. (let* ((element (org-element-at-point))
  18159. (element-end (org-element-property :end element)))
  18160. (if (eq (org-element-type element) 'fixed-width)
  18161. (progn (goto-char element-end)
  18162. (skip-chars-backward " \r\t\n")
  18163. (forward-line))
  18164. (let ((limit (min end element-end)))
  18165. (while (< (point) limit)
  18166. (org-move-to-column min-ind t)
  18167. (insert ": ")
  18168. (forward-line))))))
  18169. (t
  18170. (org-move-to-column min-ind t)
  18171. (insert ": ")
  18172. (forward-line)))))))
  18173. (set-marker end nil))))
  18174. ;;; Blocks
  18175. (defun org-block-map (function &optional start end)
  18176. "Call FUNCTION at the head of all source blocks in the current buffer.
  18177. Optional arguments START and END can be used to limit the range."
  18178. (let ((start (or start (point-min)))
  18179. (end (or end (point-max))))
  18180. (save-excursion
  18181. (goto-char start)
  18182. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  18183. (save-excursion
  18184. (save-match-data
  18185. (goto-char (match-beginning 0))
  18186. (funcall function)))))))
  18187. (defun org-next-block (arg &optional backward block-regexp)
  18188. "Jump to the next block.
  18189. With a prefix argument ARG, jump forward ARG many blocks.
  18190. When BACKWARD is non-nil, jump to the previous block.
  18191. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  18192. Match data is set according to this regexp when the function
  18193. returns.
  18194. Return point at beginning of the opening line of found block.
  18195. Throw an error if no block is found."
  18196. (interactive "p")
  18197. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  18198. (case-fold-search t)
  18199. (search-fn (if backward #'re-search-backward #'re-search-forward))
  18200. (count (or arg 1))
  18201. (origin (point))
  18202. last-element)
  18203. (if backward (beginning-of-line) (end-of-line))
  18204. (while (and (> count 0) (funcall search-fn re nil t))
  18205. (let ((element (save-excursion
  18206. (goto-char (match-beginning 0))
  18207. (save-match-data (org-element-at-point)))))
  18208. (when (and (memq (org-element-type element)
  18209. '(center-block comment-block dynamic-block
  18210. example-block export-block quote-block
  18211. special-block src-block verse-block))
  18212. (<= (match-beginning 0)
  18213. (org-element-property :post-affiliated element)))
  18214. (setq last-element element)
  18215. (cl-decf count))))
  18216. (if (= count 0)
  18217. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  18218. (save-match-data (org-show-context)))
  18219. (goto-char origin)
  18220. (user-error "No %s code blocks" (if backward "previous" "further")))))
  18221. (defun org-previous-block (arg &optional block-regexp)
  18222. "Jump to the previous block.
  18223. With a prefix argument ARG, jump backward ARG many source blocks.
  18224. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  18225. (interactive "p")
  18226. (org-next-block arg t block-regexp))
  18227. ;;; Comments
  18228. ;; Org comments syntax is quite complex. It requires the entire line
  18229. ;; to be just a comment. Also, even with the right syntax at the
  18230. ;; beginning of line, some elements (e.g., verse-block or
  18231. ;; example-block) don't accept comments. Usual Emacs comment commands
  18232. ;; cannot cope with those requirements. Therefore, Org replaces them.
  18233. ;; Org still relies on `comment-dwim', but cannot trust
  18234. ;; `comment-only-p'. So, `comment-region-function' and
  18235. ;; `uncomment-region-function' both point
  18236. ;; to`org-comment-or-uncomment-region'. Eventually,
  18237. ;; `org-insert-comment' takes care of insertion of comments at the
  18238. ;; beginning of line.
  18239. ;; `org-setup-comments-handling' install comments related variables
  18240. ;; during `org-mode' initialization.
  18241. (defun org-setup-comments-handling ()
  18242. (interactive)
  18243. (setq-local comment-use-syntax nil)
  18244. (setq-local comment-start "# ")
  18245. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  18246. (setq-local comment-insert-comment-function 'org-insert-comment)
  18247. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  18248. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  18249. (defun org-insert-comment ()
  18250. "Insert an empty comment above current line.
  18251. If the line is empty, insert comment at its beginning. When
  18252. point is within a source block, comment according to the related
  18253. major mode."
  18254. (if (let ((element (org-element-at-point)))
  18255. (and (eq (org-element-type element) 'src-block)
  18256. (< (save-excursion
  18257. (goto-char (org-element-property :post-affiliated element))
  18258. (line-end-position))
  18259. (point))
  18260. (> (save-excursion
  18261. (goto-char (org-element-property :end element))
  18262. (skip-chars-backward " \r\t\n")
  18263. (line-beginning-position))
  18264. (point))))
  18265. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  18266. (beginning-of-line)
  18267. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  18268. (open-line 1))
  18269. (org-indent-line)
  18270. (insert "# ")))
  18271. (defvar comment-empty-lines) ; From newcomment.el.
  18272. (defun org-comment-or-uncomment-region (beg end &rest _)
  18273. "Comment or uncomment each non-blank line in the region.
  18274. Uncomment each non-blank line between BEG and END if it only
  18275. contains commented lines. Otherwise, comment them. If region is
  18276. strictly within a source block, use appropriate comment syntax."
  18277. (if (let ((element (org-element-at-point)))
  18278. (and (eq (org-element-type element) 'src-block)
  18279. (< (save-excursion
  18280. (goto-char (org-element-property :post-affiliated element))
  18281. (line-end-position))
  18282. beg)
  18283. (>= (save-excursion
  18284. (goto-char (org-element-property :end element))
  18285. (skip-chars-backward " \r\t\n")
  18286. (line-beginning-position))
  18287. end)))
  18288. ;; Translate region boundaries for the Org buffer to the source
  18289. ;; buffer.
  18290. (let ((offset (- end beg)))
  18291. (save-excursion
  18292. (goto-char beg)
  18293. (org-babel-do-in-edit-buffer
  18294. (comment-or-uncomment-region (point) (+ offset (point))))))
  18295. (save-restriction
  18296. ;; Restrict region
  18297. (narrow-to-region (save-excursion (goto-char beg)
  18298. (skip-chars-forward " \r\t\n" end)
  18299. (line-beginning-position))
  18300. (save-excursion (goto-char end)
  18301. (skip-chars-backward " \r\t\n" beg)
  18302. (line-end-position)))
  18303. (let ((uncommentp
  18304. ;; UNCOMMENTP is non-nil when every non blank line between
  18305. ;; BEG and END is a comment.
  18306. (save-excursion
  18307. (goto-char (point-min))
  18308. (while (and (not (eobp))
  18309. (let ((element (org-element-at-point)))
  18310. (and (eq (org-element-type element) 'comment)
  18311. (goto-char (min (point-max)
  18312. (org-element-property
  18313. :end element)))))))
  18314. (eobp))))
  18315. (if uncommentp
  18316. ;; Only blank lines and comments in region: uncomment it.
  18317. (save-excursion
  18318. (goto-char (point-min))
  18319. (while (not (eobp))
  18320. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  18321. (replace-match "" nil nil nil 1))
  18322. (forward-line)))
  18323. ;; Comment each line in region.
  18324. (let ((min-indent (point-max)))
  18325. ;; First find the minimum indentation across all lines.
  18326. (save-excursion
  18327. (goto-char (point-min))
  18328. (while (and (not (eobp)) (not (zerop min-indent)))
  18329. (unless (looking-at "[ \t]*$")
  18330. (setq min-indent (min min-indent (current-indentation))))
  18331. (forward-line)))
  18332. ;; Then loop over all lines.
  18333. (save-excursion
  18334. (goto-char (point-min))
  18335. (while (not (eobp))
  18336. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  18337. ;; Don't get fooled by invisible text (e.g. link path)
  18338. ;; when moving to column MIN-INDENT.
  18339. (let ((buffer-invisibility-spec nil))
  18340. (org-move-to-column min-indent t))
  18341. (insert comment-start))
  18342. (forward-line)))))))))
  18343. (defun org-comment-dwim (_arg)
  18344. "Call the comment command you mean.
  18345. Call `org-toggle-comment' if on a heading, otherwise call
  18346. `comment-dwim', within a source edit buffer if needed."
  18347. (interactive "*P")
  18348. (cond ((org-at-heading-p)
  18349. (call-interactively #'org-toggle-comment))
  18350. ((org-in-src-block-p)
  18351. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  18352. (t (call-interactively #'comment-dwim))))
  18353. ;;; Timestamps API
  18354. ;; This section contains tools to operate on, or create, timestamp
  18355. ;; objects, as returned by, e.g. `org-element-context'.
  18356. (defun org-timestamp-from-string (s)
  18357. "Convert Org timestamp S, as a string, into a timestamp object.
  18358. Return nil if S is not a valid timestamp string."
  18359. (when (org-string-nw-p s)
  18360. (with-temp-buffer
  18361. (save-excursion (insert s))
  18362. (org-element-timestamp-parser))))
  18363. (defun org-timestamp-from-time (time &optional with-time inactive)
  18364. "Convert a time value into a timestamp object.
  18365. TIME is an Emacs internal time representation, as returned, e.g.,
  18366. by `current-time'.
  18367. When optional argument WITH-TIME is non-nil, return a timestamp
  18368. object with a time part, i.e., with hours and minutes.
  18369. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  18370. return an active timestamp."
  18371. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  18372. (org-element-create 'timestamp
  18373. (list :type (if inactive 'inactive 'active)
  18374. :year-start year
  18375. :month-start month
  18376. :day-start day
  18377. :hour-start (and with-time hour)
  18378. :minute-start (and with-time minute)))))
  18379. (defun org-timestamp-to-time (timestamp &optional end)
  18380. "Convert TIMESTAMP object into an Emacs internal time value.
  18381. Use end of date range or time range when END is non-nil.
  18382. Otherwise, use its start."
  18383. (apply #'encode-time
  18384. (cons 0
  18385. (mapcar
  18386. (lambda (prop) (or (org-element-property prop timestamp) 0))
  18387. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  18388. '(:minute-start :hour-start :day-start :month-start
  18389. :year-start))))))
  18390. (defun org-timestamp-has-time-p (timestamp)
  18391. "Non-nil when TIMESTAMP has a time specified."
  18392. (org-element-property :hour-start timestamp))
  18393. (defun org-timestamp-format (timestamp format &optional end utc)
  18394. "Format a TIMESTAMP object into a string.
  18395. FORMAT is a format specifier to be passed to
  18396. `format-time-string'.
  18397. When optional argument END is non-nil, use end of date-range or
  18398. time-range, if possible.
  18399. When optional argument UTC is non-nil, time is be expressed as
  18400. Universal Time."
  18401. (format-time-string format (org-timestamp-to-time timestamp end)
  18402. (and utc t)))
  18403. (defun org-timestamp-split-range (timestamp &optional end)
  18404. "Extract a TIMESTAMP object from a date or time range.
  18405. END, when non-nil, means extract the end of the range.
  18406. Otherwise, extract its start.
  18407. Return a new timestamp object."
  18408. (let ((type (org-element-property :type timestamp)))
  18409. (if (memq type '(active inactive diary)) timestamp
  18410. (let ((split-ts (org-element-copy timestamp)))
  18411. ;; Set new type.
  18412. (org-element-put-property
  18413. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  18414. ;; Copy start properties over end properties if END is
  18415. ;; non-nil. Otherwise, copy end properties over `start' ones.
  18416. (let ((p-alist '((:minute-start . :minute-end)
  18417. (:hour-start . :hour-end)
  18418. (:day-start . :day-end)
  18419. (:month-start . :month-end)
  18420. (:year-start . :year-end))))
  18421. (dolist (p-cell p-alist)
  18422. (org-element-put-property
  18423. split-ts
  18424. (funcall (if end #'car #'cdr) p-cell)
  18425. (org-element-property
  18426. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  18427. ;; Eventually refresh `:raw-value'.
  18428. (org-element-put-property split-ts :raw-value nil)
  18429. (org-element-put-property
  18430. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  18431. (defun org-timestamp-translate (timestamp &optional boundary)
  18432. "Translate TIMESTAMP object to custom format.
  18433. Format string is defined in `org-time-stamp-custom-formats',
  18434. which see.
  18435. When optional argument BOUNDARY is non-nil, it is either the
  18436. symbol `start' or `end'. In this case, only translate the
  18437. starting or ending part of TIMESTAMP if it is a date or time
  18438. range. Otherwise, translate both parts.
  18439. Return timestamp as-is if `org-display-custom-times' is nil or if
  18440. it has a `diary' type."
  18441. (let ((type (org-element-property :type timestamp)))
  18442. (if (or (not org-display-custom-times) (eq type 'diary))
  18443. (org-element-interpret-data timestamp)
  18444. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  18445. org-time-stamp-custom-formats)))
  18446. (if (and (not boundary) (memq type '(active-range inactive-range)))
  18447. (concat (org-timestamp-format timestamp fmt)
  18448. "--"
  18449. (org-timestamp-format timestamp fmt t))
  18450. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  18451. ;;; Other stuff
  18452. (defvar reftex-docstruct-symbol)
  18453. (defvar org--rds)
  18454. (defun org-reftex-citation ()
  18455. "Use reftex-citation to insert a citation into the buffer.
  18456. This looks for a line like
  18457. #+BIBLIOGRAPHY: foo plain option:-d
  18458. and derives from it that foo.bib is the bibliography file relevant
  18459. for this document. It then installs the necessary environment for RefTeX
  18460. to work in this buffer and calls `reftex-citation' to insert a citation
  18461. into the buffer.
  18462. Export of such citations to both LaTeX and HTML is handled by the contributed
  18463. package ox-bibtex by Taru Karttunen."
  18464. (interactive)
  18465. (let ((reftex-docstruct-symbol 'org--rds)
  18466. org--rds bib)
  18467. (org-with-wide-buffer
  18468. (let ((case-fold-search t)
  18469. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  18470. (if (not (save-excursion
  18471. (or (re-search-forward re nil t)
  18472. (re-search-backward re nil t))))
  18473. (user-error "No bibliography defined in file")
  18474. (setq bib (concat (match-string 1) ".bib")
  18475. org--rds (list (list 'bib bib))))))
  18476. (call-interactively 'reftex-citation)))
  18477. ;;;; Functions extending outline functionality
  18478. (defun org-beginning-of-line (&optional n)
  18479. "Go to the beginning of the current visible line.
  18480. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18481. symbol `reversed', on the first attempt move to where the
  18482. headline text starts, and only move to beginning of line when the
  18483. cursor is already before the start of the text of the headline.
  18484. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  18485. start of the text on the second attempt.
  18486. With argument N not nil or 1, move forward N - 1 lines first."
  18487. (interactive "^p")
  18488. (let ((origin (point))
  18489. (special (pcase org-special-ctrl-a/e
  18490. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  18491. deactivate-mark)
  18492. ;; First move to a visible line.
  18493. (if (bound-and-true-p visual-line-mode)
  18494. (beginning-of-visual-line n)
  18495. (move-beginning-of-line n)
  18496. ;; `move-beginning-of-line' may leave point after invisible
  18497. ;; characters if line starts with such of these (e.g., with
  18498. ;; a link at column 0). Really move to the beginning of the
  18499. ;; current visible line.
  18500. (beginning-of-line))
  18501. (cond
  18502. ;; No special behavior. Point is already at the beginning of
  18503. ;; a line, logical or visual.
  18504. ((not special))
  18505. ;; `beginning-of-visual-line' left point before logical beginning
  18506. ;; of line: point is at the beginning of a visual line. Bail
  18507. ;; out.
  18508. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  18509. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  18510. ;; At a headline, special position is before the title, but
  18511. ;; after any TODO keyword or priority cookie.
  18512. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  18513. (line-end-position)))
  18514. (bol (point)))
  18515. (if (eq special 'reversed)
  18516. (when (and (= origin bol) (eq last-command this-command))
  18517. (goto-char refpos))
  18518. (when (or (> origin refpos) (= origin bol))
  18519. (goto-char refpos)))))
  18520. ((and (looking-at org-list-full-item-re)
  18521. (memq (org-element-type (save-match-data (org-element-at-point)))
  18522. '(item plain-list)))
  18523. ;; Set special position at first white space character after
  18524. ;; bullet, and check-box, if any.
  18525. (let ((after-bullet
  18526. (let ((box (match-end 3)))
  18527. (cond ((not box) (match-end 1))
  18528. ((eq (char-after box) ?\s) (1+ box))
  18529. (t box)))))
  18530. (if (eq special 'reversed)
  18531. (when (and (= (point) origin) (eq last-command this-command))
  18532. (goto-char after-bullet))
  18533. (when (or (> origin after-bullet) (= (point) origin))
  18534. (goto-char after-bullet)))))
  18535. ;; No special context. Point is already at beginning of line.
  18536. (t nil))))
  18537. (defun org-end-of-line (&optional n)
  18538. "Go to the end of the line, but before ellipsis, if any.
  18539. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18540. symbol `reversed', ignore tags on the first attempt, and only
  18541. move to after the tags when the cursor is already beyond the end
  18542. of the headline.
  18543. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  18544. on the second attempt.
  18545. With argument N not nil or 1, move forward N - 1 lines first."
  18546. (interactive "^p")
  18547. (let ((origin (point))
  18548. (special (pcase org-special-ctrl-a/e
  18549. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  18550. deactivate-mark)
  18551. ;; First move to a visible line.
  18552. (if (bound-and-true-p visual-line-mode)
  18553. (beginning-of-visual-line n)
  18554. (move-beginning-of-line n))
  18555. (cond
  18556. ;; At a headline, with tags.
  18557. ((and special
  18558. (save-excursion
  18559. (beginning-of-line)
  18560. (let ((case-fold-search nil))
  18561. (looking-at org-complex-heading-regexp)))
  18562. (match-end 5))
  18563. (let ((tags (save-excursion
  18564. (goto-char (match-beginning 5))
  18565. (skip-chars-backward " \t")
  18566. (point)))
  18567. (visual-end (and (bound-and-true-p visual-line-mode)
  18568. (save-excursion
  18569. (end-of-visual-line)
  18570. (point)))))
  18571. ;; If `end-of-visual-line' brings us before end of line or
  18572. ;; even tags, i.e., the headline spans over multiple visual
  18573. ;; lines, move there.
  18574. (cond ((and visual-end
  18575. (< visual-end tags)
  18576. (<= origin visual-end))
  18577. (goto-char visual-end))
  18578. ((eq special 'reversed)
  18579. (if (and (= origin (line-end-position))
  18580. (eq this-command last-command))
  18581. (goto-char tags)
  18582. (end-of-line)))
  18583. (t
  18584. (if (or (< origin tags) (= origin (line-end-position)))
  18585. (goto-char tags)
  18586. (end-of-line))))))
  18587. ((bound-and-true-p visual-line-mode)
  18588. (let ((bol (line-beginning-position)))
  18589. (end-of-visual-line)
  18590. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18591. ;; end of a line, backtrack and use `end-of-line' instead.
  18592. (when (/= bol (line-beginning-position))
  18593. (goto-char bol)
  18594. (end-of-line))))
  18595. (t (end-of-line)))))
  18596. (defun org-backward-sentence (&optional _arg)
  18597. "Go to beginning of sentence, or beginning of table field.
  18598. This will call `backward-sentence' or `org-table-beginning-of-field',
  18599. depending on context."
  18600. (interactive)
  18601. (let* ((element (org-element-at-point))
  18602. (contents-begin (org-element-property :contents-begin element))
  18603. (table (org-element-lineage element '(table) t)))
  18604. (if (and table
  18605. (> (point) contents-begin)
  18606. (<= (point) (org-element-property :contents-end table)))
  18607. (call-interactively #'org-table-beginning-of-field)
  18608. (save-restriction
  18609. (when (and contents-begin
  18610. (< (point-min) contents-begin)
  18611. (> (point) contents-begin))
  18612. (narrow-to-region contents-begin
  18613. (org-element-property :contents-end element)))
  18614. (call-interactively #'backward-sentence)))))
  18615. (defun org-forward-sentence (&optional _arg)
  18616. "Go to end of sentence, or end of table field.
  18617. This will call `forward-sentence' or `org-table-end-of-field',
  18618. depending on context."
  18619. (interactive)
  18620. (if (and (org-at-heading-p)
  18621. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18622. (save-restriction
  18623. (narrow-to-region (line-beginning-position) (line-end-position))
  18624. (call-interactively #'forward-sentence))
  18625. (let* ((element (org-element-at-point))
  18626. (contents-end (org-element-property :contents-end element))
  18627. (table (org-element-lineage element '(table) t)))
  18628. (if (and table
  18629. (>= (point) (org-element-property :contents-begin table))
  18630. (< (point) contents-end))
  18631. (call-interactively #'org-table-end-of-field)
  18632. (save-restriction
  18633. (when (and contents-end
  18634. (> (point-max) contents-end)
  18635. ;; Skip blank lines between elements.
  18636. (< (org-element-property :end element)
  18637. (save-excursion (goto-char contents-end)
  18638. (skip-chars-forward " \r\t\n"))))
  18639. (narrow-to-region (org-element-property :contents-begin element)
  18640. contents-end))
  18641. ;; End of heading is considered as the end of a sentence.
  18642. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18643. (call-interactively #'forward-sentence)))))))
  18644. (defun org-kill-line (&optional _arg)
  18645. "Kill line, to tags or end of line."
  18646. (interactive)
  18647. (cond
  18648. ((or (not org-special-ctrl-k)
  18649. (bolp)
  18650. (not (org-at-heading-p)))
  18651. (when (and (get-char-property (line-end-position) 'invisible)
  18652. org-ctrl-k-protect-subtree
  18653. (or (eq org-ctrl-k-protect-subtree 'error)
  18654. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18655. (user-error
  18656. (substitute-command-keys
  18657. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18658. (call-interactively
  18659. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18660. ((org-match-line org-tag-line-re)
  18661. (let ((end (save-excursion
  18662. (goto-char (match-beginning 1))
  18663. (skip-chars-backward " \t")
  18664. (point))))
  18665. (if (<= end (point)) ;on tags part
  18666. (kill-region (point) (line-end-position))
  18667. (kill-region (point) end)))
  18668. (org-align-tags))
  18669. (t (kill-region (point) (line-end-position)))))
  18670. (defun org-yank (&optional arg)
  18671. "Yank. If the kill is a subtree, treat it specially.
  18672. This command will look at the current kill and check if is a single
  18673. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18674. cursor is at the beginning of a line or after the stars of a currently
  18675. empty headline, then the yank is handled specially. How exactly depends
  18676. on the value of the following variables.
  18677. `org-yank-folded-subtrees'
  18678. By default, this variable is non-nil, which results in
  18679. subtree(s) being folded after insertion, except if doing so
  18680. would swallow text after the yanked text.
  18681. `org-yank-adjusted-subtrees'
  18682. When non-nil (the default value is nil), the subtree will be
  18683. promoted or demoted in order to fit into the local outline tree
  18684. structure, which means that the level will be adjusted so that it
  18685. becomes the smaller one of the two *visible* surrounding headings.
  18686. Any prefix to this command will cause `yank' to be called directly with
  18687. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18688. will just
  18689. plainly yank the text as it is.
  18690. \[1] The test checks if the first non-white line is a heading
  18691. and if there are no other headings with fewer stars."
  18692. (interactive "P")
  18693. (org-yank-generic 'yank arg))
  18694. (defun org-yank-generic (command arg)
  18695. "Perform some yank-like command.
  18696. This function implements the behavior described in the `org-yank'
  18697. documentation. However, it has been generalized to work for any
  18698. interactive command with similar behavior."
  18699. ;; pretend to be command COMMAND
  18700. (setq this-command command)
  18701. (if arg
  18702. (call-interactively command)
  18703. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18704. (and (org-kill-is-subtree-p)
  18705. (or (bolp)
  18706. (and (looking-at "[ \t]*$")
  18707. (string-match
  18708. "\\`\\*+\\'"
  18709. (buffer-substring (point-at-bol) (point)))))))
  18710. swallowp)
  18711. (cond
  18712. ((and subtreep org-yank-folded-subtrees)
  18713. (let ((beg (point))
  18714. end)
  18715. (if (and subtreep org-yank-adjusted-subtrees)
  18716. (org-paste-subtree nil nil 'for-yank)
  18717. (call-interactively command))
  18718. (setq end (point))
  18719. (goto-char beg)
  18720. (when (and (bolp) subtreep
  18721. (not (setq swallowp
  18722. (org-yank-folding-would-swallow-text beg end))))
  18723. (org-with-limited-levels
  18724. (or (looking-at org-outline-regexp)
  18725. (re-search-forward org-outline-regexp-bol end t))
  18726. (while (and (< (point) end) (looking-at org-outline-regexp))
  18727. (outline-hide-subtree)
  18728. (org-cycle-show-empty-lines 'folded)
  18729. (condition-case nil
  18730. (outline-forward-same-level 1)
  18731. (error (goto-char end))))))
  18732. (when swallowp
  18733. (message
  18734. "Inserted text not folded because that would swallow text"))
  18735. (goto-char end)
  18736. (skip-chars-forward " \t\n\r")
  18737. (beginning-of-line 1)
  18738. (push-mark beg 'nomsg)))
  18739. ((and subtreep org-yank-adjusted-subtrees)
  18740. (let ((beg (point-at-bol)))
  18741. (org-paste-subtree nil nil 'for-yank)
  18742. (push-mark beg 'nomsg)))
  18743. (t
  18744. (call-interactively command))))))
  18745. (defun org-yank-folding-would-swallow-text (beg end)
  18746. "Would hide-subtree at BEG swallow any text after END?"
  18747. (let (level)
  18748. (org-with-limited-levels
  18749. (save-excursion
  18750. (goto-char beg)
  18751. (when (or (looking-at org-outline-regexp)
  18752. (re-search-forward org-outline-regexp-bol end t))
  18753. (setq level (org-outline-level)))
  18754. (goto-char end)
  18755. (skip-chars-forward " \t\r\n\v\f")
  18756. (not (or (eobp)
  18757. (and (bolp) (looking-at-p org-outline-regexp)
  18758. (<= (org-outline-level) level))))))))
  18759. (defun org-back-to-heading (&optional invisible-ok)
  18760. "Call `outline-back-to-heading', but provide a better error message."
  18761. (condition-case nil
  18762. (outline-back-to-heading invisible-ok)
  18763. (error (error "Before first headline at position %d in buffer %s"
  18764. (point) (current-buffer)))))
  18765. (defun org-before-first-heading-p ()
  18766. "Before first heading?"
  18767. (org-with-limited-levels
  18768. (save-excursion
  18769. (end-of-line)
  18770. (null (re-search-backward org-outline-regexp-bol nil t)))))
  18771. (defun org-at-heading-p (&optional _)
  18772. "Non-nil when on a headline."
  18773. (outline-on-heading-p t))
  18774. (defun org-in-commented-heading-p (&optional no-inheritance)
  18775. "Non-nil if point is under a commented heading.
  18776. This function also checks ancestors of the current headline,
  18777. unless optional argument NO-INHERITANCE is non-nil."
  18778. (cond
  18779. ((org-before-first-heading-p) nil)
  18780. ((let ((headline (nth 4 (org-heading-components))))
  18781. (and headline
  18782. (let ((case-fold-search nil))
  18783. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  18784. headline)))))
  18785. (no-inheritance nil)
  18786. (t
  18787. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  18788. (defun org-at-comment-p nil
  18789. "Is cursor in a commented line?"
  18790. (save-excursion
  18791. (save-match-data
  18792. (beginning-of-line)
  18793. (looking-at "^[ \t]*# "))))
  18794. (defun org-at-drawer-p nil
  18795. "Is cursor at a drawer keyword?"
  18796. (save-excursion
  18797. (move-beginning-of-line 1)
  18798. (looking-at org-drawer-regexp)))
  18799. (defun org-at-block-p nil
  18800. "Is cursor at a block keyword?"
  18801. (save-excursion
  18802. (move-beginning-of-line 1)
  18803. (looking-at org-block-regexp)))
  18804. (defun org-point-at-end-of-empty-headline ()
  18805. "If point is at the end of an empty headline, return t, else nil.
  18806. If the heading only contains a TODO keyword, it is still still considered
  18807. empty."
  18808. (let ((case-fold-search nil))
  18809. (and (looking-at "[ \t]*$")
  18810. org-todo-line-regexp
  18811. (save-excursion
  18812. (beginning-of-line)
  18813. (looking-at org-todo-line-regexp)
  18814. (string= (match-string 3) "")))))
  18815. (defun org-at-heading-or-item-p ()
  18816. (or (org-at-heading-p) (org-at-item-p)))
  18817. (defun org-up-heading-all (arg)
  18818. "Move to the heading line of which the present line is a subheading.
  18819. This function considers both visible and invisible heading lines.
  18820. With argument, move up ARG levels."
  18821. (outline-up-heading arg t))
  18822. (defun org-up-heading-safe ()
  18823. "Move to the heading line of which the present line is a subheading.
  18824. This version will not throw an error. It will return the level of the
  18825. headline found, or nil if no higher level is found.
  18826. Also, this function will be a lot faster than `outline-up-heading',
  18827. because it relies on stars being the outline starters. This can really
  18828. make a significant difference in outlines with very many siblings."
  18829. (when (ignore-errors (org-back-to-heading t))
  18830. (let ((level-up (1- (funcall outline-level))))
  18831. (and (> level-up 0)
  18832. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  18833. (funcall outline-level)))))
  18834. (defun org-first-sibling-p ()
  18835. "Is this heading the first child of its parents?"
  18836. (interactive)
  18837. (let ((re org-outline-regexp-bol)
  18838. level l)
  18839. (unless (org-at-heading-p t)
  18840. (user-error "Not at a heading"))
  18841. (setq level (funcall outline-level))
  18842. (save-excursion
  18843. (if (not (re-search-backward re nil t))
  18844. t
  18845. (setq l (funcall outline-level))
  18846. (< l level)))))
  18847. (defun org-goto-sibling (&optional previous)
  18848. "Goto the next sibling, even if it is invisible.
  18849. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18850. when a sibling was found. When none is found, return nil and don't
  18851. move point."
  18852. (let ((fun (if previous 're-search-backward 're-search-forward))
  18853. (pos (point))
  18854. (re org-outline-regexp-bol)
  18855. level l)
  18856. (when (ignore-errors (org-back-to-heading t))
  18857. (setq level (funcall outline-level))
  18858. (catch 'exit
  18859. (or previous (forward-char 1))
  18860. (while (funcall fun re nil t)
  18861. (setq l (funcall outline-level))
  18862. (when (< l level) (goto-char pos) (throw 'exit nil))
  18863. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18864. (goto-char pos)
  18865. nil))))
  18866. (defun org-show-siblings ()
  18867. "Show all siblings of the current headline."
  18868. (save-excursion
  18869. (while (org-goto-sibling) (org-flag-heading nil)))
  18870. (save-excursion
  18871. (while (org-goto-sibling 'previous)
  18872. (org-flag-heading nil))))
  18873. (defun org-goto-first-child ()
  18874. "Goto the first child, even if it is invisible.
  18875. Return t when a child was found. Otherwise don't move point and
  18876. return nil."
  18877. (let (level (pos (point)) (re org-outline-regexp-bol))
  18878. (when (ignore-errors (org-back-to-heading t))
  18879. (setq level (outline-level))
  18880. (forward-char 1)
  18881. (if (and (re-search-forward re nil t) (> (outline-level) level))
  18882. (progn (goto-char (match-beginning 0)) t)
  18883. (goto-char pos) nil))))
  18884. (defun org-show-hidden-entry ()
  18885. "Show an entry where even the heading is hidden."
  18886. (save-excursion
  18887. (org-show-entry)))
  18888. (defun org-flag-heading (flag &optional entry)
  18889. "Flag the current heading. FLAG non-nil means make invisible.
  18890. When ENTRY is non-nil, show the entire entry."
  18891. (save-excursion
  18892. (org-back-to-heading t)
  18893. ;; Check if we should show the entire entry
  18894. (if (not entry)
  18895. (org-flag-region
  18896. (line-end-position 0) (line-end-position) flag 'outline)
  18897. (org-show-entry)
  18898. (save-excursion
  18899. (and (outline-next-heading)
  18900. (org-flag-heading nil))))))
  18901. (defun org-get-next-sibling ()
  18902. "Move to next heading of the same level, and return point.
  18903. If there is no such heading, return nil.
  18904. This is like outline-next-sibling, but invisible headings are ok."
  18905. (let ((level (funcall outline-level)))
  18906. (outline-next-heading)
  18907. (while (and (not (eobp)) (> (funcall outline-level) level))
  18908. (outline-next-heading))
  18909. (unless (or (eobp) (< (funcall outline-level) level))
  18910. (point))))
  18911. (defun org-get-last-sibling ()
  18912. "Move to previous heading of the same level, and return point.
  18913. If there is no such heading, return nil."
  18914. (let ((opoint (point))
  18915. (level (funcall outline-level)))
  18916. (outline-previous-heading)
  18917. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18918. (while (and (> (funcall outline-level) level)
  18919. (not (bobp)))
  18920. (outline-previous-heading))
  18921. (unless (< (funcall outline-level) level)
  18922. (point)))))
  18923. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  18924. "Goto to the end of a subtree."
  18925. ;; This contains an exact copy of the original function, but it uses
  18926. ;; `org-back-to-heading', to make it work also in invisible
  18927. ;; trees. And is uses an invisible-ok argument.
  18928. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18929. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18930. ;; with many children and grandchildren etc, this can be much faster
  18931. ;; than the outline version.
  18932. (org-back-to-heading invisible-ok)
  18933. (let ((first t)
  18934. (level (funcall outline-level)))
  18935. (if (and (derived-mode-p 'org-mode) (< level 1000))
  18936. ;; A true heading (not a plain list item), in Org
  18937. ;; This means we can easily find the end by looking
  18938. ;; only for the right number of stars. Using a regexp to do
  18939. ;; this is so much faster than using a Lisp loop.
  18940. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  18941. (forward-char 1)
  18942. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  18943. ;; something else, do it the slow way
  18944. (while (and (not (eobp))
  18945. (or first (> (funcall outline-level) level)))
  18946. (setq first nil)
  18947. (outline-next-heading)))
  18948. (unless to-heading
  18949. (when (memq (preceding-char) '(?\n ?\^M))
  18950. ;; Go to end of line before heading
  18951. (forward-char -1)
  18952. (when (memq (preceding-char) '(?\n ?\^M))
  18953. ;; leave blank line before heading
  18954. (forward-char -1)))))
  18955. (point))
  18956. (defun org-end-of-meta-data (&optional full)
  18957. "Skip planning line and properties drawer in current entry.
  18958. When optional argument FULL is non-nil, also skip empty lines,
  18959. clocking lines and regular drawers at the beginning of the
  18960. entry."
  18961. (org-back-to-heading t)
  18962. (forward-line)
  18963. (when (looking-at-p org-planning-line-re) (forward-line))
  18964. (when (looking-at org-property-drawer-re)
  18965. (goto-char (match-end 0))
  18966. (forward-line))
  18967. (when (and full (not (org-at-heading-p)))
  18968. (catch 'exit
  18969. (let ((end (save-excursion (outline-next-heading) (point)))
  18970. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  18971. (while (not (eobp))
  18972. (cond ((looking-at-p org-drawer-regexp)
  18973. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18974. (forward-line)
  18975. (throw 'exit t)))
  18976. ((looking-at-p re) (forward-line))
  18977. (t (throw 'exit t))))))))
  18978. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  18979. "Move forward to the ARG'th subheading at same level as this one.
  18980. Stop at the first and last subheadings of a superior heading.
  18981. Normally this only looks at visible headings, but when INVISIBLE-OK is
  18982. non-nil it will also look at invisible ones."
  18983. (interactive "p")
  18984. (let ((backward? (and arg (< arg 0))))
  18985. (if (org-before-first-heading-p)
  18986. (if backward? (goto-char (point-min)) (outline-next-heading))
  18987. (org-back-to-heading invisible-ok)
  18988. (unless backward? (end-of-line)) ;do not match current headline
  18989. (let ((level (- (match-end 0) (match-beginning 0) 1))
  18990. (f (if backward? #'re-search-backward #'re-search-forward))
  18991. (count (if arg (abs arg) 1))
  18992. (result (point)))
  18993. (while (and (> count 0)
  18994. (funcall f org-outline-regexp-bol nil 'move))
  18995. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  18996. (cond ((< l level) (setq count 0))
  18997. ((and (= l level)
  18998. (or invisible-ok
  18999. (not (org-invisible-p
  19000. (line-beginning-position)))))
  19001. (cl-decf count)
  19002. (when (= l level) (setq result (point)))))))
  19003. (goto-char result))
  19004. (beginning-of-line))))
  19005. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  19006. "Move backward to the ARG'th subheading at same level as this one.
  19007. Stop at the first and last subheadings of a superior heading."
  19008. (interactive "p")
  19009. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  19010. (defun org-next-visible-heading (arg)
  19011. "Move to the next visible heading.
  19012. This function wraps `outline-next-visible-heading' with
  19013. `org-with-limited-levels' in order to skip over inline tasks and
  19014. respect customization of `org-odd-levels-only'."
  19015. (interactive "p")
  19016. (org-with-limited-levels
  19017. (outline-next-visible-heading arg)))
  19018. (defun org-previous-visible-heading (arg)
  19019. "Move to the previous visible heading.
  19020. This function wraps `outline-previous-visible-heading' with
  19021. `org-with-limited-levels' in order to skip over inline tasks and
  19022. respect customization of `org-odd-levels-only'."
  19023. (interactive "p")
  19024. (org-with-limited-levels
  19025. (outline-previous-visible-heading arg)))
  19026. (defun org-forward-paragraph ()
  19027. "Move forward to beginning of next paragraph or equivalent.
  19028. The function moves point to the beginning of the next visible
  19029. structural element, which can be a paragraph, a table, a list
  19030. item, etc. It also provides some special moves for convenience:
  19031. - On an affiliated keyword, jump to the beginning of the
  19032. relative element.
  19033. - On an item or a footnote definition, move to the second
  19034. element inside, if any.
  19035. - On a table or a property drawer, jump after it.
  19036. - On a verse or source block, stop after blank lines."
  19037. (interactive)
  19038. (unless (eobp)
  19039. (let* ((deactivate-mark nil)
  19040. (element (org-element-at-point))
  19041. (type (org-element-type element))
  19042. (post-affiliated (org-element-property :post-affiliated element))
  19043. (contents-begin (org-element-property :contents-begin element))
  19044. (contents-end (org-element-property :contents-end element))
  19045. (end (let ((end (org-element-property :end element)) (parent element))
  19046. (while (and (setq parent (org-element-property :parent parent))
  19047. (= (org-element-property :contents-end parent) end))
  19048. (setq end (org-element-property :end parent)))
  19049. end)))
  19050. (cond ((not element)
  19051. (skip-chars-forward " \r\t\n")
  19052. (or (eobp) (beginning-of-line)))
  19053. ;; On affiliated keywords, move to element's beginning.
  19054. ((< (point) post-affiliated)
  19055. (goto-char post-affiliated))
  19056. ;; At a table row, move to the end of the table. Similarly,
  19057. ;; at a node property, move to the end of the property
  19058. ;; drawer.
  19059. ((memq type '(node-property table-row))
  19060. (goto-char (org-element-property
  19061. :end (org-element-property :parent element))))
  19062. ((memq type '(property-drawer table)) (goto-char end))
  19063. ;; Consider blank lines as separators in verse and source
  19064. ;; blocks to ease editing.
  19065. ((memq type '(src-block verse-block))
  19066. (when (eq type 'src-block)
  19067. (setq contents-end
  19068. (save-excursion (goto-char end)
  19069. (skip-chars-backward " \r\t\n")
  19070. (line-beginning-position))))
  19071. (beginning-of-line)
  19072. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  19073. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  19074. (goto-char end)
  19075. (skip-chars-forward " \r\t\n")
  19076. (if (= (point) contents-end) (goto-char end)
  19077. (beginning-of-line))))
  19078. ;; With no contents, just skip element.
  19079. ((not contents-begin) (goto-char end))
  19080. ;; If contents are invisible, skip the element altogether.
  19081. ((org-invisible-p (line-end-position))
  19082. (cl-case type
  19083. (headline
  19084. (org-with-limited-levels (outline-next-visible-heading 1)))
  19085. ;; At a plain list, make sure we move to the next item
  19086. ;; instead of skipping the whole list.
  19087. (plain-list (forward-char)
  19088. (org-forward-paragraph))
  19089. (otherwise (goto-char end))))
  19090. ((>= (point) contents-end) (goto-char end))
  19091. ((>= (point) contents-begin)
  19092. ;; This can only happen on paragraphs and plain lists.
  19093. (cl-case type
  19094. (paragraph (goto-char end))
  19095. ;; At a plain list, try to move to second element in
  19096. ;; first item, if possible.
  19097. (plain-list (end-of-line)
  19098. (org-forward-paragraph))))
  19099. ;; When contents start on the middle of a line (e.g. in
  19100. ;; items and footnote definitions), try to reach first
  19101. ;; element starting after current line.
  19102. ((> (line-end-position) contents-begin)
  19103. (end-of-line)
  19104. (org-forward-paragraph))
  19105. (t (goto-char contents-begin))))))
  19106. (defun org-backward-paragraph ()
  19107. "Move backward to start of previous paragraph or equivalent.
  19108. The function moves point to the beginning of the current
  19109. structural element, which can be a paragraph, a table, a list
  19110. item, etc., or to the beginning of the previous visible one if
  19111. point is already there. It also provides some special moves for
  19112. convenience:
  19113. - On an affiliated keyword, jump to the first one.
  19114. - On a table or a property drawer, move to its beginning.
  19115. - On comment, example, export, src and verse blocks, stop
  19116. before blank lines."
  19117. (interactive)
  19118. (unless (bobp)
  19119. (let* ((deactivate-mark nil)
  19120. (element (org-element-at-point))
  19121. (type (org-element-type element))
  19122. (contents-end (org-element-property :contents-end element))
  19123. (post-affiliated (org-element-property :post-affiliated element))
  19124. (begin (org-element-property :begin element))
  19125. (special? ;blocks handled specially
  19126. (memq type '(comment-block example-block export-block src-block
  19127. verse-block)))
  19128. (contents-begin
  19129. (if special?
  19130. ;; These types have no proper contents. Fake line
  19131. ;; below the block opening line as contents beginning.
  19132. (save-excursion (goto-char begin) (line-beginning-position 2))
  19133. (org-element-property :contents-begin element))))
  19134. (cond
  19135. ((not element) (goto-char (point-min)))
  19136. ((= (point) begin)
  19137. (backward-char)
  19138. (org-backward-paragraph))
  19139. ((<= (point) post-affiliated) (goto-char begin))
  19140. ;; Special behavior: on a table or a property drawer, move to
  19141. ;; its beginning.
  19142. ((memq type '(node-property table-row))
  19143. (goto-char (org-element-property
  19144. :post-affiliated (org-element-property :parent element))))
  19145. (special?
  19146. (if (<= (point) contents-begin) (goto-char post-affiliated)
  19147. ;; Inside a verse block, see blank lines as paragraph
  19148. ;; separators.
  19149. (let ((origin (point)))
  19150. (skip-chars-backward " \r\t\n" contents-begin)
  19151. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  19152. (skip-chars-forward " \r\t\n" origin)
  19153. (if (= (point) origin) (goto-char contents-begin)
  19154. (beginning-of-line))))))
  19155. ((eq type 'paragraph) (goto-char contents-begin)
  19156. ;; When at first paragraph in an item or a footnote definition,
  19157. ;; move directly to beginning of line.
  19158. (let ((parent-contents
  19159. (org-element-property
  19160. :contents-begin (org-element-property :parent element))))
  19161. (when (and parent-contents (= parent-contents contents-begin))
  19162. (beginning-of-line))))
  19163. ;; At the end of a greater element, move to the beginning of
  19164. ;; the last element within.
  19165. ((and contents-end (>= (point) contents-end))
  19166. (goto-char (1- contents-end))
  19167. (org-backward-paragraph))
  19168. (t (goto-char (or post-affiliated begin))))
  19169. ;; Ensure we never leave point invisible.
  19170. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  19171. (defun org-forward-element ()
  19172. "Move forward by one element.
  19173. Move to the next element at the same level, when possible."
  19174. (interactive)
  19175. (cond ((eobp) (user-error "Cannot move further down"))
  19176. ((org-with-limited-levels (org-at-heading-p))
  19177. (let ((origin (point)))
  19178. (goto-char (org-end-of-subtree nil t))
  19179. (unless (org-with-limited-levels (org-at-heading-p))
  19180. (goto-char origin)
  19181. (user-error "Cannot move further down"))))
  19182. (t
  19183. (let* ((elem (org-element-at-point))
  19184. (end (org-element-property :end elem))
  19185. (parent (org-element-property :parent elem)))
  19186. (cond ((and parent (= (org-element-property :contents-end parent) end))
  19187. (goto-char (org-element-property :end parent)))
  19188. ((integer-or-marker-p end) (goto-char end))
  19189. (t (message "No element at point")))))))
  19190. (defun org-backward-element ()
  19191. "Move backward by one element.
  19192. Move to the previous element at the same level, when possible."
  19193. (interactive)
  19194. (cond ((bobp) (user-error "Cannot move further up"))
  19195. ((org-with-limited-levels (org-at-heading-p))
  19196. ;; At a headline, move to the previous one, if any, or stay
  19197. ;; here.
  19198. (let ((origin (point)))
  19199. (org-with-limited-levels (org-backward-heading-same-level 1))
  19200. ;; When current headline has no sibling above, move to its
  19201. ;; parent.
  19202. (when (= (point) origin)
  19203. (or (org-with-limited-levels (org-up-heading-safe))
  19204. (progn (goto-char origin)
  19205. (user-error "Cannot move further up"))))))
  19206. (t
  19207. (let* ((elem (org-element-at-point))
  19208. (beg (org-element-property :begin elem)))
  19209. (cond
  19210. ;; Move to beginning of current element if point isn't
  19211. ;; there already.
  19212. ((null beg) (message "No element at point"))
  19213. ((/= (point) beg) (goto-char beg))
  19214. (t (goto-char beg)
  19215. (skip-chars-backward " \r\t\n")
  19216. (unless (bobp)
  19217. (let ((prev (org-element-at-point)))
  19218. (goto-char (org-element-property :begin prev))
  19219. (while (and (setq prev (org-element-property :parent prev))
  19220. (<= (org-element-property :end prev) beg))
  19221. (goto-char (org-element-property :begin prev)))))))))))
  19222. (defun org-up-element ()
  19223. "Move to upper element."
  19224. (interactive)
  19225. (if (org-with-limited-levels (org-at-heading-p))
  19226. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19227. (let* ((elem (org-element-at-point))
  19228. (parent (org-element-property :parent elem)))
  19229. (if parent (goto-char (org-element-property :begin parent))
  19230. (if (org-with-limited-levels (org-before-first-heading-p))
  19231. (user-error "No surrounding element")
  19232. (org-with-limited-levels (org-back-to-heading)))))))
  19233. (defun org-down-element ()
  19234. "Move to inner element."
  19235. (interactive)
  19236. (let ((element (org-element-at-point)))
  19237. (cond
  19238. ((memq (org-element-type element) '(plain-list table))
  19239. (goto-char (org-element-property :contents-begin element))
  19240. (forward-char))
  19241. ((memq (org-element-type element) org-element-greater-elements)
  19242. ;; If contents are hidden, first disclose them.
  19243. (when (org-invisible-p (line-end-position)) (org-cycle))
  19244. (goto-char (or (org-element-property :contents-begin element)
  19245. (user-error "No content for this element"))))
  19246. (t (user-error "No inner element")))))
  19247. (defun org-drag-element-backward ()
  19248. "Move backward element at point."
  19249. (interactive)
  19250. (let ((elem (or (org-element-at-point)
  19251. (user-error "No element at point"))))
  19252. (if (eq (org-element-type elem) 'headline)
  19253. ;; Preserve point when moving a whole tree, even if point was
  19254. ;; on blank lines below the headline.
  19255. (let ((offset (skip-chars-backward " \t\n")))
  19256. (unwind-protect (org-move-subtree-up)
  19257. (forward-char (- offset))))
  19258. (let ((prev-elem
  19259. (save-excursion
  19260. (goto-char (org-element-property :begin elem))
  19261. (skip-chars-backward " \r\t\n")
  19262. (unless (bobp)
  19263. (let* ((beg (org-element-property :begin elem))
  19264. (prev (org-element-at-point))
  19265. (up prev))
  19266. (while (and (setq up (org-element-property :parent up))
  19267. (<= (org-element-property :end up) beg))
  19268. (setq prev up))
  19269. prev)))))
  19270. ;; Error out if no previous element or previous element is
  19271. ;; a parent of the current one.
  19272. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19273. (user-error "Cannot drag element backward")
  19274. (let ((pos (point)))
  19275. (org-element-swap-A-B prev-elem elem)
  19276. (goto-char (+ (org-element-property :begin prev-elem)
  19277. (- pos (org-element-property :begin elem))))))))))
  19278. (defun org-drag-element-forward ()
  19279. "Move forward element at point."
  19280. (interactive)
  19281. (let* ((pos (point))
  19282. (elem (or (org-element-at-point)
  19283. (user-error "No element at point"))))
  19284. (when (= (point-max) (org-element-property :end elem))
  19285. (user-error "Cannot drag element forward"))
  19286. (goto-char (org-element-property :end elem))
  19287. (let ((next-elem (org-element-at-point)))
  19288. (when (or (org-element-nested-p elem next-elem)
  19289. (and (eq (org-element-type next-elem) 'headline)
  19290. (not (eq (org-element-type elem) 'headline))))
  19291. (goto-char pos)
  19292. (user-error "Cannot drag element forward"))
  19293. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19294. ;; body's length (without final blanks) and by the length of
  19295. ;; blanks between ELEM and NEXT-ELEM.
  19296. (let ((size-next (- (save-excursion
  19297. (goto-char (org-element-property :end next-elem))
  19298. (skip-chars-backward " \r\t\n")
  19299. (forward-line)
  19300. ;; Small correction if buffer doesn't end
  19301. ;; with a newline character.
  19302. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19303. (org-element-property :begin next-elem)))
  19304. (size-blank (- (org-element-property :end elem)
  19305. (save-excursion
  19306. (goto-char (org-element-property :end elem))
  19307. (skip-chars-backward " \r\t\n")
  19308. (forward-line)
  19309. (point)))))
  19310. (org-element-swap-A-B elem next-elem)
  19311. (goto-char (+ pos size-next size-blank))))))
  19312. (defun org-drag-line-forward (arg)
  19313. "Drag the line at point ARG lines forward."
  19314. (interactive "p")
  19315. (dotimes (_ (abs arg))
  19316. (let ((c (current-column)))
  19317. (if (< 0 arg)
  19318. (progn
  19319. (beginning-of-line 2)
  19320. (transpose-lines 1)
  19321. (beginning-of-line 0))
  19322. (transpose-lines 1)
  19323. (beginning-of-line -1))
  19324. (org-move-to-column c))))
  19325. (defun org-drag-line-backward (arg)
  19326. "Drag the line at point ARG lines backward."
  19327. (interactive "p")
  19328. (org-drag-line-forward (- arg)))
  19329. (defun org-mark-element ()
  19330. "Put point at beginning of this element, mark at end.
  19331. Interactively, if this command is repeated or (in Transient Mark
  19332. mode) if the mark is active, it marks the next element after the
  19333. ones already marked."
  19334. (interactive)
  19335. (let (deactivate-mark)
  19336. (if (and (called-interactively-p 'any)
  19337. (or (and (eq last-command this-command) (mark t))
  19338. (and transient-mark-mode mark-active)))
  19339. (set-mark
  19340. (save-excursion
  19341. (goto-char (mark))
  19342. (goto-char (org-element-property :end (org-element-at-point)))))
  19343. (let ((element (org-element-at-point)))
  19344. (end-of-line)
  19345. (push-mark (org-element-property :end element) t t)
  19346. (goto-char (org-element-property :begin element))))))
  19347. (defun org-narrow-to-element ()
  19348. "Narrow buffer to current element."
  19349. (interactive)
  19350. (let ((elem (org-element-at-point)))
  19351. (cond
  19352. ((eq (car elem) 'headline)
  19353. (narrow-to-region
  19354. (org-element-property :begin elem)
  19355. (org-element-property :end elem)))
  19356. ((memq (car elem) org-element-greater-elements)
  19357. (narrow-to-region
  19358. (org-element-property :contents-begin elem)
  19359. (org-element-property :contents-end elem)))
  19360. (t
  19361. (narrow-to-region
  19362. (org-element-property :begin elem)
  19363. (org-element-property :end elem))))))
  19364. (defun org-transpose-element ()
  19365. "Transpose current and previous elements, keeping blank lines between.
  19366. Point is moved after both elements."
  19367. (interactive)
  19368. (org-skip-whitespace)
  19369. (let ((end (org-element-property :end (org-element-at-point))))
  19370. (org-drag-element-backward)
  19371. (goto-char end)))
  19372. (defun org-unindent-buffer ()
  19373. "Un-indent the visible part of the buffer.
  19374. Relative indentation (between items, inside blocks, etc.) isn't
  19375. modified."
  19376. (interactive)
  19377. (unless (eq major-mode 'org-mode)
  19378. (user-error "Cannot un-indent a buffer not in Org mode"))
  19379. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19380. (unindent-tree
  19381. (lambda (contents)
  19382. (dolist (element (reverse contents))
  19383. (if (memq (org-element-type element) '(headline section))
  19384. (funcall unindent-tree (org-element-contents element))
  19385. (save-excursion
  19386. (save-restriction
  19387. (narrow-to-region
  19388. (org-element-property :begin element)
  19389. (org-element-property :end element))
  19390. (org-do-remove-indentation))))))))
  19391. (funcall unindent-tree (org-element-contents parse-tree))))
  19392. (defun org-make-options-regexp (kwds &optional extra)
  19393. "Make a regular expression for keyword lines.
  19394. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19395. when non-nil, is a regexp matching keywords names."
  19396. (concat "^[ \t]*#\\+\\("
  19397. (regexp-opt kwds)
  19398. (and extra (concat (and kwds "\\|") extra))
  19399. "\\):[ \t]*\\(.*\\)"))
  19400. ;;; Conveniently switch to Info nodes
  19401. (defun org-info-find-node (&optional nodename)
  19402. "Find Info documentation NODENAME or Org documentation according context.
  19403. Started from `gnus-info-find-node'."
  19404. (interactive)
  19405. (Info-goto-node
  19406. (or nodename
  19407. (let ((default-org-info-node "(org) Top"))
  19408. (cond
  19409. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19410. ((eq 'org-mode major-mode)
  19411. (let* ((context (org-element-at-point))
  19412. (element-info-nodes ; compare to `org-element-all-elements'.
  19413. `((babel-call . "(org) Evaluating Code Blocks")
  19414. (center-block . "(org) Paragraphs")
  19415. (clock . ,default-org-info-node)
  19416. (comment . "(org) Comment Lines")
  19417. (comment-block . "(org) Comment Lines")
  19418. (diary-sexp . ,default-org-info-node)
  19419. (drawer . "(org) Drawers")
  19420. (dynamic-block . "(org) Dynamic Blocks")
  19421. (example-block . "(org) Literal Examples")
  19422. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19423. (fixed-width . ,default-org-info-node)
  19424. (footnote-definition . "(org) Creating Footnotes")
  19425. (headline . "(org) Document Structure")
  19426. (horizontal-rule . "(org) Built-in Table Editor")
  19427. (inlinetask . ,default-org-info-node)
  19428. (item . "(org) Plain Lists")
  19429. (keyword . "(org) Per-file keywords")
  19430. (latex-environment . "(org) LaTeX Export")
  19431. (node-property . "(org) Properties and Columns")
  19432. (paragraph . "(org) Paragraphs")
  19433. (plain-list . "(org) Plain Lists")
  19434. (planning . "(org) Deadlines and Scheduling")
  19435. (property-drawer . "(org) Properties and Columns")
  19436. (quote-block . "(org) Paragraphs")
  19437. (section . ,default-org-info-node)
  19438. (special-block . ,default-org-info-node)
  19439. (src-block . "(org) Working with Source Code")
  19440. (table . "(org) Tables")
  19441. (table-row . "(org) Tables")
  19442. (verse-block . "(org) Paragraphs"))))
  19443. (or (cdr (assoc (car context) element-info-nodes))
  19444. default-org-info-node)))
  19445. (t default-org-info-node))))))
  19446. ;;; Finish up
  19447. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  19448. (lambda () (add-hook 'change-major-mode-hook
  19449. 'org-show-all 'append 'local)))
  19450. (provide 'org)
  19451. (run-hooks 'org-load-hook)
  19452. ;;; org.el ends here