org.el 801 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218
  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-2020 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Bastien Guerry <bzg@gnu.org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: https://orgmode.org
  9. ;; Version: 9.4
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  26. ;; project planning with a fast and effective plain-text system.
  27. ;;
  28. ;; Org mode develops organizational tasks around NOTES files that
  29. ;; contain information about projects as plain text. Org mode is
  30. ;; implemented on top of outline-mode, which makes it possible to keep
  31. ;; the content of large files well structured. Visibility cycling and
  32. ;; structure editing help to work with the tree. Tables are easily
  33. ;; created with a built-in table editor. Org mode supports ToDo
  34. ;; items, deadlines, time stamps, and scheduling. It dynamically
  35. ;; compiles entries into an agenda that utilizes and smoothly
  36. ;; integrates much of the Emacs calendar and diary. Plain text
  37. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  38. ;; entries, and any files related to the projects. For printing and
  39. ;; sharing of notes, an Org file can be exported as a structured ASCII
  40. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  41. ;; file. It can also serve as a publishing tool for a set of linked
  42. ;; webpages.
  43. ;;
  44. ;; Installation and Activation
  45. ;; ---------------------------
  46. ;; See the corresponding sections in the manual at
  47. ;;
  48. ;; https://orgmode.org/org.html#Installation
  49. ;;
  50. ;; Documentation
  51. ;; -------------
  52. ;; The documentation of Org mode can be found in the TeXInfo file. The
  53. ;; distribution also contains a PDF version of it. At the homepage of
  54. ;; Org mode, you can read the same text online as HTML. There is also an
  55. ;; excellent reference card made by Philip Rooke. This card can be found
  56. ;; in the doc/ directory.
  57. ;;
  58. ;; A list of recent changes can be found at
  59. ;; https://orgmode.org/Changes.html
  60. ;;
  61. ;;; Code:
  62. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  63. (defvar org-inlinetask-min-level)
  64. ;;;; Require other packages
  65. (require 'cl-lib)
  66. (eval-when-compile (require 'gnus-sum))
  67. (require 'calendar)
  68. (require 'find-func)
  69. (require 'format-spec)
  70. (or (eq this-command 'eval-buffer)
  71. (condition-case nil
  72. (load (concat (file-name-directory load-file-name)
  73. "org-loaddefs.el")
  74. nil t t t)
  75. (error
  76. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  77. (sit-for 3)
  78. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  79. (sit-for 3))))
  80. (eval-and-compile (require 'org-macs))
  81. (require 'org-compat)
  82. (require 'org-keys)
  83. (require 'ol)
  84. (require 'org-table)
  85. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  86. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  87. (defvar org-outline-regexp "\\*+ "
  88. "Regexp to match Org headlines.")
  89. (defvar org-outline-regexp-bol "^\\*+ "
  90. "Regexp to match Org headlines.
  91. This is similar to `org-outline-regexp' but additionally makes
  92. sure that we are at the beginning of the line.")
  93. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  94. "Matches a headline, putting stars and text into groups.
  95. Stars are put in group 1 and the trimmed body in group 2.")
  96. (declare-function calendar-check-holidays "holidays" (date))
  97. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  98. (declare-function cdlatex-math-symbol "ext:cdlatex")
  99. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  100. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  101. (declare-function org-add-archive-files "org-archive" (files))
  102. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  103. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  104. (declare-function org-agenda-redo "org-agenda" (&optional all))
  105. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  106. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  107. (declare-function org-archive-subtree-default "org-archive" ())
  108. (declare-function org-archive-to-archive-sibling "org-archive" ())
  109. (declare-function org-attach "org-attach" ())
  110. (declare-function org-attach-dir "org-attach"
  111. (&optional create-if-not-exists-p no-fs-check))
  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-auto-clockout "org-clock" ())
  116. (declare-function org-clock-cancel "org-clock" ())
  117. (declare-function org-clock-display "org-clock" (&optional arg))
  118. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  119. (declare-function org-clock-goto "org-clock" (&optional select))
  120. (declare-function org-clock-in "org-clock" (&optional select start-time))
  121. (declare-function org-clock-in-last "org-clock" (&optional arg))
  122. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  123. (declare-function org-clock-out-if-current "org-clock" ())
  124. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  125. (declare-function org-clock-report "org-clock" (&optional arg))
  126. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  127. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  128. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  129. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  130. (declare-function org-clock-update-time-maybe "org-clock" ())
  131. (declare-function org-clocking-buffer "org-clock" ())
  132. (declare-function org-clocktable-shift "org-clock" (dir n))
  133. (declare-function org-columns-quit "org-colview" ())
  134. (declare-function org-columns-insert-dblock "org-colview" ())
  135. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  136. (declare-function org-element-at-point "org-element" ())
  137. (declare-function org-element-cache-refresh "org-element" (pos))
  138. (declare-function org-element-cache-reset "org-element" (&optional all))
  139. (declare-function org-element-contents "org-element" (element))
  140. (declare-function org-element-context "org-element" (&optional element))
  141. (declare-function org-element-copy "org-element" (datum))
  142. (declare-function org-element-create "org-element" (type &optional props &rest children))
  143. (declare-function org-element-interpret-data "org-element" (data))
  144. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  145. (declare-function org-element-link-parser "org-element" ())
  146. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  147. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  148. (declare-function org-element-property "org-element" (property element))
  149. (declare-function org-element-put-property "org-element" (element property value))
  150. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  151. (declare-function org-element-timestamp-parser "org-element" ())
  152. (declare-function org-element-type "org-element" (element))
  153. (declare-function org-export-dispatch "ox" (&optional arg))
  154. (declare-function org-export-get-backend "ox" (name))
  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-id-find-id-file "org-id" (id))
  160. (declare-function org-id-get-create "org-id" (&optional force))
  161. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  162. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  163. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  164. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  165. (declare-function org-num-mode "org-num" (&optional arg))
  166. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  167. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  168. (declare-function org-timer "org-timer" (&optional restart no-insert))
  169. (declare-function org-timer-item "org-timer" (&optional arg))
  170. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  171. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  172. (declare-function org-timer-start "org-timer" (&optional offset))
  173. (declare-function org-timer-stop "org-timer" ())
  174. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  175. (declare-function org-update-radio-target-regexp "ol" ())
  176. (defvar ffap-url-regexp)
  177. (defvar org-element-paragraph-separate)
  178. (defvar org-indent-indentation-per-level)
  179. (defvar org-radio-target-regexp)
  180. (defvar org-target-link-regexp)
  181. (defvar org-target-regexp)
  182. (defvar org-id-overriding-file-name)
  183. ;; load languages based on value of `org-babel-load-languages'
  184. (defvar org-babel-load-languages)
  185. ;;;###autoload
  186. (defun org-babel-do-load-languages (sym value)
  187. "Load the languages defined in `org-babel-load-languages'."
  188. (set-default sym value)
  189. (dolist (pair org-babel-load-languages)
  190. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  191. (if active
  192. (require (intern (concat "ob-" lang)))
  193. (fmakunbound
  194. (intern (concat "org-babel-execute:" lang)))
  195. (fmakunbound
  196. (intern (concat "org-babel-expand-body:" lang)))))))
  197. ;;;###autoload
  198. (defun org-babel-load-file (file &optional compile)
  199. "Load Emacs Lisp source code blocks in the Org FILE.
  200. This function exports the source code using `org-babel-tangle'
  201. and then loads the resulting file using `load-file'. With
  202. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  203. byte-compiled before it is loaded."
  204. (interactive "fFile to load: \nP")
  205. (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
  206. ;; Tangle only if the Org file is newer than the Elisp file.
  207. (unless (org-file-newer-than-p
  208. tangled-file
  209. (file-attribute-modification-time
  210. (file-attributes (file-truename file))))
  211. (org-babel-tangle-file file tangled-file "emacs-lisp\\|elisp"))
  212. (if compile
  213. (progn
  214. (byte-compile-file tangled-file)
  215. (load tangled-file)
  216. (message "Compiled and loaded %s" tangled-file))
  217. (load-file tangled-file)
  218. (message "Loaded %s" tangled-file))))
  219. (defcustom org-babel-load-languages '((emacs-lisp . t))
  220. "Languages which can be evaluated in Org buffers.
  221. \\<org-mode-map>
  222. This list can be used to load support for any of the languages
  223. below. Each language will depend on a different set of system
  224. executables and/or Emacs modes.
  225. When a language is \"loaded\", code blocks in that language can
  226. be evaluated with `org-babel-execute-src-block', which is bound
  227. by default to \\[org-ctrl-c-ctrl-c].
  228. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  229. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  230. default, only Emacs Lisp is loaded, since it has no specific
  231. requirement."
  232. :group 'org-babel
  233. :set 'org-babel-do-load-languages
  234. :version "24.1"
  235. :type '(alist :tag "Babel Languages"
  236. :key-type
  237. (choice
  238. (const :tag "Awk" awk)
  239. (const :tag "C" C)
  240. (const :tag "R" R)
  241. (const :tag "Asymptote" asymptote)
  242. (const :tag "Calc" calc)
  243. (const :tag "Clojure" clojure)
  244. (const :tag "CSS" css)
  245. (const :tag "Ditaa" ditaa)
  246. (const :tag "Dot" dot)
  247. (const :tag "Ebnf2ps" ebnf2ps)
  248. (const :tag "Emacs Lisp" emacs-lisp)
  249. (const :tag "Forth" forth)
  250. (const :tag "Fortran" fortran)
  251. (const :tag "Gnuplot" gnuplot)
  252. (const :tag "Haskell" haskell)
  253. (const :tag "hledger" hledger)
  254. (const :tag "IO" io)
  255. (const :tag "J" J)
  256. (const :tag "Java" java)
  257. (const :tag "Javascript" js)
  258. (const :tag "LaTeX" latex)
  259. (const :tag "Ledger" ledger)
  260. (const :tag "Lilypond" lilypond)
  261. (const :tag "Lisp" lisp)
  262. (const :tag "Makefile" makefile)
  263. (const :tag "Maxima" maxima)
  264. (const :tag "Matlab" matlab)
  265. (const :tag "Mscgen" mscgen)
  266. (const :tag "Ocaml" ocaml)
  267. (const :tag "Octave" octave)
  268. (const :tag "Org" org)
  269. (const :tag "Perl" perl)
  270. (const :tag "Pico Lisp" picolisp)
  271. (const :tag "PlantUML" plantuml)
  272. (const :tag "Python" python)
  273. (const :tag "Ruby" ruby)
  274. (const :tag "Sass" sass)
  275. (const :tag "Scala" scala)
  276. (const :tag "Scheme" scheme)
  277. (const :tag "Screen" screen)
  278. (const :tag "Shell Script" shell)
  279. (const :tag "Shen" shen)
  280. (const :tag "Sql" sql)
  281. (const :tag "Sqlite" sqlite)
  282. (const :tag "Stan" stan)
  283. (const :tag "Vala" vala))
  284. :value-type (boolean :tag "Activate" :value t)))
  285. ;;;; Customization variables
  286. (defcustom org-clone-delete-id nil
  287. "Remove ID property of clones of a subtree.
  288. When non-nil, clones of a subtree don't inherit the ID property.
  289. Otherwise they inherit the ID property with a new unique
  290. identifier."
  291. :type 'boolean
  292. :version "24.1"
  293. :group 'org-id)
  294. ;;; Version
  295. (org-check-version)
  296. ;;;###autoload
  297. (defun org-version (&optional here full message)
  298. "Show the Org version.
  299. Interactively, or when MESSAGE is non-nil, show it in echo area.
  300. With prefix argument, or when HERE is non-nil, insert it at point.
  301. In non-interactive uses, a reduced version string is output unless
  302. FULL is given."
  303. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  304. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  305. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  306. (load-suffixes (list ".el"))
  307. (org-install-dir
  308. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  309. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  310. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  311. (let* ((load-suffixes save-load-suffixes)
  312. (release (org-release))
  313. (git-version (org-git-version))
  314. (version (format "Org mode version %s (%s @ %s)"
  315. release
  316. git-version
  317. (if org-install-dir
  318. (if (string= org-dir org-install-dir)
  319. org-install-dir
  320. (concat "mixed installation! "
  321. org-install-dir
  322. " and "
  323. org-dir))
  324. "org-loaddefs.el can not be found!")))
  325. (version1 (if full version release)))
  326. (when here (insert version1))
  327. (when message (message "%s" version1))
  328. version1)))
  329. (defconst org-version (org-version))
  330. ;;; Syntax Constants
  331. ;;;; Comments
  332. (defconst org-comment-regexp
  333. (rx (seq bol (zero-or-more (any "\t ")) "#" (or " " eol)))
  334. "Regular expression for comment lines.")
  335. ;;;; Keyword
  336. (defconst org-keyword-regexp "^[ \t]*#\\+\\(\\S-+?\\):[ \t]*\\(.*\\)$"
  337. "Regular expression for keyword-lines.")
  338. ;;;; Block
  339. (defconst org-block-regexp
  340. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  341. "Regular expression for hiding blocks.")
  342. (defconst org-dblock-start-re
  343. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  344. "Matches the start line of a dynamic block, with parameters.")
  345. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  346. "Matches the end of a dynamic block.")
  347. ;;;; Timestamp
  348. (defconst org-ts--internal-regexp
  349. (rx (seq
  350. (= 4 digit) "-" (= 2 digit) "-" (= 2 digit)
  351. (optional " " (*? nonl))))
  352. "Regular expression matching the innards of a time stamp.")
  353. (defconst org-ts-regexp (format "<\\(%s\\)>" org-ts--internal-regexp)
  354. "Regular expression for fast time stamp matching.")
  355. (defconst org-ts-regexp-inactive
  356. (format "\\[\\(%s\\)\\]" org-ts--internal-regexp)
  357. "Regular expression for fast inactive time stamp matching.")
  358. (defconst org-ts-regexp-both (format "[[<]\\(%s\\)[]>]" org-ts--internal-regexp)
  359. "Regular expression for fast time stamp matching.")
  360. (defconst org-ts-regexp0
  361. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  362. "Regular expression matching time strings for analysis.
  363. This one does not require the space after the date, so it can be used
  364. on a string that terminates immediately after the date.")
  365. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  366. "Regular expression matching time strings for analysis.")
  367. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  368. "Regular expression matching time stamps, with groups.")
  369. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  370. "Regular expression matching time stamps (also [..]), with groups.")
  371. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  372. "Regular expression matching a time stamp range.")
  373. (defconst org-tr-regexp-both
  374. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  375. "Regular expression matching a time stamp range.")
  376. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  377. org-ts-regexp "\\)?")
  378. "Regular expression matching a time stamp or time stamp range.")
  379. (defconst org-tsr-regexp-both
  380. (concat org-ts-regexp-both "\\(--?-?"
  381. org-ts-regexp-both "\\)?")
  382. "Regular expression matching a time stamp or time stamp range.
  383. The time stamps may be either active or inactive.")
  384. (defconst org-repeat-re
  385. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  386. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  387. "Regular expression for specifying repeated events.
  388. After a match, group 1 contains the repeat expression.")
  389. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  390. "Formats for `format-time-string' which are used for time stamps.")
  391. ;;;; Clock and Planning
  392. (defconst org-clock-string "CLOCK:"
  393. "String used as prefix for timestamps clocking work hours on an item.")
  394. (defvar org-closed-string "CLOSED:"
  395. "String used as the prefix for timestamps logging closing a TODO entry.")
  396. (defvar org-deadline-string "DEADLINE:"
  397. "String to mark deadline entries.
  398. \\<org-mode-map>
  399. A deadline is this string, followed by a time stamp. It must be
  400. a word, terminated by a colon. You can insert a schedule keyword
  401. and a timestamp with `\\[org-deadline]'.")
  402. (defvar org-scheduled-string "SCHEDULED:"
  403. "String to mark scheduled TODO entries.
  404. \\<org-mode-map>
  405. A schedule is this string, followed by a time stamp. It must be
  406. a word, terminated by a colon. You can insert a schedule keyword
  407. and a timestamp with `\\[org-schedule]'.")
  408. (defconst org-ds-keyword-length
  409. (+ 2
  410. (apply #'max
  411. (mapcar #'length
  412. (list org-deadline-string org-scheduled-string
  413. org-clock-string org-closed-string))))
  414. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  415. (defconst org-planning-line-re
  416. (concat "^[ \t]*"
  417. (regexp-opt
  418. (list org-closed-string org-deadline-string org-scheduled-string)
  419. t))
  420. "Matches a line with planning info.
  421. Matched keyword is in group 1.")
  422. (defconst org-clock-line-re
  423. (concat "^[ \t]*" org-clock-string)
  424. "Matches a line with clock info.")
  425. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  426. "Matches the DEADLINE keyword.")
  427. (defconst org-deadline-time-regexp
  428. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  429. "Matches the DEADLINE keyword together with a time stamp.")
  430. (defconst org-deadline-time-hour-regexp
  431. (concat "\\<" org-deadline-string
  432. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  433. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  434. (defconst org-deadline-line-regexp
  435. (concat "\\<\\(" org-deadline-string "\\).*")
  436. "Matches the DEADLINE keyword and the rest of the line.")
  437. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  438. "Matches the SCHEDULED keyword.")
  439. (defconst org-scheduled-time-regexp
  440. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  441. "Matches the SCHEDULED keyword together with a time stamp.")
  442. (defconst org-scheduled-time-hour-regexp
  443. (concat "\\<" org-scheduled-string
  444. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  445. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  446. (defconst org-closed-time-regexp
  447. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  448. "Matches the CLOSED keyword together with a time stamp.")
  449. (defconst org-keyword-time-regexp
  450. (concat "\\<"
  451. (regexp-opt
  452. (list org-scheduled-string org-deadline-string org-closed-string
  453. org-clock-string)
  454. t)
  455. " *[[<]\\([^]>]+\\)[]>]")
  456. "Matches any of the 4 keywords, together with the time stamp.")
  457. (defconst org-keyword-time-not-clock-regexp
  458. (concat
  459. "\\<"
  460. (regexp-opt
  461. (list org-scheduled-string org-deadline-string org-closed-string) t)
  462. " *[[<]\\([^]>]+\\)[]>]")
  463. "Matches any of the 3 keywords, together with the time stamp.")
  464. (defconst org-all-time-keywords
  465. (mapcar (lambda (w) (substring w 0 -1))
  466. (list org-scheduled-string org-deadline-string
  467. org-clock-string org-closed-string))
  468. "List of time keywords.")
  469. ;;;; Drawer
  470. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  471. "Matches first or last line of a hidden block.
  472. Group 1 contains drawer's name or \"END\".")
  473. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  474. "Regular expression matching the first line of a property drawer.")
  475. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  476. "Regular expression matching the last line of a property drawer.")
  477. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  478. "Regular expression matching the first line of a clock drawer.")
  479. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  480. "Regular expression matching the last line of a clock drawer.")
  481. (defconst org-logbook-drawer-re
  482. (rx (seq bol (0+ (any "\t ")) ":LOGBOOK:" (0+ (any "\t ")) "\n"
  483. (*? (0+ nonl) "\n")
  484. (0+ (any "\t ")) ":END:" (0+ (any "\t ")) eol))
  485. "Matches an entire LOGBOOK drawer.")
  486. (defconst org-property-drawer-re
  487. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  488. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  489. "[ \t]*:END:[ \t]*$")
  490. "Matches an entire property drawer.")
  491. (defconst org-clock-drawer-re
  492. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  493. org-clock-drawer-end-re "\\)\n?")
  494. "Matches an entire clock drawer.")
  495. ;;;; Headline
  496. (defconst org-heading-keyword-regexp-format
  497. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  498. "Printf format for a regexp matching a headline with some keyword.
  499. This regexp will match the headline of any node which has the
  500. exact keyword that is put into the format. The keyword isn't in
  501. any group by default, but the stars and the body are.")
  502. (defconst org-heading-keyword-maybe-regexp-format
  503. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  504. "Printf format for a regexp matching a headline, possibly with some keyword.
  505. This regexp can match any headline with the specified keyword, or
  506. without a keyword. The keyword isn't in any group by default,
  507. but the stars and the body are.")
  508. (defconst org-archive-tag "ARCHIVE"
  509. "The tag that marks a subtree as archived.
  510. An archived subtree does not open during visibility cycling, and does
  511. not contribute to the agenda listings.")
  512. (defconst org-tag-re "[[:alnum:]_@#%]+"
  513. "Regexp matching a single tag.")
  514. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  515. "Regexp matching the tag group at the end of a line, with leading spaces.
  516. Tags are stored in match group 1. Match group 2 stores the tags
  517. without the enclosing colons.")
  518. (defconst org-tag-line-re
  519. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  520. "Regexp matching tags in a headline.
  521. Tags are stored in match group 1. Match group 2 stores the tags
  522. without the enclosing colons.")
  523. (eval-and-compile
  524. (defconst org-comment-string "COMMENT"
  525. "Entries starting with this keyword will never be exported.
  526. \\<org-mode-map>
  527. An entry can be toggled between COMMENT and normal with
  528. `\\[org-toggle-comment]'."))
  529. ;;;; LaTeX Environments and Fragments
  530. (defconst org-latex-regexps
  531. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  532. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  533. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  534. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  535. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  536. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  537. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  538. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  539. "Regular expressions for matching embedded LaTeX.")
  540. ;;;; Node Property
  541. (defconst org-effort-property "Effort"
  542. "The property that is being used to keep track of effort estimates.
  543. Effort estimates given in this property need to be in the format
  544. defined in org-duration.el.")
  545. ;;; The custom variables
  546. (defgroup org nil
  547. "Outline-based notes management and organizer."
  548. :tag "Org"
  549. :group 'outlines
  550. :group 'calendar)
  551. (defcustom org-mode-hook nil
  552. "Mode hook for Org mode, run after the mode was turned on."
  553. :group 'org
  554. :type 'hook)
  555. (defcustom org-load-hook nil
  556. "Hook that is run after org.el has been loaded."
  557. :group 'org
  558. :type 'hook)
  559. (defcustom org-log-buffer-setup-hook nil
  560. "Hook that is run after an Org log buffer is created."
  561. :group 'org
  562. :version "24.1"
  563. :type 'hook)
  564. (defvar org-modules) ; defined below
  565. (defvar org-modules-loaded nil
  566. "Have the modules been loaded already?")
  567. ;;;###autoload
  568. (defun org-load-modules-maybe (&optional force)
  569. "Load all extensions listed in `org-modules'."
  570. (when (or force (not org-modules-loaded))
  571. (dolist (ext org-modules)
  572. (condition-case nil (require ext)
  573. (error (message "Problems while trying to load feature `%s'" ext))))
  574. (setq org-modules-loaded t)))
  575. (defun org-set-modules (var value)
  576. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  577. (set var value)
  578. (when (featurep 'org)
  579. (org-load-modules-maybe 'force)
  580. (org-element-cache-reset 'all)))
  581. (defcustom org-modules '(ol-w3m ol-bbdb ol-bibtex ol-docview ol-gnus ol-info ol-irc ol-mhe ol-rmail ol-eww)
  582. "Modules that should always be loaded together with org.el.
  583. If a description starts with <C>, the file is not part of Emacs
  584. and loading it will require that you have downloaded and properly
  585. installed the Org mode distribution.
  586. You can also use this system to load external packages (i.e. neither Org
  587. core modules, nor modules from the CONTRIB directory). Just add symbols
  588. to the end of the list. If the package is called org-xyz.el, then you need
  589. to add the symbol `xyz', and the package must have a call to:
  590. (provide \\='org-xyz)
  591. For export specific modules, see also `org-export-backends'."
  592. :group 'org
  593. :set 'org-set-modules
  594. :version "26.1"
  595. :package-version '(Org . "9.2")
  596. :type
  597. '(set :greedy t
  598. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  599. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  600. (const :tag " crypt: Encryption of subtrees" org-crypt)
  601. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  602. (const :tag " docview: Links to Docview buffers" ol-docview)
  603. (const :tag " eww: Store link to URL of Eww" ol-eww)
  604. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  605. (const :tag " habit: Track your consistency with habits" org-habit)
  606. (const :tag " id: Global IDs for identifying entries" org-id)
  607. (const :tag " info: Links to Info nodes" ol-info)
  608. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  609. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  610. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  611. (const :tag " mouse: Additional mouse support" org-mouse)
  612. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  613. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  614. (const :tag " tempo: Fast completion for structures" org-tempo)
  615. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  616. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  617. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  618. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  619. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  620. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  621. (const :tag "C collector: Collect properties into tables" org-collector)
  622. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  623. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  624. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  625. (const :tag "C eval: Include command output as text" org-eval)
  626. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  627. (const :tag "C git-link: Links to specific file version" ol-git-link)
  628. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  629. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  630. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  631. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  632. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  633. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  634. (const :tag "C man: Links to man pages in Org mode" ol-man)
  635. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  636. (const :tag "C notify: Notifications for Org mode" org-notify)
  637. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  638. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  639. (const :tag "C registry: A registry for Org links" org-registry)
  640. (const :tag "C screen: Visit screen sessions through links" org-screen)
  641. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  642. (const :tag "C secretary: Team management with Org" org-secretary)
  643. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  644. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  645. (const :tag "C track: Keep up with Org mode development" org-track)
  646. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  647. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  648. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  649. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  650. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  651. (defvar org-export-registered-backends) ; From ox.el.
  652. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  653. (declare-function org-export-backend-name "ox" (backend) t)
  654. (defcustom org-export-backends '(ascii html icalendar latex odt)
  655. "List of export back-ends that should be always available.
  656. If a description starts with <C>, the file is not part of Emacs
  657. and loading it will require that you have downloaded and properly
  658. installed the Org mode distribution.
  659. Unlike to `org-modules', libraries in this list will not be
  660. loaded along with Org, but only once the export framework is
  661. needed.
  662. This variable needs to be set before org.el is loaded. If you
  663. need to make a change while Emacs is running, use the customize
  664. interface or run the following code, where VAL stands for the new
  665. value of the variable, after updating it:
  666. (progn
  667. (setq org-export-registered-backends
  668. (cl-remove-if-not
  669. (lambda (backend)
  670. (let ((name (org-export-backend-name backend)))
  671. (or (memq name val)
  672. (catch \\='parentp
  673. (dolist (b val)
  674. (and (org-export-derived-backend-p b name)
  675. (throw \\='parentp t)))))))
  676. org-export-registered-backends))
  677. (let ((new-list (mapcar #\\='org-export-backend-name
  678. org-export-registered-backends)))
  679. (dolist (backend val)
  680. (cond
  681. ((not (load (format \"ox-%s\" backend) t t))
  682. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  683. backend))
  684. ((not (memq backend new-list)) (push backend new-list))))
  685. (set-default \\='org-export-backends new-list)))
  686. Adding a back-end to this list will also pull the back-end it
  687. depends on, if any."
  688. :group 'org
  689. :group 'org-export
  690. :version "26.1"
  691. :package-version '(Org . "9.0")
  692. :initialize 'custom-initialize-set
  693. :set (lambda (var val)
  694. (if (not (featurep 'ox)) (set-default var val)
  695. ;; Any back-end not required anymore (not present in VAL and not
  696. ;; a parent of any back-end in the new value) is removed from the
  697. ;; list of registered back-ends.
  698. (setq org-export-registered-backends
  699. (cl-remove-if-not
  700. (lambda (backend)
  701. (let ((name (org-export-backend-name backend)))
  702. (or (memq name val)
  703. (catch 'parentp
  704. (dolist (b val)
  705. (and (org-export-derived-backend-p b name)
  706. (throw 'parentp t)))))))
  707. org-export-registered-backends))
  708. ;; Now build NEW-LIST of both new back-ends and required
  709. ;; parents.
  710. (let ((new-list (mapcar #'org-export-backend-name
  711. org-export-registered-backends)))
  712. (dolist (backend val)
  713. (cond
  714. ((not (load (format "ox-%s" backend) t t))
  715. (message "Problems while trying to load export back-end `%s'"
  716. backend))
  717. ((not (memq backend new-list)) (push backend new-list))))
  718. ;; Set VAR to that list with fixed dependencies.
  719. (set-default var new-list))))
  720. :type '(set :greedy t
  721. (const :tag " ascii Export buffer to ASCII format" ascii)
  722. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  723. (const :tag " html Export buffer to HTML format" html)
  724. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  725. (const :tag " latex Export buffer to LaTeX format" latex)
  726. (const :tag " man Export buffer to MAN format" man)
  727. (const :tag " md Export buffer to Markdown format" md)
  728. (const :tag " odt Export buffer to ODT format" odt)
  729. (const :tag " org Export buffer to Org format" org)
  730. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  731. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  732. (const :tag "C deck Export buffer to deck.js presentations" deck)
  733. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  734. (const :tag "C groff Export buffer to Groff format" groff)
  735. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  736. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  737. (const :tag "C s5 Export buffer to s5 presentations" s5)
  738. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  739. (eval-after-load 'ox
  740. '(dolist (backend org-export-backends)
  741. (condition-case nil (require (intern (format "ox-%s" backend)))
  742. (error (message "Problems while trying to load export back-end `%s'"
  743. backend)))))
  744. (defcustom org-support-shift-select nil
  745. "Non-nil means make shift-cursor commands select text when possible.
  746. \\<org-mode-map>
  747. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  748. start selecting a region, or enlarge regions started in this way.
  749. In Org mode, in special contexts, these same keys are used for
  750. other purposes, important enough to compete with shift selection.
  751. Org tries to balance these needs by supporting `shift-select-mode'
  752. outside these special contexts, under control of this variable.
  753. The default of this variable is nil, to avoid confusing behavior. Shifted
  754. cursor keys will then execute Org commands in the following contexts:
  755. - on a headline, changing TODO state (left/right) and priority (up/down)
  756. - on a time stamp, changing the time
  757. - in a plain list item, changing the bullet type
  758. - in a property definition line, switching between allowed values
  759. - in the BEGIN line of a clock table (changing the time block).
  760. - in a table, moving the cell in the specified direction.
  761. Outside these contexts, the commands will throw an error.
  762. When this variable is t and the cursor is not in a special
  763. context, Org mode will support shift-selection for making and
  764. enlarging regions. To make this more effective, the bullet
  765. cycling will no longer happen anywhere in an item line, but only
  766. if the cursor is exactly on the bullet.
  767. If you set this variable to the symbol `always', then the keys
  768. will not be special in headlines, property lines, item lines, and
  769. table cells, to make shift selection work there as well. If this is
  770. what you want, you can use the following alternative commands:
  771. `\\[org-todo]' and `\\[org-priority]' \
  772. to change TODO state and priority,
  773. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  774. can be used to switch TODO sets,
  775. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  776. and properties can be edited by hand or in column view.
  777. However, when the cursor is on a timestamp, shift-cursor commands
  778. will still edit the time stamp - this is just too good to give up."
  779. :group 'org
  780. :type '(choice
  781. (const :tag "Never" nil)
  782. (const :tag "When outside special context" t)
  783. (const :tag "Everywhere except timestamps" always)))
  784. (defcustom org-loop-over-headlines-in-active-region t
  785. "Shall some commands act upon headlines in the active region?
  786. When set to t, some commands will be performed in all headlines
  787. within the active region.
  788. When set to `start-level', some commands will be performed in all
  789. headlines within the active region, provided that these headlines
  790. are of the same level than the first one.
  791. When set to a string, those commands will be performed on the
  792. matching headlines within the active region. Such string must be
  793. a tags/property/todo match as it is used in the agenda tags view.
  794. The list of commands is: `org-schedule', `org-deadline',
  795. `org-todo', `org-set-tags-command', `org-archive-subtree',
  796. `org-archive-set-tag', `org-toggle-archive-tag' and
  797. `org-archive-to-archive-sibling'. The archiving commands skip
  798. already archived entries.
  799. See `org-agenda-loop-over-headlines-in-active-region' for the
  800. equivalent option for agenda views."
  801. :type '(choice (const :tag "Don't loop" nil)
  802. (const :tag "All headlines in active region" t)
  803. (const :tag "In active region, headlines at the same level than the first one" start-level)
  804. (string :tag "Tags/Property/Todo matcher"))
  805. :package-version '(Org . "9.4")
  806. :group 'org-todo
  807. :group 'org-archive)
  808. (defcustom org-startup-folded 'showeverything
  809. "Non-nil means entering Org mode will switch to OVERVIEW.
  810. This can also be configured on a per-file basis by adding one of
  811. the following lines anywhere in the buffer:
  812. #+STARTUP: fold (or `overview', this is equivalent)
  813. #+STARTUP: nofold (or `showall', this is equivalent)
  814. #+STARTUP: content
  815. #+STARTUP: showeverything
  816. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  817. to ignore this option when Org opens agenda files for the first
  818. time."
  819. :group 'org-startup
  820. :package-version '(Org . "9.4")
  821. :type '(choice
  822. (const :tag "nofold: show all" nil)
  823. (const :tag "fold: overview" t)
  824. (const :tag "content: all headlines" content)
  825. (const :tag "show everything, even drawers" showeverything)))
  826. (defcustom org-startup-truncated t
  827. "Non-nil means entering Org mode will set `truncate-lines'.
  828. This is useful since some lines containing links can be very long and
  829. uninteresting. Also tables look terrible when wrapped.
  830. The variable `org-startup-truncated' allows to configure
  831. truncation for Org mode different to the other modes that use the
  832. variable `truncate-lines' and as a shortcut instead of putting
  833. the variable `truncate-lines' into the `org-mode-hook'. If one
  834. wants to configure truncation for Org mode not statically but
  835. dynamically e.g. in a hook like `ediff-prepare-buffer-hook' then
  836. the variable `truncate-lines' has to be used because in such a
  837. case it is too late to set the variable `org-startup-truncated'."
  838. :group 'org-startup
  839. :type 'boolean)
  840. (defcustom org-startup-indented nil
  841. "Non-nil means turn on `org-indent-mode' on startup.
  842. This can also be configured on a per-file basis by adding one of
  843. the following lines anywhere in the buffer:
  844. #+STARTUP: indent
  845. #+STARTUP: noindent"
  846. :group 'org-structure
  847. :type '(choice
  848. (const :tag "Not" nil)
  849. (const :tag "Globally (slow on startup in large files)" t)))
  850. (defcustom org-startup-numerated nil
  851. "Non-nil means turn on `org-num-mode' on startup.
  852. This can also be configured on a per-file basis by adding one of
  853. the following lines anywhere in the buffer:
  854. #+STARTUP: num
  855. #+STARTUP: nonum"
  856. :group 'org-structure
  857. :package-version '(Org . "9.4")
  858. :type '(choice
  859. (const :tag "Not" nil)
  860. (const :tag "Globally" t)))
  861. (defcustom org-use-sub-superscripts t
  862. "Non-nil means interpret \"_\" and \"^\" for display.
  863. If you want to control how Org exports those characters, see
  864. `org-export-with-sub-superscripts'.
  865. When this option is turned on, you can use TeX-like syntax for
  866. sub- and superscripts within the buffer. Several characters after
  867. \"_\" or \"^\" will be considered as a single item - so grouping
  868. with {} is normally not needed. For example, the following things
  869. will be parsed as single sub- or superscripts:
  870. 10^24 or 10^tau several digits will be considered 1 item.
  871. 10^-12 or 10^-tau a leading sign with digits or a word
  872. x^2-y^3 will be read as x^2 - y^3, because items are
  873. terminated by almost any nonword/nondigit char.
  874. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  875. Still, ambiguity is possible. So when in doubt, use {} to enclose
  876. the sub/superscript. If you set this variable to the symbol `{}',
  877. the braces are *required* in order to trigger interpretations as
  878. sub/superscript. This can be helpful in documents that need \"_\"
  879. frequently in plain text."
  880. :group 'org-startup
  881. :version "24.4"
  882. :package-version '(Org . "8.0")
  883. :type '(choice
  884. (const :tag "Always interpret" t)
  885. (const :tag "Only with braces" {})
  886. (const :tag "Never interpret" nil)))
  887. (defcustom org-startup-with-beamer-mode nil
  888. "Non-nil means turn on `org-beamer-mode' on startup.
  889. This can also be configured on a per-file basis by adding one of
  890. the following lines anywhere in the buffer:
  891. #+STARTUP: beamer"
  892. :group 'org-startup
  893. :version "24.1"
  894. :type 'boolean)
  895. (defcustom org-startup-align-all-tables nil
  896. "Non-nil means align all tables when visiting a file.
  897. This can also be configured on a per-file basis by adding one of
  898. the following lines anywhere in the buffer:
  899. #+STARTUP: align
  900. #+STARTUP: noalign"
  901. :group 'org-startup
  902. :type 'boolean)
  903. (defcustom org-startup-shrink-all-tables nil
  904. "Non-nil means shrink all table columns with a width cookie.
  905. This can also be configured on a per-file basis by adding one of
  906. the following lines anywhere in the buffer:
  907. #+STARTUP: shrink"
  908. :group 'org-startup
  909. :type 'boolean
  910. :version "27.1"
  911. :package-version '(Org . "9.2")
  912. :safe #'booleanp)
  913. (defcustom org-startup-with-inline-images nil
  914. "Non-nil means show inline images when loading a new Org file.
  915. This can also be configured on a per-file basis by adding one of
  916. the following lines anywhere in the buffer:
  917. #+STARTUP: inlineimages
  918. #+STARTUP: noinlineimages"
  919. :group 'org-startup
  920. :version "24.1"
  921. :type 'boolean)
  922. (defcustom org-startup-with-latex-preview nil
  923. "Non-nil means preview LaTeX fragments when loading a new Org file.
  924. This can also be configured on a per-file basis by adding one of
  925. the following lines anywhere in the buffer:
  926. #+STARTUP: latexpreview
  927. #+STARTUP: nolatexpreview"
  928. :group 'org-startup
  929. :version "24.4"
  930. :package-version '(Org . "8.0")
  931. :type 'boolean)
  932. (defcustom org-insert-mode-line-in-empty-file nil
  933. "Non-nil means insert the first line setting Org mode in empty files.
  934. When the function `org-mode' is called interactively in an empty file, this
  935. normally means that the file name does not automatically trigger Org mode.
  936. To ensure that the file will always be in Org mode in the future, a
  937. line enforcing Org mode will be inserted into the buffer, if this option
  938. has been set."
  939. :group 'org-startup
  940. :type 'boolean)
  941. (defcustom org-ellipsis nil
  942. "The ellipsis to use in the Org mode outline.
  943. When nil, just use the standard three dots. When a non-empty string,
  944. use that string instead.
  945. The change affects only Org mode (which will then use its own display table).
  946. Changing this requires executing `\\[org-mode]' in a buffer to become
  947. effective. It cannot be set as a local variable."
  948. :group 'org-startup
  949. :type '(choice (const :tag "Default" nil)
  950. (string :tag "String" :value "...#")))
  951. (defvar org-display-table nil
  952. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  953. (defcustom org-directory "~/org"
  954. "Directory with Org files.
  955. This is just a default location to look for Org files. There is no need
  956. at all to put your files into this directory. It is used in the
  957. following situations:
  958. 1. When a capture template specifies a target file that is not an
  959. absolute path. The path will then be interpreted relative to
  960. `org-directory'
  961. 2. When the value of variable `org-agenda-files' is a single file, any
  962. relative paths in this file will be taken as relative to
  963. `org-directory'."
  964. :group 'org-refile
  965. :group 'org-capture
  966. :type 'directory)
  967. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  968. "Default target for storing notes.
  969. Used as a fall back file for org-capture.el, for templates that
  970. do not specify a target file."
  971. :group 'org-refile
  972. :group 'org-capture
  973. :type 'file)
  974. (defcustom org-reverse-note-order nil
  975. "Non-nil means store new notes at the beginning of a file or entry.
  976. When nil, new notes will be filed to the end of a file or entry.
  977. This can also be a list with cons cells of regular expressions that
  978. are matched against file names, and values."
  979. :group 'org-capture
  980. :group 'org-refile
  981. :type '(choice
  982. (const :tag "Reverse always" t)
  983. (const :tag "Reverse never" nil)
  984. (repeat :tag "By file name regexp"
  985. (cons regexp boolean))))
  986. (defgroup org-keywords nil
  987. "Keywords in Org mode."
  988. :tag "Org Keywords"
  989. :group 'org)
  990. (defcustom org-closed-keep-when-no-todo nil
  991. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  992. :group 'org-todo
  993. :group 'org-keywords
  994. :version "24.4"
  995. :package-version '(Org . "8.0")
  996. :type 'boolean)
  997. (defgroup org-structure nil
  998. "Options concerning the general structure of Org files."
  999. :tag "Org Structure"
  1000. :group 'org)
  1001. (defgroup org-reveal-location nil
  1002. "Options about how to make context of a location visible."
  1003. :tag "Org Reveal Location"
  1004. :group 'org-structure)
  1005. (defcustom org-show-context-detail '((agenda . local)
  1006. (bookmark-jump . lineage)
  1007. (isearch . lineage)
  1008. (default . ancestors))
  1009. "Alist between context and visibility span when revealing a location.
  1010. \\<org-mode-map>Some actions may move point into invisible
  1011. locations. As a consequence, Org always exposes a neighborhood
  1012. around point. How much is shown depends on the initial action,
  1013. or context. Valid contexts are
  1014. agenda when exposing an entry from the agenda
  1015. org-goto when using the command `org-goto' (`\\[org-goto]')
  1016. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1017. tags-tree when constructing a sparse tree based on tags matches
  1018. link-search when exposing search matches associated with a link
  1019. mark-goto when exposing the jump goal of a mark
  1020. bookmark-jump when exposing a bookmark location
  1021. isearch when exiting from an incremental search
  1022. default default for all contexts not set explicitly
  1023. Allowed visibility spans are
  1024. minimal show current headline; if point is not on headline,
  1025. also show entry
  1026. local show current headline, entry and next headline
  1027. ancestors show current headline and its direct ancestors; if
  1028. point is not on headline, also show entry
  1029. lineage show current headline, its direct ancestors and all
  1030. their children; if point is not on headline, also show
  1031. entry and first child
  1032. tree show current headline, its direct ancestors and all
  1033. their children; if point is not on headline, also show
  1034. entry and all children
  1035. canonical show current headline, its direct ancestors along with
  1036. their entries and children; if point is not located on
  1037. the headline, also show current entry and all children
  1038. As special cases, a nil or t value means show all contexts in
  1039. `minimal' or `canonical' view, respectively.
  1040. Some views can make displayed information very compact, but also
  1041. make it harder to edit the location of the match. In such
  1042. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1043. more context."
  1044. :group 'org-reveal-location
  1045. :version "26.1"
  1046. :package-version '(Org . "9.0")
  1047. :type '(choice
  1048. (const :tag "Canonical" t)
  1049. (const :tag "Minimal" nil)
  1050. (repeat :greedy t :tag "Individual contexts"
  1051. (cons
  1052. (choice :tag "Context"
  1053. (const agenda)
  1054. (const org-goto)
  1055. (const occur-tree)
  1056. (const tags-tree)
  1057. (const link-search)
  1058. (const mark-goto)
  1059. (const bookmark-jump)
  1060. (const isearch)
  1061. (const default))
  1062. (choice :tag "Detail level"
  1063. (const minimal)
  1064. (const local)
  1065. (const ancestors)
  1066. (const lineage)
  1067. (const tree)
  1068. (const canonical))))))
  1069. (defcustom org-indirect-buffer-display 'other-window
  1070. "How should indirect tree buffers be displayed?
  1071. This applies to indirect buffers created with the commands
  1072. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1073. Valid values are:
  1074. current-window Display in the current window
  1075. other-window Just display in another window.
  1076. dedicated-frame Create one new frame, and re-use it each time.
  1077. new-frame Make a new frame each time. Note that in this case
  1078. previously-made indirect buffers are kept, and you need to
  1079. kill these buffers yourself."
  1080. :group 'org-structure
  1081. :group 'org-agenda-windows
  1082. :type '(choice
  1083. (const :tag "In current window" current-window)
  1084. (const :tag "In current frame, other window" other-window)
  1085. (const :tag "Each time a new frame" new-frame)
  1086. (const :tag "One dedicated frame" dedicated-frame)))
  1087. (defconst org-file-apps-gnu
  1088. '((remote . emacs)
  1089. (system . mailcap)
  1090. (t . mailcap))
  1091. "Default file applications on a UNIX or GNU/Linux system.
  1092. See `org-file-apps'.")
  1093. (defconst org-file-apps-macos
  1094. '((remote . emacs)
  1095. (system . "open %s")
  1096. ("ps.gz" . "gv %s")
  1097. ("eps.gz" . "gv %s")
  1098. ("dvi" . "xdvi %s")
  1099. ("fig" . "xfig %s")
  1100. (t . "open %s"))
  1101. "Default file applications on a macOS system.
  1102. The system \"open\" is known as a default, but we use X11 applications
  1103. for some files for which the OS does not have a good default.
  1104. See `org-file-apps'.")
  1105. (defconst org-file-apps-windowsnt
  1106. (list '(remote . emacs)
  1107. (cons 'system (lambda (file _path)
  1108. (with-no-warnings (w32-shell-execute "open" file))))
  1109. (cons t (lambda (file _path)
  1110. (with-no-warnings (w32-shell-execute "open" file)))))
  1111. "Default file applications on a Windows NT system.
  1112. The system \"open\" is used for most files.
  1113. See `org-file-apps'.")
  1114. (defcustom org-file-apps
  1115. '((auto-mode . emacs)
  1116. (directory . emacs)
  1117. ("\\.mm\\'" . default)
  1118. ("\\.x?html?\\'" . default)
  1119. ("\\.pdf\\'" . default))
  1120. "Applications for opening `file:path' items in a document.
  1121. \\<org-mode-map>
  1122. Org mode uses system defaults for different file types, but you
  1123. can use this variable to set the application for a given file
  1124. extension. The entries in this list are cons cells where the car
  1125. identifies files and the cdr the corresponding command.
  1126. Possible values for the file identifier are:
  1127. \"string\" A string as a file identifier can be interpreted in different
  1128. ways, depending on its contents:
  1129. - Alphanumeric characters only:
  1130. Match links with this file extension.
  1131. Example: (\"pdf\" . \"evince %s\")
  1132. to open PDFs with evince.
  1133. - Regular expression: Match links where the
  1134. filename matches the regexp. If you want to
  1135. use groups here, use shy groups.
  1136. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1137. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1138. to open *.html and *.xhtml with firefox.
  1139. - Regular expression which contains (non-shy) groups:
  1140. Match links where the whole link, including \"::\", and
  1141. anything after that, matches the regexp.
  1142. In a custom command string, %1, %2, etc. are replaced with
  1143. the parts of the link that were matched by the groups.
  1144. For backwards compatibility, if a command string is given
  1145. that does not use any of the group matches, this case is
  1146. handled identically to the second one (i.e. match against
  1147. file name only).
  1148. In a custom function, you can access the group matches with
  1149. (match-string n link).
  1150. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1151. \"evince -p %1 %s\")
  1152. to open [[file:document.pdf::5]] with evince at page 5.
  1153. `directory' Matches a directory
  1154. `remote' Matches a remote file, accessible through tramp or efs.
  1155. Remote files most likely should be visited through Emacs
  1156. because external applications cannot handle such paths.
  1157. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1158. so all files Emacs knows how to handle. Using this with
  1159. command `emacs' will open most files in Emacs. Beware that this
  1160. will also open html files inside Emacs, unless you add
  1161. (\"html\" . default) to the list as well.
  1162. `system' The system command to open files, like `open' on Windows
  1163. and macOS, and mailcap under GNU/Linux. This is the command
  1164. that will be selected if you call `org-open-at-point' with a
  1165. double prefix argument (`\\[universal-argument] \
  1166. \\[universal-argument] \\[org-open-at-point]').
  1167. t Default for files not matched by any of the other options.
  1168. Possible values for the command are:
  1169. `emacs' The file will be visited by the current Emacs process.
  1170. `default' Use the default application for this file type, which is the
  1171. association for t in the list, most likely in the system-specific
  1172. part. This can be used to overrule an unwanted setting in the
  1173. system-specific variable.
  1174. `system' Use the system command for opening files, like \"open\".
  1175. This command is specified by the entry whose car is `system'.
  1176. Most likely, the system-specific version of this variable
  1177. does define this command, but you can overrule/replace it
  1178. here.
  1179. `mailcap' Use command specified in the mailcaps.
  1180. string A command to be executed by a shell; %s will be replaced
  1181. by the path to the file.
  1182. function A Lisp function, which will be called with two arguments:
  1183. the file path and the original link string, without the
  1184. \"file:\" prefix.
  1185. For more examples, see the system specific constants
  1186. `org-file-apps-macos'
  1187. `org-file-apps-windowsnt'
  1188. `org-file-apps-gnu'."
  1189. :group 'org
  1190. :package-version '(Org . "9.4")
  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-hide-drawers
  1331. org-cycle-show-empty-lines
  1332. org-optimize-window-after-visibility-change)
  1333. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1334. The function(s) in this hook must accept a single argument which indicates
  1335. the new state that was set by the most recent `org-cycle' command. The
  1336. argument is a symbol. After a global state change, it can have the values
  1337. `overview', `contents', or `all'. After a local state change, it can have
  1338. the values `folded', `children', or `subtree'."
  1339. :group 'org-cycle
  1340. :package-version '(Org . "9.4")
  1341. :type 'hook)
  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 to t, Org assumes that you write
  1363. outlines by indenting text in each node to align with the
  1364. headline (after the stars).
  1365. When this variable is set to 'headline-data, only adapt the
  1366. indentation of the data lines right below the headline, such as
  1367. planning/clock lines and property/logbook drawers.
  1368. The following issues are influenced by this variable:
  1369. - The indentation is increased by one space in a demotion
  1370. command, and decreased by one in a promotion command. However,
  1371. in the latter case, if shifting some line in the entry body
  1372. would alter document structure (e.g., insert a new headline),
  1373. indentation is not changed at all.
  1374. - Property drawers and planning information is inserted indented
  1375. when this variable is set. When nil, they will not be indented.
  1376. - TAB indents a line relative to current level. The lines below
  1377. a headline will be indented when this variable is set to t.
  1378. Note that this is all about true indentation, by adding and
  1379. removing space characters. See also \"org-indent.el\" which does
  1380. level-dependent indentation in a virtual way, i.e. at display
  1381. time in Emacs."
  1382. :group 'org-edit-structure
  1383. :type '(choice
  1384. (const :tag "Adapt indentation for all lines" t)
  1385. (const :tag "Adapt indentation for headline data lines"
  1386. 'headline-data)
  1387. (const :tag "Do not adapt indentation at all" nil))
  1388. :safe #'booleanp)
  1389. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1390. (defcustom org-special-ctrl-a/e nil
  1391. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1392. When t, `C-a' will bring back the cursor to the beginning of the
  1393. headline text, i.e. after the stars and after a possible TODO
  1394. keyword. In an item, this will be the position after bullet and
  1395. check-box, if any. When the cursor is already at that position,
  1396. another `C-a' will bring it to the beginning of the line.
  1397. `C-e' will jump to the end of the headline, ignoring the presence
  1398. of tags in the headline. A second `C-e' will then jump to the
  1399. true end of the line, after any tags. This also means that, when
  1400. this variable is non-nil, `C-e' also will never jump beyond the
  1401. end of the heading of a folded section, i.e. not after the
  1402. ellipses.
  1403. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1404. normally, going to the true line boundary first. Only a directly
  1405. following, identical keypress will bring the cursor to the
  1406. special positions.
  1407. This may also be a cons cell where the behavior for `C-a' and
  1408. `C-e' is set separately."
  1409. :group 'org-edit-structure
  1410. :type '(choice
  1411. (const :tag "off" nil)
  1412. (const :tag "on: after stars/bullet and before tags first" t)
  1413. (const :tag "reversed: true line boundary first" reversed)
  1414. (cons :tag "Set C-a and C-e separately"
  1415. (choice :tag "Special C-a"
  1416. (const :tag "off" nil)
  1417. (const :tag "on: after stars/bullet first" t)
  1418. (const :tag "reversed: before stars/bullet first" reversed))
  1419. (choice :tag "Special C-e"
  1420. (const :tag "off" nil)
  1421. (const :tag "on: before tags first" t)
  1422. (const :tag "reversed: after tags first" reversed)))))
  1423. (defcustom org-special-ctrl-k nil
  1424. "Non-nil means `C-k' will behave specially in headlines.
  1425. When nil, `C-k' will call the default `kill-line' command.
  1426. When t, the following will happen while the cursor is in the headline:
  1427. - When at the beginning of a headline, kill the entire subtree.
  1428. - When in the middle of the headline text, kill the text up to the tags.
  1429. - When after the headline text and before the tags, kill all the tags."
  1430. :group 'org-edit-structure
  1431. :type 'boolean)
  1432. (defcustom org-ctrl-k-protect-subtree nil
  1433. "Non-nil means, do not delete a hidden subtree with `C-k'.
  1434. When set to the symbol `error', simply throw an error when `C-k' is
  1435. used to kill (part-of) a headline that has hidden text behind it.
  1436. Any other non-nil value will result in a query to the user, if it is
  1437. OK to kill that hidden subtree. When nil, kill without remorse."
  1438. :group 'org-edit-structure
  1439. :version "24.1"
  1440. :type '(choice
  1441. (const :tag "Do not protect hidden subtrees" nil)
  1442. (const :tag "Protect hidden subtrees with a security query" t)
  1443. (const :tag "Never kill a hidden subtree with C-k" error)))
  1444. (defcustom org-special-ctrl-o t
  1445. "Non-nil means, make `C-o' insert a row in tables."
  1446. :group 'org-edit-structure
  1447. :type 'boolean)
  1448. (defcustom org-catch-invisible-edits nil
  1449. "Check if in invisible region before inserting or deleting a character.
  1450. Valid values are:
  1451. nil Do not check, so just do invisible edits.
  1452. error Throw an error and do nothing.
  1453. show Make point visible, and do the requested edit.
  1454. show-and-error Make point visible, then throw an error and abort the edit.
  1455. smart Make point visible, and do insertion/deletion if it is
  1456. adjacent to visible text and the change feels predictable.
  1457. Never delete a previously invisible character or add in the
  1458. middle or right after an invisible region. Basically, this
  1459. allows insertion and backward-delete right before ellipses.
  1460. FIXME: maybe in this case we should not even show?"
  1461. :group 'org-edit-structure
  1462. :version "24.1"
  1463. :type '(choice
  1464. (const :tag "Do not check" nil)
  1465. (const :tag "Throw error when trying to edit" error)
  1466. (const :tag "Unhide, but do not do the edit" show-and-error)
  1467. (const :tag "Show invisible part and do the edit" show)
  1468. (const :tag "Be smart and do the right thing" smart)))
  1469. (defcustom org-yank-folded-subtrees t
  1470. "Non-nil means when yanking subtrees, fold them.
  1471. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1472. it starts with a heading and all other headings in it are either children
  1473. or siblings, then fold all the subtrees. However, do this only if no
  1474. text after the yank would be swallowed into a folded tree by this action."
  1475. :group 'org-edit-structure
  1476. :type 'boolean)
  1477. (defcustom org-yank-adjusted-subtrees nil
  1478. "Non-nil means when yanking subtrees, adjust the level.
  1479. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1480. this function for details."
  1481. :group 'org-edit-structure
  1482. :type 'boolean)
  1483. (defcustom org-M-RET-may-split-line '((default . t))
  1484. "Non-nil means M-RET will split the line at the cursor position.
  1485. When nil, it will go to the end of the line before making a
  1486. new line.
  1487. You may also set this option in a different way for different
  1488. contexts. Valid contexts are:
  1489. headline when creating a new headline
  1490. item when creating a new item
  1491. table in a table field
  1492. default the value to be used for all contexts not explicitly
  1493. customized"
  1494. :group 'org-structure
  1495. :group 'org-table
  1496. :type '(choice
  1497. (const :tag "Always" t)
  1498. (const :tag "Never" nil)
  1499. (repeat :greedy t :tag "Individual contexts"
  1500. (cons
  1501. (choice :tag "Context"
  1502. (const headline)
  1503. (const item)
  1504. (const table)
  1505. (const default))
  1506. (boolean)))))
  1507. (defcustom org-insert-heading-respect-content nil
  1508. "Non-nil means insert new headings after the current subtree.
  1509. \\<org-mode-map>
  1510. When nil, the new heading is created directly after the current line.
  1511. The commands `\\[org-insert-heading-respect-content]' and \
  1512. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1513. for the duration of the command."
  1514. :group 'org-structure
  1515. :type 'boolean)
  1516. (defcustom org-blank-before-new-entry '((heading . auto)
  1517. (plain-list-item . auto))
  1518. "Should `org-insert-heading' leave a blank line before new heading/item?
  1519. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1520. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1521. which case Org will look at the surrounding headings/items and try to
  1522. make an intelligent decision whether to insert a blank line or not."
  1523. :group 'org-edit-structure
  1524. :type '(list
  1525. (cons (const heading)
  1526. (choice (const :tag "Never" nil)
  1527. (const :tag "Always" t)
  1528. (const :tag "Auto" auto)))
  1529. (cons (const plain-list-item)
  1530. (choice (const :tag "Never" nil)
  1531. (const :tag "Always" t)
  1532. (const :tag "Auto" auto)))))
  1533. (defcustom org-insert-heading-hook nil
  1534. "Hook being run after inserting a new heading."
  1535. :group 'org-edit-structure
  1536. :type 'hook)
  1537. (defgroup org-sparse-trees nil
  1538. "Options concerning sparse trees in Org mode."
  1539. :tag "Org Sparse Trees"
  1540. :group 'org-structure)
  1541. (defcustom org-highlight-sparse-tree-matches t
  1542. "Non-nil means highlight all matches that define a sparse tree.
  1543. The highlights will automatically disappear the next time the buffer is
  1544. changed by an edit command."
  1545. :group 'org-sparse-trees
  1546. :type 'boolean)
  1547. (defcustom org-remove-highlights-with-change t
  1548. "Non-nil means any change to the buffer will remove temporary highlights.
  1549. \\<org-mode-map>\
  1550. Such highlights are created by `org-occur' and `org-clock-display'.
  1551. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1552. to get rid of the highlights.
  1553. The highlights created by `org-latex-preview' always need
  1554. `\\[org-latex-preview]' to be removed."
  1555. :group 'org-sparse-trees
  1556. :group 'org-time
  1557. :type 'boolean)
  1558. (defcustom org-occur-case-fold-search t
  1559. "Non-nil means `org-occur' should be case-insensitive.
  1560. If set to `smart' the search will be case-insensitive only if it
  1561. doesn't specify any upper case character."
  1562. :group 'org-sparse-trees
  1563. :version "26.1"
  1564. :type '(choice
  1565. (const :tag "Case-sensitive" nil)
  1566. (const :tag "Case-insensitive" t)
  1567. (const :tag "Case-insensitive for lower case searches only" smart)))
  1568. (defcustom org-occur-hook '(org-first-headline-recenter)
  1569. "Hook that is run after `org-occur' has constructed a sparse tree.
  1570. This can be used to recenter the window to show as much of the structure
  1571. as possible."
  1572. :group 'org-sparse-trees
  1573. :type 'hook)
  1574. (defcustom org-self-insert-cluster-for-undo nil
  1575. "Non-nil means cluster self-insert commands for undo when possible.
  1576. If this is set, then, like in the Emacs command loop, 20 consecutive
  1577. characters will be undone together.
  1578. This is configurable, because there is some impact on typing performance."
  1579. :group 'org-table
  1580. :type 'boolean)
  1581. (defvaralias 'org-activate-links 'org-highlight-links)
  1582. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1583. "Types of links that should be highlighted in Org files.
  1584. This is a list of symbols, each one of them leading to the
  1585. highlighting of a certain link type.
  1586. You can still open links that are not highlighted.
  1587. In principle, it does not hurt to turn on highlighting for all
  1588. link types. There may be a small gain when turning off unused
  1589. link types. The types are:
  1590. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1591. angle Links in angular brackets that may contain whitespace like
  1592. <bbdb:Carsten Dominik>.
  1593. plain Plain links in normal text, no whitespace, like http://google.com.
  1594. radio Text that is matched by a radio target, see manual for details.
  1595. tag Tag settings in a headline (link to tag search).
  1596. date Time stamps (link to calendar).
  1597. footnote Footnote labels.
  1598. If you set this variable during an Emacs session, use `org-mode-restart'
  1599. in the Org buffer so that the change takes effect."
  1600. :group 'org-appearance
  1601. :type '(set :greedy t
  1602. (const :tag "Double bracket links" bracket)
  1603. (const :tag "Angular bracket links" angle)
  1604. (const :tag "Plain text links" plain)
  1605. (const :tag "Radio target matches" radio)
  1606. (const :tag "Tags" tag)
  1607. (const :tag "Timestamps" date)
  1608. (const :tag "Footnotes" footnote)))
  1609. (defcustom org-mark-ring-length 4
  1610. "Number of different positions to be recorded in the ring.
  1611. Changing this requires a restart of Emacs to work correctly."
  1612. :group 'org-link-follow
  1613. :type 'integer)
  1614. (defgroup org-todo nil
  1615. "Options concerning TODO items in Org mode."
  1616. :tag "Org TODO"
  1617. :group 'org)
  1618. (defgroup org-progress nil
  1619. "Options concerning Progress logging in Org mode."
  1620. :tag "Org Progress"
  1621. :group 'org-time)
  1622. (defvar org-todo-interpretation-widgets
  1623. '((:tag "Sequence (cycling hits every state)" sequence)
  1624. (:tag "Type (cycling directly to DONE)" type))
  1625. "The available interpretation symbols for customizing `org-todo-keywords'.
  1626. Interested libraries should add to this list.")
  1627. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1628. "List of TODO entry keyword sequences and their interpretation.
  1629. \\<org-mode-map>This is a list of sequences.
  1630. Each sequence starts with a symbol, either `sequence' or `type',
  1631. indicating if the keywords should be interpreted as a sequence of
  1632. action steps, or as different types of TODO items. The first
  1633. keywords are states requiring action - these states will select a headline
  1634. for inclusion into the global TODO list Org produces. If one of the
  1635. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1636. signify that no further action is necessary. If \"|\" is not found,
  1637. the last keyword is treated as the only DONE state of the sequence.
  1638. The command `\\[org-todo]' cycles an entry through these states, and one
  1639. additional state where no keyword is present. For details about this
  1640. cycling, see the manual.
  1641. TODO keywords and interpretation can also be set on a per-file basis with
  1642. the special #+SEQ_TODO and #+TYP_TODO lines.
  1643. Each keyword can optionally specify a character for fast state selection
  1644. \(in combination with the variable `org-use-fast-todo-selection')
  1645. and specifiers for state change logging, using the same syntax that
  1646. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1647. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1648. indicates to record a time stamp each time this state is selected.
  1649. Each keyword may also specify if a timestamp or a note should be
  1650. recorded when entering or leaving the state, by adding additional
  1651. characters in the parenthesis after the keyword. This looks like this:
  1652. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1653. record only the time of the state change. With X and Y being either
  1654. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1655. Y when leaving the state if and only if the *target* state does not
  1656. define X. You may omit any of the fast-selection key or X or /Y,
  1657. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1658. For backward compatibility, this variable may also be just a list
  1659. of keywords. In this case the interpretation (sequence or type) will be
  1660. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1661. :group 'org-todo
  1662. :group 'org-keywords
  1663. :type '(choice
  1664. (repeat :tag "Old syntax, just keywords"
  1665. (string :tag "Keyword"))
  1666. (repeat :tag "New syntax"
  1667. (cons
  1668. (choice
  1669. :tag "Interpretation"
  1670. ;;Quick and dirty way to see
  1671. ;;`org-todo-interpretation'. This takes the
  1672. ;;place of item arguments
  1673. :convert-widget
  1674. (lambda (widget)
  1675. (widget-put widget
  1676. :args (mapcar
  1677. (lambda (x)
  1678. (widget-convert
  1679. (cons 'const x)))
  1680. org-todo-interpretation-widgets))
  1681. widget))
  1682. (repeat
  1683. (string :tag "Keyword"))))))
  1684. (defvar-local org-todo-keywords-1 nil
  1685. "All TODO and DONE keywords active in a buffer.")
  1686. (defvar org-todo-keywords-for-agenda nil)
  1687. (defvar org-done-keywords-for-agenda nil)
  1688. (defvar org-todo-keyword-alist-for-agenda nil)
  1689. (defvar org-tag-alist-for-agenda nil
  1690. "Alist of all tags from all agenda files.")
  1691. (defvar org-tag-groups-alist-for-agenda nil
  1692. "Alist of all groups tags from all current agenda files.")
  1693. (defvar-local org-tag-groups-alist nil)
  1694. (defvar org-agenda-contributing-files nil)
  1695. (defvar-local org-current-tag-alist nil
  1696. "Alist of all tag groups in current buffer.
  1697. This variable takes into consideration `org-tag-alist',
  1698. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1699. (defvar-local org-not-done-keywords nil)
  1700. (defvar-local org-done-keywords nil)
  1701. (defvar-local org-todo-heads nil)
  1702. (defvar-local org-todo-sets nil)
  1703. (defvar-local org-todo-log-states nil)
  1704. (defvar-local org-todo-kwd-alist nil)
  1705. (defvar-local org-todo-key-alist nil)
  1706. (defvar-local org-todo-key-trigger nil)
  1707. (defcustom org-todo-interpretation 'sequence
  1708. "Controls how TODO keywords are interpreted.
  1709. This variable is in principle obsolete and is only used for
  1710. backward compatibility, if the interpretation of todo keywords is
  1711. not given already in `org-todo-keywords'. See that variable for
  1712. more information."
  1713. :group 'org-todo
  1714. :group 'org-keywords
  1715. :type '(choice (const sequence)
  1716. (const type)))
  1717. (defcustom org-use-fast-todo-selection 'auto
  1718. "\\<org-mode-map>\
  1719. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1720. This variable describes if and under what circumstances the cycling
  1721. mechanism for TODO keywords will be replaced by a single-key, direct
  1722. selection scheme, where the choices are displayed in a little window.
  1723. When nil, fast selection is never used. This means that the command
  1724. will always switch to the next state.
  1725. When it is the symbol `auto', fast selection is whenever selection
  1726. keys have been defined.
  1727. `expert' is like `auto', but no special window with the keyword
  1728. will be shown, choices will only be listed in the prompt.
  1729. In all cases, the special interface is only used if access keys have
  1730. actually been assigned by the user, i.e. if keywords in the configuration
  1731. are followed by a letter in parenthesis, like TODO(t)."
  1732. :group 'org-todo
  1733. :set (lambda (var val)
  1734. (cond
  1735. ((eq var t) (set var 'auto))
  1736. ((eq var 'prefix) (set var nil))
  1737. (t (set var val))))
  1738. :type '(choice
  1739. (const :tag "Never" nil)
  1740. (const :tag "Automatically, when key letter have been defined" auto)
  1741. (const :tag "Automatically, but don't show the selection window" expert)))
  1742. (defcustom org-provide-todo-statistics t
  1743. "Non-nil means update todo statistics after insert and toggle.
  1744. ALL-HEADLINES means update todo statistics by including headlines
  1745. with no TODO keyword as well, counting them as not done.
  1746. A list of TODO keywords means the same, but skip keywords that are
  1747. not in this list.
  1748. When set to a list of two lists, the first list contains keywords
  1749. to consider as TODO keywords, the second list contains keywords
  1750. to consider as DONE keywords.
  1751. When this is set, todo statistics is updated in the parent of the
  1752. current entry each time a todo state is changed."
  1753. :group 'org-todo
  1754. :type '(choice
  1755. (const :tag "Yes, only for TODO entries" t)
  1756. (const :tag "Yes, including all entries" all-headlines)
  1757. (repeat :tag "Yes, for TODOs in this list"
  1758. (string :tag "TODO keyword"))
  1759. (list :tag "Yes, for TODOs and DONEs in these lists"
  1760. (repeat (string :tag "TODO keyword"))
  1761. (repeat (string :tag "DONE keyword")))
  1762. (other :tag "No TODO statistics" nil)))
  1763. (defcustom org-hierarchical-todo-statistics t
  1764. "Non-nil means TODO statistics covers just direct children.
  1765. When nil, all entries in the subtree are considered.
  1766. This has only an effect if `org-provide-todo-statistics' is set.
  1767. To set this to nil for only a single subtree, use a COOKIE_DATA
  1768. property and include the word \"recursive\" into the value."
  1769. :group 'org-todo
  1770. :type 'boolean)
  1771. (defcustom org-after-todo-state-change-hook nil
  1772. "Hook which is run after the state of a TODO item was changed.
  1773. The new state (a string with a TODO keyword, or nil) is available in the
  1774. Lisp variable `org-state'."
  1775. :group 'org-todo
  1776. :type 'hook)
  1777. (defvar org-blocker-hook nil
  1778. "Hook for functions that are allowed to block a state change.
  1779. Functions in this hook should not modify the buffer.
  1780. Each function gets as its single argument a property list,
  1781. see `org-trigger-hook' for more information about this list.
  1782. If any of the functions in this hook returns nil, the state change
  1783. is blocked.")
  1784. (defvar org-trigger-hook nil
  1785. "Hook for functions that are triggered by a state change.
  1786. Each function gets as its single argument a property list with at
  1787. least the following elements:
  1788. (:type type-of-change :position pos-at-entry-start
  1789. :from old-state :to new-state)
  1790. Depending on the type, more properties may be present.
  1791. This mechanism is currently implemented for:
  1792. TODO state changes
  1793. ------------------
  1794. :type todo-state-change
  1795. :from previous state (keyword as a string), or nil, or a symbol
  1796. `todo' or `done', to indicate the general type of state.
  1797. :to new state, like in :from")
  1798. (defcustom org-enforce-todo-dependencies nil
  1799. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1800. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1801. be blocked if any prior sibling is not yet done.
  1802. Finally, if the parent is blocked because of ordered siblings of its own,
  1803. the child will also be blocked."
  1804. :set (lambda (var val)
  1805. (set var val)
  1806. (if val
  1807. (add-hook 'org-blocker-hook
  1808. 'org-block-todo-from-children-or-siblings-or-parent)
  1809. (remove-hook 'org-blocker-hook
  1810. 'org-block-todo-from-children-or-siblings-or-parent)))
  1811. :group 'org-todo
  1812. :type 'boolean)
  1813. (defcustom org-enforce-todo-checkbox-dependencies nil
  1814. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1815. When this is nil, checkboxes have no influence on switching TODO states.
  1816. When non-nil, you first need to check off all check boxes before the TODO
  1817. entry can be switched to DONE.
  1818. This variable needs to be set before org.el is loaded, and you need to
  1819. restart Emacs after a change to make the change effective. The only way
  1820. to change it while Emacs is running is through the customize interface."
  1821. :set (lambda (var val)
  1822. (set var val)
  1823. (if val
  1824. (add-hook 'org-blocker-hook
  1825. 'org-block-todo-from-checkboxes)
  1826. (remove-hook 'org-blocker-hook
  1827. 'org-block-todo-from-checkboxes)))
  1828. :group 'org-todo
  1829. :type 'boolean)
  1830. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1831. "Non-nil means inserting a TODO heading is treated as state change.
  1832. So when the command `\\[org-insert-todo-heading]' is used, state change
  1833. logging will apply if appropriate. When nil, the new TODO item will
  1834. be inserted directly, and no logging will take place."
  1835. :group 'org-todo
  1836. :type 'boolean)
  1837. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1838. "Non-nil means switching TODO states with S-cursor counts as state change.
  1839. This is the default behavior. However, setting this to nil allows a
  1840. convenient way to select a TODO state and bypass any logging associated
  1841. with that."
  1842. :group 'org-todo
  1843. :type 'boolean)
  1844. (defcustom org-todo-state-tags-triggers nil
  1845. "Tag changes that should be triggered by TODO state changes.
  1846. This is a list. Each entry is
  1847. (state-change (tag . flag) .......)
  1848. State-change can be a string with a state, and empty string to indicate the
  1849. state that has no TODO keyword, or it can be one of the symbols `todo'
  1850. or `done', meaning any not-done or done state, respectively."
  1851. :group 'org-todo
  1852. :group 'org-tags
  1853. :type '(repeat
  1854. (cons (choice :tag "When changing to"
  1855. (const :tag "Not-done state" todo)
  1856. (const :tag "Done state" done)
  1857. (string :tag "State"))
  1858. (repeat
  1859. (cons :tag "Tag action"
  1860. (string :tag "Tag")
  1861. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1862. (defcustom org-log-done nil
  1863. "Information to record when a task moves to the DONE state.
  1864. Possible values are:
  1865. nil Don't add anything, just change the keyword
  1866. time Add a time stamp to the task
  1867. note Prompt for a note and add it with template `org-log-note-headings'
  1868. This option can also be set with on a per-file-basis with
  1869. #+STARTUP: nologdone
  1870. #+STARTUP: logdone
  1871. #+STARTUP: lognotedone
  1872. You can have local logging settings for a subtree by setting the LOGGING
  1873. property to one or more of these keywords."
  1874. :group 'org-todo
  1875. :group 'org-progress
  1876. :type '(choice
  1877. (const :tag "No logging" nil)
  1878. (const :tag "Record CLOSED timestamp" time)
  1879. (const :tag "Record CLOSED timestamp with note." note)))
  1880. ;; Normalize old uses of org-log-done.
  1881. (cond
  1882. ((eq org-log-done t) (setq org-log-done 'time))
  1883. ((and (listp org-log-done) (memq 'done org-log-done))
  1884. (setq org-log-done 'note)))
  1885. (defcustom org-log-reschedule nil
  1886. "Information to record when the scheduling date of a task is modified.
  1887. Possible values are:
  1888. nil Don't add anything, just change the date
  1889. time Add a time stamp to the task
  1890. note Prompt for a note and add it with template `org-log-note-headings'
  1891. This option can also be set with on a per-file-basis with
  1892. #+STARTUP: nologreschedule
  1893. #+STARTUP: logreschedule
  1894. #+STARTUP: lognotereschedule
  1895. You can have local logging settings for a subtree by setting the LOGGING
  1896. property to one or more of these keywords.
  1897. This variable has an effect when calling `org-schedule' or
  1898. `org-agenda-schedule' only."
  1899. :group 'org-todo
  1900. :group 'org-progress
  1901. :type '(choice
  1902. (const :tag "No logging" nil)
  1903. (const :tag "Record timestamp" time)
  1904. (const :tag "Record timestamp with note" note)))
  1905. (defcustom org-log-redeadline nil
  1906. "Information to record when the deadline date of a task is modified.
  1907. Possible values are:
  1908. nil Don't add anything, just change the date
  1909. time Add a time stamp to the task
  1910. note Prompt for a note and add it with template `org-log-note-headings'
  1911. This option can also be set with on a per-file-basis with
  1912. #+STARTUP: nologredeadline
  1913. #+STARTUP: logredeadline
  1914. #+STARTUP: lognoteredeadline
  1915. You can have local logging settings for a subtree by setting the LOGGING
  1916. property to one or more of these keywords.
  1917. This variable has an effect when calling `org-deadline' or
  1918. `org-agenda-deadline' only."
  1919. :group 'org-todo
  1920. :group 'org-progress
  1921. :type '(choice
  1922. (const :tag "No logging" nil)
  1923. (const :tag "Record timestamp" time)
  1924. (const :tag "Record timestamp with note." note)))
  1925. (defcustom org-log-note-clock-out nil
  1926. "Non-nil means record a note when clocking out of an item.
  1927. This can also be configured on a per-file basis by adding one of
  1928. the following lines anywhere in the buffer:
  1929. #+STARTUP: lognoteclock-out
  1930. #+STARTUP: nolognoteclock-out"
  1931. :group 'org-todo
  1932. :group 'org-progress
  1933. :type 'boolean)
  1934. (defcustom org-log-done-with-time t
  1935. "Non-nil means the CLOSED time stamp will contain date and time.
  1936. When nil, only the date will be recorded."
  1937. :group 'org-progress
  1938. :type 'boolean)
  1939. (defcustom org-log-note-headings
  1940. '((done . "CLOSING NOTE %t")
  1941. (state . "State %-12s from %-12S %t")
  1942. (note . "Note taken on %t")
  1943. (reschedule . "Rescheduled from %S on %t")
  1944. (delschedule . "Not scheduled, was %S on %t")
  1945. (redeadline . "New deadline from %S on %t")
  1946. (deldeadline . "Removed deadline, was %S on %t")
  1947. (refile . "Refiled on %t")
  1948. (clock-out . ""))
  1949. "Headings for notes added to entries.
  1950. The value is an alist, with the car being a symbol indicating the
  1951. note context, and the cdr is the heading to be used. The heading
  1952. may also be the empty string. The following placeholders can be
  1953. used:
  1954. %t a time stamp.
  1955. %T an active time stamp instead the default inactive one
  1956. %d a short-format time stamp.
  1957. %D an active short-format time stamp.
  1958. %s the new TODO state or time stamp (inactive), in double quotes.
  1959. %S the old TODO state or time stamp (inactive), in double quotes.
  1960. %u the user name.
  1961. %U full user name.
  1962. In fact, it is not a good idea to change the `state' entry,
  1963. because Agenda Log mode depends on the format of these entries."
  1964. :group 'org-todo
  1965. :group 'org-progress
  1966. :type '(list :greedy t
  1967. (cons (const :tag "Heading when closing an item" done) string)
  1968. (cons (const :tag
  1969. "Heading when changing todo state (todo sequence only)"
  1970. state) string)
  1971. (cons (const :tag "Heading when just taking a note" note) string)
  1972. (cons (const :tag "Heading when rescheduling" reschedule) string)
  1973. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  1974. (cons (const :tag "Heading when changing deadline" redeadline) string)
  1975. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  1976. (cons (const :tag "Heading when refiling" refile) string)
  1977. (cons (const :tag "Heading when clocking out" clock-out) string)))
  1978. (unless (assq 'note org-log-note-headings)
  1979. (push '(note . "%t") org-log-note-headings))
  1980. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  1981. (defcustom org-log-into-drawer nil
  1982. "Non-nil means insert state change notes and time stamps into a drawer.
  1983. When nil, state changes notes will be inserted after the headline and
  1984. any scheduling and clock lines, but not inside a drawer.
  1985. The value of this variable should be the name of the drawer to use.
  1986. LOGBOOK is proposed as the default drawer for this purpose, you can
  1987. also set this to a string to define the drawer of your choice.
  1988. A value of t is also allowed, representing \"LOGBOOK\".
  1989. A value of t or nil can also be set with on a per-file-basis with
  1990. #+STARTUP: logdrawer
  1991. #+STARTUP: nologdrawer
  1992. If this variable is set, `org-log-state-notes-insert-after-drawers'
  1993. will be ignored.
  1994. You can set the property LOG_INTO_DRAWER to overrule this setting for
  1995. a subtree.
  1996. Do not check directly this variable in a Lisp program. Call
  1997. function `org-log-into-drawer' instead."
  1998. :group 'org-todo
  1999. :group 'org-progress
  2000. :type '(choice
  2001. (const :tag "Not into a drawer" nil)
  2002. (const :tag "LOGBOOK" t)
  2003. (string :tag "Other")))
  2004. (defun org-log-into-drawer ()
  2005. "Name of the log drawer, as a string, or nil.
  2006. This is the value of `org-log-into-drawer'. However, if the
  2007. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2008. be used instead of the default value."
  2009. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2010. (cond ((equal p "nil") nil)
  2011. ((equal p "t") "LOGBOOK")
  2012. ((stringp p) p)
  2013. (p "LOGBOOK")
  2014. ((stringp org-log-into-drawer) org-log-into-drawer)
  2015. (org-log-into-drawer "LOGBOOK"))))
  2016. (defcustom org-log-state-notes-insert-after-drawers nil
  2017. "Non-nil means insert state change notes after any drawers in entry.
  2018. Only the drawers that *immediately* follow the headline and the
  2019. deadline/scheduled line are skipped.
  2020. When nil, insert notes right after the heading and perhaps the line
  2021. with deadline/scheduling if present.
  2022. This variable will have no effect if `org-log-into-drawer' is
  2023. set."
  2024. :group 'org-todo
  2025. :group 'org-progress
  2026. :type 'boolean)
  2027. (defcustom org-log-states-order-reversed t
  2028. "Non-nil means the latest state note will be directly after heading.
  2029. When nil, the state change notes will be ordered according to time.
  2030. This option can also be set with on a per-file-basis with
  2031. #+STARTUP: logstatesreversed
  2032. #+STARTUP: nologstatesreversed"
  2033. :group 'org-todo
  2034. :group 'org-progress
  2035. :type 'boolean)
  2036. (defcustom org-todo-repeat-to-state nil
  2037. "The TODO state to which a repeater should return the repeating task.
  2038. By default this is the first task of a TODO sequence or the
  2039. previous state of a TYPE_TODO set. But you can specify to use
  2040. the previous state in a TODO sequence or a string.
  2041. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2042. entry, which has precedence over this option."
  2043. :group 'org-todo
  2044. :version "24.1"
  2045. :type '(choice (const :tag "Use the previous TODO state" t)
  2046. (const :tag "Use the head of the TODO sequence" nil)
  2047. (string :tag "Use a specific TODO state")))
  2048. (defcustom org-log-repeat 'time
  2049. "Non-nil means record moving through the DONE state when triggering repeat.
  2050. An auto-repeating task is immediately switched back to TODO when
  2051. marked DONE. If you are not logging state changes (by adding \"@\"
  2052. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2053. record a closing note, there will be no record of the task moving
  2054. through DONE. This variable forces taking a note anyway.
  2055. nil Don't force a record
  2056. time Record a time stamp
  2057. note Prompt for a note and add it with template `org-log-note-headings'
  2058. This option can also be set with on a per-file-basis with
  2059. #+STARTUP: nologrepeat
  2060. #+STARTUP: logrepeat
  2061. #+STARTUP: lognoterepeat
  2062. You can have local logging settings for a subtree by setting the LOGGING
  2063. property to one or more of these keywords."
  2064. :group 'org-todo
  2065. :group 'org-progress
  2066. :type '(choice
  2067. (const :tag "Don't force a record" nil)
  2068. (const :tag "Force recording the DONE state" time)
  2069. (const :tag "Force recording a note with the DONE state" note)))
  2070. (defcustom org-todo-repeat-hook nil
  2071. "Hook that is run after a task has been repeated."
  2072. :package-version '(Org . "9.2")
  2073. :group 'org-todo
  2074. :type 'hook)
  2075. (defgroup org-priorities nil
  2076. "Priorities in Org mode."
  2077. :tag "Org Priorities"
  2078. :group 'org-todo)
  2079. (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
  2080. (defcustom org-priority-enable-commands t
  2081. "Non-nil means priority commands are active.
  2082. When nil, these commands will be disabled, so that you never accidentally
  2083. set a priority."
  2084. :group 'org-priorities
  2085. :type 'boolean)
  2086. (defvaralias 'org-highest-priority 'org-priority-highest)
  2087. (defcustom org-priority-highest ?A
  2088. "The highest priority of TODO items.
  2089. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  2090. Must be smaller than `org-priority-lowest'."
  2091. :group 'org-priorities
  2092. :type '(choice
  2093. (character :tag "Character")
  2094. (integer :tag "Integer (< 65)")))
  2095. (defvaralias 'org-lowest-priority 'org-priority-lowest)
  2096. (defcustom org-priority-lowest ?C
  2097. "The lowest priority of TODO items.
  2098. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  2099. Must be higher than `org-priority-highest'."
  2100. :group 'org-priorities
  2101. :type '(choice
  2102. (character :tag "Character")
  2103. (integer :tag "Integer (< 65)")))
  2104. (defvaralias 'org-default-priority 'org-priority-default)
  2105. (defcustom org-priority-default ?B
  2106. "The default priority of TODO items.
  2107. This is the priority an item gets if no explicit priority is given.
  2108. When starting to cycle on an empty priority the first step in the cycle
  2109. depends on `org-priority-start-cycle-with-default'. The resulting first
  2110. step priority must not exceed the range from `org-priority-highest' to
  2111. `org-priority-lowest' which means that `org-priority-default' has to be
  2112. in this range exclusive or inclusive to the range boundaries. Else the
  2113. first step refuses to set the default and the second will fall back on
  2114. \(depending on the command used) the highest or lowest priority."
  2115. :group 'org-priorities
  2116. :type '(choice
  2117. (character :tag "Character")
  2118. (integer :tag "Integer (< 65)")))
  2119. (defcustom org-priority-start-cycle-with-default t
  2120. "Non-nil means start with default priority when starting to cycle.
  2121. When this is nil, the first step in the cycle will be (depending on the
  2122. command used) one higher or lower than the default priority.
  2123. See also `org-priority-default'."
  2124. :group 'org-priorities
  2125. :type 'boolean)
  2126. (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
  2127. (defcustom org-priority-get-priority-function nil
  2128. "Function to extract the priority from a string.
  2129. The string is normally the headline. If this is nil, Org
  2130. computes the priority from the priority cookie like [#A] in the
  2131. headline. It returns an integer, increasing by 1000 for each
  2132. priority level.
  2133. The user can set a different function here, which should take a
  2134. string as an argument and return the numeric priority."
  2135. :group 'org-priorities
  2136. :version "24.1"
  2137. :type '(choice
  2138. (const nil)
  2139. (function)))
  2140. (defgroup org-time nil
  2141. "Options concerning time stamps and deadlines in Org mode."
  2142. :tag "Org Time"
  2143. :group 'org)
  2144. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2145. "Number of minutes to round time stamps to.
  2146. \\<org-mode-map>\
  2147. These are two values, the first applies when first creating a time stamp.
  2148. The second applies when changing it with the commands `S-up' and `S-down'.
  2149. When changing the time stamp, this means that it will change in steps
  2150. of N minutes, as given by the second value.
  2151. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2152. numbers should be factors of 60, so for example 5, 10, 15.
  2153. When this is larger than 1, you can still force an exact time stamp by using
  2154. a double prefix argument to a time stamp command like \
  2155. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2156. and by using a prefix arg to `S-up/down' to specify the exact number
  2157. of minutes to shift."
  2158. :group 'org-time
  2159. :get (lambda (var) ; Make sure both elements are there
  2160. (if (integerp (default-value var))
  2161. (list (default-value var) 5)
  2162. (default-value var)))
  2163. :type '(list
  2164. (integer :tag "when inserting times")
  2165. (integer :tag "when modifying times")))
  2166. ;; Normalize old customizations of this variable.
  2167. (when (integerp org-time-stamp-rounding-minutes)
  2168. (setq org-time-stamp-rounding-minutes
  2169. (list org-time-stamp-rounding-minutes
  2170. org-time-stamp-rounding-minutes)))
  2171. (defcustom org-display-custom-times nil
  2172. "Non-nil means overlay custom formats over all time stamps.
  2173. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2174. To turn this on on a per-file basis, insert anywhere in the file:
  2175. #+STARTUP: customtime"
  2176. :group 'org-time
  2177. :set 'set-default
  2178. :type 'sexp)
  2179. (make-variable-buffer-local 'org-display-custom-times)
  2180. (defcustom org-time-stamp-custom-formats
  2181. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2182. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2183. These are overlaid over the default ISO format if the variable
  2184. `org-display-custom-times' is set. Time like %H:%M should be at the
  2185. end of the second format. The custom formats are also honored by export
  2186. commands, if custom time display is turned on at the time of export."
  2187. :group 'org-time
  2188. :type 'sexp)
  2189. (defun org-time-stamp-format (&optional long inactive)
  2190. "Get the right format for a time string."
  2191. (let ((f (if long (cdr org-time-stamp-formats)
  2192. (car org-time-stamp-formats))))
  2193. (if inactive
  2194. (concat "[" (substring f 1 -1) "]")
  2195. f)))
  2196. (defcustom org-deadline-warning-days 14
  2197. "Number of days before expiration during which a deadline becomes active.
  2198. This variable governs the display in sparse trees and in the agenda.
  2199. When 0 or negative, it means use this number (the absolute value of it)
  2200. even if a deadline has a different individual lead time specified.
  2201. Custom commands can set this variable in the options section."
  2202. :group 'org-time
  2203. :group 'org-agenda-daily/weekly
  2204. :type 'integer)
  2205. (defcustom org-scheduled-delay-days 0
  2206. "Number of days before a scheduled item becomes active.
  2207. This variable governs the display in sparse trees and in the agenda.
  2208. The default value (i.e. 0) means: don't delay scheduled item.
  2209. When negative, it means use this number (the absolute value of it)
  2210. even if a scheduled item has a different individual delay time
  2211. specified.
  2212. Custom commands can set this variable in the options section."
  2213. :group 'org-time
  2214. :group 'org-agenda-daily/weekly
  2215. :version "24.4"
  2216. :package-version '(Org . "8.0")
  2217. :type 'integer)
  2218. (defcustom org-read-date-prefer-future t
  2219. "Non-nil means assume future for incomplete date input from user.
  2220. This affects the following situations:
  2221. 1. The user gives a month but not a year.
  2222. For example, if it is April and you enter \"feb 2\", this will be read
  2223. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2224. 2. The user gives a day, but no month.
  2225. For example, if today is the 15th, and you enter \"3\", Org will read
  2226. this as the third of *next* month. However, if you enter \"17\",
  2227. it will be considered as *this* month.
  2228. If you set this variable to the symbol `time', then also the following
  2229. will work:
  2230. 3. If the user gives a time.
  2231. If the time is before now, it will be interpreted as tomorrow.
  2232. Currently none of this works for ISO week specifications.
  2233. When this option is nil, the current day, month and year will always be
  2234. used as defaults.
  2235. See also `org-agenda-jump-prefer-future'."
  2236. :group 'org-time
  2237. :type '(choice
  2238. (const :tag "Never" nil)
  2239. (const :tag "Check month and day" t)
  2240. (const :tag "Check month, day, and time" time)))
  2241. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2242. "Should the agenda jump command prefer the future for incomplete dates?
  2243. The default is to do the same as configured in `org-read-date-prefer-future'.
  2244. But you can also set a deviating value here.
  2245. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2246. :group 'org-agenda
  2247. :group 'org-time
  2248. :version "24.1"
  2249. :type '(choice
  2250. (const :tag "Use org-read-date-prefer-future"
  2251. org-read-date-prefer-future)
  2252. (const :tag "Never" nil)
  2253. (const :tag "Always" t)))
  2254. (defcustom org-read-date-force-compatible-dates t
  2255. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2256. Depending on the system Emacs is running on, certain dates cannot
  2257. be represented with the type used internally to represent time.
  2258. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2259. correctly. Some systems allow for earlier dates, some for later,
  2260. some for both. One way to find out is to insert any date into an
  2261. Org buffer, putting the cursor on the year and hitting S-up and
  2262. S-down to test the range.
  2263. When this variable is set to t, the date/time prompt will not let
  2264. you specify dates outside the 1970-2037 range, so it is certain that
  2265. these dates will work in whatever version of Emacs you are
  2266. running, and also that you can move a file from one Emacs implementation
  2267. to another. Whenever Org is forcing the year for you, it will display
  2268. a message and beep.
  2269. When this variable is nil, Org will check if the date is
  2270. representable in the specific Emacs implementation you are using.
  2271. If not, it will force a year, usually the current year, and beep
  2272. to remind you. Currently this setting is not recommended because
  2273. the likelihood that you will open your Org files in an Emacs that
  2274. has limited date range is not negligible.
  2275. A workaround for this problem is to use diary sexp dates for time
  2276. stamps outside of this range."
  2277. :group 'org-time
  2278. :version "24.1"
  2279. :type 'boolean)
  2280. (defcustom org-read-date-display-live t
  2281. "Non-nil means display current interpretation of date prompt live.
  2282. This display will be in an overlay, in the minibuffer. Note that
  2283. live display is only active when `org-read-date-popup-calendar'
  2284. is non-nil."
  2285. :group 'org-time
  2286. :type 'boolean)
  2287. (defvaralias 'org-popup-calendar-for-date-prompt
  2288. 'org-read-date-popup-calendar)
  2289. (defcustom org-read-date-popup-calendar t
  2290. "Non-nil means pop up a calendar when prompting for a date.
  2291. In the calendar, the date can be selected with mouse-1. However, the
  2292. minibuffer will also be active, and you can simply enter the date as well.
  2293. When nil, only the minibuffer will be available."
  2294. :group 'org-time
  2295. :type 'boolean)
  2296. (defcustom org-extend-today-until 0
  2297. "The hour when your day really ends. Must be an integer.
  2298. This has influence for the following applications:
  2299. - When switching the agenda to \"today\". If it is still earlier than
  2300. the time given here, the day recognized as TODAY is actually yesterday.
  2301. - When a date is read from the user and it is still before the time given
  2302. here, the current date and time will be assumed to be yesterday, 23:59.
  2303. Also, timestamps inserted in capture templates follow this rule.
  2304. IMPORTANT: This is a feature whose implementation is and likely will
  2305. remain incomplete. Really, it is only here because past midnight seems to
  2306. be the favorite working time of John Wiegley :-)"
  2307. :group 'org-time
  2308. :type 'integer)
  2309. (defcustom org-use-effective-time nil
  2310. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2311. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2312. \"effective time\" of any timestamps between midnight and 8am will be
  2313. 23:59 of the previous day."
  2314. :group 'org-time
  2315. :version "24.1"
  2316. :type 'boolean)
  2317. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2318. "When non-nil, use the last clock out time for `org-todo'.
  2319. Note that this option has precedence over the combined use of
  2320. `org-use-effective-time' and `org-extend-today-until'."
  2321. :group 'org-time
  2322. :version "24.4"
  2323. :package-version '(Org . "8.0")
  2324. :type 'boolean)
  2325. (defcustom org-edit-timestamp-down-means-later nil
  2326. "Non-nil means S-down will increase the time in a time stamp.
  2327. When nil, S-up will increase."
  2328. :group 'org-time
  2329. :type 'boolean)
  2330. (defcustom org-calendar-follow-timestamp-change t
  2331. "Non-nil means make the calendar window follow timestamp changes.
  2332. When a timestamp is modified and the calendar window is visible, it will be
  2333. moved to the new date."
  2334. :group 'org-time
  2335. :type 'boolean)
  2336. (defgroup org-tags nil
  2337. "Options concerning tags in Org mode."
  2338. :tag "Org Tags"
  2339. :group 'org)
  2340. (defcustom org-tag-alist nil
  2341. "Default tags available in Org files.
  2342. The value of this variable is an alist. Associations either:
  2343. (TAG)
  2344. (TAG . SELECT)
  2345. (SPECIAL)
  2346. where TAG is a tag as a string, SELECT is character, used to
  2347. select that tag through the fast tag selection interface, and
  2348. SPECIAL is one of the following keywords: `:startgroup',
  2349. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2350. `:newline'. These keywords are used to define a hierarchy of
  2351. tags. See manual for details.
  2352. When this variable is nil, Org mode bases tag input on what is
  2353. already in the buffer. The value can be overridden locally by
  2354. using a TAGS keyword, e.g.,
  2355. #+TAGS: tag1 tag2
  2356. See also `org-tag-persistent-alist' to sidestep this behavior."
  2357. :group 'org-tags
  2358. :type '(repeat
  2359. (choice
  2360. (cons :tag "Tag with key"
  2361. (string :tag "Tag name")
  2362. (character :tag "Access char"))
  2363. (list :tag "Tag" (string :tag "Tag name"))
  2364. (const :tag "Start radio group" (:startgroup))
  2365. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2366. (const :tag "Group tags delimiter" (:grouptags))
  2367. (const :tag "End radio group" (:endgroup))
  2368. (const :tag "End tag group, non distinct" (:endgrouptag))
  2369. (const :tag "New line" (:newline)))))
  2370. (defcustom org-tag-persistent-alist nil
  2371. "Tags always available in Org files.
  2372. The value of this variable is an alist. Associations either:
  2373. (TAG)
  2374. (TAG . SELECT)
  2375. (SPECIAL)
  2376. where TAG is a tag as a string, SELECT is a character, used to
  2377. select that tag through the fast tag selection interface, and
  2378. SPECIAL is one of the following keywords: `:startgroup',
  2379. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2380. `:newline'. These keywords are used to define a hierarchy of
  2381. tags. See manual for details.
  2382. Unlike to `org-tag-alist', tags defined in this variable do not
  2383. depend on a local TAGS keyword. Instead, to disable these tags
  2384. on a per-file basis, insert anywhere in the file:
  2385. #+STARTUP: noptag"
  2386. :group 'org-tags
  2387. :type '(repeat
  2388. (choice
  2389. (cons :tag "Tag with key"
  2390. (string :tag "Tag name")
  2391. (character :tag "Access char"))
  2392. (list :tag "Tag" (string :tag "Tag name"))
  2393. (const :tag "Start radio group" (:startgroup))
  2394. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2395. (const :tag "Group tags delimiter" (:grouptags))
  2396. (const :tag "End radio group" (:endgroup))
  2397. (const :tag "End tag group, non distinct" (:endgrouptag))
  2398. (const :tag "New line" (:newline)))))
  2399. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2400. "If non-nil, always offer completion for all tags of all agenda files.
  2401. Setting this variable locally allows for dynamic generation of tag
  2402. completions in capture buffers.
  2403. (add-hook \\='org-capture-mode-hook
  2404. (lambda ()
  2405. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2406. :group 'org-tags
  2407. :version "24.1"
  2408. :type 'boolean)
  2409. (defvar org-file-tags nil
  2410. "List of tags that can be inherited by all entries in the file.
  2411. The tags will be inherited if the variable `org-use-tag-inheritance'
  2412. says they should be.
  2413. This variable is populated from #+FILETAGS lines.")
  2414. (defcustom org-use-fast-tag-selection 'auto
  2415. "Non-nil means use fast tag selection scheme.
  2416. This is a special interface to select and deselect tags with single keys.
  2417. When nil, fast selection is never used.
  2418. When the symbol `auto', fast selection is used if and only if selection
  2419. characters for tags have been configured, either through the variable
  2420. `org-tag-alist' or through a #+TAGS line in the buffer.
  2421. When t, fast selection is always used and selection keys are assigned
  2422. automatically if necessary."
  2423. :group 'org-tags
  2424. :type '(choice
  2425. (const :tag "Always" t)
  2426. (const :tag "Never" nil)
  2427. (const :tag "When selection characters are configured" auto)))
  2428. (defcustom org-fast-tag-selection-single-key nil
  2429. "Non-nil means fast tag selection exits after first change.
  2430. When nil, you have to press RET to exit it.
  2431. During fast tag selection, you can toggle this flag with `C-c'.
  2432. This variable can also have the value `expert'. In this case, the window
  2433. displaying the tags menu is not even shown, until you press `C-c' again."
  2434. :group 'org-tags
  2435. :type '(choice
  2436. (const :tag "No" nil)
  2437. (const :tag "Yes" t)
  2438. (const :tag "Expert" expert)))
  2439. (defvar org-fast-tag-selection-include-todo nil
  2440. "Non-nil means fast tags selection interface will also offer TODO states.
  2441. This is an undocumented feature, you should not rely on it.")
  2442. (defcustom org-tags-column -77
  2443. "The column to which tags should be indented in a headline.
  2444. If this number is positive, it specifies the column. If it is negative,
  2445. it means that the tags should be flushright to that column. For example,
  2446. -80 works well for a normal 80 character screen.
  2447. When 0, place tags directly after headline text, with only one space in
  2448. between."
  2449. :group 'org-tags
  2450. :type 'integer)
  2451. (defcustom org-auto-align-tags t
  2452. "Non-nil keeps tags aligned when modifying headlines.
  2453. Some operations (i.e. demoting) change the length of a headline and
  2454. therefore shift the tags around. With this option turned on, after
  2455. each such operation the tags are again aligned to `org-tags-column'."
  2456. :group 'org-tags
  2457. :type 'boolean)
  2458. (defcustom org-use-tag-inheritance t
  2459. "Non-nil means tags in levels apply also for sublevels.
  2460. When nil, only the tags directly given in a specific line apply there.
  2461. This may also be a list of tags that should be inherited, or a regexp that
  2462. matches tags that should be inherited. Additional control is possible
  2463. with the variable `org-tags-exclude-from-inheritance' which gives an
  2464. explicit list of tags to be excluded from inheritance, even if the value of
  2465. `org-use-tag-inheritance' would select it for inheritance.
  2466. If this option is t, a match early-on in a tree can lead to a large
  2467. number of matches in the subtree when constructing the agenda or creating
  2468. a sparse tree. If you only want to see the first match in a tree during
  2469. a search, check out the variable `org-tags-match-list-sublevels'."
  2470. :group 'org-tags
  2471. :type '(choice
  2472. (const :tag "Not" nil)
  2473. (const :tag "Always" t)
  2474. (repeat :tag "Specific tags" (string :tag "Tag"))
  2475. (regexp :tag "Tags matched by regexp")))
  2476. (defcustom org-tags-exclude-from-inheritance nil
  2477. "List of tags that should never be inherited.
  2478. This is a way to exclude a few tags from inheritance. For way to do
  2479. the opposite, to actively allow inheritance for selected tags,
  2480. see the variable `org-use-tag-inheritance'."
  2481. :group 'org-tags
  2482. :type '(repeat (string :tag "Tag")))
  2483. (defun org-tag-inherit-p (tag)
  2484. "Check if TAG is one that should be inherited."
  2485. (cond
  2486. ((member tag org-tags-exclude-from-inheritance) nil)
  2487. ((eq org-use-tag-inheritance t) t)
  2488. ((not org-use-tag-inheritance) nil)
  2489. ((stringp org-use-tag-inheritance)
  2490. (string-match org-use-tag-inheritance tag))
  2491. ((listp org-use-tag-inheritance)
  2492. (member tag org-use-tag-inheritance))
  2493. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2494. (defcustom org-tags-match-list-sublevels t
  2495. "Non-nil means list also sublevels of headlines matching a search.
  2496. This variable applies to tags/property searches, and also to stuck
  2497. projects because this search is based on a tags match as well.
  2498. When set to the symbol `indented', sublevels are indented with
  2499. leading dots.
  2500. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2501. the sublevels of a headline matching a tag search often also match
  2502. the same search. Listing all of them can create very long lists.
  2503. Setting this variable to nil causes subtrees of a match to be skipped.
  2504. This variable is semi-obsolete and probably should always be true. It
  2505. is better to limit inheritance to certain tags using the variables
  2506. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2507. :group 'org-tags
  2508. :type '(choice
  2509. (const :tag "No, don't list them" nil)
  2510. (const :tag "Yes, do list them" t)
  2511. (const :tag "List them, indented with leading dots" indented)))
  2512. (defcustom org-tags-sort-function nil
  2513. "When set, tags are sorted using this function as a comparator."
  2514. :group 'org-tags
  2515. :type '(choice
  2516. (const :tag "No sorting" nil)
  2517. (const :tag "Alphabetical" org-string-collate-lessp)
  2518. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2519. (function :tag "Custom function" nil)))
  2520. (defvar org-tags-history nil
  2521. "History of minibuffer reads for tags.")
  2522. (defvar org-last-tags-completion-table nil
  2523. "The last used completion table for tags.")
  2524. (defvar org-after-tags-change-hook nil
  2525. "Hook that is run after the tags in a line have changed.")
  2526. (defgroup org-properties nil
  2527. "Options concerning properties in Org mode."
  2528. :tag "Org Properties"
  2529. :group 'org)
  2530. (defcustom org-property-format "%-10s %s"
  2531. "How property key/value pairs should be formatted by `indent-line'.
  2532. When `indent-line' hits a property definition, it will format the line
  2533. according to this format, mainly to make sure that the values are
  2534. lined-up with respect to each other."
  2535. :group 'org-properties
  2536. :type 'string)
  2537. (defcustom org-properties-postprocess-alist nil
  2538. "Alist of properties and functions to adjust inserted values.
  2539. Elements of this alist must be of the form
  2540. ([string] [function])
  2541. where [string] must be a property name and [function] must be a
  2542. lambda expression: this lambda expression must take one argument,
  2543. the value to adjust, and return the new value as a string.
  2544. For example, this element will allow the property \"Remaining\"
  2545. to be updated wrt the relation between the \"Effort\" property
  2546. and the clock summary:
  2547. ((\"Remaining\" (lambda(value)
  2548. (let ((clocksum (org-clock-sum-current-item))
  2549. (effort (org-duration-to-minutes
  2550. (org-entry-get (point) \"Effort\"))))
  2551. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2552. :group 'org-properties
  2553. :version "24.1"
  2554. :type '(alist :key-type (string :tag "Property")
  2555. :value-type (function :tag "Function")))
  2556. (defcustom org-use-property-inheritance nil
  2557. "Non-nil means properties apply also for sublevels.
  2558. This setting is chiefly used during property searches. Turning it on can
  2559. cause significant overhead when doing a search, which is why it is not
  2560. on by default.
  2561. When nil, only the properties directly given in the current entry count.
  2562. When t, every property is inherited. The value may also be a list of
  2563. properties that should have inheritance, or a regular expression matching
  2564. properties that should be inherited.
  2565. However, note that some special properties use inheritance under special
  2566. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2567. and the properties ending in \"_ALL\" when they are used as descriptor
  2568. for valid values of a property.
  2569. Note for programmers:
  2570. When querying an entry with `org-entry-get', you can control if inheritance
  2571. should be used. By default, `org-entry-get' looks only at the local
  2572. properties. You can request inheritance by setting the inherit argument
  2573. to t (to force inheritance) or to `selective' (to respect the setting
  2574. in this variable)."
  2575. :group 'org-properties
  2576. :type '(choice
  2577. (const :tag "Not" nil)
  2578. (const :tag "Always" t)
  2579. (repeat :tag "Specific properties" (string :tag "Property"))
  2580. (regexp :tag "Properties matched by regexp")))
  2581. (defun org-property-inherit-p (property)
  2582. "Return a non-nil value if PROPERTY should be inherited."
  2583. (cond
  2584. ((eq org-use-property-inheritance t) t)
  2585. ((not org-use-property-inheritance) nil)
  2586. ((stringp org-use-property-inheritance)
  2587. (string-match org-use-property-inheritance property))
  2588. ((listp org-use-property-inheritance)
  2589. (member-ignore-case property org-use-property-inheritance))
  2590. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2591. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2592. "The default column format, if no other format has been defined.
  2593. This variable can be set on the per-file basis by inserting a line
  2594. #+COLUMNS: %25ITEM ....."
  2595. :group 'org-properties
  2596. :type 'string)
  2597. (defcustom org-columns-default-format-for-agenda nil
  2598. "The default column format in an agenda buffer.
  2599. This will be used for column view in the agenda unless a format has
  2600. been set by adding `org-overriding-columns-format' to the local
  2601. settings list of a custom agenda view. When nil, the columns format
  2602. for the first item in the agenda list will be used, or as a fall-back,
  2603. `org-columns-default-format'."
  2604. :group 'org-properties
  2605. :type '(choice
  2606. (const :tag "No default" nil)
  2607. (string :tag "Format string")))
  2608. (defcustom org-columns-ellipses ".."
  2609. "The ellipses to be used when a field in column view is truncated.
  2610. When this is the empty string, as many characters as possible are shown,
  2611. but then there will be no visual indication that the field has been truncated.
  2612. When this is a string of length N, the last N characters of a truncated
  2613. field are replaced by this string. If the column is narrower than the
  2614. ellipses string, only part of the ellipses string will be shown."
  2615. :group 'org-properties
  2616. :type 'string)
  2617. (defconst org-global-properties-fixed
  2618. '(("VISIBILITY_ALL" . "folded children content all")
  2619. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2620. "List of property/value pairs that can be inherited by any entry.
  2621. These are fixed values, for the preset properties. The user variable
  2622. that can be used to add to this list is `org-global-properties'.
  2623. The entries in this list are cons cells where the car is a property
  2624. name and cdr is a string with the value. If the value represents
  2625. multiple items like an \"_ALL\" property, separate the items by
  2626. spaces.")
  2627. (defcustom org-global-properties nil
  2628. "List of property/value pairs that can be inherited by any entry.
  2629. This list will be combined with the constant `org-global-properties-fixed'.
  2630. The entries in this list are cons cells where the car is a property
  2631. name and cdr is a string with the value.
  2632. Buffer local properties are added either by a document property drawer
  2633. :PROPERTIES:
  2634. :NAME: VALUE
  2635. :END:
  2636. or by adding lines like
  2637. #+PROPERTY: NAME VALUE"
  2638. :group 'org-properties
  2639. :type '(repeat
  2640. (cons (string :tag "Property")
  2641. (string :tag "Value"))))
  2642. (defvar-local org-keyword-properties nil
  2643. "List of property/value pairs inherited by any entry.
  2644. Valid for the current buffer. This variable is populated from
  2645. PROPERTY keywords.
  2646. Note that properties are defined also in property drawers.
  2647. Properties defined there take precedence over properties defined
  2648. as keywords.")
  2649. (defgroup org-agenda nil
  2650. "Options concerning agenda views in Org mode."
  2651. :tag "Org Agenda"
  2652. :group 'org)
  2653. (defvar-local org-category nil
  2654. "Variable used by Org files to set a category for agenda display.
  2655. There are multiple ways to set the category. One way is to set
  2656. it in the document property drawer. For example:
  2657. :PROPERTIES:
  2658. :CATEGORY: ELisp
  2659. :END:
  2660. Other ways to define it is as an emacs file variable, for example
  2661. # -*- mode: org; org-category: \"ELisp\"
  2662. or for the file to contain a special line:
  2663. #+CATEGORY: ELisp
  2664. If the file does not specify a category, then file's base name
  2665. is used instead.")
  2666. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2667. (defcustom org-agenda-files nil
  2668. "The files to be used for agenda display.
  2669. If an entry is a directory, all files in that directory that are matched
  2670. by `org-agenda-file-regexp' will be part of the file list.
  2671. If the value of the variable is not a list but a single file name, then
  2672. the list of agenda files is actually stored and maintained in that file,
  2673. one agenda file per line. In this file paths can be given relative to
  2674. `org-directory'. Tilde expansion and environment variable substitution
  2675. are also made.
  2676. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2677. and removed with `\\[org-remove-file]'."
  2678. :group 'org-agenda
  2679. :type '(choice
  2680. (repeat :tag "List of files and directories" file)
  2681. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2682. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2683. "Regular expression to match files for `org-agenda-files'.
  2684. If any element in the list in that variable contains a directory instead
  2685. of a normal file, all files in that directory that are matched by this
  2686. regular expression will be included."
  2687. :group 'org-agenda
  2688. :type 'regexp)
  2689. (defvaralias 'org-agenda-multi-occur-extra-files
  2690. 'org-agenda-text-search-extra-files)
  2691. (defcustom org-agenda-text-search-extra-files nil
  2692. "List of extra files to be searched by text search commands.
  2693. These files will be searched in addition to the agenda files by the
  2694. commands `org-search-view' (`\\[org-agenda] s') \
  2695. and `org-occur-in-agenda-files'.
  2696. Note that these files will only be searched for text search commands,
  2697. not for the other agenda views like todo lists, tag searches or the weekly
  2698. agenda. This variable is intended to list notes and possibly archive files
  2699. that should also be searched by these two commands.
  2700. In fact, if the first element in the list is the symbol `agenda-archives',
  2701. then all archive files of all agenda files will be added to the search
  2702. scope."
  2703. :group 'org-agenda
  2704. :type '(set :greedy t
  2705. (const :tag "Agenda Archives" agenda-archives)
  2706. (repeat :inline t (file))))
  2707. (defcustom org-agenda-skip-unavailable-files nil
  2708. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2709. A nil value means to remove them, after a query, from the list."
  2710. :group 'org-agenda
  2711. :type 'boolean)
  2712. (defgroup org-latex nil
  2713. "Options for embedding LaTeX code into Org mode."
  2714. :tag "Org LaTeX"
  2715. :group 'org)
  2716. (defcustom org-format-latex-options
  2717. '(:foreground default :background default :scale 1.0
  2718. :html-foreground "Black" :html-background "Transparent"
  2719. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2720. "Options for creating images from LaTeX fragments.
  2721. This is a property list with the following properties:
  2722. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2723. `default' means use the foreground of the default face.
  2724. `auto' means use the foreground from the text face.
  2725. :background the background color, or \"Transparent\".
  2726. `default' means use the background of the default face.
  2727. `auto' means use the background from the text face.
  2728. :scale a scaling factor for the size of the images, to get more pixels
  2729. :html-foreground, :html-background, :html-scale
  2730. the same numbers for HTML export.
  2731. :matchers a list indicating which matchers should be used to
  2732. find LaTeX fragments. Valid members of this list are:
  2733. \"begin\" find environments
  2734. \"$1\" find single characters surrounded by $.$
  2735. \"$\" find math expressions surrounded by $...$
  2736. \"$$\" find math expressions surrounded by $$....$$
  2737. \"\\(\" find math expressions surrounded by \\(...\\)
  2738. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2739. :group 'org-latex
  2740. :type 'plist)
  2741. (defcustom org-format-latex-signal-error t
  2742. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2743. When nil, just push out a message."
  2744. :group 'org-latex
  2745. :version "24.1"
  2746. :type 'boolean)
  2747. (defcustom org-latex-to-mathml-jar-file nil
  2748. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2749. Use this to specify additional executable file say a jar file.
  2750. When using MathToWeb as the converter, specify the full-path to
  2751. your mathtoweb.jar file."
  2752. :group 'org-latex
  2753. :version "24.1"
  2754. :type '(choice
  2755. (const :tag "None" nil)
  2756. (file :tag "JAR file" :must-match t)))
  2757. (defcustom org-latex-to-mathml-convert-command nil
  2758. "Command to convert LaTeX fragments to MathML.
  2759. Replace format-specifiers in the command as noted below and use
  2760. `shell-command' to convert LaTeX to MathML.
  2761. %j: Executable file in fully expanded form as specified by
  2762. `org-latex-to-mathml-jar-file'.
  2763. %I: Input LaTeX file in fully expanded form.
  2764. %i: The latex fragment to be converted.
  2765. %o: Output MathML file.
  2766. This command is used by `org-create-math-formula'.
  2767. When using MathToWeb as the converter, set this option to
  2768. \"java -jar %j -unicode -force -df %o %I\".
  2769. When using LaTeXML set this option to
  2770. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2771. :group 'org-latex
  2772. :version "24.1"
  2773. :type '(choice
  2774. (const :tag "None" nil)
  2775. (string :tag "\nShell command")))
  2776. (defcustom org-latex-to-html-convert-command nil
  2777. "Command to convert LaTeX fragments to HTML.
  2778. This command is very open-ended: the output of the command will
  2779. directly replace the LaTeX fragment in the resulting HTML.
  2780. Replace format-specifiers in the command as noted below and use
  2781. `shell-command' to convert LaTeX to HTML.
  2782. %i: The LaTeX fragment to be converted.
  2783. For example, this could be used with LaTeXML as
  2784. \"latexmlc 'literal:%i' --profile=math --preload=siunitx.sty 2>/dev/null\"."
  2785. :group 'org-latex
  2786. :package-version '(Org . "9.4")
  2787. :type '(choice
  2788. (const :tag "None" nil)
  2789. (string :tag "Shell command")))
  2790. (defcustom org-preview-latex-default-process 'dvipng
  2791. "The default process to convert LaTeX fragments to image files.
  2792. All available processes and theirs documents can be found in
  2793. `org-preview-latex-process-alist', which see."
  2794. :group 'org-latex
  2795. :version "26.1"
  2796. :package-version '(Org . "9.0")
  2797. :type 'symbol)
  2798. (defcustom org-preview-latex-process-alist
  2799. '((dvipng
  2800. :programs ("latex" "dvipng")
  2801. :description "dvi > png"
  2802. :message "you need to install the programs: latex and dvipng."
  2803. :image-input-type "dvi"
  2804. :image-output-type "png"
  2805. :image-size-adjust (1.0 . 1.0)
  2806. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2807. :image-converter ("dvipng -D %D -T tight -o %O %f"))
  2808. (dvisvgm
  2809. :programs ("latex" "dvisvgm")
  2810. :description "dvi > svg"
  2811. :message "you need to install the programs: latex and dvisvgm."
  2812. :image-input-type "dvi"
  2813. :image-output-type "svg"
  2814. :image-size-adjust (1.7 . 1.5)
  2815. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2816. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2817. (imagemagick
  2818. :programs ("latex" "convert")
  2819. :description "pdf > png"
  2820. :message "you need to install the programs: latex and imagemagick."
  2821. :image-input-type "pdf"
  2822. :image-output-type "png"
  2823. :image-size-adjust (1.0 . 1.0)
  2824. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2825. :image-converter
  2826. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2827. "Definitions of external processes for LaTeX previewing.
  2828. Org mode can use some external commands to generate TeX snippet's images for
  2829. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2830. `org-create-formula-image' how to call them.
  2831. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2832. PROPERTIES accepts the following attributes:
  2833. :programs list of strings, required programs.
  2834. :description string, describe the process.
  2835. :message string, message it when required programs cannot be found.
  2836. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2837. :image-output-type string, output file type of image converter (e.g., \"png\").
  2838. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2839. image size showed in buffer and the cdr element is for
  2840. HTML file. This option is only useful for process
  2841. developers, users should use variable
  2842. `org-format-latex-options' instead.
  2843. :post-clean list of strings, files matched are to be cleaned up once
  2844. the image is generated. When nil, the files with \".dvi\",
  2845. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2846. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2847. be cleaned up.
  2848. :latex-header list of strings, the LaTeX header of the snippet file.
  2849. When nil, the fallback value is used instead, which is
  2850. controlled by `org-format-latex-header',
  2851. `org-latex-default-packages-alist' and
  2852. `org-latex-packages-alist', which see.
  2853. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2854. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2855. replaced with values defined below.
  2856. :image-converter list of image converter commands strings. Each of them is
  2857. given to the shell and supports any of the following
  2858. place-holders defined below.
  2859. Place-holders used by `:image-converter' and `:latex-compiler':
  2860. %f input file name
  2861. %b base name of input file
  2862. %o base directory of input file
  2863. %O absolute output file name
  2864. Place-holders only used by `:image-converter':
  2865. %D dpi, which is used to adjust image size by some processing commands.
  2866. %S the image size scale ratio, which is used to adjust image size by some
  2867. processing commands."
  2868. :group 'org-latex
  2869. :version "26.1"
  2870. :package-version '(Org . "9.0")
  2871. :type '(alist :tag "LaTeX to image backends"
  2872. :value-type (plist)))
  2873. (defcustom org-preview-latex-image-directory "ltximg/"
  2874. "Path to store latex preview images.
  2875. A relative path here creates many directories relative to the
  2876. processed Org files paths. An absolute path puts all preview
  2877. images at the same place."
  2878. :group 'org-latex
  2879. :version "26.1"
  2880. :package-version '(Org . "9.0")
  2881. :type 'string)
  2882. (defun org-format-latex-mathml-available-p ()
  2883. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2884. (save-match-data
  2885. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2886. org-latex-to-mathml-convert-command)
  2887. (let ((executable (car (split-string
  2888. org-latex-to-mathml-convert-command))))
  2889. (when (executable-find executable)
  2890. (if (string-match
  2891. "%j" org-latex-to-mathml-convert-command)
  2892. (file-readable-p org-latex-to-mathml-jar-file)
  2893. t))))))
  2894. (defcustom org-format-latex-header "\\documentclass{article}
  2895. \\usepackage[usenames]{color}
  2896. \[PACKAGES]
  2897. \[DEFAULT-PACKAGES]
  2898. \\pagestyle{empty} % do not remove
  2899. % The settings below are copied from fullpage.sty
  2900. \\setlength{\\textwidth}{\\paperwidth}
  2901. \\addtolength{\\textwidth}{-3cm}
  2902. \\setlength{\\oddsidemargin}{1.5cm}
  2903. \\addtolength{\\oddsidemargin}{-2.54cm}
  2904. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2905. \\setlength{\\textheight}{\\paperheight}
  2906. \\addtolength{\\textheight}{-\\headheight}
  2907. \\addtolength{\\textheight}{-\\headsep}
  2908. \\addtolength{\\textheight}{-\\footskip}
  2909. \\addtolength{\\textheight}{-3cm}
  2910. \\setlength{\\topmargin}{1.5cm}
  2911. \\addtolength{\\topmargin}{-2.54cm}"
  2912. "The document header used for processing LaTeX fragments.
  2913. It is imperative that this header make sure that no page number
  2914. appears on the page. The package defined in the variables
  2915. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2916. will either replace the placeholder \"[PACKAGES]\" in this
  2917. header, or they will be appended."
  2918. :group 'org-latex
  2919. :type 'string)
  2920. (defun org-set-packages-alist (var val)
  2921. "Set the packages alist and make sure it has 3 elements per entry."
  2922. (set var (mapcar (lambda (x)
  2923. (if (and (consp x) (= (length x) 2))
  2924. (list (car x) (nth 1 x) t)
  2925. x))
  2926. val)))
  2927. (defun org-get-packages-alist (var)
  2928. "Get the packages alist and make sure it has 3 elements per entry."
  2929. (mapcar (lambda (x)
  2930. (if (and (consp x) (= (length x) 2))
  2931. (list (car x) (nth 1 x) t)
  2932. x))
  2933. (default-value var)))
  2934. (defcustom org-latex-default-packages-alist
  2935. '(("AUTO" "inputenc" t ("pdflatex"))
  2936. ("T1" "fontenc" t ("pdflatex"))
  2937. ("" "graphicx" t)
  2938. ("" "grffile" t)
  2939. ("" "longtable" nil)
  2940. ("" "wrapfig" nil)
  2941. ("" "rotating" nil)
  2942. ("normalem" "ulem" t)
  2943. ("" "amsmath" t)
  2944. ("" "textcomp" t)
  2945. ("" "amssymb" t)
  2946. ("" "capt-of" nil)
  2947. ("" "hyperref" nil))
  2948. "Alist of default packages to be inserted in the header.
  2949. Change this only if one of the packages here causes an
  2950. incompatibility with another package you are using.
  2951. The packages in this list are needed by one part or another of
  2952. Org mode to function properly:
  2953. - inputenc, fontenc: for basic font and character selection
  2954. - graphicx: for including images
  2955. - grffile: allow periods and spaces in graphics file names
  2956. - longtable: For multipage tables
  2957. - wrapfig: for figure placement
  2958. - rotating: for sideways figures and tables
  2959. - ulem: for underline and strike-through
  2960. - amsmath: for subscript and superscript and math environments
  2961. - textcomp, amssymb: for various symbols used
  2962. for interpreting the entities in `org-entities'. You can skip
  2963. some of these packages if you don't use any of their symbols.
  2964. - capt-of: for captions outside of floats
  2965. - hyperref: for cross references
  2966. Therefore you should not modify this variable unless you know
  2967. what you are doing. The one reason to change it anyway is that
  2968. you might be loading some other package that conflicts with one
  2969. of the default packages. Each element is either a cell or
  2970. a string.
  2971. A cell is of the format
  2972. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2973. If SNIPPET-FLAG is non-nil, the package also needs to be included
  2974. when compiling LaTeX snippets into images for inclusion into
  2975. non-LaTeX output.
  2976. COMPILERS is a list of compilers that should include the package,
  2977. see `org-latex-compiler'. If the document compiler is not in the
  2978. list, and the list is non-nil, the package will not be inserted
  2979. in the final document.
  2980. A string will be inserted as-is in the header of the document."
  2981. :group 'org-latex
  2982. :group 'org-export-latex
  2983. :set 'org-set-packages-alist
  2984. :get 'org-get-packages-alist
  2985. :version "26.1"
  2986. :package-version '(Org . "8.3")
  2987. :type '(repeat
  2988. (choice
  2989. (list :tag "options/package pair"
  2990. (string :tag "options")
  2991. (string :tag "package")
  2992. (boolean :tag "Snippet")
  2993. (choice
  2994. (const :tag "For all compilers" nil)
  2995. (repeat :tag "Allowed compiler" string)))
  2996. (string :tag "A line of LaTeX"))))
  2997. (defcustom org-latex-packages-alist nil
  2998. "Alist of packages to be inserted in every LaTeX header.
  2999. These will be inserted after `org-latex-default-packages-alist'.
  3000. Each element is either a cell or a string.
  3001. A cell is of the format:
  3002. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3003. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3004. needed when turning LaTeX snippets into images for inclusion into
  3005. non-LaTeX output.
  3006. COMPILERS is a list of compilers that should include the package,
  3007. see `org-latex-compiler'. If the document compiler is not in the
  3008. list, and the list is non-nil, the package will not be inserted
  3009. in the final document.
  3010. A string will be inserted as-is in the header of the document.
  3011. Make sure that you only list packages here which:
  3012. - you want in every file;
  3013. - do not conflict with the setup in `org-format-latex-header';
  3014. - do not conflict with the default packages in
  3015. `org-latex-default-packages-alist'."
  3016. :group 'org-latex
  3017. :group 'org-export-latex
  3018. :set 'org-set-packages-alist
  3019. :get 'org-get-packages-alist
  3020. :type '(repeat
  3021. (choice
  3022. (list :tag "options/package pair"
  3023. (string :tag "options")
  3024. (string :tag "package")
  3025. (boolean :tag "Snippet"))
  3026. (string :tag "A line of LaTeX"))))
  3027. (defgroup org-appearance nil
  3028. "Settings for Org mode appearance."
  3029. :tag "Org Appearance"
  3030. :group 'org)
  3031. (defcustom org-level-color-stars-only nil
  3032. "Non-nil means fontify only the stars in each headline.
  3033. When nil, the entire headline is fontified.
  3034. Changing it requires restart of `font-lock-mode' to become effective
  3035. also in regions already fontified."
  3036. :group 'org-appearance
  3037. :type 'boolean)
  3038. (defcustom org-hide-leading-stars nil
  3039. "Non-nil means hide the first N-1 stars in a headline.
  3040. This works by using the face `org-hide' for these stars. This
  3041. face is white for a light background, and black for a dark
  3042. background. You may have to customize the face `org-hide' to
  3043. make this work.
  3044. Changing it requires restart of `font-lock-mode' to become effective
  3045. also in regions already fontified.
  3046. You may also set this on a per-file basis by adding one of the following
  3047. lines to the buffer:
  3048. #+STARTUP: hidestars
  3049. #+STARTUP: showstars"
  3050. :group 'org-appearance
  3051. :type 'boolean)
  3052. (defcustom org-hidden-keywords nil
  3053. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3054. For example, a value \\='(title) for this list makes the document's title
  3055. appear in the buffer without the initial \"#+TITLE:\" part."
  3056. :group 'org-appearance
  3057. :version "24.1"
  3058. :type '(set (const :tag "#+AUTHOR" author)
  3059. (const :tag "#+DATE" date)
  3060. (const :tag "#+EMAIL" email)
  3061. (const :tag "#+TITLE" title)))
  3062. (defcustom org-custom-properties nil
  3063. "List of properties (as strings) with a special meaning.
  3064. The default use of these custom properties is to let the user
  3065. hide them with `org-toggle-custom-properties-visibility'."
  3066. :group 'org-properties
  3067. :group 'org-appearance
  3068. :version "24.3"
  3069. :type '(repeat (string :tag "Property Name")))
  3070. (defcustom org-fontify-todo-headline nil
  3071. "Non-nil means change the face of a headline if it is marked as TODO.
  3072. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3073. When this is non-nil, the headline after the keyword is set to the
  3074. `org-headline-todo' as an additional indication."
  3075. :group 'org-appearance
  3076. :package-version '(Org . "9.4")
  3077. :type 'boolean
  3078. :safe t)
  3079. (defcustom org-fontify-done-headline t
  3080. "Non-nil means change the face of a headline if it is marked DONE.
  3081. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3082. When this is non-nil, the headline after the keyword is set to the
  3083. `org-headline-done' as an additional indication."
  3084. :group 'org-appearance
  3085. :package-version '(Org . "9.4")
  3086. :type 'boolean)
  3087. (defcustom org-fontify-emphasized-text t
  3088. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3089. Changing this variable requires a restart of Emacs to take effect."
  3090. :group 'org-appearance
  3091. :type 'boolean)
  3092. (defcustom org-fontify-whole-heading-line nil
  3093. "Non-nil means fontify the whole line for headings.
  3094. This is useful when setting a background color for the
  3095. org-level-* faces."
  3096. :group 'org-appearance
  3097. :type 'boolean)
  3098. (defcustom org-fontify-whole-block-delimiter-line t
  3099. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3100. This is useful when setting a background color for the
  3101. org-block-begin-line and org-block-end-line faces."
  3102. :group 'org-appearance
  3103. :type 'boolean)
  3104. (defcustom org-highlight-latex-and-related nil
  3105. "Non-nil means highlight LaTeX related syntax in the buffer.
  3106. When non-nil, the value should be a list containing any of the
  3107. following symbols:
  3108. `native' Highlight LaTeX snippets and environments natively.
  3109. `latex' Highlight LaTeX snippets and environments.
  3110. `script' Highlight subscript and superscript.
  3111. `entities' Highlight entities."
  3112. :group 'org-appearance
  3113. :version "24.4"
  3114. :package-version '(Org . "8.0")
  3115. :type '(choice
  3116. (const :tag "No highlighting" nil)
  3117. (set :greedy t :tag "Highlight"
  3118. (const :tag "LaTeX snippets and environments (native)" native)
  3119. (const :tag "LaTeX snippets and environments" latex)
  3120. (const :tag "Subscript and superscript" script)
  3121. (const :tag "Entities" entities))))
  3122. (defcustom org-hide-emphasis-markers nil
  3123. "Non-nil mean font-lock should hide the emphasis marker characters."
  3124. :group 'org-appearance
  3125. :type 'boolean
  3126. :safe #'booleanp)
  3127. (defcustom org-hide-macro-markers nil
  3128. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3129. :group 'org-appearance
  3130. :type 'boolean)
  3131. (defcustom org-pretty-entities nil
  3132. "Non-nil means show entities as UTF8 characters.
  3133. When nil, the \\name form remains in the buffer."
  3134. :group 'org-appearance
  3135. :version "24.1"
  3136. :type 'boolean)
  3137. (defcustom org-pretty-entities-include-sub-superscripts t
  3138. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3139. :group 'org-appearance
  3140. :version "24.1"
  3141. :type 'boolean)
  3142. (defvar org-emph-re nil
  3143. "Regular expression for matching emphasis.
  3144. After a match, the match groups contain these elements:
  3145. 0 The match of the full regular expression, including the characters
  3146. before and after the proper match
  3147. 1 The character before the proper match, or empty at beginning of line
  3148. 2 The proper match, including the leading and trailing markers
  3149. 3 The leading marker like * or /, indicating the type of highlighting
  3150. 4 The text between the emphasis markers, not including the markers
  3151. 5 The character after the match, empty at the end of a line")
  3152. (defvar org-verbatim-re nil
  3153. "Regular expression for matching verbatim text.")
  3154. (defvar org-emphasis-regexp-components) ; defined just below
  3155. (defvar org-emphasis-alist) ; defined just below
  3156. (defun org-set-emph-re (var val)
  3157. "Set variable and compute the emphasis regular expression."
  3158. (set var val)
  3159. (when (and (boundp 'org-emphasis-alist)
  3160. (boundp 'org-emphasis-regexp-components)
  3161. org-emphasis-alist org-emphasis-regexp-components)
  3162. (pcase-let*
  3163. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3164. (body (if (<= nl 0) body
  3165. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3166. (template
  3167. (format (concat "\\([%s]\\|^\\)" ;before markers
  3168. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3169. "\\([%s]\\|$\\)") ;after markers
  3170. pre border border body border post)))
  3171. (setq org-emph-re (format template "*/_+"))
  3172. (setq org-verbatim-re (format template "=~")))))
  3173. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3174. ;; set this option proved cumbersome. See this message/thread:
  3175. ;; https://orgmode.org/list/B72CDC2B-72F6-43A8-AC70-E6E6295766EC@gmail.com
  3176. (defvar org-emphasis-regexp-components
  3177. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3178. "Components used to build the regular expression for emphasis.
  3179. This is a list with five entries. Terminology: In an emphasis string
  3180. like \" *strong word* \", we call the initial space PREMATCH, the final
  3181. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3182. and \"trong wor\" is the body. The different components in this variable
  3183. specify what is allowed/forbidden in each part:
  3184. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3185. post Chars allowed as postmatch. End of line will be allowed too.
  3186. border The chars *forbidden* as border characters.
  3187. body-regexp A regexp like \".\" to match a body character. Don't use
  3188. non-shy groups here, and don't allow newline here.
  3189. newline The maximum number of newlines allowed in an emphasis exp.
  3190. You need to reload Org or to restart Emacs after setting this.")
  3191. (defcustom org-emphasis-alist
  3192. '(("*" bold)
  3193. ("/" italic)
  3194. ("_" underline)
  3195. ("=" org-verbatim verbatim)
  3196. ("~" org-code verbatim)
  3197. ("+" (:strike-through t)))
  3198. "Alist of characters and faces to emphasize text.
  3199. Text starting and ending with a special character will be emphasized,
  3200. for example *bold*, _underlined_ and /italic/. This variable sets the
  3201. marker characters and the face to be used by font-lock for highlighting
  3202. in Org buffers.
  3203. You need to reload Org or to restart Emacs after customizing this."
  3204. :group 'org-appearance
  3205. :set 'org-set-emph-re
  3206. :version "24.4"
  3207. :package-version '(Org . "8.0")
  3208. :type '(repeat
  3209. (list
  3210. (string :tag "Marker character")
  3211. (choice
  3212. (face :tag "Font-lock-face")
  3213. (plist :tag "Face property list"))
  3214. (option (const verbatim)))))
  3215. (defvar org-protecting-blocks '("src" "example" "export")
  3216. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3217. This is needed for font-lock setup.")
  3218. ;;; Functions and variables from their packages
  3219. ;; Declared here to avoid compiler warnings
  3220. (defvar mark-active)
  3221. ;; Various packages
  3222. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3223. (declare-function calendar-forward-day "cal-move" (arg))
  3224. (declare-function calendar-goto-date "cal-move" (date))
  3225. (declare-function calendar-goto-today "cal-move" ())
  3226. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3227. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3228. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3229. (declare-function cdlatex-tab "ext:cdlatex" ())
  3230. (declare-function dired-get-filename
  3231. "dired"
  3232. (&optional localp no-error-if-not-filep))
  3233. (declare-function iswitchb-read-buffer
  3234. "iswitchb"
  3235. (prompt &optional
  3236. default require-match _predicate start matches-set))
  3237. (declare-function org-agenda-change-all-lines
  3238. "org-agenda"
  3239. (newhead hdmarker &optional fixface just-this))
  3240. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3241. "org-agenda"
  3242. (&optional end))
  3243. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3244. (declare-function org-agenda-format-item
  3245. "org-agenda"
  3246. (extra txt &optional level category tags dotime
  3247. remove-re habitp))
  3248. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3249. (declare-function org-agenda-save-markers-for-cut-and-paste
  3250. "org-agenda"
  3251. (beg end))
  3252. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3253. (declare-function org-agenda-skip "org-agenda" ())
  3254. (declare-function org-attach-expand "org-attach" (file))
  3255. (declare-function org-attach-reveal "org-attach" ())
  3256. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3257. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3258. (declare-function org-indent-mode "org-indent" (&optional arg))
  3259. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3260. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3261. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3262. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3263. (declare-function parse-time-string "parse-time" (string))
  3264. (defvar align-mode-rules-list)
  3265. (defvar calc-embedded-close-formula)
  3266. (defvar calc-embedded-open-formula)
  3267. (defvar calc-embedded-open-mode)
  3268. (defvar font-lock-unfontify-region-function)
  3269. (defvar iswitchb-temp-buflist)
  3270. (defvar org-agenda-tags-todo-honor-ignore-options)
  3271. (defvar remember-data-file)
  3272. (defvar texmathp-why)
  3273. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3274. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3275. (declare-function org-resolve-clocks "org-clock"
  3276. (&optional also-non-dangling-p prompt last-valid))
  3277. (defvar org-clock-start-time)
  3278. (defvar org-clock-marker (make-marker)
  3279. "Marker recording the last clock-in.")
  3280. (defvar org-clock-hd-marker (make-marker)
  3281. "Marker recording the last clock-in, but the headline position.")
  3282. (defvar org-clock-heading ""
  3283. "The heading of the current clock entry.")
  3284. (defun org-clock-is-active ()
  3285. "Return the buffer where the clock is currently running.
  3286. Return nil if no clock is running."
  3287. (marker-buffer org-clock-marker))
  3288. (defun org-check-running-clock ()
  3289. "Check if the current buffer contains the running clock.
  3290. If yes, offer to stop it and to save the buffer with the changes."
  3291. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3292. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3293. (buffer-name))))
  3294. (org-clock-out)
  3295. (when (y-or-n-p "Save changed buffer?")
  3296. (save-buffer))))
  3297. (defun org-clocktable-try-shift (dir n)
  3298. "Check if this line starts a clock table, if yes, shift the time block."
  3299. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3300. (org-clocktable-shift dir n)))
  3301. ;;;###autoload
  3302. (defun org-clock-persistence-insinuate ()
  3303. "Set up hooks for clock persistence."
  3304. (require 'org-clock)
  3305. (add-hook 'org-mode-hook 'org-clock-load)
  3306. (add-hook 'kill-emacs-hook 'org-clock-save))
  3307. (defun org-clock-auto-clockout-insinuate ()
  3308. "Set up hook for auto clocking out when Emacs is idle.
  3309. See `org-clock-auto-clockout-timer'.
  3310. This function is meant to be added to the user configuration."
  3311. (require 'org-clock)
  3312. (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t))
  3313. (defgroup org-archive nil
  3314. "Options concerning archiving in Org mode."
  3315. :tag "Org Archive"
  3316. :group 'org-structure)
  3317. (defcustom org-archive-location "%s_archive::"
  3318. "The location where subtrees should be archived.
  3319. The value of this variable is a string, consisting of two parts,
  3320. separated by a double-colon. The first part is a filename and
  3321. the second part is a headline.
  3322. When the filename is omitted, archiving happens in the same file.
  3323. %s in the filename will be replaced by the current file
  3324. name (without the directory part). Archiving to a different file
  3325. is useful to keep archived entries from contributing to the
  3326. Org Agenda.
  3327. The archived entries will be filed as subtrees of the specified
  3328. headline. When the headline is omitted, the subtrees are simply
  3329. filed away at the end of the file, as top-level entries. Also in
  3330. the heading you can use %s to represent the file name, this can be
  3331. useful when using the same archive for a number of different files.
  3332. Here are a few examples:
  3333. \"%s_archive::\"
  3334. If the current file is Projects.org, archive in file
  3335. Projects.org_archive, as top-level trees. This is the default.
  3336. \"::* Archived Tasks\"
  3337. Archive in the current file, under the top-level headline
  3338. \"* Archived Tasks\".
  3339. \"~/org/archive.org::\"
  3340. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3341. \"~/org/archive.org::* From %s\"
  3342. Archive in file ~/org/archive.org (absolute path), under headlines
  3343. \"From FILENAME\" where file name is the current file name.
  3344. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3345. The \"datetree/\" string is special, signifying to archive
  3346. items to the datetree. Items are placed in either the CLOSED
  3347. date of the item, or the current date if there is no CLOSED date.
  3348. The heading will be a subentry to the current date. There doesn't
  3349. need to be a heading, but there always needs to be a slash after
  3350. datetree. For example, to store archived items directly in the
  3351. datetree, use \"~/org/datetree.org::datetree/\".
  3352. \"basement::** Finished Tasks\"
  3353. Archive in file ./basement (relative path), as level 3 trees
  3354. below the level 2 heading \"** Finished Tasks\".
  3355. You may define it locally by setting an ARCHIVE property. If
  3356. such a property is found in the file or in an entry, and anywhere
  3357. up the hierarchy, it will be used.
  3358. You can also set it for the whole file using the keyword-syntax:
  3359. #+ARCHIVE: basement::** Finished Tasks"
  3360. :group 'org-archive
  3361. :type 'string)
  3362. (defcustom org-agenda-skip-archived-trees t
  3363. "Non-nil means the agenda will skip any items located in archived trees.
  3364. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3365. variable is no longer recommended, you should leave it at the value t.
  3366. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3367. :group 'org-archive
  3368. :group 'org-agenda-skip
  3369. :type 'boolean)
  3370. (defcustom org-columns-skip-archived-trees t
  3371. "Non-nil means ignore archived trees when creating column view."
  3372. :group 'org-archive
  3373. :group 'org-properties
  3374. :type 'boolean)
  3375. (defcustom org-cycle-open-archived-trees nil
  3376. "Non-nil means `org-cycle' will open archived trees.
  3377. An archived tree is a tree marked with the tag ARCHIVE.
  3378. When nil, archived trees will stay folded. You can still open them with
  3379. normal outline commands like `show-all', but not with the cycling commands."
  3380. :group 'org-archive
  3381. :group 'org-cycle
  3382. :type 'boolean)
  3383. (defcustom org-sparse-tree-open-archived-trees nil
  3384. "Non-nil means sparse tree construction shows matches in archived trees.
  3385. When nil, matches in these trees are highlighted, but the trees are kept in
  3386. collapsed state."
  3387. :group 'org-archive
  3388. :group 'org-sparse-trees
  3389. :type 'boolean)
  3390. (defcustom org-sparse-tree-default-date-type nil
  3391. "The default date type when building a sparse tree.
  3392. When this is nil, a date is a scheduled or a deadline timestamp.
  3393. Otherwise, these types are allowed:
  3394. all: all timestamps
  3395. active: only active timestamps (<...>)
  3396. inactive: only inactive timestamps ([...])
  3397. scheduled: only scheduled timestamps
  3398. deadline: only deadline timestamps"
  3399. :type '(choice (const :tag "Scheduled or deadline" nil)
  3400. (const :tag "All timestamps" all)
  3401. (const :tag "Only active timestamps" active)
  3402. (const :tag "Only inactive timestamps" inactive)
  3403. (const :tag "Only scheduled timestamps" scheduled)
  3404. (const :tag "Only deadline timestamps" deadline)
  3405. (const :tag "Only closed timestamps" closed))
  3406. :version "26.1"
  3407. :package-version '(Org . "8.3")
  3408. :group 'org-sparse-trees)
  3409. (defun org-cycle-hide-archived-subtrees (state)
  3410. "Re-hide all archived subtrees after a visibility state change.
  3411. STATE should be one of the symbols listed in the docstring of
  3412. `org-cycle-hook'."
  3413. (when (and (not org-cycle-open-archived-trees)
  3414. (not (memq state '(overview folded))))
  3415. (save-excursion
  3416. (let* ((globalp (memq state '(contents all)))
  3417. (beg (if globalp (point-min) (point)))
  3418. (end (if globalp (point-max) (org-end-of-subtree t))))
  3419. (org-hide-archived-subtrees beg end)
  3420. (goto-char beg)
  3421. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3422. (message "%s" (substitute-command-keys
  3423. "Subtree is archived and stays closed. Use \
  3424. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3425. (defun org-force-cycle-archived ()
  3426. "Cycle subtree even if it is archived."
  3427. (interactive)
  3428. (setq this-command 'org-cycle)
  3429. (let ((org-cycle-open-archived-trees t))
  3430. (call-interactively 'org-cycle)))
  3431. (defun org-hide-archived-subtrees (beg end)
  3432. "Re-hide all archived subtrees after a visibility state change."
  3433. (org-with-wide-buffer
  3434. (let ((case-fold-search nil)
  3435. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3436. (goto-char beg)
  3437. ;; Include headline point is currently on.
  3438. (beginning-of-line)
  3439. (while (and (< (point) end) (re-search-forward re end t))
  3440. (when (member org-archive-tag (org-get-tags nil t))
  3441. (org-flag-subtree t)
  3442. (org-end-of-subtree t))))))
  3443. (defun org-flag-subtree (flag)
  3444. (save-excursion
  3445. (org-back-to-heading t)
  3446. (org-flag-region (line-end-position)
  3447. (progn (org-end-of-subtree t) (point))
  3448. flag
  3449. 'outline)))
  3450. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3451. ;; Declare Column View Code
  3452. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3453. (declare-function org-columns-compute "org-colview" (property))
  3454. ;; Declare ID code
  3455. (declare-function org-id-store-link "org-id")
  3456. (declare-function org-id-locations-load "org-id")
  3457. (declare-function org-id-locations-save "org-id")
  3458. (defvar org-id-track-globally)
  3459. ;;; Variables for pre-computed regular expressions, all buffer local
  3460. (defvar-local org-todo-regexp nil
  3461. "Matches any of the TODO state keywords.
  3462. Since TODO keywords are case-sensitive, `case-fold-search' is
  3463. expected to be bound to nil when matching against this regexp.")
  3464. (defvar-local org-not-done-regexp nil
  3465. "Matches any of the TODO state keywords except the last one.
  3466. Since TODO keywords are case-sensitive, `case-fold-search' is
  3467. expected to be bound to nil when matching against this regexp.")
  3468. (defvar-local org-not-done-heading-regexp nil
  3469. "Matches a TODO headline that is not done.
  3470. Since TODO keywords are case-sensitive, `case-fold-search' is
  3471. expected to be bound to nil when matching against this regexp.")
  3472. (defvar-local org-todo-line-regexp nil
  3473. "Matches a headline and puts TODO state into group 2 if present.
  3474. Since TODO keywords are case-sensitive, `case-fold-search' is
  3475. expected to be bound to nil when matching against this regexp.")
  3476. (defvar-local org-complex-heading-regexp nil
  3477. "Matches a headline and puts everything into groups:
  3478. group 1: Stars
  3479. group 2: The TODO keyword, maybe
  3480. group 3: Priority cookie
  3481. group 4: True headline
  3482. group 5: Tags
  3483. Since TODO keywords are case-sensitive, `case-fold-search' is
  3484. expected to be bound to nil when matching against this regexp.")
  3485. (defvar-local org-complex-heading-regexp-format nil
  3486. "Printf format to make regexp to match an exact headline.
  3487. This regexp will match the headline of any node which has the
  3488. exact headline text that is put into the format, but may have any
  3489. TODO state, priority and tags.")
  3490. (defvar-local org-todo-line-tags-regexp nil
  3491. "Matches a headline and puts TODO state into group 2 if present.
  3492. Also put tags into group 4 if tags are present.")
  3493. (defconst org-plain-time-of-day-regexp
  3494. (concat
  3495. "\\(\\<[012]?[0-9]"
  3496. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3497. "\\(--?"
  3498. "\\(\\<[012]?[0-9]"
  3499. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3500. "\\)?")
  3501. "Regular expression to match a plain time or time range.
  3502. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3503. groups carry important information:
  3504. 0 the full match
  3505. 1 the first time, range or not
  3506. 8 the second time, if it is a range.")
  3507. (defconst org-plain-time-extension-regexp
  3508. (concat
  3509. "\\(\\<[012]?[0-9]"
  3510. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3511. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3512. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3513. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3514. groups carry important information:
  3515. 0 the full match
  3516. 7 hours of duration
  3517. 9 minutes of duration")
  3518. (defconst org-stamp-time-of-day-regexp
  3519. (concat
  3520. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3521. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  3522. "\\(--?"
  3523. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3524. "Regular expression to match a timestamp time or time range.
  3525. After a match, the following groups carry important information:
  3526. 0 the full match
  3527. 1 date plus weekday, for back referencing to make sure both times are on the same day
  3528. 2 the first time, range or not
  3529. 4 the second time, if it is a range.")
  3530. (defconst org-startup-options
  3531. '(("fold" org-startup-folded t)
  3532. ("overview" org-startup-folded t)
  3533. ("nofold" org-startup-folded nil)
  3534. ("showall" org-startup-folded nil)
  3535. ("showeverything" org-startup-folded showeverything)
  3536. ("content" org-startup-folded content)
  3537. ("indent" org-startup-indented t)
  3538. ("noindent" org-startup-indented nil)
  3539. ("num" org-startup-numerated t)
  3540. ("nonum" org-startup-numerated nil)
  3541. ("hidestars" org-hide-leading-stars t)
  3542. ("showstars" org-hide-leading-stars nil)
  3543. ("odd" org-odd-levels-only t)
  3544. ("oddeven" org-odd-levels-only nil)
  3545. ("align" org-startup-align-all-tables t)
  3546. ("noalign" org-startup-align-all-tables nil)
  3547. ("shrink" org-startup-shrink-all-tables t)
  3548. ("inlineimages" org-startup-with-inline-images t)
  3549. ("noinlineimages" org-startup-with-inline-images nil)
  3550. ("latexpreview" org-startup-with-latex-preview t)
  3551. ("nolatexpreview" org-startup-with-latex-preview nil)
  3552. ("customtime" org-display-custom-times t)
  3553. ("logdone" org-log-done time)
  3554. ("lognotedone" org-log-done note)
  3555. ("nologdone" org-log-done nil)
  3556. ("lognoteclock-out" org-log-note-clock-out t)
  3557. ("nolognoteclock-out" org-log-note-clock-out nil)
  3558. ("logrepeat" org-log-repeat state)
  3559. ("lognoterepeat" org-log-repeat note)
  3560. ("logdrawer" org-log-into-drawer t)
  3561. ("nologdrawer" org-log-into-drawer nil)
  3562. ("logstatesreversed" org-log-states-order-reversed t)
  3563. ("nologstatesreversed" org-log-states-order-reversed nil)
  3564. ("nologrepeat" org-log-repeat nil)
  3565. ("logreschedule" org-log-reschedule time)
  3566. ("lognotereschedule" org-log-reschedule note)
  3567. ("nologreschedule" org-log-reschedule nil)
  3568. ("logredeadline" org-log-redeadline time)
  3569. ("lognoteredeadline" org-log-redeadline note)
  3570. ("nologredeadline" org-log-redeadline nil)
  3571. ("logrefile" org-log-refile time)
  3572. ("lognoterefile" org-log-refile note)
  3573. ("nologrefile" org-log-refile nil)
  3574. ("fninline" org-footnote-define-inline t)
  3575. ("nofninline" org-footnote-define-inline nil)
  3576. ("fnlocal" org-footnote-section nil)
  3577. ("fnauto" org-footnote-auto-label t)
  3578. ("fnprompt" org-footnote-auto-label nil)
  3579. ("fnconfirm" org-footnote-auto-label confirm)
  3580. ("fnplain" org-footnote-auto-label plain)
  3581. ("fnadjust" org-footnote-auto-adjust t)
  3582. ("nofnadjust" org-footnote-auto-adjust nil)
  3583. ("constcgs" constants-unit-system cgs)
  3584. ("constSI" constants-unit-system SI)
  3585. ("noptag" org-tag-persistent-alist nil)
  3586. ("hideblocks" org-hide-block-startup t)
  3587. ("nohideblocks" org-hide-block-startup nil)
  3588. ("beamer" org-startup-with-beamer-mode t)
  3589. ("entitiespretty" org-pretty-entities t)
  3590. ("entitiesplain" org-pretty-entities nil))
  3591. "Variable associated with STARTUP options for Org.
  3592. Each element is a list of three items: the startup options (as written
  3593. in the #+STARTUP line), the corresponding variable, and the value to set
  3594. this variable to if the option is found. An optional forth element PUSH
  3595. means to push this value onto the list in the variable.")
  3596. (defcustom org-group-tags t
  3597. "When non-nil (the default), use group tags.
  3598. This can be turned on/off through `org-toggle-tags-groups'."
  3599. :group 'org-tags
  3600. :group 'org-startup
  3601. :type 'boolean)
  3602. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3603. (defun org-toggle-tags-groups ()
  3604. "Toggle support for group tags.
  3605. Support for group tags is controlled by the option
  3606. `org-group-tags', which is non-nil by default."
  3607. (interactive)
  3608. (setq org-group-tags (not org-group-tags))
  3609. (cond ((and (derived-mode-p 'org-agenda-mode)
  3610. org-group-tags)
  3611. (org-agenda-redo))
  3612. ((derived-mode-p 'org-mode)
  3613. (let ((org-inhibit-startup t)) (org-mode))))
  3614. (message "Groups tags support has been turned %s"
  3615. (if org-group-tags "on" "off")))
  3616. (defun org--tag-add-to-alist (alist1 alist2)
  3617. "Merge tags from ALIST1 into ALIST2.
  3618. Duplicates tags outside a group are removed. Keywords and order
  3619. are preserved.
  3620. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3621. See `org-tag-alist' for their structure."
  3622. (cond
  3623. ((null alist2) alist1)
  3624. ((null alist1) alist2)
  3625. (t
  3626. (let ((to-add nil)
  3627. (group-flag nil))
  3628. (dolist (tag-pair alist1)
  3629. (pcase tag-pair
  3630. (`(,(or :startgrouptag :startgroup))
  3631. (setq group-flag t)
  3632. (push tag-pair to-add))
  3633. (`(,(or :endgrouptag :endgroup))
  3634. (setq group-flag nil)
  3635. (push tag-pair to-add))
  3636. (`(,(or :grouptags :newline))
  3637. (push tag-pair to-add))
  3638. (`(,tag . ,_)
  3639. ;; Remove duplicates from ALIST1, unless they are in
  3640. ;; a group. Indeed, it makes sense to have a tag appear in
  3641. ;; multiple groups.
  3642. (when (or group-flag (not (assoc tag alist2)))
  3643. (push tag-pair to-add)))
  3644. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3645. ;; Preserve order of ALIST1.
  3646. (append (nreverse to-add) alist2)))))
  3647. (defun org-priority-to-value (s)
  3648. "Convert priority string S to its numeric value."
  3649. (or (save-match-data
  3650. (and (string-match "\\([0-9]+\\)" s)
  3651. (string-to-number (match-string 1 s))))
  3652. (string-to-char s)))
  3653. (defun org-set-regexps-and-options (&optional tags-only)
  3654. "Precompute regular expressions used in the current buffer.
  3655. When optional argument TAGS-ONLY is non-nil, only compute tags
  3656. related expressions."
  3657. (when (derived-mode-p 'org-mode)
  3658. (let ((alist (org-collect-keywords
  3659. (append '("FILETAGS" "TAGS")
  3660. (and (not tags-only)
  3661. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3662. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3663. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))
  3664. '("ARCHIVE" "CATEGORY" "COLUMNS" "PRIORITIES"))))
  3665. ;; Startup options. Get this early since it does change
  3666. ;; behavior for other options (e.g., tags).
  3667. (let ((startup (cl-mapcan (lambda (value) (split-string value))
  3668. (cdr (assoc "STARTUP" alist)))))
  3669. (dolist (option startup)
  3670. (pcase (assoc-string option org-startup-options t)
  3671. (`(,_ ,variable ,value t)
  3672. (unless (listp (symbol-value variable))
  3673. (set (make-local-variable variable) nil))
  3674. (add-to-list variable value))
  3675. (`(,_ ,variable ,value . ,_)
  3676. (set (make-local-variable variable) value))
  3677. (_ nil))))
  3678. (setq-local org-file-tags
  3679. (mapcar #'org-add-prop-inherited
  3680. (cl-mapcan (lambda (value)
  3681. (cl-mapcan
  3682. (lambda (k) (org-split-string k ":"))
  3683. (split-string value)))
  3684. (cdr (assoc "FILETAGS" alist)))))
  3685. (setq org-current-tag-alist
  3686. (org--tag-add-to-alist
  3687. org-tag-persistent-alist
  3688. (let ((tags (cdr (assoc "TAGS" alist))))
  3689. (if tags
  3690. (org-tag-string-to-alist
  3691. (mapconcat #'identity tags "\n"))
  3692. org-tag-alist))))
  3693. (setq org-tag-groups-alist
  3694. (org-tag-alist-to-groups org-current-tag-alist))
  3695. (unless tags-only
  3696. ;; Properties.
  3697. (let ((properties nil))
  3698. (dolist (value (cdr (assoc "PROPERTY" alist)))
  3699. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3700. (setq properties (org--update-property-plist
  3701. (match-string-no-properties 1 value)
  3702. (match-string-no-properties 2 value)
  3703. properties))))
  3704. (setq-local org-keyword-properties properties))
  3705. ;; Archive location.
  3706. (let ((archive (cdr (assoc "ARCHIVE" alist))))
  3707. (when archive (setq-local org-archive-location archive)))
  3708. ;; Category.
  3709. (let ((category (cdr (assoc "CATEGORY" alist))))
  3710. (when category
  3711. (setq-local org-category (intern category))
  3712. (setq-local org-keyword-properties
  3713. (org--update-property-plist
  3714. "CATEGORY" category org-keyword-properties))))
  3715. ;; Columns.
  3716. (let ((column (cdr (assoc "COLUMNS" alist))))
  3717. (when column (setq-local org-columns-default-format column)))
  3718. ;; Constants.
  3719. (let ((store nil))
  3720. (dolist (pair (cl-mapcan #'split-string
  3721. (cdr (assoc "CONSTANTS" alist))))
  3722. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" pair)
  3723. (let* ((name (match-string 1 pair))
  3724. (value (match-string 2 pair))
  3725. (old (assoc name store)))
  3726. (if old (setcdr old value)
  3727. (push (cons name value) store)))))
  3728. (setq org-table-formula-constants-local store))
  3729. ;; Link abbreviations.
  3730. (let ((links
  3731. (delq nil
  3732. (mapcar
  3733. (lambda (value)
  3734. (and (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3735. (cons (match-string-no-properties 1 value)
  3736. (match-string-no-properties 2 value))))
  3737. (cdr (assoc "LINK" alist))))))
  3738. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3739. ;; Priorities.
  3740. (let ((value (cdr (assoc "PRIORITIES" alist))))
  3741. (pcase (and value (split-string value))
  3742. (`(,high ,low ,default . ,_)
  3743. (setq-local org-priority-highest (org-priority-to-value high))
  3744. (setq-local org-priority-lowest (org-priority-to-value low))
  3745. (setq-local org-priority-default (org-priority-to-value default)))))
  3746. ;; Scripts.
  3747. (let ((value (cdr (assoc "OPTIONS" alist))))
  3748. (dolist (option value)
  3749. (when (string-match "\\^:\\(t\\|nil\\|{}\\)" option)
  3750. (setq-local org-use-sub-superscripts
  3751. (read (match-string 1 option))))))
  3752. ;; TODO keywords.
  3753. (setq-local org-todo-kwd-alist nil)
  3754. (setq-local org-todo-key-alist nil)
  3755. (setq-local org-todo-key-trigger nil)
  3756. (setq-local org-todo-keywords-1 nil)
  3757. (setq-local org-done-keywords nil)
  3758. (setq-local org-todo-heads nil)
  3759. (setq-local org-todo-sets nil)
  3760. (setq-local org-todo-log-states nil)
  3761. (let ((todo-sequences
  3762. (or (append (mapcar (lambda (value)
  3763. (cons 'type (split-string value)))
  3764. (cdr (assoc "TYP_TODO" alist)))
  3765. (mapcar (lambda (value)
  3766. (cons 'sequence (split-string value)))
  3767. (append (cdr (assoc "TODO" alist))
  3768. (cdr (assoc "SEQ_TODO" alist)))))
  3769. (let ((d (default-value 'org-todo-keywords)))
  3770. (if (not (stringp (car d))) d
  3771. ;; XXX: Backward compatibility code.
  3772. (list (cons org-todo-interpretation d)))))))
  3773. (dolist (sequence todo-sequences)
  3774. (let* ((sequence (or (run-hook-with-args-until-success
  3775. 'org-todo-setup-filter-hook sequence)
  3776. sequence))
  3777. (sequence-type (car sequence))
  3778. (keywords (cdr sequence))
  3779. (sep (member "|" keywords))
  3780. names alist)
  3781. (dolist (k (remove "|" keywords))
  3782. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3783. k)
  3784. (error "Invalid TODO keyword %s" k))
  3785. (let ((name (match-string 1 k))
  3786. (key (match-string 2 k))
  3787. (log (org-extract-log-state-settings k)))
  3788. (push name names)
  3789. (push (cons name (and key (string-to-char key))) alist)
  3790. (when log (push log org-todo-log-states))))
  3791. (let* ((names (nreverse names))
  3792. (done (if sep (org-remove-keyword-keys (cdr sep))
  3793. (last names)))
  3794. (head (car names))
  3795. (tail (list sequence-type head (car done) (org-last done))))
  3796. (add-to-list 'org-todo-heads head 'append)
  3797. (push names org-todo-sets)
  3798. (setq org-done-keywords (append org-done-keywords done nil))
  3799. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3800. (setq org-todo-key-alist
  3801. (append org-todo-key-alist
  3802. (and alist
  3803. (append '((:startgroup))
  3804. (nreverse alist)
  3805. '((:endgroup))))))
  3806. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3807. (setq org-todo-sets (nreverse org-todo-sets)
  3808. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3809. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3810. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3811. ;; Compute the regular expressions and other local variables.
  3812. ;; Using `org-outline-regexp-bol' would complicate them much,
  3813. ;; because of the fixed white space at the end of that string.
  3814. (unless org-done-keywords
  3815. (setq org-done-keywords
  3816. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3817. (setq org-not-done-keywords
  3818. (org-delete-all org-done-keywords
  3819. (copy-sequence org-todo-keywords-1))
  3820. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3821. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3822. org-not-done-heading-regexp
  3823. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3824. org-todo-line-regexp
  3825. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3826. org-complex-heading-regexp
  3827. (concat "^\\(\\*+\\)"
  3828. "\\(?: +" org-todo-regexp "\\)?"
  3829. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3830. "\\(?: +\\(.*?\\)\\)??"
  3831. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3832. "[ \t]*$")
  3833. org-complex-heading-regexp-format
  3834. (concat "^\\(\\*+\\)"
  3835. "\\(?: +" org-todo-regexp "\\)?"
  3836. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3837. "\\(?: +"
  3838. ;; Stats cookies can be stuck to body.
  3839. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3840. "\\(%s\\)"
  3841. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3842. "\\)"
  3843. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3844. "[ \t]*$")
  3845. org-todo-line-tags-regexp
  3846. (concat "^\\(\\*+\\)"
  3847. "\\(?: +" org-todo-regexp "\\)?"
  3848. "\\(?: +\\(.*?\\)\\)??"
  3849. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3850. "[ \t]*$"))
  3851. (org-compute-latex-and-related-regexp)))))
  3852. (defun org-collect-keywords (keywords &optional unique directory)
  3853. "Return values for KEYWORDS in current buffer, as an alist.
  3854. KEYWORDS is a list of strings. Return value is a list of
  3855. elements with the pattern:
  3856. (NAME . LIST-OF-VALUES)
  3857. where NAME is the upcase name of the keyword, and LIST-OF-VALUES
  3858. is a list of non-empty values, as strings, in order of appearance
  3859. in the buffer.
  3860. When KEYWORD appears in UNIQUE list, LIST-OF-VALUE is its first
  3861. value, empty or not, appearing in the buffer, as a string.
  3862. When KEYWORD appears in DIRECTORIES, each value is a cons cell:
  3863. (VALUE . DIRECTORY)
  3864. where VALUE is the regular value, and DIRECTORY is the variable
  3865. `default-directory' for the buffer containing the keyword. This
  3866. is important for values containing relative file names, since the
  3867. function follows SETUPFILE keywords, and may change its working
  3868. directory."
  3869. (let* ((keywords (cons "SETUPFILE" (mapcar #'upcase keywords)))
  3870. (unique (mapcar #'upcase unique))
  3871. (alist (org--collect-keywords-1
  3872. keywords unique directory
  3873. (and buffer-file-name (list buffer-file-name))
  3874. nil)))
  3875. ;; Re-order results.
  3876. (dolist (entry alist)
  3877. (pcase entry
  3878. (`(,_ . ,(and value (pred consp)))
  3879. (setcdr entry (nreverse value)))))
  3880. (nreverse alist)))
  3881. (defun org--collect-keywords-1 (keywords unique directory files alist)
  3882. (org-with-point-at 1
  3883. (let ((case-fold-search t)
  3884. (regexp (org-make-options-regexp keywords)))
  3885. (while (and keywords (re-search-forward regexp nil t))
  3886. (let ((element (org-element-at-point)))
  3887. (when (eq 'keyword (org-element-type element))
  3888. (let ((value (org-element-property :value element)))
  3889. (pcase (org-element-property :key element)
  3890. ("SETUPFILE"
  3891. (when (and (org-string-nw-p value)
  3892. (not buffer-read-only)) ;FIXME: bug in Gnus?
  3893. (let* ((uri (org-strip-quotes value))
  3894. (uri-is-url (org-file-url-p uri))
  3895. (uri (if uri-is-url
  3896. uri
  3897. (expand-file-name uri))))
  3898. (unless (member uri files)
  3899. (with-temp-buffer
  3900. (unless uri-is-url
  3901. (setq default-directory (file-name-directory uri)))
  3902. (let ((contents (org-file-contents uri :noerror)))
  3903. (when contents
  3904. (insert contents)
  3905. ;; Fake Org mode: `org-element-at-point'
  3906. ;; doesn't need full set-up.
  3907. (let ((major-mode 'org-mode))
  3908. (setq alist
  3909. (org--collect-keywords-1
  3910. keywords unique directory
  3911. (cons uri files)
  3912. alist))))))))))
  3913. (keyword
  3914. (let ((entry (assoc keyword alist))
  3915. (final
  3916. (cond ((not (member keyword directory)) value)
  3917. (buffer-file-name
  3918. (cons value
  3919. (file-name-directory buffer-file-name)))
  3920. (t (cons value default-directory)))))
  3921. (cond ((member keyword unique)
  3922. (push (cons keyword final) alist)
  3923. (setq keywords (remove keyword keywords))
  3924. (setq regexp (org-make-options-regexp keywords)))
  3925. ((null entry) (push (list keyword final) alist))
  3926. (t (push final (cdr entry)))))))))))
  3927. alist)))
  3928. (defun org-tag-string-to-alist (s)
  3929. "Return tag alist associated to string S.
  3930. S is a value for TAGS keyword or produced with
  3931. `org-tag-alist-to-string'. Return value is an alist suitable for
  3932. `org-tag-alist' or `org-tag-persistent-alist'."
  3933. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3934. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3935. "\\(?:(\\(.\\))\\)?\\'"))
  3936. alist group-flag)
  3937. (dolist (tokens lines (cdr (nreverse alist)))
  3938. (push '(:newline) alist)
  3939. (while tokens
  3940. (let ((token (pop tokens)))
  3941. (pcase token
  3942. ("{"
  3943. (push '(:startgroup) alist)
  3944. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3945. ("}"
  3946. (push '(:endgroup) alist)
  3947. (setq group-flag nil))
  3948. ("["
  3949. (push '(:startgrouptag) alist)
  3950. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3951. ("]"
  3952. (push '(:endgrouptag) alist)
  3953. (setq group-flag nil))
  3954. (":"
  3955. (push '(:grouptags) alist))
  3956. ((guard (string-match tag-re token))
  3957. (let ((tag (match-string 1 token))
  3958. (key (and (match-beginning 2)
  3959. (string-to-char (match-string 2 token)))))
  3960. ;; Push all tags in groups, no matter if they already
  3961. ;; appear somewhere else in the list.
  3962. (when (or group-flag (not (assoc tag alist)))
  3963. (push (cons tag key) alist))))))))))
  3964. (defun org-tag-alist-to-string (alist &optional skip-key)
  3965. "Return tag string associated to ALIST.
  3966. ALIST is an alist, as defined in `org-tag-alist' or
  3967. `org-tag-persistent-alist', or produced with
  3968. `org-tag-string-to-alist'.
  3969. Return value is a string suitable as a value for \"TAGS\"
  3970. keyword.
  3971. When optional argument SKIP-KEY is non-nil, skip selection keys
  3972. next to tags."
  3973. (mapconcat (lambda (token)
  3974. (pcase token
  3975. (`(:startgroup) "{")
  3976. (`(:endgroup) "}")
  3977. (`(:startgrouptag) "[")
  3978. (`(:endgrouptag) "]")
  3979. (`(:grouptags) ":")
  3980. (`(:newline) "\\n")
  3981. ((and
  3982. (guard (not skip-key))
  3983. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  3984. (format "%s(%c)" tag key))
  3985. (`(,(and tag (pred stringp)) . ,_) tag)
  3986. (_ (user-error "Invalid tag token: %S" token))))
  3987. alist
  3988. " "))
  3989. (defun org-tag-alist-to-groups (alist)
  3990. "Return group alist from tag ALIST.
  3991. ALIST is an alist, as defined in `org-tag-alist' or
  3992. `org-tag-persistent-alist', or produced with
  3993. `org-tag-string-to-alist'. Return value is an alist following
  3994. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  3995. a string, summarizing TAGS, as a list of strings."
  3996. (let (groups group-status current-group)
  3997. (dolist (token alist (nreverse groups))
  3998. (pcase token
  3999. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4000. (`(,(or :endgroup :endgrouptag))
  4001. (when (eq group-status 'append)
  4002. (push (nreverse current-group) groups))
  4003. (setq group-status nil current-group nil))
  4004. (`(:grouptags) (setq group-status 'append))
  4005. ((and `(,tag . ,_) (guard group-status))
  4006. (if (eq group-status 'append) (push tag current-group)
  4007. (setq current-group (list tag))))
  4008. (_ nil)))))
  4009. (defvar org--file-cache (make-hash-table :test #'equal)
  4010. "Hash table to store contents of files referenced via a URL.
  4011. This is the cache of file URLs read using `org-file-contents'.")
  4012. (defun org-reset-file-cache ()
  4013. "Reset the cache of files downloaded by `org-file-contents'."
  4014. (clrhash org--file-cache))
  4015. (defun org-file-url-p (file)
  4016. "Non-nil if FILE is a URL."
  4017. (require 'ffap)
  4018. (string-match-p ffap-url-regexp file))
  4019. (defun org-file-contents (file &optional noerror nocache)
  4020. "Return the contents of FILE, as a string.
  4021. FILE can be a file name or URL.
  4022. If FILE is a URL, download the contents. If the URL contents are
  4023. already cached in the `org--file-cache' hash table, the download step
  4024. is skipped.
  4025. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4026. from file or URL, and return nil.
  4027. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4028. is available. This option applies only if FILE is a URL."
  4029. (let* ((is-url (org-file-url-p file))
  4030. (cache (and is-url
  4031. (not nocache)
  4032. (gethash file org--file-cache))))
  4033. (cond
  4034. (cache)
  4035. (is-url
  4036. (with-current-buffer (url-retrieve-synchronously file)
  4037. (goto-char (point-min))
  4038. ;; Move point to after the url-retrieve header.
  4039. (search-forward "\n\n" nil :move)
  4040. ;; Search for the success code only in the url-retrieve header.
  4041. (if (save-excursion
  4042. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4043. ;; Update the cache `org--file-cache' and return contents.
  4044. (puthash file
  4045. (buffer-substring-no-properties (point) (point-max))
  4046. org--file-cache)
  4047. (funcall (if noerror #'message #'user-error)
  4048. "Unable to fetch file from %S"
  4049. file)
  4050. nil)))
  4051. (t
  4052. (with-temp-buffer
  4053. (condition-case nil
  4054. (progn
  4055. (insert-file-contents file)
  4056. (buffer-string))
  4057. (file-error
  4058. (funcall (if noerror #'message #'user-error)
  4059. "Unable to read file %S"
  4060. file)
  4061. nil)))))))
  4062. (defun org-extract-log-state-settings (x)
  4063. "Extract the log state setting from a TODO keyword string.
  4064. This will extract info from a string like \"WAIT(w@/!)\"."
  4065. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4066. (let ((kw (match-string 1 x))
  4067. (log1 (and (match-end 3) (match-string 3 x)))
  4068. (log2 (and (match-end 4) (match-string 4 x))))
  4069. (and (or log1 log2)
  4070. (list kw
  4071. (and log1 (if (equal log1 "!") 'time 'note))
  4072. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4073. (defun org-remove-keyword-keys (list)
  4074. "Remove a pair of parenthesis at the end of each string in LIST."
  4075. (mapcar (lambda (x)
  4076. (if (string-match "(.*)$" x)
  4077. (substring x 0 (match-beginning 0))
  4078. x))
  4079. list))
  4080. (defun org-assign-fast-keys (alist)
  4081. "Assign fast keys to a keyword-key alist.
  4082. Respect keys that are already there."
  4083. (let (new e (alt ?0))
  4084. (while (setq e (pop alist))
  4085. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4086. (cdr e)) ;; Key already assigned.
  4087. (push e new)
  4088. (let ((clist (string-to-list (downcase (car e))))
  4089. (used (append new alist)))
  4090. (when (= (car clist) ?@)
  4091. (pop clist))
  4092. (while (and clist (rassoc (car clist) used))
  4093. (pop clist))
  4094. (unless clist
  4095. (while (rassoc alt used)
  4096. (cl-incf alt)))
  4097. (push (cons (car e) (or (car clist) alt)) new))))
  4098. (nreverse new)))
  4099. ;;; Some variables used in various places
  4100. (defvar org-window-configuration nil
  4101. "Used in various places to store a window configuration.")
  4102. (defvar org-selected-window nil
  4103. "Used in various places to store a window configuration.")
  4104. (defvar org-finish-function nil
  4105. "Function to be called when `C-c C-c' is used.
  4106. This is for getting out of special buffers like capture.")
  4107. (defvar org-last-state)
  4108. ;; Defined somewhere in this file, but used before definition.
  4109. (defvar org-entities) ;; defined in org-entities.el
  4110. (defvar org-struct-menu)
  4111. (defvar org-org-menu)
  4112. (defvar org-tbl-menu)
  4113. ;;;; Define the Org mode
  4114. (defun org-before-change-function (_beg _end)
  4115. "Every change indicates that a table might need an update."
  4116. (setq org-table-may-need-update t))
  4117. (defvar org-mode-map)
  4118. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4119. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4120. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4121. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4122. (defvar bidi-paragraph-direction)
  4123. (defvar buffer-face-mode-face)
  4124. (require 'outline)
  4125. ;; Other stuff we need.
  4126. (require 'time-date)
  4127. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4128. (require 'easymenu)
  4129. (require 'overlay)
  4130. (require 'org-entities)
  4131. (require 'org-faces)
  4132. (require 'org-list)
  4133. (require 'org-pcomplete)
  4134. (require 'org-src)
  4135. (require 'org-footnote)
  4136. (require 'org-macro)
  4137. ;; babel
  4138. (require 'ob)
  4139. ;;;###autoload
  4140. (define-derived-mode org-mode outline-mode "Org"
  4141. "Outline-based notes management and organizer, alias
  4142. \"Carsten's outline-mode for keeping track of everything.\"
  4143. Org mode develops organizational tasks around a NOTES file which
  4144. contains information about projects as plain text. Org mode is
  4145. implemented on top of Outline mode, which is ideal to keep the content
  4146. of large files well structured. It supports ToDo items, deadlines and
  4147. time stamps, which magically appear in the diary listing of the Emacs
  4148. calendar. Tables are easily created with a built-in table editor.
  4149. Plain text URL-like links connect to websites, emails (VM), Usenet
  4150. messages (Gnus), BBDB entries, and any files related to the project.
  4151. For printing and sharing of notes, an Org file (or a part of it)
  4152. can be exported as a structured ASCII or HTML file.
  4153. The following commands are available:
  4154. \\{org-mode-map}"
  4155. (org-load-modules-maybe)
  4156. (org-install-agenda-files-menu)
  4157. (when org-link-descriptive (add-to-invisibility-spec '(org-link)))
  4158. (add-to-invisibility-spec '(org-hide-block . t))
  4159. (setq-local outline-regexp org-outline-regexp)
  4160. (setq-local outline-level 'org-outline-level)
  4161. (setq bidi-paragraph-direction 'left-to-right)
  4162. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4163. (unless org-display-table
  4164. (setq org-display-table (make-display-table)))
  4165. (set-display-table-slot
  4166. org-display-table 4
  4167. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4168. org-ellipsis)))
  4169. (setq buffer-display-table org-display-table))
  4170. (org-set-regexps-and-options)
  4171. (org-set-font-lock-defaults)
  4172. (when (and org-tag-faces (not org-tags-special-faces-re))
  4173. ;; tag faces set outside customize.... force initialization.
  4174. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4175. ;; Calc embedded
  4176. (setq-local calc-embedded-open-mode "# ")
  4177. ;; Modify a few syntax entries
  4178. (modify-syntax-entry ?\" "\"")
  4179. (modify-syntax-entry ?\\ "_")
  4180. (modify-syntax-entry ?~ "_")
  4181. (modify-syntax-entry ?< "(>")
  4182. (modify-syntax-entry ?> ")<")
  4183. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4184. ;; Activate before-change-function
  4185. (setq-local org-table-may-need-update t)
  4186. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4187. ;; Check for running clock before killing a buffer
  4188. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4189. ;; Initialize macros templates.
  4190. (org-macro-initialize-templates)
  4191. ;; Initialize radio targets.
  4192. (org-update-radio-target-regexp)
  4193. ;; Indentation.
  4194. (setq-local indent-line-function 'org-indent-line)
  4195. (setq-local indent-region-function 'org-indent-region)
  4196. ;; Filling and auto-filling.
  4197. (org-setup-filling)
  4198. ;; Comments.
  4199. (org-setup-comments-handling)
  4200. ;; Initialize cache.
  4201. (org-element-cache-reset)
  4202. ;; Beginning/end of defun
  4203. (setq-local beginning-of-defun-function 'org-backward-element)
  4204. (setq-local end-of-defun-function
  4205. (lambda ()
  4206. (if (not (org-at-heading-p))
  4207. (org-forward-element)
  4208. (org-forward-element)
  4209. (forward-char -1))))
  4210. ;; Next error for sparse trees
  4211. (setq-local next-error-function 'org-occur-next-match)
  4212. ;; Make commit log messages from Org documents easier.
  4213. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4214. ;; Make sure dependence stuff works reliably, even for users who set it
  4215. ;; too late :-(
  4216. (if org-enforce-todo-dependencies
  4217. (add-hook 'org-blocker-hook
  4218. 'org-block-todo-from-children-or-siblings-or-parent)
  4219. (remove-hook 'org-blocker-hook
  4220. 'org-block-todo-from-children-or-siblings-or-parent))
  4221. (if org-enforce-todo-checkbox-dependencies
  4222. (add-hook 'org-blocker-hook
  4223. 'org-block-todo-from-checkboxes)
  4224. (remove-hook 'org-blocker-hook
  4225. 'org-block-todo-from-checkboxes))
  4226. ;; Align options lines
  4227. (setq-local
  4228. align-mode-rules-list
  4229. '((org-in-buffer-settings
  4230. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4231. (modes . '(org-mode)))))
  4232. ;; Setup the pcomplete hooks
  4233. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4234. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4235. (setq-local pcomplete-default-completion-function #'ignore)
  4236. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4237. (setq-local pcomplete-termination-string "")
  4238. (add-hook 'completion-at-point-functions
  4239. #'pcomplete-completions-at-point nil t)
  4240. (setq-local buffer-face-mode-face 'org-default)
  4241. ;; If empty file that did not turn on Org mode automatically, make
  4242. ;; it to.
  4243. (when (and org-insert-mode-line-in-empty-file
  4244. (called-interactively-p 'any)
  4245. (= (point-min) (point-max)))
  4246. (insert "# -*- mode: org -*-\n\n"))
  4247. (unless org-inhibit-startup
  4248. (org-unmodified
  4249. (when org-startup-with-beamer-mode (org-beamer-mode))
  4250. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4251. (org-table-map-tables
  4252. (cond ((and org-startup-align-all-tables
  4253. org-startup-shrink-all-tables)
  4254. (lambda () (org-table-align) (org-table-shrink)))
  4255. (org-startup-align-all-tables #'org-table-align)
  4256. (t #'org-table-shrink))
  4257. t))
  4258. (when org-startup-with-inline-images (org-display-inline-images))
  4259. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4260. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4261. (when org-startup-truncated (setq truncate-lines t))
  4262. (when org-startup-numerated (require 'org-num) (org-num-mode 1))
  4263. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4264. ;; Activate `org-table-header-line-mode'
  4265. (when org-table-header-line-p
  4266. (org-table-header-line-mode 1))
  4267. ;; Try to set `org-hide' face correctly.
  4268. (let ((foreground (org-find-invisible-foreground)))
  4269. (when foreground
  4270. (set-face-foreground 'org-hide foreground)))
  4271. ;; Set face extension as requested.
  4272. (org--set-faces-extend '(org-block-begin-line org-block-end-line)
  4273. org-fontify-whole-block-delimiter-line)
  4274. (org--set-faces-extend org-level-faces org-fontify-whole-heading-line))
  4275. ;; Update `customize-package-emacs-version-alist'
  4276. (add-to-list 'customize-package-emacs-version-alist
  4277. '(Org ("8.0" . "24.4")
  4278. ("8.1" . "24.4")
  4279. ("8.2" . "24.4")
  4280. ("8.2.7" . "24.4")
  4281. ("8.3" . "26.1")
  4282. ("9.0" . "26.1")
  4283. ("9.1" . "26.1")
  4284. ("9.2" . "27.1")
  4285. ("9.3" . "27.1")
  4286. ("9.4" . "28.1")))
  4287. (defvar org-mode-transpose-word-syntax-table
  4288. (let ((st (make-syntax-table text-mode-syntax-table)))
  4289. (dolist (c org-emphasis-alist st)
  4290. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4291. (when (fboundp 'abbrev-table-put)
  4292. (abbrev-table-put org-mode-abbrev-table
  4293. :parents (list text-mode-abbrev-table)))
  4294. (defun org-find-invisible-foreground ()
  4295. (let ((candidates (remove
  4296. "unspecified-bg"
  4297. (nconc
  4298. (list (face-background 'default)
  4299. (face-background 'org-default))
  4300. (mapcar
  4301. (lambda (alist)
  4302. (when (boundp alist)
  4303. (cdr (assq 'background-color (symbol-value alist)))))
  4304. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4305. (list (face-foreground 'org-hide))))))
  4306. (car (remove nil candidates))))
  4307. (defun org-current-time (&optional rounding-minutes past)
  4308. "Current time, possibly rounded to ROUNDING-MINUTES.
  4309. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4310. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4311. the rounding returns a past time."
  4312. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4313. (car org-time-stamp-rounding-minutes)))
  4314. (now (current-time)))
  4315. (if (< r 1)
  4316. now
  4317. (let* ((time (decode-time now))
  4318. (res (apply #'encode-time 0 (* r (round (nth 1 time) r))
  4319. (nthcdr 2 time))))
  4320. (if (or (not past) (org-time-less-p res now))
  4321. res
  4322. (org-time-subtract res (* r 60)))))))
  4323. (defun org-today ()
  4324. "Return today date, considering `org-extend-today-until'."
  4325. (time-to-days
  4326. (org-time-since (* 3600 org-extend-today-until))))
  4327. ;;;; Font-Lock stuff, including the activators
  4328. (require 'font-lock)
  4329. (defconst org-match-sexp-depth 3
  4330. "Number of stacked braces for sub/superscript matching.")
  4331. (defun org-create-multibrace-regexp (left right n)
  4332. "Create a regular expression which will match a balanced sexp.
  4333. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4334. as single character strings.
  4335. The regexp returned will match the entire expression including the
  4336. delimiters. It will also define a single group which contains the
  4337. match except for the outermost delimiters. The maximum depth of
  4338. stacked delimiters is N. Escaping delimiters is not possible."
  4339. (let* ((nothing (concat "[^" left right "]*?"))
  4340. (or "\\|")
  4341. (re nothing)
  4342. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4343. (while (> n 1)
  4344. (setq n (1- n)
  4345. re (concat re or next)
  4346. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4347. (concat left "\\(" re "\\)" right)))
  4348. (defconst org-match-substring-regexp
  4349. (concat
  4350. "\\(\\S-\\)\\([_^]\\)\\("
  4351. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4352. "\\|"
  4353. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4354. "\\|"
  4355. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4356. "The regular expression matching a sub- or superscript.")
  4357. (defconst org-match-substring-with-braces-regexp
  4358. (concat
  4359. "\\(\\S-\\)\\([_^]\\)"
  4360. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4361. "The regular expression matching a sub- or superscript, forcing braces.")
  4362. (defvar org-emph-face nil)
  4363. (defun org-do-emphasis-faces (limit)
  4364. "Run through the buffer and emphasize strings."
  4365. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4366. (car org-emphasis-regexp-components))))
  4367. (catch :exit
  4368. (while (re-search-forward quick-re limit t)
  4369. (let* ((marker (match-string 2))
  4370. (verbatim? (member marker '("~" "="))))
  4371. (when (save-excursion
  4372. (goto-char (match-beginning 0))
  4373. (and
  4374. ;; Do not match table hlines.
  4375. (not (and (equal marker "+")
  4376. (org-match-line
  4377. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4378. ;; Do not match headline stars. Do not consider
  4379. ;; stars of a headline as closing marker for bold
  4380. ;; markup either.
  4381. (not (and (equal marker "*")
  4382. (save-excursion
  4383. (forward-char)
  4384. (skip-chars-backward "*")
  4385. (looking-at-p org-outline-regexp-bol))))
  4386. ;; Match full emphasis markup regexp.
  4387. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4388. ;; Do not span over paragraph boundaries.
  4389. (not (string-match-p org-element-paragraph-separate
  4390. (match-string 2)))
  4391. ;; Do not span over cells in table rows.
  4392. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4393. (string-match-p "|" (match-string 4))))))
  4394. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
  4395. (m (if org-hide-emphasis-markers 4 2)))
  4396. (font-lock-prepend-text-property
  4397. (match-beginning m) (match-end m) 'face face)
  4398. (when verbatim?
  4399. (org-remove-flyspell-overlays-in
  4400. (match-beginning 0) (match-end 0))
  4401. (remove-text-properties (match-beginning 2) (match-end 2)
  4402. '(display t invisible t intangible t)))
  4403. (add-text-properties (match-beginning 2) (match-end 2)
  4404. '(font-lock-multiline t org-emphasis t))
  4405. (when (and org-hide-emphasis-markers
  4406. (not (org-at-comment-p)))
  4407. (add-text-properties (match-end 4) (match-beginning 5)
  4408. '(invisible org-link))
  4409. (add-text-properties (match-beginning 3) (match-end 3)
  4410. '(invisible org-link)))
  4411. (throw :exit t))))))))
  4412. (defun org-emphasize (&optional char)
  4413. "Insert or change an emphasis, i.e. a font like bold or italic.
  4414. If there is an active region, change that region to a new emphasis.
  4415. If there is no region, just insert the marker characters and position
  4416. the cursor between them.
  4417. CHAR should be the marker character. If it is a space, it means to
  4418. remove the emphasis of the selected region.
  4419. If CHAR is not given (for example in an interactive call) it will be
  4420. prompted for."
  4421. (interactive)
  4422. (let ((erc org-emphasis-regexp-components)
  4423. (string "") beg end move s)
  4424. (if (org-region-active-p)
  4425. (setq beg (region-beginning)
  4426. end (region-end)
  4427. string (buffer-substring beg end))
  4428. (setq move t))
  4429. (unless char
  4430. (message "Emphasis marker or tag: [%s]"
  4431. (mapconcat #'car org-emphasis-alist ""))
  4432. (setq char (read-char-exclusive)))
  4433. (if (equal char ?\s)
  4434. (setq s ""
  4435. move nil)
  4436. (unless (assoc (char-to-string char) org-emphasis-alist)
  4437. (user-error "No such emphasis marker: \"%c\"" char))
  4438. (setq s (char-to-string char)))
  4439. (while (and (> (length string) 1)
  4440. (equal (substring string 0 1) (substring string -1))
  4441. (assoc (substring string 0 1) org-emphasis-alist))
  4442. (setq string (substring string 1 -1)))
  4443. (setq string (concat s string s))
  4444. (when beg (delete-region beg end))
  4445. (unless (or (bolp)
  4446. (string-match (concat "[" (nth 0 erc) "\n]")
  4447. (char-to-string (char-before (point)))))
  4448. (insert " "))
  4449. (unless (or (eobp)
  4450. (string-match (concat "[" (nth 1 erc) "\n]")
  4451. (char-to-string (char-after (point)))))
  4452. (insert " ") (backward-char 1))
  4453. (insert string)
  4454. (and move (backward-char 1))))
  4455. (defconst org-nonsticky-props
  4456. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4457. (defsubst org-rear-nonsticky-at (pos)
  4458. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4459. (defun org-activate-links (limit)
  4460. "Add link properties to links.
  4461. This includes angle, plain, and bracket links."
  4462. (catch :exit
  4463. (while (re-search-forward org-link-any-re limit t)
  4464. (let* ((start (match-beginning 0))
  4465. (end (match-end 0))
  4466. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4467. (visible-end (or (match-end 3) (match-end 2)))
  4468. (style (cond ((eq ?< (char-after start)) 'angle)
  4469. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4470. (t 'plain))))
  4471. (when (and (memq style org-highlight-links)
  4472. ;; Do not span over paragraph boundaries.
  4473. (not (string-match-p org-element-paragraph-separate
  4474. (match-string 0)))
  4475. ;; Do not confuse plain links with tags.
  4476. (not (and (eq style 'plain)
  4477. (let ((face (get-text-property
  4478. (max (1- start) (point-min)) 'face)))
  4479. (if (consp face) (memq 'org-tag face)
  4480. (eq 'org-tag face))))))
  4481. (let* ((link-object (save-excursion
  4482. (goto-char start)
  4483. (save-match-data (org-element-link-parser))))
  4484. (link (org-element-property :raw-link link-object))
  4485. (type (org-element-property :type link-object))
  4486. (path (org-element-property :path link-object))
  4487. (properties ;for link's visible part
  4488. (list
  4489. 'face (pcase (org-link-get-parameter type :face)
  4490. ((and (pred functionp) face) (funcall face path))
  4491. ((and (pred facep) face) face)
  4492. ((and (pred consp) face) face) ;anonymous
  4493. (_ 'org-link))
  4494. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4495. 'highlight)
  4496. 'keymap (or (org-link-get-parameter type :keymap)
  4497. org-mouse-map)
  4498. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4499. ((and (pred stringp) echo) echo)
  4500. ((and (pred functionp) echo) echo)
  4501. (_ (concat "LINK: " link)))
  4502. 'htmlize-link (pcase (org-link-get-parameter type
  4503. :htmlize-link)
  4504. ((and (pred functionp) f) (funcall f))
  4505. (_ `(:uri ,link)))
  4506. 'font-lock-multiline t)))
  4507. (org-remove-flyspell-overlays-in start end)
  4508. (org-rear-nonsticky-at end)
  4509. (if (not (eq 'bracket style))
  4510. (add-text-properties start end properties)
  4511. ;; Handle invisible parts in bracket links.
  4512. (remove-text-properties start end '(invisible nil))
  4513. (let ((hidden
  4514. (append `(invisible
  4515. ,(or (org-link-get-parameter type :display)
  4516. 'org-link))
  4517. properties)))
  4518. (add-text-properties start visible-start hidden)
  4519. (add-text-properties visible-start visible-end properties)
  4520. (add-text-properties visible-end end hidden)
  4521. (org-rear-nonsticky-at visible-start)
  4522. (org-rear-nonsticky-at visible-end)))
  4523. (let ((f (org-link-get-parameter type :activate-func)))
  4524. (when (functionp f)
  4525. (funcall f start end path (eq style 'bracket))))
  4526. (throw :exit t))))) ;signal success
  4527. nil))
  4528. (defun org-activate-code (limit)
  4529. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4530. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4531. (remove-text-properties (match-beginning 0) (match-end 0)
  4532. '(display t invisible t intangible t))
  4533. t))
  4534. (defcustom org-src-fontify-natively t
  4535. "When non-nil, fontify code in code blocks.
  4536. See also the `org-block' face."
  4537. :type 'boolean
  4538. :version "26.1"
  4539. :package-version '(Org . "8.3")
  4540. :group 'org-appearance
  4541. :group 'org-babel)
  4542. (defcustom org-allow-promoting-top-level-subtree nil
  4543. "When non-nil, allow promoting a top level subtree.
  4544. The leading star of the top level headline will be replaced
  4545. by a #."
  4546. :type 'boolean
  4547. :version "24.1"
  4548. :group 'org-appearance)
  4549. (defun org-fontify-meta-lines-and-blocks (limit)
  4550. (condition-case nil
  4551. (org-fontify-meta-lines-and-blocks-1 limit)
  4552. (error (message "Org mode fontification error in %S at %d"
  4553. (current-buffer)
  4554. (line-number-at-pos)))))
  4555. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4556. "Fontify #+ lines and blocks."
  4557. (let ((case-fold-search t))
  4558. (when (re-search-forward
  4559. (rx bol (group (zero-or-more (any " \t")) "#"
  4560. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4561. (any " \t")
  4562. eol))
  4563. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4564. (zero-or-more (any " \t"))
  4565. (group (group (zero-or-more (not (any " \t\n"))))
  4566. (zero-or-more (any " \t"))
  4567. (group (zero-or-more any)))))
  4568. limit t)
  4569. (let ((beg (match-beginning 0))
  4570. (end-of-beginline (match-end 0))
  4571. ;; Including \n at end of #+begin line will include \n
  4572. ;; after the end of block content.
  4573. (block-start (match-end 0))
  4574. (block-end nil)
  4575. (lang (match-string 7)) ; The language, if it is a source block.
  4576. (bol-after-beginline (line-beginning-position 2))
  4577. (dc1 (downcase (match-string 2)))
  4578. (dc3 (downcase (match-string 3)))
  4579. (whole-blockline org-fontify-whole-block-delimiter-line)
  4580. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4581. (cond
  4582. ((and (match-end 4) (equal dc3 "+begin"))
  4583. ;; Truly a block
  4584. (setq block-type (downcase (match-string 5))
  4585. ;; Src, example, export, maybe more.
  4586. quoting (member block-type org-protecting-blocks))
  4587. (when (re-search-forward
  4588. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4589. (seq (zero-or-more (any " \t"))
  4590. "#+end"
  4591. ,(match-string 4)
  4592. word-end
  4593. (zero-or-more any)))))
  4594. ;; We look further than LIMIT on purpose.
  4595. nil t)
  4596. ;; We do have a matching #+end line.
  4597. (setq beg-of-endline (match-beginning 0)
  4598. end-of-endline (match-end 0)
  4599. nl-before-endline (1- (match-beginning 0)))
  4600. (setq block-end (match-beginning 0)) ; Include the final newline.
  4601. (when quoting
  4602. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4603. (remove-text-properties beg end-of-endline
  4604. '(display t invisible t intangible t)))
  4605. (add-text-properties
  4606. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4607. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4608. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4609. (cond
  4610. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4611. (org-src-font-lock-fontify-block lang block-start block-end)
  4612. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4613. (quoting
  4614. (add-text-properties
  4615. bol-after-beginline beg-of-endline
  4616. (list 'face
  4617. (list :inherit
  4618. (let ((face-name
  4619. (intern (format "org-block-%s" lang))))
  4620. (append (and (facep face-name) (list face-name))
  4621. '(org-block)))))))
  4622. ((not org-fontify-quote-and-verse-blocks))
  4623. ((string= block-type "quote")
  4624. (add-face-text-property
  4625. bol-after-beginline beg-of-endline 'org-quote t))
  4626. ((string= block-type "verse")
  4627. (add-face-text-property
  4628. bol-after-beginline beg-of-endline 'org-verse t)))
  4629. ;; Fontify the #+begin and #+end lines of the blocks
  4630. (add-text-properties
  4631. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4632. '(face org-block-begin-line))
  4633. (unless (eq (char-after beg-of-endline) ?*)
  4634. (add-text-properties
  4635. beg-of-endline
  4636. (if whole-blockline
  4637. (let ((beg-of-next-line (1+ end-of-endline)))
  4638. (min (point-max) beg-of-next-line))
  4639. (min (point-max) end-of-endline))
  4640. '(face org-block-end-line)))
  4641. t))
  4642. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  4643. (org-remove-flyspell-overlays-in
  4644. (match-beginning 0)
  4645. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4646. (add-text-properties
  4647. beg (match-end 3)
  4648. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4649. '(font-lock-fontified t invisible t)
  4650. '(font-lock-fontified t face org-document-info-keyword)))
  4651. (add-text-properties
  4652. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4653. (if (string-equal dc1 "+title:")
  4654. '(font-lock-fontified t face org-document-title)
  4655. '(font-lock-fontified t face org-document-info))))
  4656. ((string-prefix-p "+caption" dc1)
  4657. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4658. (remove-text-properties (match-beginning 0) (match-end 0)
  4659. '(display t invisible t intangible t))
  4660. ;; Handle short captions
  4661. (save-excursion
  4662. (beginning-of-line)
  4663. (looking-at (rx (group (zero-or-more (any " \t"))
  4664. "#+caption"
  4665. (optional "[" (zero-or-more any) "]")
  4666. ":")
  4667. (zero-or-more (any " \t")))))
  4668. (add-text-properties (line-beginning-position) (match-end 1)
  4669. '(font-lock-fontified t face org-meta-line))
  4670. (add-text-properties (match-end 0) (line-end-position)
  4671. '(font-lock-fontified t face org-block))
  4672. t)
  4673. ((member dc3 '(" " ""))
  4674. ;; Just a comment, the plus was not there
  4675. (org-remove-flyspell-overlays-in beg (match-end 0))
  4676. (add-text-properties
  4677. beg (match-end 0)
  4678. '(font-lock-fontified t face font-lock-comment-face)))
  4679. (t ;; Just any other in-buffer setting, but not indented
  4680. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4681. (remove-text-properties (match-beginning 0) (match-end 0)
  4682. '(display t invisible t intangible t))
  4683. (add-text-properties beg (match-end 0)
  4684. '(font-lock-fontified t face org-meta-line))
  4685. t))))))
  4686. (defun org-fontify-drawers (limit)
  4687. "Fontify drawers."
  4688. (when (re-search-forward org-drawer-regexp limit t)
  4689. (add-text-properties (1- (match-beginning 1)) (1+ (match-end 1))
  4690. '(font-lock-fontified t face org-drawer))
  4691. (org-remove-flyspell-overlays-in
  4692. (line-beginning-position) (line-beginning-position 2))
  4693. t))
  4694. (defun org-fontify-macros (limit)
  4695. "Fontify macros."
  4696. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4697. (let ((begin (match-beginning 0))
  4698. (opening-end (match-beginning 1)))
  4699. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4700. (match-string 1))
  4701. (let ((end (match-end 1))
  4702. (closing-start (match-beginning 1)))
  4703. (add-text-properties
  4704. begin end
  4705. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4706. (org-remove-flyspell-overlays-in begin end)
  4707. (when org-hide-macro-markers
  4708. (add-text-properties begin opening-end '(invisible t))
  4709. (add-text-properties closing-start end '(invisible t)))
  4710. t)))))
  4711. (defun org-fontify-extend-region (beg end _old-len)
  4712. (let ((begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4713. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4714. (extend (lambda (r1 r2 dir)
  4715. (let ((re (replace-regexp-in-string "\\(begin\\|end\\)" r1
  4716. (replace-regexp-in-string "[][]" r2
  4717. (match-string-no-properties 0)))))
  4718. (re-search-forward (regexp-quote re) nil t dir)))))
  4719. (save-match-data
  4720. (save-excursion
  4721. (goto-char beg)
  4722. (back-to-indentation)
  4723. (cond ((looking-at end-re)
  4724. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4725. ((looking-at begin-re)
  4726. (cons beg (or (funcall extend "end" "]" 1) end)))
  4727. (t (cons beg end)))))))
  4728. (defun org-activate-footnote-links (limit)
  4729. "Add text properties for footnotes."
  4730. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4731. (when fn
  4732. (let* ((beg (nth 1 fn))
  4733. (end (nth 2 fn))
  4734. (label (car fn))
  4735. (referencep (/= (line-beginning-position) beg)))
  4736. (when (and referencep (nth 3 fn))
  4737. (save-excursion
  4738. (goto-char beg)
  4739. (search-forward (or label "fn:"))
  4740. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4741. (add-text-properties beg end
  4742. (list 'mouse-face 'highlight
  4743. 'keymap org-mouse-map
  4744. 'help-echo
  4745. (if referencep "Footnote reference"
  4746. "Footnote definition")
  4747. 'font-lock-fontified t
  4748. 'font-lock-multiline t
  4749. 'face 'org-footnote))))))
  4750. (defun org-activate-dates (limit)
  4751. "Add text properties for dates."
  4752. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4753. (not (equal (char-before (match-beginning 0)) 91)))
  4754. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4755. (add-text-properties (match-beginning 0) (match-end 0)
  4756. (list 'mouse-face 'highlight
  4757. 'keymap org-mouse-map))
  4758. (org-rear-nonsticky-at (match-end 0))
  4759. (when org-display-custom-times
  4760. ;; If it's a date range, activate custom time for second date.
  4761. (when (match-end 3)
  4762. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4763. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4764. t))
  4765. (defun org-activate-target-links (limit)
  4766. "Add text properties for target matches."
  4767. (when org-target-link-regexp
  4768. (let ((case-fold-search t))
  4769. ;; `org-target-link-regexp' matches one character before the
  4770. ;; actual target.
  4771. (unless (bolp) (forward-char -1))
  4772. (when (re-search-forward org-target-link-regexp limit t)
  4773. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4774. (add-text-properties (match-beginning 1) (match-end 1)
  4775. (list 'mouse-face 'highlight
  4776. 'keymap org-mouse-map
  4777. 'help-echo "Radio target link"
  4778. 'org-linked-text t))
  4779. (org-rear-nonsticky-at (match-end 1))
  4780. t))))
  4781. (defvar org-latex-and-related-regexp nil
  4782. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4783. (defun org-compute-latex-and-related-regexp ()
  4784. "Compute regular expression for LaTeX, entities and sub/superscript.
  4785. Result depends on variable `org-highlight-latex-and-related'."
  4786. (let ((re-sub
  4787. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4788. ((eq org-use-sub-superscripts '{})
  4789. (list org-match-substring-with-braces-regexp))
  4790. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4791. (re-latex
  4792. (when (or (memq 'latex org-highlight-latex-and-related)
  4793. (memq 'native org-highlight-latex-and-related))
  4794. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4795. (delq nil
  4796. (mapcar (lambda (x)
  4797. (and (member (car x) matchers) (nth 1 x)))
  4798. org-latex-regexps)))))
  4799. (re-entities
  4800. (when (memq 'entities org-highlight-latex-and-related)
  4801. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4802. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4803. (setq-local org-latex-and-related-regexp
  4804. (mapconcat #'identity
  4805. (append re-latex re-entities re-sub)
  4806. "\\|"))))
  4807. (defun org-do-latex-and-related (limit)
  4808. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4809. Stop at first highlighted object, if any. Return t if some
  4810. highlighting was done, nil otherwise."
  4811. (when (org-string-nw-p org-latex-and-related-regexp)
  4812. (let ((latex-prefix-re (rx (or "$" "\\(" "\\[")))
  4813. (blank-line-re (rx (and "\n" (zero-or-more (or " " "\t")) "\n"))))
  4814. (catch 'found
  4815. (while (and (< (point) limit)
  4816. (re-search-forward org-latex-and-related-regexp nil t))
  4817. (cond
  4818. ((cl-some (lambda (f)
  4819. (memq f '(org-code org-verbatim underline
  4820. org-special-keyword)))
  4821. (save-excursion
  4822. (goto-char (1+ (match-beginning 0)))
  4823. (face-at-point nil t))))
  4824. ;; Try to limit false positives. In this case, ignore
  4825. ;; $$...$$, \(...\), and \[...\] LaTeX constructs if they
  4826. ;; contain an empty line.
  4827. ((save-excursion
  4828. (goto-char (match-beginning 0))
  4829. (and (looking-at-p latex-prefix-re)
  4830. (save-match-data
  4831. (re-search-forward blank-line-re (1- (match-end 0)) t)))))
  4832. (t
  4833. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4834. '(?_ ?^))
  4835. 1
  4836. 0))
  4837. (start (+ offset (match-beginning 0)))
  4838. (end (match-end 0)))
  4839. (if (memq 'native org-highlight-latex-and-related)
  4840. (org-src-font-lock-fontify-block "latex" start end)
  4841. (font-lock-prepend-text-property start end
  4842. 'face 'org-latex-and-related))
  4843. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4844. '(font-lock-multiline t))
  4845. (throw 'found t)))))
  4846. nil))))
  4847. (defun org-restart-font-lock ()
  4848. "Restart `font-lock-mode', to force refontification."
  4849. (when (and (boundp 'font-lock-mode) font-lock-mode)
  4850. (font-lock-mode -1)
  4851. (font-lock-mode 1)))
  4852. (defun org-activate-tags (limit)
  4853. (when (re-search-forward org-tag-line-re limit t)
  4854. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4855. (add-text-properties (match-beginning 1) (match-end 1)
  4856. (list 'mouse-face 'highlight
  4857. 'keymap org-mouse-map))
  4858. (org-rear-nonsticky-at (match-end 1))
  4859. t))
  4860. (defun org-outline-level ()
  4861. "Compute the outline level of the heading at point.
  4862. If this is called at a normal headline, the level is the number
  4863. of stars. Use `org-reduced-level' to remove the effect of
  4864. `org-odd-levels'. Unlike to `org-current-level', this function
  4865. takes into consideration inlinetasks."
  4866. (org-with-wide-buffer
  4867. (end-of-line)
  4868. (if (re-search-backward org-outline-regexp-bol nil t)
  4869. (1- (- (match-end 0) (match-beginning 0)))
  4870. 0)))
  4871. (defvar org-font-lock-keywords nil)
  4872. (defsubst org-re-property (property &optional literal allow-null value)
  4873. "Return a regexp matching a PROPERTY line.
  4874. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4875. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4876. non-nil, match properties even without a value.
  4877. Match group 3 is set to the value when it exists. If there is no
  4878. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4879. With optional argument VALUE, match only property lines with
  4880. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4881. unless LITERAL is non-nil."
  4882. (concat
  4883. "^\\(?4:[ \t]*\\)"
  4884. (format "\\(?1::\\(?2:%s\\):\\)"
  4885. (if literal property (regexp-quote property)))
  4886. (cond (value
  4887. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4888. (if literal value (regexp-quote value))))
  4889. (allow-null
  4890. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4891. (t
  4892. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4893. (defconst org-property-re
  4894. (org-re-property "\\S-+" 'literal t)
  4895. "Regular expression matching a property line.
  4896. There are four matching groups:
  4897. 1: :PROPKEY: including the leading and trailing colon,
  4898. 2: PROPKEY without the leading and trailing colon,
  4899. 3: PROPVAL without leading or trailing spaces,
  4900. 4: the indentation of the current line,
  4901. 5: trailing whitespace.")
  4902. (defvar org-font-lock-hook nil
  4903. "Functions to be called for special font lock stuff.")
  4904. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4905. (defvar org-font-lock-set-keywords-hook nil
  4906. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4907. This is called after `org-font-lock-extra-keywords' is defined, but before
  4908. it is installed to be used by font lock. This can be useful if something
  4909. needs to be inserted at a specific position in the font-lock sequence.")
  4910. (defun org-font-lock-hook (limit)
  4911. "Run `org-font-lock-hook' within LIMIT."
  4912. (run-hook-with-args 'org-font-lock-hook limit))
  4913. (defun org-set-font-lock-defaults ()
  4914. "Set font lock defaults for the current buffer."
  4915. (let* ((em org-fontify-emphasized-text)
  4916. (lk org-highlight-links)
  4917. (org-font-lock-extra-keywords
  4918. (list
  4919. ;; Call the hook
  4920. '(org-font-lock-hook)
  4921. ;; Headlines
  4922. `(,(if org-fontify-whole-heading-line
  4923. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4924. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4925. (1 (org-get-level-face 1))
  4926. (2 (org-get-level-face 2))
  4927. (3 (org-get-level-face 3)))
  4928. ;; Table lines
  4929. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4930. (1 'org-table t))
  4931. ;; Table internals
  4932. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  4933. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  4934. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  4935. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  4936. ;; Properties
  4937. (list org-property-re
  4938. '(1 'org-special-keyword t)
  4939. '(3 'org-property-value t))
  4940. ;; Drawers
  4941. '(org-fontify-drawers)
  4942. ;; Link related fontification.
  4943. '(org-activate-links)
  4944. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  4945. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  4946. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  4947. (when (memq 'footnote lk) '(org-activate-footnote-links))
  4948. ;; Targets.
  4949. (list org-radio-target-regexp '(0 'org-target t))
  4950. (list org-target-regexp '(0 'org-target t))
  4951. ;; Diary sexps.
  4952. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  4953. ;; Macro
  4954. '(org-fontify-macros)
  4955. ;; TODO keyword
  4956. (list (format org-heading-keyword-regexp-format
  4957. org-todo-regexp)
  4958. '(2 (org-get-todo-face 2) t))
  4959. ;; TODO
  4960. (when org-fontify-todo-headline
  4961. (list (format org-heading-keyword-regexp-format
  4962. (concat
  4963. "\\(?:"
  4964. (mapconcat 'regexp-quote org-not-done-keywords "\\|")
  4965. "\\)"))
  4966. '(2 'org-headline-todo t)))
  4967. ;; DONE
  4968. (when org-fontify-done-headline
  4969. (list (format org-heading-keyword-regexp-format
  4970. (concat
  4971. "\\(?:"
  4972. (mapconcat 'regexp-quote org-done-keywords "\\|")
  4973. "\\)"))
  4974. '(2 'org-headline-done t)))
  4975. ;; Priorities
  4976. '(org-font-lock-add-priority-faces)
  4977. ;; Tags
  4978. '(org-font-lock-add-tag-faces)
  4979. ;; Tags groups
  4980. (when (and org-group-tags org-tag-groups-alist)
  4981. (list (concat org-outline-regexp-bol ".+\\(:"
  4982. (regexp-opt (mapcar 'car org-tag-groups-alist))
  4983. ":\\).*$")
  4984. '(1 'org-tag-group prepend)))
  4985. ;; Special keywords
  4986. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  4987. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  4988. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  4989. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  4990. ;; Emphasis
  4991. (when em '(org-do-emphasis-faces))
  4992. ;; Checkboxes
  4993. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  4994. 1 'org-checkbox prepend)
  4995. (when (cdr (assq 'checkbox org-list-automatic-rules))
  4996. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  4997. (0 (org-get-checkbox-statistics-face) t)))
  4998. ;; Description list items
  4999. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5000. 1 'org-list-dt prepend)
  5001. ;; ARCHIVEd headings
  5002. (list (concat
  5003. org-outline-regexp-bol
  5004. "\\(.*:" org-archive-tag ":.*\\)")
  5005. '(1 'org-archived prepend))
  5006. ;; Specials
  5007. '(org-do-latex-and-related)
  5008. '(org-fontify-entities)
  5009. '(org-raise-scripts)
  5010. ;; Code
  5011. '(org-activate-code (1 'org-code t))
  5012. ;; COMMENT
  5013. (list (format
  5014. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5015. org-todo-regexp
  5016. org-comment-string)
  5017. '(9 'org-special-keyword t))
  5018. ;; Blocks and meta lines
  5019. '(org-fontify-meta-lines-and-blocks))))
  5020. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5021. (run-hooks 'org-font-lock-set-keywords-hook)
  5022. ;; Now set the full font-lock-keywords
  5023. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5024. (setq-local font-lock-defaults
  5025. '(org-font-lock-keywords t nil nil backward-paragraph))
  5026. (setq-local font-lock-extend-after-change-region-function
  5027. #'org-fontify-extend-region)
  5028. (kill-local-variable 'font-lock-keywords)
  5029. nil))
  5030. (defun org-toggle-pretty-entities ()
  5031. "Toggle the composition display of entities as UTF8 characters."
  5032. (interactive)
  5033. (setq-local org-pretty-entities (not org-pretty-entities))
  5034. (org-restart-font-lock)
  5035. (if org-pretty-entities
  5036. (message "Entities are now displayed as UTF8 characters")
  5037. (save-restriction
  5038. (widen)
  5039. (decompose-region (point-min) (point-max))
  5040. (message "Entities are now displayed as plain text"))))
  5041. (defvar-local org-custom-properties-overlays nil
  5042. "List of overlays used for custom properties.")
  5043. (defun org-toggle-custom-properties-visibility ()
  5044. "Display or hide properties in `org-custom-properties'."
  5045. (interactive)
  5046. (if org-custom-properties-overlays
  5047. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5048. (setq org-custom-properties-overlays nil))
  5049. (when org-custom-properties
  5050. (org-with-wide-buffer
  5051. (goto-char (point-min))
  5052. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5053. (while (re-search-forward regexp nil t)
  5054. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5055. (when (and end (< (point) end))
  5056. ;; Hide first custom property in current drawer.
  5057. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5058. (overlay-put o 'invisible t)
  5059. (overlay-put o 'org-custom-property t)
  5060. (push o org-custom-properties-overlays))
  5061. ;; Hide additional custom properties in the same drawer.
  5062. (while (re-search-forward regexp end t)
  5063. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5064. (overlay-put o 'invisible t)
  5065. (overlay-put o 'org-custom-property t)
  5066. (push o org-custom-properties-overlays)))))
  5067. ;; Each entry is limited to a single property drawer.
  5068. (outline-next-heading)))))))
  5069. (defun org-fontify-entities (limit)
  5070. "Find an entity to fontify."
  5071. (let (ee)
  5072. (when org-pretty-entities
  5073. (catch 'match
  5074. ;; "\_ "-family is left out on purpose. Only the first one,
  5075. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5076. ;; confusing when adding a second white space character.
  5077. (while (re-search-forward
  5078. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5079. limit t)
  5080. (when (and (not (org-at-comment-p))
  5081. (setq ee (org-entity-get (match-string 1)))
  5082. (= (length (nth 6 ee)) 1))
  5083. (let* ((end (if (equal (match-string 2) "{}")
  5084. (match-end 2)
  5085. (match-end 1))))
  5086. (add-text-properties
  5087. (match-beginning 0) end
  5088. (list 'font-lock-fontified t))
  5089. (compose-region (match-beginning 0) end
  5090. (nth 6 ee) nil)
  5091. (backward-char 1)
  5092. (throw 'match t))))
  5093. nil))))
  5094. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5095. "Fontify string S like in Org mode."
  5096. (with-temp-buffer
  5097. (insert s)
  5098. (let ((org-odd-levels-only odd-levels))
  5099. (org-mode)
  5100. (org-font-lock-ensure)
  5101. (buffer-string))))
  5102. (defun org-get-level-face (n)
  5103. "Get the right face for match N in font-lock matching of headlines."
  5104. (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
  5105. (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
  5106. (org-f (if org-cycle-level-faces
  5107. (nth (% (1- org-l) org-n-level-faces) org-level-faces)
  5108. (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
  5109. (cond
  5110. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5111. ((eq n 2) org-f)
  5112. (t (unless org-level-color-stars-only org-f)))))
  5113. (defun org-face-from-face-or-color (context inherit face-or-color)
  5114. "Create a face list that inherits INHERIT, but sets the foreground color.
  5115. When FACE-OR-COLOR is not a string, just return it."
  5116. (if (stringp face-or-color)
  5117. (list :inherit inherit
  5118. (cdr (assoc context org-faces-easy-properties))
  5119. face-or-color)
  5120. face-or-color))
  5121. (defun org-get-todo-face (kwd)
  5122. "Get the right face for a TODO keyword KWD.
  5123. If KWD is a number, get the corresponding match group."
  5124. (when (numberp kwd) (setq kwd (match-string kwd)))
  5125. (or (org-face-from-face-or-color
  5126. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5127. (and (member kwd org-done-keywords) 'org-done)
  5128. 'org-todo))
  5129. (defun org-get-priority-face (priority)
  5130. "Get the right face for PRIORITY.
  5131. PRIORITY is a character."
  5132. (or (org-face-from-face-or-color
  5133. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5134. 'org-priority))
  5135. (defun org-get-tag-face (tag)
  5136. "Get the right face for TAG.
  5137. If TAG is a number, get the corresponding match group."
  5138. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5139. (or (org-face-from-face-or-color
  5140. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5141. 'org-tag)))
  5142. (defvar org-priority-regexp) ; defined later in the file
  5143. (defun org-font-lock-add-priority-faces (limit)
  5144. "Add the special priority faces."
  5145. (while (re-search-forward org-priority-regexp limit t)
  5146. (add-text-properties
  5147. (match-beginning 1) (1+ (match-end 2))
  5148. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5149. 'font-lock-fontified t))))
  5150. (defun org-font-lock-add-tag-faces (limit)
  5151. "Add the special tag faces."
  5152. (when (and org-tag-faces org-tags-special-faces-re)
  5153. (while (re-search-forward org-tags-special-faces-re limit t)
  5154. (add-text-properties (match-beginning 1) (match-end 1)
  5155. (list 'face (org-get-tag-face 1)
  5156. 'font-lock-fontified t))
  5157. (backward-char 1))))
  5158. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5159. "Remove fontification and activation overlays from links."
  5160. (font-lock-default-unfontify-region beg end)
  5161. (let* ((buffer-undo-list t)
  5162. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5163. (inhibit-modification-hooks t)
  5164. deactivate-mark buffer-file-name buffer-file-truename)
  5165. (decompose-region beg end)
  5166. (remove-text-properties beg end
  5167. '(mouse-face t keymap t org-linked-text t
  5168. invisible t intangible t
  5169. org-emphasis t))
  5170. (org-remove-font-lock-display-properties beg end)))
  5171. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5172. ((raise 0.3) (height 0.7))
  5173. ((raise -0.5))
  5174. ((raise 0.5)))
  5175. "Display properties for showing superscripts and subscripts.")
  5176. (defun org-remove-font-lock-display-properties (beg end)
  5177. "Remove specific display properties that have been added by font lock.
  5178. The will remove the raise properties that are used to show superscripts
  5179. and subscripts."
  5180. (let (next prop)
  5181. (while (< beg end)
  5182. (setq next (next-single-property-change beg 'display nil end)
  5183. prop (get-text-property beg 'display))
  5184. (when (member prop org-script-display)
  5185. (put-text-property beg next 'display nil))
  5186. (setq beg next))))
  5187. (defun org-raise-scripts (limit)
  5188. "Add raise properties to sub/superscripts."
  5189. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5190. (re-search-forward
  5191. (if (eq org-use-sub-superscripts t)
  5192. org-match-substring-regexp
  5193. org-match-substring-with-braces-regexp)
  5194. limit t))
  5195. (let* ((pos (point)) table-p comment-p
  5196. (mpos (match-beginning 3))
  5197. (emph-p (get-text-property mpos 'org-emphasis))
  5198. (link-p (get-text-property mpos 'mouse-face))
  5199. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5200. (goto-char (point-at-bol))
  5201. (setq table-p (looking-at-p org-table-dataline-regexp)
  5202. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5203. (goto-char pos)
  5204. ;; Handle a_b^c
  5205. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5206. (unless (or comment-p emph-p link-p keyw-p)
  5207. (put-text-property (match-beginning 3) (match-end 0)
  5208. 'display
  5209. (if (equal (char-after (match-beginning 2)) ?^)
  5210. (nth (if table-p 3 1) org-script-display)
  5211. (nth (if table-p 2 0) org-script-display)))
  5212. (add-text-properties (match-beginning 2) (match-end 2)
  5213. (list 'invisible t))
  5214. (when (and (eq (char-after (match-beginning 3)) ?{)
  5215. (eq (char-before (match-end 3)) ?}))
  5216. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5217. (list 'invisible t))
  5218. (add-text-properties (1- (match-end 3)) (match-end 3)
  5219. (list 'invisible t))))
  5220. t)))
  5221. (defun org-remove-empty-overlays-at (pos)
  5222. "Remove outline overlays that do not contain non-white stuff."
  5223. (dolist (o (overlays-at pos))
  5224. (and (eq 'outline (overlay-get o 'invisible))
  5225. (not (string-match-p "\\S-" (buffer-substring (overlay-start o)
  5226. (overlay-end o))))
  5227. (delete-overlay o))))
  5228. (defun org-show-empty-lines-in-parent ()
  5229. "Move to the parent and re-show empty lines before visible headlines."
  5230. (save-excursion
  5231. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5232. (org-cycle-show-empty-lines context))))
  5233. (defun org-files-list ()
  5234. "Return `org-agenda-files' list, plus all open Org files.
  5235. This is useful for operations that need to scan all of a user's
  5236. open and agenda-wise Org files."
  5237. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5238. (dolist (buf (buffer-list))
  5239. (with-current-buffer buf
  5240. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5241. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5242. :test #'equal))))
  5243. files))
  5244. (defsubst org-entry-beginning-position ()
  5245. "Return the beginning position of the current entry."
  5246. (save-excursion (org-back-to-heading t) (point)))
  5247. (defsubst org-entry-end-position ()
  5248. "Return the end position of the current entry."
  5249. (save-excursion (outline-next-heading) (point)))
  5250. (defun org-subtree-end-visible-p ()
  5251. "Is the end of the current subtree visible?"
  5252. (pos-visible-in-window-p
  5253. (save-excursion (org-end-of-subtree t) (point))))
  5254. (defun org-first-headline-recenter ()
  5255. "Move cursor to the first headline and recenter the headline."
  5256. (let ((window (get-buffer-window)))
  5257. (when window
  5258. (goto-char (point-min))
  5259. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5260. (set-window-start window (line-beginning-position))))))
  5261. ;;; Visibility (headlines, blocks, drawers)
  5262. ;;;; Headlines visibility
  5263. (defun org-show-entry ()
  5264. "Show the body directly following its heading.
  5265. Show the heading too, if it is currently invisible."
  5266. (interactive)
  5267. (save-excursion
  5268. (org-back-to-heading-or-point-min t)
  5269. (org-flag-region
  5270. (line-end-position 0)
  5271. (save-excursion
  5272. (if (re-search-forward
  5273. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5274. (match-beginning 1)
  5275. (point-max)))
  5276. nil
  5277. 'outline)
  5278. (org-cycle-hide-drawers 'children)))
  5279. (defun org-hide-entry ()
  5280. "Hide the body directly following its heading."
  5281. (interactive)
  5282. (save-excursion
  5283. (org-back-to-heading-or-point-min t)
  5284. (when (org-at-heading-p) (forward-line))
  5285. (org-flag-region
  5286. (line-end-position 0)
  5287. (save-excursion
  5288. (if (re-search-forward
  5289. (concat "[\r\n]" org-outline-regexp) nil t)
  5290. (line-end-position 0)
  5291. (point-max)))
  5292. t
  5293. 'outline)))
  5294. (defun org-show-children (&optional level)
  5295. "Show all direct subheadings of this heading.
  5296. Prefix arg LEVEL is how many levels below the current level
  5297. should be shown. Default is enough to cause the following
  5298. heading to appear."
  5299. (interactive "p")
  5300. (unless (org-before-first-heading-p)
  5301. (save-excursion
  5302. (org-with-limited-levels (org-back-to-heading t))
  5303. (let* ((current-level (funcall outline-level))
  5304. (max-level (org-get-valid-level
  5305. current-level
  5306. (if level (prefix-numeric-value level) 1)))
  5307. (end (save-excursion (org-end-of-subtree t t)))
  5308. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5309. (past-first-child nil)
  5310. ;; Make sure to skip inlinetasks.
  5311. (re (format regexp-fmt
  5312. current-level
  5313. (cond
  5314. ((not (featurep 'org-inlinetask)) "")
  5315. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5316. 3))
  5317. (t (1- org-inlinetask-min-level))))))
  5318. ;; Display parent heading.
  5319. (org-flag-heading nil)
  5320. (forward-line)
  5321. ;; Display children. First child may be deeper than expected
  5322. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5323. ;; MAX-LEVEL accordingly.
  5324. (while (re-search-forward re end t)
  5325. (unless past-first-child
  5326. (setq re (format regexp-fmt
  5327. current-level
  5328. (max (funcall outline-level) max-level)))
  5329. (setq past-first-child t))
  5330. (org-flag-heading nil))))))
  5331. (defun org-show-subtree ()
  5332. "Show everything after this heading at deeper levels."
  5333. (interactive)
  5334. (org-flag-region
  5335. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5336. ;;;; Blocks and drawers visibility
  5337. (defun org--hide-wrapper-toggle (element category force no-error)
  5338. "Toggle visibility for ELEMENT.
  5339. ELEMENT is a block or drawer type parsed element. CATEGORY is
  5340. either `block' or `drawer'. When FORCE is `off', show the block
  5341. or drawer. If it is non-nil, hide it unconditionally. Throw an
  5342. error when not at a block or drawer, unless NO-ERROR is non-nil.
  5343. Return a non-nil value when toggling is successful."
  5344. (let ((type (org-element-type element)))
  5345. (cond
  5346. ((memq type
  5347. (pcase category
  5348. (`drawer '(drawer property-drawer))
  5349. (`block '(center-block
  5350. comment-block dynamic-block example-block export-block
  5351. quote-block special-block src-block verse-block))
  5352. (_ (error "Unknown category: %S" category))))
  5353. (let* ((post (org-element-property :post-affiliated element))
  5354. (start (save-excursion
  5355. (goto-char post)
  5356. (line-end-position)))
  5357. (end (save-excursion
  5358. (goto-char (org-element-property :end element))
  5359. (skip-chars-backward " \t\n")
  5360. (line-end-position))))
  5361. ;; Do nothing when not before or at the block opening line or
  5362. ;; at the block closing line.
  5363. (unless (let ((eol (line-end-position)))
  5364. (and (> eol start) (/= eol end)))
  5365. (let* ((spec (if (eq category 'block) 'org-hide-block 'outline))
  5366. (flag
  5367. (cond ((eq force 'off) nil)
  5368. (force t)
  5369. ((eq spec (get-char-property start 'invisible)) nil)
  5370. (t t))))
  5371. (org-flag-region start end flag spec))
  5372. ;; When the block is hidden away, make sure point is left in
  5373. ;; a visible part of the buffer.
  5374. (when (invisible-p (max (1- (point)) (point-min)))
  5375. (goto-char post))
  5376. ;; Signal success.
  5377. t)))
  5378. (no-error nil)
  5379. (t
  5380. (user-error (if (eq category 'drawer)
  5381. "Not at a drawer"
  5382. "Not at a block"))))))
  5383. (defun org-hide-block-toggle (&optional force no-error element)
  5384. "Toggle the visibility of the current block.
  5385. When optional argument FORCE is `off', make block visible. If it
  5386. is non-nil, hide it unconditionally. Throw an error when not at
  5387. a block, unless NO-ERROR is non-nil. When optional argument
  5388. ELEMENT is provided, consider it instead of the current block.
  5389. Return a non-nil value when toggling is successful."
  5390. (interactive)
  5391. (org--hide-wrapper-toggle
  5392. (or element (org-element-at-point)) 'block force no-error))
  5393. (defun org-hide-drawer-toggle (&optional force no-error element)
  5394. "Toggle the visibility of the current drawer.
  5395. When optional argument FORCE is `off', make drawer visible. If
  5396. it is non-nil, hide it unconditionally. Throw an error when not
  5397. at a drawer, unless NO-ERROR is non-nil. When optional argument
  5398. ELEMENT is provided, consider it instead of the current drawer.
  5399. Return a non-nil value when toggling is successful."
  5400. (interactive)
  5401. (org--hide-wrapper-toggle
  5402. (or element (org-element-at-point)) 'drawer force no-error))
  5403. (defun org-hide-block-all ()
  5404. "Fold all blocks in the current buffer."
  5405. (interactive)
  5406. (org-show-all '(blocks))
  5407. (org-block-map 'org-hide-block-toggle))
  5408. (defun org-hide-drawer-all ()
  5409. "Fold all drawers in the current buffer."
  5410. (save-excursion
  5411. (goto-char (point-min))
  5412. (while (re-search-forward org-drawer-regexp nil t)
  5413. (let* ((pair (get-char-property-and-overlay (line-beginning-position)
  5414. 'invisible))
  5415. (o (cdr-safe pair)))
  5416. (if (overlayp o) (goto-char (overlay-end o)) ;invisible drawer
  5417. (pcase (get-char-property-and-overlay (point) 'invisible)
  5418. (`(outline . ,o) (goto-char (overlay-end o))) ;already folded
  5419. (_
  5420. (let* ((drawer (org-element-at-point))
  5421. (type (org-element-type drawer)))
  5422. (when (memq type '(drawer property-drawer))
  5423. (org-hide-drawer-toggle t nil drawer)
  5424. ;; Make sure to skip drawer entirely or we might flag it
  5425. ;; another time when matching its ending line with
  5426. ;; `org-drawer-regexp'.
  5427. (goto-char (org-element-property :end drawer)))))))))))
  5428. (defun org-cycle-hide-drawers (state)
  5429. "Re-hide all drawers after a visibility state change.
  5430. STATE should be one of the symbols listed in the docstring of
  5431. `org-cycle-hook'."
  5432. (when (and (derived-mode-p 'org-mode)
  5433. (not (memq state '(overview folded contents))))
  5434. (let* ((global? (eq state 'all))
  5435. (beg (if global? (point-min) (line-beginning-position)))
  5436. (end (cond (global? (point-max))
  5437. ((eq state 'children) (org-entry-end-position))
  5438. (t (save-excursion (org-end-of-subtree t t))))))
  5439. (save-excursion
  5440. (goto-char beg)
  5441. (while (re-search-forward org-drawer-regexp end t)
  5442. (pcase (get-char-property-and-overlay (point) 'invisible)
  5443. ;; Do not fold already folded drawers.
  5444. (`(outline . ,o) (goto-char (overlay-end o)))
  5445. (_
  5446. (let ((drawer (org-element-at-point)))
  5447. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5448. (org-hide-drawer-toggle t nil drawer)
  5449. ;; Make sure to skip drawer entirely or we might flag
  5450. ;; it another time when matching its ending line with
  5451. ;; `org-drawer-regexp'.
  5452. (goto-char (org-element-property :end drawer)))))))))))
  5453. ;;;; Visibility cycling
  5454. (defvar-local org-cycle-global-status nil)
  5455. (put 'org-cycle-global-status 'org-state t)
  5456. (defvar-local org-cycle-subtree-status nil)
  5457. (put 'org-cycle-subtree-status 'org-state t)
  5458. (defun org-show-all (&optional types)
  5459. "Show all contents in the visible part of the buffer.
  5460. By default, the function expands headings, blocks and drawers.
  5461. When optional argument TYPE is a list of symbols among `blocks',
  5462. `drawers' and `headings', to only expand one specific type."
  5463. (interactive)
  5464. (let ((types (or types '(blocks drawers headings))))
  5465. (when (memq 'blocks types)
  5466. (org-flag-region (point-min) (point-max) nil 'org-hide-block))
  5467. (cond
  5468. ;; Fast path. Since headings and drawers share the same
  5469. ;; invisible spec, clear everything in one go.
  5470. ((and (memq 'headings types)
  5471. (memq 'drawers types))
  5472. (org-flag-region (point-min) (point-max) nil 'outline))
  5473. ((memq 'headings types)
  5474. (org-flag-region (point-min) (point-max) nil 'outline)
  5475. (org-cycle-hide-drawers 'all))
  5476. ((memq 'drawers types)
  5477. (save-excursion
  5478. (goto-char (point-min))
  5479. (while (re-search-forward org-drawer-regexp nil t)
  5480. (let* ((pair (get-char-property-and-overlay (line-beginning-position)
  5481. 'invisible))
  5482. (o (cdr-safe pair)))
  5483. (if (overlayp o) (goto-char (overlay-end o))
  5484. (pcase (get-char-property-and-overlay (point) 'invisible)
  5485. (`(outline . ,o)
  5486. (goto-char (overlay-end o))
  5487. (delete-overlay o))
  5488. (_ nil))))))))))
  5489. ;;;###autoload
  5490. (defun org-cycle (&optional arg)
  5491. "TAB-action and visibility cycling for Org mode.
  5492. This is the command invoked in Org mode by the `TAB' key. Its main
  5493. purpose is outline visibility cycling, but it also invokes other actions
  5494. in special contexts.
  5495. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5496. the entire
  5497. buffer through 3 states (global cycling)
  5498. 1. OVERVIEW: Show only top-level headlines.
  5499. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5500. 3. SHOW ALL: Show everything.
  5501. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5502. switch to the startup visibility,
  5503. determined by the variable `org-startup-folded', and by any VISIBILITY
  5504. properties in the buffer.
  5505. With a `\\[universal-argument] \\[universal-argument] \
  5506. \\[universal-argument]' prefix argument, show the entire buffer, including
  5507. any drawers.
  5508. When inside a table, re-align the table and move to the next field.
  5509. When point is at the beginning of a headline, rotate the subtree started
  5510. by this line through 3 different states (local cycling)
  5511. 1. FOLDED: Only the main headline is shown.
  5512. 2. CHILDREN: The main headline and the direct children are shown.
  5513. From this state, you can move to one of the children
  5514. and zoom in further.
  5515. 3. SUBTREE: Show the entire subtree, including body text.
  5516. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5517. When point is at the beginning of an empty headline and the variable
  5518. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5519. of the headline by demoting and promoting it to likely levels. This
  5520. speeds up creation document structure by pressing `TAB' once or several
  5521. times right after creating a new headline.
  5522. When there is a numeric prefix, go up to a heading with level ARG, do
  5523. a `show-subtree' and return to the previous cursor position. If ARG
  5524. is negative, go up that many levels.
  5525. When point is not at the beginning of a headline, execute the global
  5526. binding for `TAB', which is re-indenting the line. See the option
  5527. `org-cycle-emulate-tab' for details.
  5528. As a special case, if point is at the very beginning of the buffer, if
  5529. there is no headline there, and if the variable `org-cycle-global-at-bob'
  5530. is non-nil, this function acts as if called with prefix argument \
  5531. \(`\\[universal-argument] TAB',
  5532. same as `S-TAB') also when called without prefix argument."
  5533. (interactive "P")
  5534. (org-load-modules-maybe)
  5535. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5536. (and org-cycle-level-after-item/entry-creation
  5537. (or (org-cycle-level)
  5538. (org-cycle-item-indentation))))
  5539. (let* ((limit-level
  5540. (or org-cycle-max-level
  5541. (and (boundp 'org-inlinetask-min-level)
  5542. org-inlinetask-min-level
  5543. (1- org-inlinetask-min-level))))
  5544. (nstars
  5545. (and limit-level
  5546. (if org-odd-levels-only
  5547. (1- (* 2 limit-level))
  5548. limit-level)))
  5549. (org-outline-regexp
  5550. (format "\\*%s " (if nstars (format "\\{1,%d\\}" nstars) "+"))))
  5551. (cond
  5552. ((equal arg '(16))
  5553. (setq last-command 'dummy)
  5554. (org-set-startup-visibility)
  5555. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5556. ((equal arg '(64))
  5557. (org-show-all)
  5558. (org-unlogged-message "Entire buffer visible, including drawers"))
  5559. ((equal arg '(4)) (org-cycle-internal-global))
  5560. ;; Show-subtree, ARG levels up from here.
  5561. ((integerp arg)
  5562. (save-excursion
  5563. (org-back-to-heading)
  5564. (outline-up-heading (if (< arg 0) (- arg)
  5565. (- (funcall outline-level) arg)))
  5566. (org-show-subtree)))
  5567. ;; Global cycling at BOB: delegate to `org-cycle-internal-global'.
  5568. ((and org-cycle-global-at-bob
  5569. (bobp)
  5570. (not (looking-at org-outline-regexp)))
  5571. (let ((org-cycle-hook
  5572. (remq 'org-optimize-window-after-visibility-change
  5573. org-cycle-hook)))
  5574. (org-cycle-internal-global)))
  5575. ;; Try CDLaTeX TAB completion.
  5576. ((org-try-cdlatex-tab))
  5577. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5578. ((and (featurep 'org-inlinetask)
  5579. (org-inlinetask-at-task-p)
  5580. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5581. (org-inlinetask-toggle-visibility))
  5582. (t
  5583. (let ((pos (point))
  5584. (element (org-element-at-point)))
  5585. (cond
  5586. ;; Try toggling visibility for block at point.
  5587. ((org-hide-block-toggle nil t element))
  5588. ;; Try toggling visibility for drawer at point.
  5589. ((org-hide-drawer-toggle nil t element))
  5590. ;; Table: enter it or move to the next field.
  5591. ((and (org-match-line "[ \t]*[|+]")
  5592. (org-element-lineage element '(table) t))
  5593. (if (and (eq 'table (org-element-type element))
  5594. (eq 'table.el (org-element-property :type element)))
  5595. (message (substitute-command-keys "\\<org-mode-map>\
  5596. Use `\\[org-edit-special]' to edit table.el tables"))
  5597. (org-table-justify-field-maybe)
  5598. (call-interactively #'org-table-next-field)))
  5599. ((run-hook-with-args-until-success
  5600. 'org-tab-after-check-for-table-hook))
  5601. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5602. ((and (or (and org-cycle-include-plain-lists
  5603. (let ((item (org-element-lineage element
  5604. '(item plain-list)
  5605. t)))
  5606. (and item
  5607. (= (line-beginning-position)
  5608. (org-element-property :post-affiliated
  5609. item)))))
  5610. (org-match-line org-outline-regexp))
  5611. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5612. (org-cycle-internal-local))
  5613. ;; From there: TAB emulation and template completion.
  5614. (buffer-read-only (org-back-to-heading))
  5615. ((run-hook-with-args-until-success
  5616. 'org-tab-after-check-for-cycling-hook))
  5617. ((run-hook-with-args-until-success
  5618. 'org-tab-before-tab-emulation-hook))
  5619. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5620. (or (not (bolp))
  5621. (not (looking-at org-outline-regexp))))
  5622. (call-interactively (global-key-binding (kbd "TAB"))))
  5623. ((or (eq org-cycle-emulate-tab t)
  5624. (and (memq org-cycle-emulate-tab '(white whitestart))
  5625. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5626. (or (and (eq org-cycle-emulate-tab 'white)
  5627. (= (match-end 0) (point-at-eol)))
  5628. (and (eq org-cycle-emulate-tab 'whitestart)
  5629. (>= (match-end 0) pos)))))
  5630. (call-interactively (global-key-binding (kbd "TAB"))))
  5631. (t
  5632. (save-excursion
  5633. (org-back-to-heading)
  5634. (org-cycle))))))))))
  5635. (defun org-cycle-internal-global ()
  5636. "Do the global cycling action."
  5637. ;; Hack to avoid display of messages for .org attachments in Gnus
  5638. (let ((ga (string-match-p "\\*fontification" (buffer-name))))
  5639. (cond
  5640. ((and (eq last-command this-command)
  5641. (eq org-cycle-global-status 'overview))
  5642. ;; We just created the overview - now do table of contents
  5643. ;; This can be slow in very large buffers, so indicate action
  5644. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5645. (unless ga (org-unlogged-message "CONTENTS..."))
  5646. (org-content)
  5647. (unless ga (org-unlogged-message "CONTENTS...done"))
  5648. (setq org-cycle-global-status 'contents)
  5649. (run-hook-with-args 'org-cycle-hook 'contents))
  5650. ((and (eq last-command this-command)
  5651. (eq org-cycle-global-status 'contents))
  5652. ;; We just showed the table of contents - now show everything
  5653. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5654. (org-show-all '(headings blocks))
  5655. (unless ga (org-unlogged-message "SHOW ALL"))
  5656. (setq org-cycle-global-status 'all)
  5657. (run-hook-with-args 'org-cycle-hook 'all))
  5658. (t
  5659. ;; Default action: go to overview
  5660. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5661. (org-overview)
  5662. (unless ga (org-unlogged-message "OVERVIEW"))
  5663. (setq org-cycle-global-status 'overview)
  5664. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5665. (defvar org-called-with-limited-levels nil
  5666. "Non-nil when `org-with-limited-levels' is currently active.")
  5667. (defun org-cycle-internal-local ()
  5668. "Do the local cycling action."
  5669. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5670. ;; First, determine end of headline (EOH), end of subtree or item
  5671. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5672. (save-excursion
  5673. (if (org-at-item-p)
  5674. (progn
  5675. (beginning-of-line)
  5676. (setq struct (org-list-struct))
  5677. (setq eoh (point-at-eol))
  5678. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5679. (setq has-children (org-list-has-child-p (point) struct)))
  5680. (org-back-to-heading)
  5681. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5682. (setq eos (save-excursion
  5683. (org-end-of-subtree t t)
  5684. (unless (eobp) (forward-char -1))
  5685. (point)))
  5686. (setq has-children
  5687. (or
  5688. (save-excursion
  5689. (let ((level (funcall outline-level)))
  5690. (outline-next-heading)
  5691. (and (org-at-heading-p t)
  5692. (> (funcall outline-level) level))))
  5693. (and (eq org-cycle-include-plain-lists 'integrate)
  5694. (save-excursion
  5695. (org-list-search-forward (org-item-beginning-re) eos t))))))
  5696. ;; Determine end invisible part of buffer (EOL)
  5697. (beginning-of-line 2)
  5698. (while (and (not (eobp)) ;this is like `next-line'
  5699. (get-char-property (1- (point)) 'invisible))
  5700. (goto-char (next-single-char-property-change (point) 'invisible))
  5701. (and (eolp) (beginning-of-line 2)))
  5702. (setq eol (point)))
  5703. ;; Find out what to do next and set `this-command'
  5704. (cond
  5705. ((= eos eoh)
  5706. ;; Nothing is hidden behind this heading
  5707. (unless (org-before-first-heading-p)
  5708. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  5709. (org-unlogged-message "EMPTY ENTRY")
  5710. (setq org-cycle-subtree-status nil)
  5711. (save-excursion
  5712. (goto-char eos)
  5713. (outline-next-heading)
  5714. (when (org-invisible-p) (org-flag-heading nil))))
  5715. ((and (or (>= eol eos)
  5716. (not (string-match "\\S-" (buffer-substring eol eos))))
  5717. (or has-children
  5718. (not (setq children-skipped
  5719. org-cycle-skip-children-state-if-no-children))))
  5720. ;; Entire subtree is hidden in one line: children view
  5721. (unless (org-before-first-heading-p)
  5722. (run-hook-with-args 'org-pre-cycle-hook 'children))
  5723. (if (org-at-item-p)
  5724. (org-list-set-item-visibility (point-at-bol) struct 'children)
  5725. (org-show-entry)
  5726. (org-with-limited-levels (org-show-children))
  5727. (org-show-set-visibility 'canonical)
  5728. ;; Fold every list in subtree to top-level items.
  5729. (when (eq org-cycle-include-plain-lists 'integrate)
  5730. (save-excursion
  5731. (org-back-to-heading)
  5732. (while (org-list-search-forward (org-item-beginning-re) eos t)
  5733. (beginning-of-line 1)
  5734. (let* ((struct (org-list-struct))
  5735. (prevs (org-list-prevs-alist struct))
  5736. (end (org-list-get-bottom-point struct)))
  5737. (dolist (e (org-list-get-all-items (point) struct prevs))
  5738. (org-list-set-item-visibility e struct 'folded))
  5739. (goto-char (if (< end eos) end eos)))))))
  5740. (org-unlogged-message "CHILDREN")
  5741. (save-excursion
  5742. (goto-char eos)
  5743. (outline-next-heading)
  5744. (when (org-invisible-p) (org-flag-heading nil)))
  5745. (setq org-cycle-subtree-status 'children)
  5746. (unless (org-before-first-heading-p)
  5747. (run-hook-with-args 'org-cycle-hook 'children)))
  5748. ((or children-skipped
  5749. (and (eq last-command this-command)
  5750. (eq org-cycle-subtree-status 'children)))
  5751. ;; We just showed the children, or no children are there,
  5752. ;; now show everything.
  5753. (unless (org-before-first-heading-p)
  5754. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  5755. (org-flag-region eoh eos nil 'outline)
  5756. (org-unlogged-message
  5757. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  5758. (setq org-cycle-subtree-status 'subtree)
  5759. (unless (org-before-first-heading-p)
  5760. (run-hook-with-args 'org-cycle-hook 'subtree)))
  5761. (t
  5762. ;; Default action: hide the subtree.
  5763. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  5764. (org-flag-region eoh eos t 'outline)
  5765. (org-unlogged-message "FOLDED")
  5766. (setq org-cycle-subtree-status 'folded)
  5767. (unless (org-before-first-heading-p)
  5768. (run-hook-with-args 'org-cycle-hook 'folded))))))
  5769. ;;;###autoload
  5770. (defun org-global-cycle (&optional arg)
  5771. "Cycle the global visibility. For details see `org-cycle'.
  5772. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  5773. With a numeric prefix, show all headlines up to that level."
  5774. (interactive "P")
  5775. (cond
  5776. ((integerp arg)
  5777. (org-content arg)
  5778. (setq org-cycle-global-status 'contents))
  5779. ((equal arg '(4))
  5780. (org-set-startup-visibility)
  5781. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  5782. (t
  5783. (org-cycle '(4)))))
  5784. (defun org-set-startup-visibility ()
  5785. "Set the visibility required by startup options and properties."
  5786. (cond
  5787. ((eq org-startup-folded t)
  5788. (org-overview))
  5789. ((eq org-startup-folded 'content)
  5790. (org-content))
  5791. ((or (eq org-startup-folded 'showeverything)
  5792. (eq org-startup-folded nil))
  5793. (org-show-all)))
  5794. (unless (eq org-startup-folded 'showeverything)
  5795. (when org-hide-block-startup (org-hide-block-all))
  5796. (org-set-visibility-according-to-property)
  5797. (org-cycle-hide-archived-subtrees 'all)
  5798. (org-cycle-hide-drawers 'all)
  5799. (org-cycle-show-empty-lines t)))
  5800. (defun org-set-visibility-according-to-property ()
  5801. "Switch subtree visibility according to VISIBILITY property."
  5802. (interactive)
  5803. (let ((regexp (org-re-property "VISIBILITY")))
  5804. (org-with-point-at 1
  5805. (while (re-search-forward regexp nil t)
  5806. (let ((state (match-string 3)))
  5807. (if (not (org-at-property-p)) (outline-next-heading)
  5808. (save-excursion
  5809. (org-back-to-heading t)
  5810. (org-flag-subtree t)
  5811. (org-reveal)
  5812. (pcase state
  5813. ("folded"
  5814. (org-flag-subtree t))
  5815. ("children"
  5816. (org-show-hidden-entry)
  5817. (org-show-children))
  5818. ("content"
  5819. (save-excursion
  5820. (save-restriction
  5821. (org-narrow-to-subtree)
  5822. (org-content))))
  5823. ((or "all" "showall")
  5824. (outline-show-subtree))
  5825. (_ nil)))
  5826. (org-end-of-subtree)))))))
  5827. (defun org-overview ()
  5828. "Switch to overview mode, showing only top-level headlines."
  5829. (interactive)
  5830. (org-show-all '(headings drawers))
  5831. (save-excursion
  5832. (goto-char (point-min))
  5833. (when (re-search-forward org-outline-regexp-bol nil t)
  5834. (let* ((last (line-end-position))
  5835. (level (- (match-end 0) (match-beginning 0) 1))
  5836. (regexp (format "^\\*\\{1,%d\\} " level)))
  5837. (while (re-search-forward regexp nil :move)
  5838. (org-flag-region last (line-end-position 0) t 'outline)
  5839. (setq last (line-end-position))
  5840. (setq level (- (match-end 0) (match-beginning 0) 1))
  5841. (setq regexp (format "^\\*\\{1,%d\\} " level)))
  5842. (org-flag-region last (point) t 'outline)))))
  5843. (defun org-content (&optional arg)
  5844. "Show all headlines in the buffer, like a table of contents.
  5845. With numerical argument N, show content up to level N."
  5846. (interactive "p")
  5847. (org-show-all '(headings drawers))
  5848. (save-excursion
  5849. (goto-char (point-max))
  5850. (let ((regexp (if (and (wholenump arg) (> arg 0))
  5851. (format "^\\*\\{1,%d\\} " arg)
  5852. "^\\*+ "))
  5853. (last (point)))
  5854. (while (re-search-backward regexp nil t)
  5855. (org-flag-region (line-end-position) last t 'outline)
  5856. (setq last (line-end-position 0))))))
  5857. (defvar org-scroll-position-to-restore nil
  5858. "Temporarily store scroll position to restore.")
  5859. (defun org-optimize-window-after-visibility-change (state)
  5860. "Adjust the window after a change in outline visibility.
  5861. This function is the default value of the hook `org-cycle-hook'."
  5862. (when (get-buffer-window (current-buffer))
  5863. (cond
  5864. ((eq state 'content) nil)
  5865. ((eq state 'all) nil)
  5866. ((and (eq state 'folded) (eq last-command this-command))
  5867. (set-window-start nil org-scroll-position-to-restore))
  5868. ((eq state 'folded) nil)
  5869. ((eq state 'children)
  5870. (setq org-scroll-position-to-restore (window-start))
  5871. (or (org-subtree-end-visible-p) (recenter 1)))
  5872. ((eq state 'subtree)
  5873. (when (not (eq last-command this-command))
  5874. (setq org-scroll-position-to-restore (window-start)))
  5875. (or (org-subtree-end-visible-p) (recenter 1))))))
  5876. (defun org-clean-visibility-after-subtree-move ()
  5877. "Fix visibility issues after moving a subtree."
  5878. ;; First, find a reasonable region to look at:
  5879. ;; Start two siblings above, end three below
  5880. (let* ((beg (save-excursion
  5881. (and (org-get-last-sibling)
  5882. (org-get-last-sibling))
  5883. (point)))
  5884. (end (save-excursion
  5885. (and (org-get-next-sibling)
  5886. (org-get-next-sibling)
  5887. (org-get-next-sibling))
  5888. (if (org-at-heading-p)
  5889. (point-at-eol)
  5890. (point))))
  5891. (level (looking-at "\\*+"))
  5892. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5893. (save-excursion
  5894. (save-restriction
  5895. (narrow-to-region beg end)
  5896. (when re
  5897. ;; Properly fold already folded siblings
  5898. (goto-char (point-min))
  5899. (while (re-search-forward re nil t)
  5900. (when (and (not (org-invisible-p))
  5901. (org-invisible-p (line-end-position)))
  5902. (outline-hide-entry))))
  5903. (org-cycle-hide-drawers 'all)
  5904. (org-cycle-show-empty-lines 'overview)))))
  5905. (defun org-cycle-show-empty-lines (state)
  5906. "Show empty lines above all visible headlines.
  5907. The region to be covered depends on STATE when called through
  5908. `org-cycle-hook'. Lisp program can use t for STATE to get the
  5909. entire buffer covered. Note that an empty line is only shown if there
  5910. are at least `org-cycle-separator-lines' empty lines before the headline."
  5911. (when (/= org-cycle-separator-lines 0)
  5912. (save-excursion
  5913. (let* ((n (abs org-cycle-separator-lines))
  5914. (re (cond
  5915. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  5916. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  5917. (t (let ((ns (number-to-string (- n 2))))
  5918. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  5919. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  5920. beg end)
  5921. (cond
  5922. ((memq state '(overview contents t))
  5923. (setq beg (point-min) end (point-max)))
  5924. ((memq state '(children folded))
  5925. (setq beg (point)
  5926. end (progn (org-end-of-subtree t t)
  5927. (line-beginning-position 2)))))
  5928. (when beg
  5929. (goto-char beg)
  5930. (while (re-search-forward re end t)
  5931. (unless (get-char-property (match-end 1) 'invisible)
  5932. (let ((e (match-end 1))
  5933. (b (if (>= org-cycle-separator-lines 0)
  5934. (match-beginning 1)
  5935. (save-excursion
  5936. (goto-char (match-beginning 0))
  5937. (skip-chars-backward " \t\n")
  5938. (line-end-position)))))
  5939. (org-flag-region b e nil 'outline))))))))
  5940. ;; Never hide empty lines at the end of the file.
  5941. (save-excursion
  5942. (goto-char (point-max))
  5943. (outline-previous-heading)
  5944. (outline-end-of-heading)
  5945. (when (and (looking-at "[ \t\n]+")
  5946. (= (match-end 0) (point-max)))
  5947. (org-flag-region (point) (match-end 0) nil 'outline))))
  5948. ;;;; Reveal point location
  5949. (defun org-show-context (&optional key)
  5950. "Make sure point and context are visible.
  5951. Optional argument KEY, when non-nil, is a symbol. See
  5952. `org-show-context-detail' for allowed values and how much is to
  5953. be shown."
  5954. (org-show-set-visibility
  5955. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  5956. ((cdr (assq key org-show-context-detail)))
  5957. (t (cdr (assq 'default org-show-context-detail))))))
  5958. (defun org-show-set-visibility (detail)
  5959. "Set visibility around point according to DETAIL.
  5960. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  5961. `tree', `canonical' or t. See `org-show-context-detail' for more
  5962. information."
  5963. ;; Show current heading and possibly its entry, following headline
  5964. ;; or all children.
  5965. (if (and (org-at-heading-p) (not (eq detail 'local)))
  5966. (org-flag-heading nil)
  5967. (org-show-entry)
  5968. ;; If point is hidden within a drawer or a block, make sure to
  5969. ;; expose it.
  5970. (dolist (o (overlays-at (point)))
  5971. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  5972. (delete-overlay o)))
  5973. (unless (org-before-first-heading-p)
  5974. (org-with-limited-levels
  5975. (cl-case detail
  5976. ((tree canonical t) (org-show-children))
  5977. ((nil minimal ancestors))
  5978. (t (save-excursion
  5979. (outline-next-heading)
  5980. (org-flag-heading nil)))))))
  5981. ;; Show all siblings.
  5982. (when (eq detail 'lineage) (org-show-siblings))
  5983. ;; Show ancestors, possibly with their children.
  5984. (when (memq detail '(ancestors lineage tree canonical t))
  5985. (save-excursion
  5986. (while (org-up-heading-safe)
  5987. (org-flag-heading nil)
  5988. (when (memq detail '(canonical t)) (org-show-entry))
  5989. (when (memq detail '(tree canonical t)) (org-show-children))))))
  5990. (defvar org-reveal-start-hook nil
  5991. "Hook run before revealing a location.")
  5992. (defun org-reveal (&optional siblings)
  5993. "Show current entry, hierarchy above it, and the following headline.
  5994. This can be used to show a consistent set of context around
  5995. locations exposed with `org-show-context'.
  5996. With optional argument SIBLINGS, on each level of the hierarchy all
  5997. siblings are shown. This repairs the tree structure to what it would
  5998. look like when opened with hierarchical calls to `org-cycle'.
  5999. With a \\[universal-argument] \\[universal-argument] prefix, \
  6000. go to the parent and show the entire tree."
  6001. (interactive "P")
  6002. (run-hooks 'org-reveal-start-hook)
  6003. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6004. ((equal siblings '(16))
  6005. (save-excursion
  6006. (when (org-up-heading-safe)
  6007. (org-show-subtree)
  6008. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6009. (t (org-show-set-visibility 'lineage))))
  6010. ;;; Indirect buffer display of subtrees
  6011. (defvar org-indirect-dedicated-frame nil
  6012. "This is the frame being used for indirect tree display.")
  6013. (defvar org-last-indirect-buffer nil)
  6014. (defun org-tree-to-indirect-buffer (&optional arg)
  6015. "Create indirect buffer and narrow it to current subtree.
  6016. With a numerical prefix ARG, go up to this level and then take that tree.
  6017. If ARG is negative, go up that many levels.
  6018. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6019. indirect buffer previously made with this command, to avoid proliferation of
  6020. indirect buffers. However, when you call the command with a \
  6021. `\\[universal-argument]' prefix, or
  6022. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6023. so that you can work with several indirect buffers at the same time. If
  6024. `org-indirect-buffer-display' is `dedicated-frame', the \
  6025. `\\[universal-argument]' prefix also
  6026. requests that a new frame be made for the new buffer, so that the dedicated
  6027. frame is not changed."
  6028. (interactive "P")
  6029. (let ((cbuf (current-buffer))
  6030. (cwin (selected-window))
  6031. (pos (point))
  6032. beg end level heading ibuf)
  6033. (save-excursion
  6034. (org-back-to-heading t)
  6035. (when (numberp arg)
  6036. (setq level (org-outline-level))
  6037. (when (< arg 0) (setq arg (+ level arg)))
  6038. (while (> (setq level (org-outline-level)) arg)
  6039. (org-up-heading-safe)))
  6040. (setq beg (point)
  6041. heading (org-get-heading 'no-tags))
  6042. (org-end-of-subtree t t)
  6043. (when (org-at-heading-p) (backward-char 1))
  6044. (setq end (point)))
  6045. (when (and (buffer-live-p org-last-indirect-buffer)
  6046. (not (eq org-indirect-buffer-display 'new-frame))
  6047. (not arg))
  6048. (kill-buffer org-last-indirect-buffer))
  6049. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6050. org-last-indirect-buffer ibuf)
  6051. (cond
  6052. ((or (eq org-indirect-buffer-display 'new-frame)
  6053. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6054. (select-frame (make-frame))
  6055. (delete-other-windows)
  6056. (pop-to-buffer-same-window ibuf)
  6057. (org-set-frame-title heading))
  6058. ((eq org-indirect-buffer-display 'dedicated-frame)
  6059. (raise-frame
  6060. (select-frame (or (and org-indirect-dedicated-frame
  6061. (frame-live-p org-indirect-dedicated-frame)
  6062. org-indirect-dedicated-frame)
  6063. (setq org-indirect-dedicated-frame (make-frame)))))
  6064. (delete-other-windows)
  6065. (pop-to-buffer-same-window ibuf)
  6066. (org-set-frame-title (concat "Indirect: " heading)))
  6067. ((eq org-indirect-buffer-display 'current-window)
  6068. (pop-to-buffer-same-window ibuf))
  6069. ((eq org-indirect-buffer-display 'other-window)
  6070. (pop-to-buffer ibuf))
  6071. (t (error "Invalid value")))
  6072. (narrow-to-region beg end)
  6073. (org-show-all '(headings drawers blocks))
  6074. (goto-char pos)
  6075. (run-hook-with-args 'org-cycle-hook 'all)
  6076. (and (window-live-p cwin) (select-window cwin))))
  6077. (defun org-get-indirect-buffer (&optional buffer heading)
  6078. (setq buffer (or buffer (current-buffer)))
  6079. (let ((n 1) (base (buffer-name buffer)) bname)
  6080. (while (buffer-live-p
  6081. (get-buffer
  6082. (setq bname
  6083. (concat base "-"
  6084. (if heading (concat heading "-" (number-to-string n))
  6085. (number-to-string n))))))
  6086. (setq n (1+ n)))
  6087. (condition-case nil
  6088. (make-indirect-buffer buffer bname 'clone)
  6089. (error (make-indirect-buffer buffer bname)))))
  6090. (defun org-set-frame-title (title)
  6091. "Set the title of the current frame to the string TITLE."
  6092. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6093. ;;;; Structure editing
  6094. ;;; Inserting headlines
  6095. (defun org--blank-before-heading-p (&optional parent)
  6096. "Non-nil when an empty line should precede a new heading here.
  6097. When optional argument PARENT is non-nil, consider parent
  6098. headline instead of current one."
  6099. (pcase (assq 'heading org-blank-before-new-entry)
  6100. (`(heading . auto)
  6101. (save-excursion
  6102. (org-with-limited-levels
  6103. (unless (and (org-before-first-heading-p)
  6104. (not (outline-next-heading)))
  6105. (org-back-to-heading t)
  6106. (when parent (org-up-heading-safe))
  6107. (cond ((not (bobp))
  6108. (org-previous-line-empty-p))
  6109. ((outline-next-heading)
  6110. (org-previous-line-empty-p))
  6111. ;; Ignore trailing spaces on last buffer line.
  6112. ((progn (skip-chars-backward " \t") (bolp))
  6113. (org-previous-line-empty-p))
  6114. (t nil))))))
  6115. (`(heading . ,value) value)
  6116. (_ nil)))
  6117. (defun org-insert-heading (&optional arg invisible-ok top)
  6118. "Insert a new heading or an item with the same depth at point.
  6119. If point is at the beginning of a heading, insert a new heading
  6120. or a new headline above the current one. When at the beginning
  6121. of a regular line of text, turn it into a heading.
  6122. If point is in the middle of a line, split it and create a new
  6123. headline with the text in the current line after point (see
  6124. `org-M-RET-may-split-line' on how to modify this behavior). As
  6125. a special case, on a headline, splitting can only happen on the
  6126. title itself. E.g., this excludes breaking stars or tags.
  6127. With a `\\[universal-argument]' prefix, set \
  6128. `org-insert-heading-respect-content' to
  6129. a non-nil value for the duration of the command. This forces the
  6130. insertion of a heading after the current subtree, independently
  6131. on the location of point.
  6132. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6133. insert the heading at the end of the tree
  6134. above the current heading. For example, if point is within a
  6135. 2nd-level heading, then it will insert a 2nd-level heading at
  6136. the end of the 1st-level parent subtree.
  6137. When INVISIBLE-OK is set, stop at invisible headlines when going
  6138. back. This is important for non-interactive uses of the
  6139. command.
  6140. When optional argument TOP is non-nil, insert a level 1 heading,
  6141. unconditionally."
  6142. (interactive "P")
  6143. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6144. (level (org-current-level))
  6145. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6146. (cond
  6147. ((or org-insert-heading-respect-content
  6148. (member arg '((4) (16)))
  6149. (and (not invisible-ok)
  6150. (invisible-p (max (1- (point)) (point-min)))))
  6151. ;; Position point at the location of insertion. Make sure we
  6152. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6153. (org-with-limited-levels
  6154. (if (not level) (outline-next-heading) ;before first headline
  6155. (org-back-to-heading invisible-ok)
  6156. (when (equal arg '(16)) (org-up-heading-safe))
  6157. (org-end-of-subtree)))
  6158. (unless (bolp) (insert "\n"))
  6159. (unless (and blank? (org-previous-line-empty-p))
  6160. (org-N-empty-lines-before-current (if blank? 1 0)))
  6161. (insert stars " ")
  6162. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6163. ;; is visible.
  6164. (unless invisible-ok
  6165. (pcase (get-char-property-and-overlay (point) 'invisible)
  6166. (`(outline . ,o)
  6167. (move-overlay o (overlay-start o) (line-end-position 0)))
  6168. (_ nil))))
  6169. ;; At a headline...
  6170. ((org-at-heading-p)
  6171. (cond ((bolp)
  6172. (when blank? (save-excursion (insert "\n")))
  6173. (save-excursion (insert stars " \n"))
  6174. (unless (and blank? (org-previous-line-empty-p))
  6175. (org-N-empty-lines-before-current (if blank? 1 0)))
  6176. (end-of-line))
  6177. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6178. (org-match-line org-complex-heading-regexp)
  6179. (org-pos-in-match-range (point) 4))
  6180. ;; Grab the text that should moved to the new headline.
  6181. ;; Preserve tags.
  6182. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6183. (if (looking-at "[ \t]*$") (replace-match "")
  6184. (org-align-tags))
  6185. (end-of-line)
  6186. (when blank? (insert "\n"))
  6187. (insert "\n" stars " ")
  6188. (when (org-string-nw-p split) (insert split))))
  6189. (t
  6190. (end-of-line)
  6191. (when blank? (insert "\n"))
  6192. (insert "\n" stars " "))))
  6193. ;; On regular text, turn line into a headline or split, if
  6194. ;; appropriate.
  6195. ((bolp)
  6196. (insert stars " ")
  6197. (unless (and blank? (org-previous-line-empty-p))
  6198. (org-N-empty-lines-before-current (if blank? 1 0))))
  6199. (t
  6200. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6201. (end-of-line))
  6202. (insert "\n" stars " ")
  6203. (unless (and blank? (org-previous-line-empty-p))
  6204. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6205. (run-hooks 'org-insert-heading-hook))
  6206. (defun org-N-empty-lines-before-current (n)
  6207. "Make the number of empty lines before current exactly N.
  6208. So this will delete or add empty lines."
  6209. (let ((column (current-column)))
  6210. (beginning-of-line)
  6211. (unless (bobp)
  6212. (let ((start (save-excursion
  6213. (skip-chars-backward " \r\t\n")
  6214. (line-end-position))))
  6215. (delete-region start (line-end-position 0))))
  6216. (insert (make-string n ?\n))
  6217. (move-to-column column)))
  6218. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6219. "Return the heading of the current entry, without the stars.
  6220. When NO-TAGS is non-nil, don't include tags.
  6221. When NO-TODO is non-nil, don't include TODO keywords.
  6222. When NO-PRIORITY is non-nil, don't include priority cookie.
  6223. When NO-COMMENT is non-nil, don't include COMMENT string.
  6224. Return nil before first heading."
  6225. (unless (org-before-first-heading-p)
  6226. (save-excursion
  6227. (org-back-to-heading t)
  6228. (let ((case-fold-search nil))
  6229. (looking-at org-complex-heading-regexp)
  6230. (let ((todo (and (not no-todo) (match-string 2)))
  6231. (priority (and (not no-priority) (match-string 3)))
  6232. (headline (pcase (match-string 4)
  6233. (`nil "")
  6234. ((and (guard no-comment) h)
  6235. (replace-regexp-in-string
  6236. (eval-when-compile
  6237. (format "\\`%s[ \t]+" org-comment-string))
  6238. "" h))
  6239. (h h)))
  6240. (tags (and (not no-tags) (match-string 5))))
  6241. (mapconcat #'identity
  6242. (delq nil (list todo priority headline tags))
  6243. " "))))))
  6244. (defun org-heading-components ()
  6245. "Return the components of the current heading.
  6246. This is a list with the following elements:
  6247. - the level as an integer
  6248. - the reduced level, different if `org-odd-levels-only' is set.
  6249. - the TODO keyword, or nil
  6250. - the priority character, like ?A, or nil if no priority is given
  6251. - the headline text itself, or the tags string if no headline text
  6252. - the tags string, or nil."
  6253. (save-excursion
  6254. (org-back-to-heading t)
  6255. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6256. (list (length (match-string 1))
  6257. (org-reduced-level (length (match-string 1)))
  6258. (match-string-no-properties 2)
  6259. (and (match-end 3) (aref (match-string 3) 2))
  6260. (match-string-no-properties 4)
  6261. (match-string-no-properties 5)))))
  6262. (defun org-get-entry ()
  6263. "Get the entry text, after heading, entire subtree."
  6264. (save-excursion
  6265. (org-back-to-heading t)
  6266. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6267. (defun org-edit-headline (&optional heading)
  6268. "Edit the current headline.
  6269. Set it to HEADING when provided."
  6270. (interactive)
  6271. (org-with-wide-buffer
  6272. (org-back-to-heading t)
  6273. (let ((case-fold-search nil))
  6274. (when (looking-at org-complex-heading-regexp)
  6275. (let* ((old (match-string-no-properties 4))
  6276. (new (save-match-data
  6277. (org-trim (or heading (read-string "Edit: " old))))))
  6278. (unless (equal old new)
  6279. (if old (replace-match new t t nil 4)
  6280. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6281. (insert " " new))
  6282. (org-align-tags)
  6283. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6284. (defun org-insert-heading-after-current ()
  6285. "Insert a new heading with same level as current, after current subtree."
  6286. (interactive)
  6287. (org-back-to-heading)
  6288. (org-insert-heading)
  6289. (org-move-subtree-down)
  6290. (end-of-line 1))
  6291. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6292. "Insert heading with `org-insert-heading-respect-content' set to t."
  6293. (interactive)
  6294. (org-insert-heading '(4) invisible-ok))
  6295. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6296. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6297. (interactive)
  6298. (org-insert-todo-heading force-state '(4)))
  6299. (defun org-insert-todo-heading (arg &optional force-heading)
  6300. "Insert a new heading with the same level and TODO state as current heading.
  6301. If the heading has no TODO state, or if the state is DONE, use
  6302. the first state (TODO by default). Also with one prefix arg,
  6303. force first state. With two prefix args, force inserting at the
  6304. end of the parent subtree.
  6305. When called at a plain list item, insert a new item with an
  6306. unchecked check box."
  6307. (interactive "P")
  6308. (when (or force-heading (not (org-insert-item 'checkbox)))
  6309. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6310. force-heading))
  6311. (save-excursion
  6312. (org-forward-heading-same-level -1)
  6313. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6314. (let* ((new-mark-x
  6315. (if (or (equal arg '(4))
  6316. (not (match-beginning 2))
  6317. (member (match-string 2) org-done-keywords))
  6318. (car org-todo-keywords-1)
  6319. (match-string 2)))
  6320. (new-mark
  6321. (or
  6322. (run-hook-with-args-until-success
  6323. 'org-todo-get-default-hook new-mark-x nil)
  6324. new-mark-x)))
  6325. (beginning-of-line 1)
  6326. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6327. (if org-treat-insert-todo-heading-as-state-change
  6328. (org-todo new-mark)
  6329. (insert new-mark " "))))
  6330. (when org-provide-todo-statistics
  6331. (org-update-parent-todo-statistics))))
  6332. (defun org-insert-subheading (arg)
  6333. "Insert a new subheading and demote it.
  6334. Works for outline headings and for plain lists alike."
  6335. (interactive "P")
  6336. (org-insert-heading arg)
  6337. (cond
  6338. ((org-at-heading-p) (org-do-demote))
  6339. ((org-at-item-p) (org-indent-item))))
  6340. (defun org-insert-todo-subheading (arg)
  6341. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6342. Works for outline headings and for plain lists alike."
  6343. (interactive "P")
  6344. (org-insert-todo-heading arg)
  6345. (cond
  6346. ((org-at-heading-p) (org-do-demote))
  6347. ((org-at-item-p) (org-indent-item))))
  6348. ;;; Promotion and Demotion
  6349. (defvar org-after-demote-entry-hook nil
  6350. "Hook run after an entry has been demoted.
  6351. The cursor will be at the beginning of the entry.
  6352. When a subtree is being demoted, the hook will be called for each node.")
  6353. (defvar org-after-promote-entry-hook nil
  6354. "Hook run after an entry has been promoted.
  6355. The cursor will be at the beginning of the entry.
  6356. When a subtree is being promoted, the hook will be called for each node.")
  6357. (defun org-promote-subtree ()
  6358. "Promote the entire subtree.
  6359. See also `org-promote'."
  6360. (interactive)
  6361. (save-excursion
  6362. (org-with-limited-levels (org-map-tree 'org-promote)))
  6363. (org-fix-position-after-promote))
  6364. (defun org-demote-subtree ()
  6365. "Demote the entire subtree.
  6366. See `org-demote' and `org-promote'."
  6367. (interactive)
  6368. (save-excursion
  6369. (org-with-limited-levels (org-map-tree 'org-demote)))
  6370. (org-fix-position-after-promote))
  6371. (defun org-do-promote ()
  6372. "Promote the current heading higher up the tree.
  6373. If the region is active in `transient-mark-mode', promote all
  6374. headings in the region."
  6375. (interactive)
  6376. (save-excursion
  6377. (if (org-region-active-p)
  6378. (org-map-region 'org-promote (region-beginning) (region-end))
  6379. (org-promote)))
  6380. (org-fix-position-after-promote))
  6381. (defun org-do-demote ()
  6382. "Demote the current heading lower down the tree.
  6383. If the region is active in `transient-mark-mode', demote all
  6384. headings in the region."
  6385. (interactive)
  6386. (save-excursion
  6387. (if (org-region-active-p)
  6388. (org-map-region 'org-demote (region-beginning) (region-end))
  6389. (org-demote)))
  6390. (org-fix-position-after-promote))
  6391. (defun org-fix-position-after-promote ()
  6392. "Fix cursor position and indentation after demoting/promoting."
  6393. (let ((pos (point)))
  6394. (when (save-excursion
  6395. (beginning-of-line)
  6396. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6397. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6398. (cond ((eobp) (insert " "))
  6399. ((eolp) (insert " "))
  6400. ((equal (char-after) ?\s) (forward-char 1))))))
  6401. (defun org-current-level ()
  6402. "Return the level of the current entry, or nil if before the first headline.
  6403. The level is the number of stars at the beginning of the
  6404. headline. Use `org-reduced-level' to remove the effect of
  6405. `org-odd-levels'. Unlike to `org-outline-level', this function
  6406. ignores inlinetasks."
  6407. (let ((level (org-with-limited-levels (org-outline-level))))
  6408. (and (> level 0) level)))
  6409. (defun org-get-previous-line-level ()
  6410. "Return the outline depth of the last headline before the current line.
  6411. Returns 0 for the first headline in the buffer, and nil if before the
  6412. first headline."
  6413. (and (org-current-level)
  6414. (or (and (/= (line-beginning-position) (point-min))
  6415. (save-excursion (beginning-of-line 0) (org-current-level)))
  6416. 0)))
  6417. (defun org-reduced-level (l)
  6418. "Compute the effective level of a heading.
  6419. This takes into account the setting of `org-odd-levels-only'."
  6420. (cond
  6421. ((zerop l) 0)
  6422. (org-odd-levels-only (1+ (floor (/ l 2))))
  6423. (t l)))
  6424. (defun org-level-increment ()
  6425. "Return the number of stars that will be added or removed at a
  6426. time to headlines when structure editing, based on the value of
  6427. `org-odd-levels-only'."
  6428. (if org-odd-levels-only 2 1))
  6429. (defun org-get-valid-level (level &optional change)
  6430. "Rectify a level change under the influence of `org-odd-levels-only'.
  6431. LEVEL is a current level, CHANGE is by how much the level should
  6432. be modified. Even if CHANGE is nil, LEVEL may be returned
  6433. modified because even level numbers will become the next higher
  6434. odd number. Returns values greater than 0."
  6435. (if org-odd-levels-only
  6436. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6437. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6438. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6439. (max 1 (+ level (or change 0)))))
  6440. (defun org-promote ()
  6441. "Promote the current heading higher up the tree."
  6442. (org-with-wide-buffer
  6443. (org-back-to-heading t)
  6444. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6445. after-change-functions))
  6446. (level (save-match-data (funcall outline-level)))
  6447. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6448. (diff (abs (- level (length up-head) -1))))
  6449. (cond
  6450. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6451. (replace-match "# " nil t))
  6452. ((= level 1)
  6453. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6454. (t (replace-match up-head nil t)))
  6455. (unless (= level 1)
  6456. (when org-auto-align-tags (org-align-tags))
  6457. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6458. (run-hooks 'org-after-promote-entry-hook))))
  6459. (defun org-demote ()
  6460. "Demote the current heading lower down the tree."
  6461. (org-with-wide-buffer
  6462. (org-back-to-heading t)
  6463. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6464. after-change-functions))
  6465. (level (save-match-data (funcall outline-level)))
  6466. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6467. (diff (abs (- level (length down-head) -1))))
  6468. (replace-match down-head nil t)
  6469. (when org-auto-align-tags (org-align-tags))
  6470. (when org-adapt-indentation (org-fixup-indentation diff))
  6471. (run-hooks 'org-after-demote-entry-hook))))
  6472. (defun org-cycle-level ()
  6473. "Cycle the level of an empty headline through possible states.
  6474. This goes first to child, then to parent, level, then up the hierarchy.
  6475. After top level, it switches back to sibling level."
  6476. (interactive)
  6477. (let ((org-adapt-indentation nil))
  6478. (when (org-point-at-end-of-empty-headline)
  6479. (setq this-command 'org-cycle-level) ; Only needed for caching
  6480. (let ((cur-level (org-current-level))
  6481. (prev-level (org-get-previous-line-level)))
  6482. (cond
  6483. ;; If first headline in file, promote to top-level.
  6484. ((= prev-level 0)
  6485. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6486. do (org-do-promote)))
  6487. ;; If same level as prev, demote one.
  6488. ((= prev-level cur-level)
  6489. (org-do-demote))
  6490. ;; If parent is top-level, promote to top level if not already.
  6491. ((= prev-level 1)
  6492. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6493. do (org-do-promote)))
  6494. ;; If top-level, return to prev-level.
  6495. ((= cur-level 1)
  6496. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6497. do (org-do-demote)))
  6498. ;; If less than prev-level, promote one.
  6499. ((< cur-level prev-level)
  6500. (org-do-promote))
  6501. ;; If deeper than prev-level, promote until higher than
  6502. ;; prev-level.
  6503. ((> cur-level prev-level)
  6504. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6505. do (org-do-promote))))
  6506. t))))
  6507. (defun org-map-tree (fun)
  6508. "Call FUN for every heading underneath the current one."
  6509. (org-back-to-heading t)
  6510. (let ((level (funcall outline-level)))
  6511. (save-excursion
  6512. (funcall fun)
  6513. (while (and (progn
  6514. (outline-next-heading)
  6515. (> (funcall outline-level) level))
  6516. (not (eobp)))
  6517. (funcall fun)))))
  6518. (defun org-map-region (fun beg end)
  6519. "Call FUN for every heading between BEG and END."
  6520. (let ((org-ignore-region t))
  6521. (save-excursion
  6522. (setq end (copy-marker end))
  6523. (goto-char beg)
  6524. (when (and (re-search-forward org-outline-regexp-bol nil t)
  6525. (< (point) end))
  6526. (funcall fun))
  6527. (while (and (progn
  6528. (outline-next-heading)
  6529. (< (point) end))
  6530. (not (eobp)))
  6531. (funcall fun)))))
  6532. (defun org-fixup-indentation (diff)
  6533. "Change the indentation in the current entry by DIFF.
  6534. DIFF is an integer. Indentation is done according to the
  6535. following rules:
  6536. - Planning information and property drawers are always indented
  6537. according to the new level of the headline;
  6538. - Footnote definitions and their contents are ignored;
  6539. - Inlinetasks' boundaries are not shifted;
  6540. - Empty lines are ignored;
  6541. - Other lines' indentation are shifted by DIFF columns, unless
  6542. it would introduce a structural change in the document, in
  6543. which case no shifting is done at all.
  6544. Assume point is at a heading or an inlinetask beginning."
  6545. (org-with-wide-buffer
  6546. (narrow-to-region (line-beginning-position)
  6547. (save-excursion
  6548. (if (org-with-limited-levels (org-at-heading-p))
  6549. (org-with-limited-levels (outline-next-heading))
  6550. (org-inlinetask-goto-end))
  6551. (point)))
  6552. (forward-line)
  6553. ;; Indent properly planning info and property drawer.
  6554. (when (looking-at-p org-planning-line-re)
  6555. (org-indent-line)
  6556. (forward-line))
  6557. (when (looking-at org-property-drawer-re)
  6558. (goto-char (match-end 0))
  6559. (forward-line)
  6560. (org-indent-region (match-beginning 0) (match-end 0)))
  6561. (when (looking-at org-logbook-drawer-re)
  6562. (let ((end-marker (move-marker (make-marker) (match-end 0)))
  6563. (ci (current-indentation)))
  6564. (while (and (not (> (point) end-marker)) (>= ci diff))
  6565. (indent-line-to (+ ci diff))
  6566. (forward-line))))
  6567. (catch 'no-shift
  6568. (when (or (zerop diff) (not (eq org-adapt-indentation t)))
  6569. (throw 'no-shift nil))
  6570. ;; If DIFF is negative, first check if a shift is possible at all
  6571. ;; (e.g., it doesn't break structure). This can only happen if
  6572. ;; some contents are not properly indented.
  6573. (let ((case-fold-search t))
  6574. (when (< diff 0)
  6575. (let ((diff (- diff))
  6576. (forbidden-re (concat org-outline-regexp
  6577. "\\|"
  6578. (substring org-footnote-definition-re 1))))
  6579. (save-excursion
  6580. (while (not (eobp))
  6581. (cond
  6582. ((looking-at-p "[ \t]*$") (forward-line))
  6583. ((and (looking-at-p org-footnote-definition-re)
  6584. (let ((e (org-element-at-point)))
  6585. (and (eq (org-element-type e) 'footnote-definition)
  6586. (goto-char (org-element-property :end e))))))
  6587. ((looking-at-p org-outline-regexp) (forward-line))
  6588. ;; Give up if shifting would move before column 0 or
  6589. ;; if it would introduce a headline or a footnote
  6590. ;; definition.
  6591. (t
  6592. (skip-chars-forward " \t")
  6593. (let ((ind (current-column)))
  6594. (when (or (< ind diff)
  6595. (and (= ind diff) (looking-at-p forbidden-re)))
  6596. (throw 'no-shift nil)))
  6597. ;; Ignore contents of example blocks and source
  6598. ;; blocks if their indentation is meant to be
  6599. ;; preserved. Jump to block's closing line.
  6600. (beginning-of-line)
  6601. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6602. (let ((e (org-element-at-point)))
  6603. (and (memq (org-element-type e)
  6604. '(example-block src-block))
  6605. (or org-src-preserve-indentation
  6606. (org-element-property :preserve-indent e))
  6607. (goto-char (org-element-property :end e))
  6608. (progn (skip-chars-backward " \r\t\n")
  6609. (beginning-of-line)
  6610. t))))
  6611. (forward-line))))))))
  6612. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6613. ;; by DIFF. Also skip contents of source or example blocks
  6614. ;; when indentation is meant to be preserved.
  6615. (while (not (eobp))
  6616. (cond
  6617. ((and (looking-at-p org-footnote-definition-re)
  6618. (let ((e (org-element-at-point)))
  6619. (and (eq (org-element-type e) 'footnote-definition)
  6620. (goto-char (org-element-property :end e))))))
  6621. ((looking-at-p org-outline-regexp) (forward-line))
  6622. ((looking-at-p "[ \t]*$") (forward-line))
  6623. (t
  6624. (indent-line-to (+ (current-indentation) diff))
  6625. (beginning-of-line)
  6626. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6627. (let ((e (org-element-at-point)))
  6628. (and (memq (org-element-type e)
  6629. '(example-block src-block))
  6630. (or org-src-preserve-indentation
  6631. (org-element-property :preserve-indent e))
  6632. (goto-char (org-element-property :end e))
  6633. (progn (skip-chars-backward " \r\t\n")
  6634. (beginning-of-line)
  6635. t))))
  6636. (forward-line)))))))))
  6637. (defun org-convert-to-odd-levels ()
  6638. "Convert an Org file with all levels allowed to one with odd levels.
  6639. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6640. level 5 etc."
  6641. (interactive)
  6642. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6643. (let ((outline-level 'org-outline-level)
  6644. (org-odd-levels-only nil) n)
  6645. (save-excursion
  6646. (goto-char (point-min))
  6647. (while (re-search-forward "^\\*\\*+ " nil t)
  6648. (setq n (- (length (match-string 0)) 2))
  6649. (while (>= (setq n (1- n)) 0)
  6650. (org-demote))
  6651. (end-of-line 1))))))
  6652. (defun org-convert-to-oddeven-levels ()
  6653. "Convert an Org file with only odd levels to one with odd/even levels.
  6654. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6655. file contains a section with an even level, conversion would
  6656. destroy the structure of the file. An error is signaled in this
  6657. case."
  6658. (interactive)
  6659. (goto-char (point-min))
  6660. ;; First check if there are no even levels
  6661. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6662. (org-show-set-visibility 'canonical)
  6663. (error "Not all levels are odd in this file. Conversion not possible"))
  6664. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6665. (let ((outline-regexp org-outline-regexp)
  6666. (outline-level 'org-outline-level)
  6667. (org-odd-levels-only nil) n)
  6668. (save-excursion
  6669. (goto-char (point-min))
  6670. (while (re-search-forward "^\\*\\*+ " nil t)
  6671. (setq n (/ (1- (length (match-string 0))) 2))
  6672. (while (>= (setq n (1- n)) 0)
  6673. (org-promote))
  6674. (end-of-line 1))))))
  6675. (defun org-tr-level (n)
  6676. "Make N odd if required."
  6677. (if org-odd-levels-only (1+ (/ n 2)) n))
  6678. ;;; Vertical tree motion, cutting and pasting of subtrees
  6679. (defun org-move-subtree-up (&optional arg)
  6680. "Move the current subtree up past ARG headlines of the same level."
  6681. (interactive "p")
  6682. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6683. (defun org-move-subtree-down (&optional arg)
  6684. "Move the current subtree down past ARG headlines of the same level."
  6685. (interactive "p")
  6686. (setq arg (prefix-numeric-value arg))
  6687. (org-preserve-local-variables
  6688. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6689. 'org-get-last-sibling))
  6690. (ins-point (make-marker))
  6691. (cnt (abs arg))
  6692. (col (current-column))
  6693. beg end txt folded)
  6694. ;; Select the tree
  6695. (org-back-to-heading)
  6696. (setq beg (point))
  6697. (save-match-data
  6698. (save-excursion (outline-end-of-heading)
  6699. (setq folded (org-invisible-p)))
  6700. (progn (org-end-of-subtree nil t)
  6701. (unless (eobp) (backward-char))))
  6702. (outline-next-heading)
  6703. (setq end (point))
  6704. (goto-char beg)
  6705. ;; Find insertion point, with error handling
  6706. (while (> cnt 0)
  6707. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6708. (goto-char beg)
  6709. (user-error "Cannot move past superior level or buffer limit"))
  6710. (setq cnt (1- cnt)))
  6711. (when (> arg 0)
  6712. ;; Moving forward - still need to move over subtree
  6713. (org-end-of-subtree t t)
  6714. (save-excursion
  6715. (org-back-over-empty-lines)
  6716. (or (bolp) (newline))))
  6717. (move-marker ins-point (point))
  6718. (setq txt (buffer-substring beg end))
  6719. (org-save-markers-in-region beg end)
  6720. (delete-region beg end)
  6721. (org-remove-empty-overlays-at beg)
  6722. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  6723. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  6724. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6725. (let ((bbb (point)))
  6726. (insert-before-markers txt)
  6727. (org-reinstall-markers-in-region bbb)
  6728. (move-marker ins-point bbb))
  6729. (or (bolp) (insert "\n"))
  6730. (goto-char ins-point)
  6731. (org-skip-whitespace)
  6732. (move-marker ins-point nil)
  6733. (if folded
  6734. (org-flag-subtree t)
  6735. (org-show-entry)
  6736. (org-show-children))
  6737. (org-clean-visibility-after-subtree-move)
  6738. ;; move back to the initial column we were at
  6739. (move-to-column col))))
  6740. (defvar org-subtree-clip ""
  6741. "Clipboard for cut and paste of subtrees.
  6742. This is actually only a copy of the kill, because we use the normal kill
  6743. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6744. (defvar org-subtree-clip-folded nil
  6745. "Was the last copied subtree folded?
  6746. This is used to fold the tree back after pasting.")
  6747. (defun org-cut-subtree (&optional n)
  6748. "Cut the current subtree into the clipboard.
  6749. With prefix arg N, cut this many sequential subtrees.
  6750. This is a short-hand for marking the subtree and then cutting it."
  6751. (interactive "p")
  6752. (org-copy-subtree n 'cut))
  6753. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6754. "Copy the current subtree into the clipboard.
  6755. With prefix arg N, copy this many sequential subtrees.
  6756. This is a short-hand for marking the subtree and then copying it.
  6757. If CUT is non-nil, actually cut the subtree.
  6758. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6759. of some markers in the region, even if CUT is non-nil. This is
  6760. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6761. (interactive "p")
  6762. (org-preserve-local-variables
  6763. (let (beg end folded (beg0 (point)))
  6764. (if (called-interactively-p 'any)
  6765. (org-back-to-heading nil) ; take what looks like a subtree
  6766. (org-back-to-heading t)) ; take what is really there
  6767. (setq beg (point))
  6768. (skip-chars-forward " \t\r\n")
  6769. (save-match-data
  6770. (if nosubtrees
  6771. (outline-next-heading)
  6772. (save-excursion (outline-end-of-heading)
  6773. (setq folded (org-invisible-p)))
  6774. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6775. (org-end-of-subtree t t)))
  6776. ;; Include the end of an inlinetask
  6777. (when (and (featurep 'org-inlinetask)
  6778. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6779. "END[ \t]*$")))
  6780. (end-of-line))
  6781. (setq end (point))
  6782. (goto-char beg0)
  6783. (when (> end beg)
  6784. (setq org-subtree-clip-folded folded)
  6785. (when (or cut force-store-markers)
  6786. (org-save-markers-in-region beg end))
  6787. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6788. (setq org-subtree-clip (current-kill 0))
  6789. (message "%s: Subtree(s) with %d characters"
  6790. (if cut "Cut" "Copied")
  6791. (length org-subtree-clip))))))
  6792. (defun org-paste-subtree (&optional level tree for-yank remove)
  6793. "Paste the clipboard as a subtree, with modification of headline level.
  6794. The entire subtree is promoted or demoted in order to match a new headline
  6795. level.
  6796. If the cursor is at the beginning of a headline, the same level as
  6797. that headline is used to paste the tree.
  6798. If not, the new level is derived from the *visible* headings
  6799. before and after the insertion point, and taken to be the inferior headline
  6800. level of the two. So if the previous visible heading is level 3 and the
  6801. next is level 4 (or vice versa), level 4 will be used for insertion.
  6802. This makes sure that the subtree remains an independent subtree and does
  6803. not swallow low level entries.
  6804. You can also force a different level, either by using a numeric prefix
  6805. argument, or by inserting the heading marker by hand. For example, if the
  6806. cursor is after \"*****\", then the tree will be shifted to level 5.
  6807. If optional TREE is given, use this text instead of the kill ring.
  6808. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6809. move back over whitespace before inserting, and move point to the end of
  6810. the inserted text when done.
  6811. When REMOVE is non-nil, remove the subtree from the clipboard."
  6812. (interactive "P")
  6813. (setq tree (or tree (and kill-ring (current-kill 0))))
  6814. (unless (org-kill-is-subtree-p tree)
  6815. (user-error
  6816. (substitute-command-keys
  6817. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6818. (org-with-limited-levels
  6819. (let* ((visp (not (org-invisible-p)))
  6820. (txt tree)
  6821. (old-level (if (string-match org-outline-regexp-bol txt)
  6822. (- (match-end 0) (match-beginning 0) 1)
  6823. -1))
  6824. (force-level
  6825. (cond
  6826. (level (prefix-numeric-value level))
  6827. ;; When point is after the stars in an otherwise empty
  6828. ;; headline, use the number of stars as the forced level.
  6829. ((and (org-match-line "^\\*+[ \t]*$")
  6830. (not (eq ?* (char-after))))
  6831. (org-outline-level))
  6832. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6833. (previous-level
  6834. (save-excursion
  6835. (org-previous-visible-heading 1)
  6836. (if (org-at-heading-p) (org-outline-level) 1)))
  6837. (next-level
  6838. (save-excursion
  6839. (if (org-at-heading-p) (org-outline-level)
  6840. (org-next-visible-heading 1)
  6841. (if (org-at-heading-p) (org-outline-level) 1))))
  6842. (new-level (or force-level (max previous-level next-level)))
  6843. (shift (if (or (= old-level -1)
  6844. (= new-level -1)
  6845. (= old-level new-level))
  6846. 0
  6847. (- new-level old-level)))
  6848. (delta (if (> shift 0) -1 1))
  6849. (func (if (> shift 0) #'org-demote #'org-promote))
  6850. (org-odd-levels-only nil)
  6851. beg end newend)
  6852. ;; Remove the forced level indicator.
  6853. (when (and force-level (not level))
  6854. (delete-region (line-beginning-position) (point)))
  6855. ;; Paste before the next visible heading or at end of buffer,
  6856. ;; unless point is at the beginning of a headline.
  6857. (unless (and (bolp) (org-at-heading-p))
  6858. (org-next-visible-heading 1)
  6859. (unless (bolp) (insert "\n")))
  6860. (setq beg (point))
  6861. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6862. (insert-before-markers txt)
  6863. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6864. (setq newend (point))
  6865. (org-reinstall-markers-in-region beg)
  6866. (setq end (point))
  6867. (goto-char beg)
  6868. (skip-chars-forward " \t\n\r")
  6869. (setq beg (point))
  6870. (when (and (org-invisible-p) visp)
  6871. (save-excursion (outline-show-heading)))
  6872. ;; Shift if necessary.
  6873. (unless (= shift 0)
  6874. (save-restriction
  6875. (narrow-to-region beg end)
  6876. (while (not (= shift 0))
  6877. (org-map-region func (point-min) (point-max))
  6878. (setq shift (+ delta shift)))
  6879. (goto-char (point-min))
  6880. (setq newend (point-max))))
  6881. (when (or for-yank (called-interactively-p 'interactive))
  6882. (message "Clipboard pasted as level %d subtree" new-level))
  6883. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6884. kill-ring
  6885. (equal org-subtree-clip (current-kill 0))
  6886. org-subtree-clip-folded)
  6887. ;; The tree was folded before it was killed/copied
  6888. (org-flag-subtree t))
  6889. (when for-yank (goto-char newend))
  6890. (when remove (pop kill-ring)))))
  6891. (defun org-kill-is-subtree-p (&optional txt)
  6892. "Check if the current kill is an outline subtree, or a set of trees.
  6893. Returns nil if kill does not start with a headline, or if the first
  6894. headline level is not the largest headline level in the tree.
  6895. So this will actually accept several entries of equal levels as well,
  6896. which is OK for `org-paste-subtree'.
  6897. If optional TXT is given, check this string instead of the current kill."
  6898. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6899. (re (org-get-limited-outline-regexp))
  6900. (^re (concat "^" re))
  6901. (start-level (and kill
  6902. (string-match
  6903. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6904. kill)
  6905. (- (match-end 2) (match-beginning 2) 1)))
  6906. (start (1+ (or (match-beginning 2) -1))))
  6907. (if (not start-level)
  6908. (progn
  6909. nil) ;; does not even start with a heading
  6910. (catch 'exit
  6911. (while (setq start (string-match ^re kill (1+ start)))
  6912. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6913. (throw 'exit nil)))
  6914. t))))
  6915. (defvar org-markers-to-move nil
  6916. "Markers that should be moved with a cut-and-paste operation.
  6917. Those markers are stored together with their positions relative to
  6918. the start of the region.")
  6919. (defun org-save-markers-in-region (beg end)
  6920. "Check markers in region.
  6921. If these markers are between BEG and END, record their position relative
  6922. to BEG, so that after moving the block of text, we can put the markers back
  6923. into place.
  6924. This function gets called just before an entry or tree gets cut from the
  6925. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  6926. called immediately, to move the markers with the entries."
  6927. (setq org-markers-to-move nil)
  6928. (when (featurep 'org-clock)
  6929. (org-clock-save-markers-for-cut-and-paste beg end))
  6930. (when (featurep 'org-agenda)
  6931. (org-agenda-save-markers-for-cut-and-paste beg end)))
  6932. (defun org-check-and-save-marker (marker beg end)
  6933. "Check if MARKER is between BEG and END.
  6934. If yes, remember the marker and the distance to BEG."
  6935. (when (and (marker-buffer marker)
  6936. (equal (marker-buffer marker) (current-buffer))
  6937. (>= marker beg) (< marker end))
  6938. (push (cons marker (- marker beg)) org-markers-to-move)))
  6939. (defun org-reinstall-markers-in-region (beg)
  6940. "Move all remembered markers to their position relative to BEG."
  6941. (dolist (x org-markers-to-move)
  6942. (move-marker (car x) (+ beg (cdr x))))
  6943. (setq org-markers-to-move nil))
  6944. (defun org-narrow-to-subtree ()
  6945. "Narrow buffer to the current subtree."
  6946. (interactive)
  6947. (save-excursion
  6948. (save-match-data
  6949. (org-with-limited-levels
  6950. (narrow-to-region
  6951. (progn (org-back-to-heading t) (point))
  6952. (progn (org-end-of-subtree t t)
  6953. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  6954. (point)))))))
  6955. (defun org-toggle-narrow-to-subtree ()
  6956. "Narrow to the subtree at point or widen a narrowed buffer."
  6957. (interactive)
  6958. (if (buffer-narrowed-p)
  6959. (progn (widen) (message "Buffer widen"))
  6960. (org-narrow-to-subtree)
  6961. (message "Buffer narrowed to current subtree")))
  6962. (defun org-narrow-to-block ()
  6963. "Narrow buffer to the current block."
  6964. (interactive)
  6965. (let* ((case-fold-search t)
  6966. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  6967. "^[ \t]*#\\+end_.*")))
  6968. (if blockp
  6969. (narrow-to-region (car blockp) (cdr blockp))
  6970. (user-error "Not in a block"))))
  6971. (defun org-clone-subtree-with-time-shift (n &optional shift)
  6972. "Clone the task (subtree) at point N times.
  6973. The clones will be inserted as siblings.
  6974. In interactive use, the user will be prompted for the number of
  6975. clones to be produced. If the entry has a timestamp, the user
  6976. will also be prompted for a time shift, which may be a repeater
  6977. as used in time stamps, for example `+3d'. To disable this,
  6978. you can call the function with a universal prefix argument.
  6979. When a valid repeater is given and the entry contains any time
  6980. stamps, the clones will become a sequence in time, with time
  6981. stamps in the subtree shifted for each clone produced. If SHIFT
  6982. is nil or the empty string, time stamps will be left alone. The
  6983. ID property of the original subtree is removed.
  6984. In each clone, all the CLOCK entries will be removed. This
  6985. prevents Org from considering that the clocked times overlap.
  6986. If the original subtree did contain time stamps with a repeater,
  6987. the following will happen:
  6988. - the repeater will be removed in each clone
  6989. - an additional clone will be produced, with the current, unshifted
  6990. date(s) in the entry.
  6991. - the original entry will be placed *after* all the clones, with
  6992. repeater intact.
  6993. - the start days in the repeater in the original entry will be shifted
  6994. to past the last clone.
  6995. In this way you can spell out a number of instances of a repeating task,
  6996. and still retain the repeater to cover future instances of the task.
  6997. As described above, N+1 clones are produced when the original
  6998. subtree has a repeater. Setting N to 0, then, can be used to
  6999. remove the repeater from a subtree and create a shifted clone
  7000. with the original repeater."
  7001. (interactive "nNumber of clones to produce: ")
  7002. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7003. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7004. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7005. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7006. (shift
  7007. (or shift
  7008. (if (and (not (equal current-prefix-arg '(4)))
  7009. (save-excursion
  7010. (goto-char beg)
  7011. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7012. (read-from-minibuffer
  7013. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7014. ""))) ;No time shift
  7015. (doshift
  7016. (and (org-string-nw-p shift)
  7017. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7018. shift)
  7019. (user-error "Invalid shift specification %s" shift)))))
  7020. (goto-char end-of-tree)
  7021. (unless (bolp) (insert "\n"))
  7022. (let* ((end (point))
  7023. (template (buffer-substring beg end))
  7024. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7025. (shift-what (pcase (and doshift (match-string 2 shift))
  7026. (`nil nil)
  7027. ("d" 'day)
  7028. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7029. ("m" 'month)
  7030. ("y" 'year)
  7031. (_ (error "Unsupported time unit"))))
  7032. (nmin 1)
  7033. (nmax n)
  7034. (n-no-remove -1)
  7035. (org-id-overriding-file-name (buffer-file-name (buffer-base-buffer)))
  7036. (idprop (org-entry-get beg "ID")))
  7037. (when (and doshift
  7038. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7039. template))
  7040. (delete-region beg end)
  7041. (setq end beg)
  7042. (setq nmin 0)
  7043. (setq nmax (1+ nmax))
  7044. (setq n-no-remove nmax))
  7045. (goto-char end)
  7046. (cl-loop for n from nmin to nmax do
  7047. (insert
  7048. ;; Prepare clone.
  7049. (with-temp-buffer
  7050. (insert template)
  7051. (org-mode)
  7052. (goto-char (point-min))
  7053. (org-show-subtree)
  7054. (and idprop (if org-clone-delete-id
  7055. (org-entry-delete nil "ID")
  7056. (org-id-get-create t)))
  7057. (unless (= n 0)
  7058. (while (re-search-forward org-clock-line-re nil t)
  7059. (delete-region (line-beginning-position)
  7060. (line-beginning-position 2)))
  7061. (goto-char (point-min))
  7062. (while (re-search-forward org-drawer-regexp nil t)
  7063. (org-remove-empty-drawer-at (point))))
  7064. (goto-char (point-min))
  7065. (when doshift
  7066. (while (re-search-forward org-ts-regexp-both nil t)
  7067. (org-timestamp-change (* n shift-n) shift-what))
  7068. (unless (= n n-no-remove)
  7069. (goto-char (point-min))
  7070. (while (re-search-forward org-ts-regexp nil t)
  7071. (save-excursion
  7072. (goto-char (match-beginning 0))
  7073. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7074. (delete-region (match-beginning 1) (match-end 1)))))))
  7075. (buffer-string)))))
  7076. (goto-char beg)))
  7077. ;;; Outline path
  7078. (defvar org-outline-path-cache nil
  7079. "Alist between buffer positions and outline paths.
  7080. It value is an alist (POSITION . PATH) where POSITION is the
  7081. buffer position at the beginning of an entry and PATH is a list
  7082. of strings describing the outline path for that entry, in reverse
  7083. order.")
  7084. (defun org--get-outline-path-1 (&optional use-cache)
  7085. "Return outline path to current headline.
  7086. Outline path is a list of strings, in reverse order. When
  7087. optional argument USE-CACHE is non-nil, make use of a cache. See
  7088. `org-get-outline-path' for details.
  7089. Assume buffer is widened and point is on a headline."
  7090. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  7091. (let ((p (point))
  7092. (heading (let ((case-fold-search nil))
  7093. (looking-at org-complex-heading-regexp)
  7094. (if (not (match-end 4)) ""
  7095. ;; Remove statistics cookies.
  7096. (org-trim
  7097. (org-link-display-format
  7098. (replace-regexp-in-string
  7099. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  7100. (match-string-no-properties 4))))))))
  7101. (if (org-up-heading-safe)
  7102. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  7103. (when use-cache
  7104. (push (cons p path) org-outline-path-cache))
  7105. path)
  7106. ;; This is a new root node. Since we assume we are moving
  7107. ;; forward, we can drop previous cache so as to limit number
  7108. ;; of associations there.
  7109. (let ((path (list heading)))
  7110. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  7111. path)))))
  7112. (defun org-get-outline-path (&optional with-self use-cache)
  7113. "Return the outline path to the current entry.
  7114. An outline path is a list of ancestors for current headline, as
  7115. a list of strings. Statistics cookies are removed and links are
  7116. replaced with their description, if any, or their path otherwise.
  7117. When optional argument WITH-SELF is non-nil, the path also
  7118. includes the current headline.
  7119. When optional argument USE-CACHE is non-nil, cache outline paths
  7120. between calls to this function so as to avoid backtracking. This
  7121. argument is useful when planning to find more than one outline
  7122. path in the same document. In that case, there are two
  7123. conditions to satisfy:
  7124. - `org-outline-path-cache' is set to nil before starting the
  7125. process;
  7126. - outline paths are computed by increasing buffer positions."
  7127. (org-with-wide-buffer
  7128. (and (or (and with-self (org-back-to-heading t))
  7129. (org-up-heading-safe))
  7130. (reverse (org--get-outline-path-1 use-cache)))))
  7131. (defun org-format-outline-path (path &optional width prefix separator)
  7132. "Format the outline path PATH for display.
  7133. WIDTH is the maximum number of characters that is available.
  7134. PREFIX is a prefix to be included in the returned string,
  7135. such as the file name.
  7136. SEPARATOR is inserted between the different parts of the path,
  7137. the default is \"/\"."
  7138. (setq width (or width 79))
  7139. (setq path (delq nil path))
  7140. (unless (> width 0)
  7141. (user-error "Argument `width' must be positive"))
  7142. (setq separator (or separator "/"))
  7143. (let* ((org-odd-levels-only nil)
  7144. (fpath (concat
  7145. prefix (and prefix path separator)
  7146. (mapconcat
  7147. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  7148. (cl-loop for head in path
  7149. for n from 0
  7150. collect (org-add-props
  7151. head nil 'face
  7152. (nth (% n org-n-level-faces) org-level-faces)))
  7153. separator))))
  7154. (when (> (length fpath) width)
  7155. (if (< width 7)
  7156. ;; It's unlikely that `width' will be this small, but don't
  7157. ;; waste characters by adding ".." if it is.
  7158. (setq fpath (substring fpath 0 width))
  7159. (setf (substring fpath (- width 2)) "..")))
  7160. fpath))
  7161. (defun org-display-outline-path (&optional file current separator just-return-string)
  7162. "Display the current outline path in the echo area.
  7163. If FILE is non-nil, prepend the output with the file name.
  7164. If CURRENT is non-nil, append the current heading to the output.
  7165. SEPARATOR is passed through to `org-format-outline-path'. It separates
  7166. the different parts of the path and defaults to \"/\".
  7167. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  7168. (interactive "P")
  7169. (let* (case-fold-search
  7170. (bfn (buffer-file-name (buffer-base-buffer)))
  7171. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  7172. res)
  7173. (when current (setq path (append path
  7174. (save-excursion
  7175. (org-back-to-heading t)
  7176. (when (looking-at org-complex-heading-regexp)
  7177. (list (match-string 4)))))))
  7178. (setq res
  7179. (org-format-outline-path
  7180. path
  7181. (1- (frame-width))
  7182. (and file bfn (concat (file-name-nondirectory bfn) separator))
  7183. separator))
  7184. (add-face-text-property 0 (length res)
  7185. `(:height ,(face-attribute 'default :height))
  7186. nil res)
  7187. (if just-return-string
  7188. res
  7189. (org-unlogged-message "%s" res))))
  7190. ;;; Outline Sorting
  7191. (defun org-sort (&optional with-case)
  7192. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7193. Optional argument WITH-CASE means sort case-sensitively."
  7194. (interactive "P")
  7195. (org-call-with-arg
  7196. (cond ((org-at-table-p) #'org-table-sort-lines)
  7197. ((org-at-item-p) #'org-sort-list)
  7198. (t #'org-sort-entries))
  7199. with-case))
  7200. (defun org-sort-remove-invisible (s)
  7201. "Remove invisible part of links and emphasis markers from string S."
  7202. (remove-text-properties 0 (length s) org-rm-props s)
  7203. (replace-regexp-in-string
  7204. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7205. (replace-regexp-in-string
  7206. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7207. (org-link-display-format s)
  7208. t t) t t))
  7209. (defvar org-after-sorting-entries-or-items-hook nil
  7210. "Hook that is run after a bunch of entries or items have been sorted.
  7211. When children are sorted, the cursor is in the parent line when this
  7212. hook gets called. When a region or a plain list is sorted, the cursor
  7213. will be in the first entry of the sorted region/list.")
  7214. (defun org-sort-entries
  7215. (&optional with-case sorting-type getkey-func compare-func property
  7216. interactive?)
  7217. "Sort entries on a certain level of an outline tree.
  7218. If there is an active region, the entries in the region are sorted.
  7219. Else, if the cursor is before the first entry, sort the top-level items.
  7220. Else, the children of the entry at point are sorted.
  7221. Sorting can be alphabetically, numerically, by date/time as given by
  7222. a time stamp, by a property, by priority order, or by a custom function.
  7223. The command prompts for the sorting type unless it has been given to the
  7224. function through the SORTING-TYPE argument, which needs to be a character,
  7225. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7226. the precise meaning of each character:
  7227. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7228. c By creation time, which is assumed to be the first inactive time stamp
  7229. at the beginning of a line.
  7230. d By deadline date/time.
  7231. k By clocking time.
  7232. n Numerically, by converting the beginning of the entry/item to a number.
  7233. o By order of TODO keywords.
  7234. p By priority according to the cookie.
  7235. r By the value of a property.
  7236. s By scheduled date/time.
  7237. t By date/time, either the first active time stamp in the entry, or, if
  7238. none exist, by the first inactive one.
  7239. Capital letters will reverse the sort order.
  7240. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7241. called with point at the beginning of the record. It must return a
  7242. value that is compatible with COMPARE-FUNC, the function used to
  7243. compare entries.
  7244. Comparing entries ignores case by default. However, with an optional argument
  7245. WITH-CASE, the sorting considers case as well.
  7246. Sorting is done against the visible part of the headlines, it ignores hidden
  7247. links.
  7248. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7249. A non-nil value for INTERACTIVE? is used to signal that this
  7250. function is being called interactively."
  7251. (interactive (list current-prefix-arg nil nil nil nil t))
  7252. (let ((case-func (if with-case 'identity 'downcase))
  7253. start beg end stars re re2
  7254. txt what tmp)
  7255. ;; Find beginning and end of region to sort
  7256. (cond
  7257. ((org-region-active-p)
  7258. ;; we will sort the region
  7259. (setq end (region-end)
  7260. what "region")
  7261. (goto-char (region-beginning))
  7262. (unless (org-at-heading-p) (outline-next-heading))
  7263. (setq start (point)))
  7264. ((or (org-at-heading-p)
  7265. (ignore-errors (progn (org-back-to-heading) t)))
  7266. ;; we will sort the children of the current headline
  7267. (org-back-to-heading)
  7268. (setq start (point)
  7269. end (progn (org-end-of-subtree t t)
  7270. (or (bolp) (insert "\n"))
  7271. (when (>= (org-back-over-empty-lines) 1)
  7272. (forward-line 1))
  7273. (point))
  7274. what "children")
  7275. (goto-char start)
  7276. (outline-show-subtree)
  7277. (outline-next-heading))
  7278. (t
  7279. ;; we will sort the top-level entries in this file
  7280. (goto-char (point-min))
  7281. (or (org-at-heading-p) (outline-next-heading))
  7282. (setq start (point))
  7283. (goto-char (point-max))
  7284. (beginning-of-line 1)
  7285. (when (looking-at ".*?\\S-")
  7286. ;; File ends in a non-white line
  7287. (end-of-line 1)
  7288. (insert "\n"))
  7289. (setq end (point-max))
  7290. (setq what "top-level")
  7291. (goto-char start)
  7292. (org-show-all '(headings drawers blocks))))
  7293. (setq beg (point))
  7294. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7295. (looking-at "\\(\\*+\\)")
  7296. (setq stars (match-string 1)
  7297. re (concat "^" (regexp-quote stars) " +")
  7298. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7299. txt (buffer-substring beg end))
  7300. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7301. (when (and (not (equal stars "*")) (string-match re2 txt))
  7302. (user-error "Region to sort contains a level above the first entry"))
  7303. (unless sorting-type
  7304. (message
  7305. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7306. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7307. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7308. what)
  7309. (setq sorting-type (read-char-exclusive)))
  7310. (unless getkey-func
  7311. (and (= (downcase sorting-type) ?f)
  7312. (setq getkey-func
  7313. (or (and interactive?
  7314. (org-read-function
  7315. "Function for extracting keys: "))
  7316. (error "Missing key extractor")))))
  7317. (and (= (downcase sorting-type) ?r)
  7318. (not property)
  7319. (setq property
  7320. (completing-read "Property: "
  7321. (mapcar #'list (org-buffer-property-keys t))
  7322. nil t)))
  7323. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7324. (message "Sorting entries...")
  7325. (save-restriction
  7326. (narrow-to-region start end)
  7327. (let ((restore-clock?
  7328. ;; The clock marker is lost when using `sort-subr'; mark
  7329. ;; the clock with temporary `:org-clock-marker-backup'
  7330. ;; text property.
  7331. (when (and (eq (org-clock-is-active) (current-buffer))
  7332. (<= start (marker-position org-clock-marker))
  7333. (>= end (marker-position org-clock-marker)))
  7334. (with-silent-modifications
  7335. (put-text-property (1- org-clock-marker) org-clock-marker
  7336. :org-clock-marker-backup t))
  7337. t))
  7338. (dcst (downcase sorting-type))
  7339. (case-fold-search nil)
  7340. (now (current-time)))
  7341. (org-preserve-local-variables
  7342. (sort-subr
  7343. (/= dcst sorting-type)
  7344. ;; This function moves to the beginning character of the
  7345. ;; "record" to be sorted.
  7346. (lambda nil
  7347. (if (re-search-forward re nil t)
  7348. (goto-char (match-beginning 0))
  7349. (goto-char (point-max))))
  7350. ;; This function moves to the last character of the "record" being
  7351. ;; sorted.
  7352. (lambda nil
  7353. (save-match-data
  7354. (condition-case nil
  7355. (outline-forward-same-level 1)
  7356. (error
  7357. (goto-char (point-max))))))
  7358. ;; This function returns the value that gets sorted against.
  7359. (lambda ()
  7360. (cond
  7361. ((= dcst ?n)
  7362. (string-to-number
  7363. (org-sort-remove-invisible (org-get-heading t t t t))))
  7364. ((= dcst ?a)
  7365. (funcall case-func
  7366. (org-sort-remove-invisible (org-get-heading t t t t))))
  7367. ((= dcst ?k)
  7368. (or (get-text-property (point) :org-clock-minutes) 0))
  7369. ((= dcst ?t)
  7370. (let ((end (save-excursion (outline-next-heading) (point))))
  7371. (if (or (re-search-forward org-ts-regexp end t)
  7372. (re-search-forward org-ts-regexp-both end t))
  7373. (org-time-string-to-seconds (match-string 0))
  7374. (float-time now))))
  7375. ((= dcst ?c)
  7376. (let ((end (save-excursion (outline-next-heading) (point))))
  7377. (if (re-search-forward
  7378. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7379. end t)
  7380. (org-time-string-to-seconds (match-string 0))
  7381. (float-time now))))
  7382. ((= dcst ?s)
  7383. (let ((end (save-excursion (outline-next-heading) (point))))
  7384. (if (re-search-forward org-scheduled-time-regexp end t)
  7385. (org-time-string-to-seconds (match-string 1))
  7386. (float-time now))))
  7387. ((= dcst ?d)
  7388. (let ((end (save-excursion (outline-next-heading) (point))))
  7389. (if (re-search-forward org-deadline-time-regexp end t)
  7390. (org-time-string-to-seconds (match-string 1))
  7391. (float-time now))))
  7392. ((= dcst ?p)
  7393. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7394. (string-to-char (match-string 2))
  7395. org-priority-default))
  7396. ((= dcst ?r)
  7397. (or (org-entry-get nil property) ""))
  7398. ((= dcst ?o)
  7399. (when (looking-at org-complex-heading-regexp)
  7400. (let* ((m (match-string 2))
  7401. (s (if (member m org-done-keywords) '- '+)))
  7402. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7403. ((= dcst ?f)
  7404. (if getkey-func
  7405. (progn
  7406. (setq tmp (funcall getkey-func))
  7407. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7408. tmp)
  7409. (error "Invalid key function `%s'" getkey-func)))
  7410. (t (error "Invalid sorting type `%c'" sorting-type))))
  7411. nil
  7412. (cond
  7413. ((= dcst ?a) 'org-string-collate-lessp)
  7414. ((= dcst ?f)
  7415. (or compare-func
  7416. (and interactive?
  7417. (org-read-function
  7418. (concat "Function for comparing keys "
  7419. "(empty for default `sort-subr' predicate): ")
  7420. 'allow-empty))))
  7421. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7422. (org-cycle-hide-drawers 'all)
  7423. (when restore-clock?
  7424. (move-marker org-clock-marker
  7425. (1+ (next-single-property-change
  7426. start :org-clock-marker-backup)))
  7427. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7428. '(:org-clock-marker-backup t)))))
  7429. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7430. (message "Sorting entries...done")))
  7431. (defun org-contextualize-keys (alist contexts)
  7432. "Return valid elements in ALIST depending on CONTEXTS.
  7433. `org-agenda-custom-commands' or `org-capture-templates' are the
  7434. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7435. or `org-capture-templates-contexts' are the associated contexts
  7436. definitions."
  7437. (let ((contexts
  7438. ;; normalize contexts
  7439. (mapcar
  7440. (lambda(c) (cond ((listp (cadr c))
  7441. (list (car c) (car c) (nth 1 c)))
  7442. ((string= "" (cadr c))
  7443. (list (car c) (car c) (nth 2 c)))
  7444. (t c)))
  7445. contexts))
  7446. (a alist) r s)
  7447. ;; loop over all commands or templates
  7448. (dolist (c a)
  7449. (let (vrules repl)
  7450. (cond
  7451. ((not (assoc (car c) contexts))
  7452. (push c r))
  7453. ((and (assoc (car c) contexts)
  7454. (setq vrules (org-contextualize-validate-key
  7455. (car c) contexts)))
  7456. (mapc (lambda (vr)
  7457. (unless (equal (car vr) (cadr vr))
  7458. (setq repl vr)))
  7459. vrules)
  7460. (if (not repl) (push c r)
  7461. (push (cadr repl) s)
  7462. (push
  7463. (cons (car c)
  7464. (cdr (or (assoc (cadr repl) alist)
  7465. (error "Undefined key `%s' as contextual replacement for `%s'"
  7466. (cadr repl) (car c)))))
  7467. r))))))
  7468. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7469. (delq
  7470. nil
  7471. (delete-dups
  7472. (mapcar (lambda (x)
  7473. (let ((tpl (car x)))
  7474. (unless (delq
  7475. nil
  7476. (mapcar (lambda (y)
  7477. (equal y tpl))
  7478. s))
  7479. x)))
  7480. (reverse r))))))
  7481. (defun org-contextualize-validate-key (key contexts)
  7482. "Check CONTEXTS for agenda or capture KEY."
  7483. (let (res)
  7484. (dolist (r contexts)
  7485. (dolist (rr (car (last r)))
  7486. (when
  7487. (and (equal key (car r))
  7488. (if (functionp rr) (funcall rr)
  7489. (or (and (eq (car rr) 'in-file)
  7490. (buffer-file-name)
  7491. (string-match (cdr rr) (buffer-file-name)))
  7492. (and (eq (car rr) 'in-mode)
  7493. (string-match (cdr rr) (symbol-name major-mode)))
  7494. (and (eq (car rr) 'in-buffer)
  7495. (string-match (cdr rr) (buffer-name)))
  7496. (when (and (eq (car rr) 'not-in-file)
  7497. (buffer-file-name))
  7498. (not (string-match (cdr rr) (buffer-file-name))))
  7499. (when (eq (car rr) 'not-in-mode)
  7500. (not (string-match (cdr rr) (symbol-name major-mode))))
  7501. (when (eq (car rr) 'not-in-buffer)
  7502. (not (string-match (cdr rr) (buffer-name)))))))
  7503. (push r res))))
  7504. (delete-dups (delq nil res))))
  7505. ;; Defined to provide a value for defcustom, since there is no
  7506. ;; string-collate-greaterp in Emacs.
  7507. (defun org-string-collate-greaterp (s1 s2)
  7508. "Return non-nil if S1 is greater than S2 in collation order."
  7509. (not (org-string-collate-lessp s1 s2)))
  7510. ;;;###autoload
  7511. (defun org-run-like-in-org-mode (cmd)
  7512. "Run a command, pretending that the current buffer is in Org mode.
  7513. This will temporarily bind local variables that are typically bound in
  7514. Org mode to the values they have in Org mode, and then interactively
  7515. call CMD."
  7516. (org-load-modules-maybe)
  7517. (let (binds)
  7518. (dolist (var (org-get-local-variables))
  7519. (when (or (not (boundp (car var)))
  7520. (eq (symbol-value (car var))
  7521. (default-value (car var))))
  7522. (push (list (car var) `(quote ,(cadr var))) binds)))
  7523. (eval `(let ,binds
  7524. (call-interactively (quote ,cmd))))))
  7525. (defun org-get-category (&optional pos force-refresh)
  7526. "Get the category applying to position POS."
  7527. (save-match-data
  7528. (when force-refresh (org-refresh-category-properties))
  7529. (let ((pos (or pos (point))))
  7530. (or (get-text-property pos 'org-category)
  7531. (progn (org-refresh-category-properties)
  7532. (get-text-property pos 'org-category))))))
  7533. ;;; Refresh properties
  7534. (defun org-refresh-properties (dprop tprop)
  7535. "Refresh buffer text properties.
  7536. DPROP is the drawer property and TPROP is either the
  7537. corresponding text property to set, or an alist with each element
  7538. being a text property (as a symbol) and a function to apply to
  7539. the value of the drawer property."
  7540. (let* ((case-fold-search t)
  7541. (inhibit-read-only t)
  7542. (inherit? (org-property-inherit-p dprop))
  7543. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7544. (global-or-keyword (and inherit?
  7545. (org--property-global-or-keyword-value dprop nil))))
  7546. (with-silent-modifications
  7547. (org-with-point-at 1
  7548. ;; Set global and keyword based values to the whole buffer.
  7549. (when global-or-keyword
  7550. (put-text-property (point-min) (point-max) tprop global-or-keyword))
  7551. ;; Set values based on property-drawers throughout the document.
  7552. (while (re-search-forward property-re nil t)
  7553. (when (org-at-property-p)
  7554. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7555. (outline-next-heading))))))
  7556. (defun org-refresh-property (tprop p &optional inherit)
  7557. "Refresh the buffer text property TPROP from the drawer property P.
  7558. The refresh happens only for the current entry, or the whole
  7559. sub-tree if optional argument INHERIT is non-nil.
  7560. If point is before first headline, the function applies to the
  7561. part before the first headline. In that particular case, when
  7562. optional argument INHERIT is non-nil, it refreshes properties for
  7563. the whole buffer."
  7564. (save-excursion
  7565. (org-back-to-heading-or-point-min t)
  7566. (let ((start (point))
  7567. (end (save-excursion
  7568. (cond ((and inherit (org-before-first-heading-p))
  7569. (point-max))
  7570. (inherit
  7571. (org-end-of-subtree t t))
  7572. ((outline-next-heading))
  7573. ((point-max))))))
  7574. (if (symbolp tprop)
  7575. ;; TPROP is a text property symbol.
  7576. (put-text-property start end tprop p)
  7577. ;; TPROP is an alist with (property . function) elements.
  7578. (pcase-dolist (`(,prop . ,f) tprop)
  7579. (put-text-property start end prop (funcall f p)))))))
  7580. (defun org-refresh-category-properties ()
  7581. "Refresh category text properties in the buffer."
  7582. (let ((case-fold-search t)
  7583. (inhibit-read-only t)
  7584. (default-category
  7585. (cond ((null org-category)
  7586. (if buffer-file-name
  7587. (file-name-sans-extension
  7588. (file-name-nondirectory buffer-file-name))
  7589. "???"))
  7590. ((symbolp org-category) (symbol-name org-category))
  7591. (t org-category))))
  7592. (with-silent-modifications
  7593. (org-with-wide-buffer
  7594. ;; Set buffer-wide property from keyword. Search last #+CATEGORY
  7595. ;; keyword. If none is found, fall-back to `org-category' or
  7596. ;; buffer file name, or set it by the document property drawer.
  7597. (put-text-property
  7598. (point-min) (point-max)
  7599. 'org-category
  7600. (catch 'buffer-category
  7601. (goto-char (point-max))
  7602. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7603. (let ((element (org-element-at-point)))
  7604. (when (eq (org-element-type element) 'keyword)
  7605. (throw 'buffer-category
  7606. (org-element-property :value element)))))
  7607. default-category))
  7608. ;; Set categories from the document property drawer or
  7609. ;; property drawers in the outline. If category is found in
  7610. ;; the property drawer for the whole buffer that value
  7611. ;; overrides the keyword-based value set above.
  7612. (goto-char (point-min))
  7613. (let ((regexp (org-re-property "CATEGORY")))
  7614. (while (re-search-forward regexp nil t)
  7615. (let ((value (match-string-no-properties 3)))
  7616. (when (org-at-property-p)
  7617. (put-text-property
  7618. (save-excursion (org-back-to-heading-or-point-min t))
  7619. (save-excursion (if (org-before-first-heading-p)
  7620. (point-max)
  7621. (org-end-of-subtree t t)))
  7622. 'org-category
  7623. value)))))))))
  7624. (defun org-refresh-stats-properties ()
  7625. "Refresh stats text properties in the buffer."
  7626. (with-silent-modifications
  7627. (org-with-point-at 1
  7628. (let ((regexp (concat org-outline-regexp-bol
  7629. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7630. (while (re-search-forward regexp nil t)
  7631. (let* ((numerator (string-to-number (match-string 1)))
  7632. (denominator (and (match-end 2)
  7633. (string-to-number (match-string 2))))
  7634. (stats (cond ((not denominator) numerator) ;percent
  7635. ((= denominator 0) 0)
  7636. (t (/ (* numerator 100) denominator)))))
  7637. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7638. 'org-stats stats)))))))
  7639. (defun org-refresh-effort-properties ()
  7640. "Refresh effort properties."
  7641. (org-refresh-properties
  7642. org-effort-property
  7643. '((effort . identity)
  7644. (effort-minutes . org-duration-to-minutes))))
  7645. (defun org-find-file-at-mouse (ev)
  7646. "Open file link or URL at mouse."
  7647. (interactive "e")
  7648. (mouse-set-point ev)
  7649. (org-open-at-point 'in-emacs))
  7650. (defun org-open-at-mouse (ev)
  7651. "Open file link or URL at mouse.
  7652. See the docstring of `org-open-file' for details."
  7653. (interactive "e")
  7654. (mouse-set-point ev)
  7655. (when (eq major-mode 'org-agenda-mode)
  7656. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7657. (org-open-at-point))
  7658. (defvar org-window-config-before-follow-link nil
  7659. "The window configuration before following a link.
  7660. This is saved in case the need arises to restore it.")
  7661. (defun org--file-default-apps ()
  7662. "Return the default applications for this operating system."
  7663. (pcase system-type
  7664. (`darwin org-file-apps-macos)
  7665. (`windows-nt org-file-apps-windowsnt)
  7666. (_ org-file-apps-gnu)))
  7667. (defun org--file-apps-entry-dlink-p (entry)
  7668. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7669. It assumes that is the case when the entry uses a regular
  7670. expression which has at least one grouping construct and the
  7671. action is either a Lisp form or a command string containing
  7672. \"%1\", i.e., using at least one subexpression match as
  7673. a parameter."
  7674. (pcase entry
  7675. (`(,selector . ,action)
  7676. (and (stringp selector)
  7677. (> (regexp-opt-depth selector) 0)
  7678. (or (and (stringp action)
  7679. (string-match "%[0-9]" action))
  7680. (consp action))))
  7681. (_ nil)))
  7682. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7683. "Convert extensions to regular expressions in the cars of LIST.
  7684. Also, weed out any non-string entries, because the return value
  7685. is used only for regexp matching.
  7686. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7687. point to the symbol `emacs', indicating that the file should be
  7688. opened in Emacs."
  7689. (append
  7690. (delq nil
  7691. (mapcar (lambda (x)
  7692. (unless (not (stringp (car x)))
  7693. (if (string-match "\\W" (car x))
  7694. x
  7695. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7696. list))
  7697. (when add-auto-mode
  7698. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7699. ;;;###autoload
  7700. (defun org-open-file (path &optional in-emacs line search)
  7701. "Open the file at PATH.
  7702. First, this expands any special file name abbreviations. Then the
  7703. configuration variable `org-file-apps' is checked if it contains an
  7704. entry for this file type, and if yes, the corresponding command is launched.
  7705. If no application is found, Emacs simply visits the file.
  7706. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7707. With a double \\[universal-argument] \\[universal-argument] \
  7708. prefix arg, Org tries to avoid opening in Emacs
  7709. and to use an external application to visit the file.
  7710. Optional LINE specifies a line to go to, optional SEARCH a string
  7711. to search for. If LINE or SEARCH is given, the file will be
  7712. opened in Emacs, unless an entry from `org-file-apps' that makes
  7713. use of groups in a regexp matches.
  7714. If you want to change the way frames are used when following a
  7715. link, please customize `org-link-frame-setup'.
  7716. If the file does not exist, throw an error."
  7717. (let* ((file (if (equal path "") buffer-file-name
  7718. (substitute-in-file-name (expand-file-name path))))
  7719. (file-apps (append org-file-apps (org--file-default-apps)))
  7720. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7721. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7722. file-apps))
  7723. (remp (and (assq 'remote apps) (file-remote-p file)))
  7724. (dirp (unless remp (file-directory-p file)))
  7725. (file (if (and dirp org-open-directory-means-index-dot-org)
  7726. (concat (file-name-as-directory file) "index.org")
  7727. file))
  7728. (a-m-a-p (assq 'auto-mode apps))
  7729. (dfile (downcase file))
  7730. ;; Reconstruct the original link from the PATH, LINE and
  7731. ;; SEARCH args.
  7732. (link (cond (line (concat file "::" (number-to-string line)))
  7733. (search (concat file "::" search))
  7734. (t file)))
  7735. (dlink (downcase link))
  7736. (ext
  7737. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7738. (match-string 1 dfile)))
  7739. (save-position-maybe
  7740. (let ((old-buffer (current-buffer))
  7741. (old-pos (point))
  7742. (old-mode major-mode))
  7743. (lambda ()
  7744. (and (derived-mode-p 'org-mode)
  7745. (eq old-mode 'org-mode)
  7746. (or (not (eq old-buffer (current-buffer)))
  7747. (not (eq old-pos (point))))
  7748. (org-mark-ring-push old-pos old-buffer)))))
  7749. cmd link-match-data)
  7750. (cond
  7751. ((member in-emacs '((16) system))
  7752. (setq cmd (cdr (assq 'system apps))))
  7753. (in-emacs (setq cmd 'emacs))
  7754. (t
  7755. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7756. (and dirp (cdr (assq 'directory apps)))
  7757. ;; First, try matching against apps-dlink if we
  7758. ;; get a match here, store the match data for
  7759. ;; later.
  7760. (let ((match (assoc-default dlink apps-dlink
  7761. 'string-match)))
  7762. (if match
  7763. (progn (setq link-match-data (match-data))
  7764. match)
  7765. (progn (setq in-emacs (or in-emacs line search))
  7766. nil))) ; if we have no match in apps-dlink,
  7767. ; always open the file in emacs if line or search
  7768. ; is given (for backwards compatibility)
  7769. (assoc-default dfile
  7770. (org--file-apps-regexp-alist apps a-m-a-p)
  7771. 'string-match)
  7772. (cdr (assoc ext apps))
  7773. (cdr (assq t apps))))))
  7774. (when (eq cmd 'system)
  7775. (setq cmd (cdr (assq 'system apps))))
  7776. (when (eq cmd 'default)
  7777. (setq cmd (cdr (assoc t apps))))
  7778. (when (eq cmd 'mailcap)
  7779. (require 'mailcap)
  7780. (mailcap-parse-mailcaps)
  7781. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7782. (command (mailcap-mime-info mime-type)))
  7783. (if (stringp command)
  7784. (setq cmd command)
  7785. (setq cmd 'emacs))))
  7786. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7787. (not (file-exists-p file))
  7788. (not org-open-non-existing-files))
  7789. (user-error "No such file: %s" file))
  7790. (cond
  7791. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7792. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7793. (while (string-match "['\"]%s['\"]" cmd)
  7794. (setq cmd (replace-match "%s" t t cmd)))
  7795. (setq cmd (replace-regexp-in-string
  7796. "%s"
  7797. (shell-quote-argument (convert-standard-filename file))
  7798. cmd
  7799. nil t))
  7800. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7801. (save-match-data
  7802. (let ((match-index 1)
  7803. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7804. (set-match-data link-match-data)
  7805. (while (<= match-index number-of-groups)
  7806. (let ((regex (concat "%" (number-to-string match-index)))
  7807. (replace-with (match-string match-index dlink)))
  7808. (while (string-match regex cmd)
  7809. (setq cmd (replace-match replace-with t t cmd))))
  7810. (setq match-index (+ match-index 1)))))
  7811. (save-window-excursion
  7812. (message "Running %s...done" cmd)
  7813. (start-process-shell-command cmd nil cmd)
  7814. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7815. ((or (stringp cmd)
  7816. (eq cmd 'emacs))
  7817. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7818. (widen)
  7819. (cond (line (org-goto-line line)
  7820. (when (derived-mode-p 'org-mode) (org-reveal)))
  7821. (search (condition-case err
  7822. (org-link-search search)
  7823. ;; Save position before error-ing out so user
  7824. ;; can easily move back to the original buffer.
  7825. (error (funcall save-position-maybe)
  7826. (error (nth 1 err)))))))
  7827. ((functionp cmd)
  7828. (save-match-data
  7829. (set-match-data link-match-data)
  7830. (condition-case nil
  7831. (funcall cmd file link)
  7832. ;; FIXME: Remove this check when most default installations
  7833. ;; of Emacs have at least Org 9.0.
  7834. ((debug wrong-number-of-arguments wrong-type-argument
  7835. invalid-function)
  7836. (user-error "Please see Org News for version 9.0 about \
  7837. `org-file-apps'--Lisp error: %S" cmd)))))
  7838. ((consp cmd)
  7839. ;; FIXME: Remove this check when most default installations of
  7840. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7841. ;; fall back to `org-link-frame-setup' for an old usage of
  7842. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7843. (user-error "Please see Org News for version 9.0 about \
  7844. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7845. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7846. (funcall save-position-maybe)))
  7847. ;;;###autoload
  7848. (defun org-open-at-point-global ()
  7849. "Follow a link or a time-stamp like Org mode does.
  7850. Also follow links and emails as seen by `thing-at-point'.
  7851. This command can be called in any mode to follow an external
  7852. link or a time-stamp that has Org mode syntax. Its behavior
  7853. is undefined when called on internal links like fuzzy links.
  7854. Raise a user error when there is nothing to follow."
  7855. (interactive)
  7856. (let ((tap-url (thing-at-point 'url))
  7857. (tap-email (thing-at-point 'email)))
  7858. (cond ((org-in-regexp org-link-any-re)
  7859. (org-link-open-from-string (match-string-no-properties 0)))
  7860. ((or (org-in-regexp org-ts-regexp-both nil t)
  7861. (org-in-regexp org-tsr-regexp-both nil t))
  7862. (org-follow-timestamp-link))
  7863. (tap-url (org-link-open-from-string tap-url))
  7864. (tap-email (org-link-open-from-string
  7865. (concat "mailto:" tap-email)))
  7866. (t (user-error "No link found")))))
  7867. (defvar org-open-at-point-functions nil
  7868. "Hook that is run when following a link at point.
  7869. Functions in this hook must return t if they identify and follow
  7870. a link at point. If they don't find anything interesting at point,
  7871. they must return nil.")
  7872. (defun org-open-at-point (&optional arg)
  7873. "Open link, timestamp, footnote or tags at point.
  7874. When point is on a link, follow it. Normally, files will be
  7875. opened by an appropriate application. If the optional prefix
  7876. argument ARG is non-nil, Emacs will visit the file. With
  7877. a double prefix argument, try to open outside of Emacs, in the
  7878. application the system uses for this file type.
  7879. When point is on a timestamp, open the agenda at the day
  7880. specified.
  7881. When point is a footnote definition, move to the first reference
  7882. found. If it is on a reference, move to the associated
  7883. definition.
  7884. When point is on a headline, display a list of every link in the
  7885. entry, so it is possible to pick one, or all, of them. If point
  7886. is on a tag, call `org-tags-view' instead.
  7887. On top of syntactically correct links, this function also tries
  7888. to open links and time-stamps in comments, node properties, and
  7889. keywords if point is on something looking like a timestamp or
  7890. a link."
  7891. (interactive "P")
  7892. (org-load-modules-maybe)
  7893. (setq org-window-config-before-follow-link (current-window-configuration))
  7894. (org-remove-occur-highlights nil nil t)
  7895. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  7896. (let* ((context
  7897. ;; Only consider supported types, even if they are not the
  7898. ;; closest one.
  7899. (org-element-lineage
  7900. (org-element-context)
  7901. '(clock comment comment-block footnote-definition
  7902. footnote-reference headline inline-src-block inlinetask
  7903. keyword link node-property planning src-block timestamp)
  7904. t))
  7905. (type (org-element-type context))
  7906. (value (org-element-property :value context)))
  7907. (cond
  7908. ((not type) (user-error "No link found"))
  7909. ;; No valid link at point. For convenience, look if something
  7910. ;; looks like a link under point in some specific places.
  7911. ((memq type '(comment comment-block node-property keyword))
  7912. (call-interactively #'org-open-at-point-global))
  7913. ;; On a headline or an inlinetask, but not on a timestamp,
  7914. ;; a link, a footnote reference.
  7915. ((memq type '(headline inlinetask))
  7916. (org-match-line org-complex-heading-regexp)
  7917. (let ((tags-beg (match-beginning 5))
  7918. (tags-end (match-end 5)))
  7919. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  7920. ;; On tags.
  7921. (org-tags-view
  7922. arg
  7923. (save-excursion
  7924. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  7925. (end-tag (search-forward ":" tags-end nil 2)))
  7926. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  7927. ;; Not on tags.
  7928. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  7929. (`(nil . ,_)
  7930. (require 'org-attach)
  7931. (when (org-attach-dir)
  7932. (message "Opening attachment")
  7933. (if (equal arg '(4))
  7934. (org-attach-reveal-in-emacs)
  7935. (org-attach-reveal))))
  7936. (`(,links . ,links-end)
  7937. (dolist (link (if (stringp links) (list links) links))
  7938. (search-forward link nil links-end)
  7939. (goto-char (match-beginning 0))
  7940. (org-open-at-point arg)))))))
  7941. ;; On a footnote reference or at definition's label.
  7942. ((or (eq type 'footnote-reference)
  7943. (and (eq type 'footnote-definition)
  7944. (save-excursion
  7945. ;; Do not validate action when point is on the
  7946. ;; spaces right after the footnote label, in order
  7947. ;; to be on par with behavior on links.
  7948. (skip-chars-forward " \t")
  7949. (let ((begin
  7950. (org-element-property :contents-begin context)))
  7951. (if begin (< (point) begin)
  7952. (= (org-element-property :post-affiliated context)
  7953. (line-beginning-position)))))))
  7954. (org-footnote-action))
  7955. ;; On a planning line. Check if we are really on a timestamp.
  7956. ((and (eq type 'planning)
  7957. (org-in-regexp org-ts-regexp-both nil t))
  7958. (org-follow-timestamp-link))
  7959. ;; On a clock line, make sure point is on the timestamp
  7960. ;; before opening it.
  7961. ((and (eq type 'clock)
  7962. value
  7963. (>= (point) (org-element-property :begin value))
  7964. (<= (point) (org-element-property :end value)))
  7965. (org-follow-timestamp-link))
  7966. ((eq type 'src-block) (org-babel-open-src-block-result))
  7967. ;; Do nothing on white spaces after an object.
  7968. ((>= (point)
  7969. (save-excursion
  7970. (goto-char (org-element-property :end context))
  7971. (skip-chars-backward " \t")
  7972. (point)))
  7973. (user-error "No link found"))
  7974. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  7975. ((eq type 'timestamp) (org-follow-timestamp-link))
  7976. ((eq type 'link) (org-link-open context arg))
  7977. (t (user-error "No link found")))))
  7978. (run-hook-with-args 'org-follow-link-hook))
  7979. ;;;###autoload
  7980. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  7981. "Offer links in the current entry and return the selected link.
  7982. If there is only one link, return it.
  7983. If NTH is an integer, return the NTH link found.
  7984. If ZERO is a string, check also this string for a link, and if
  7985. there is one, return it."
  7986. (with-current-buffer buffer
  7987. (org-with-wide-buffer
  7988. (goto-char marker)
  7989. (let ((cnt ?0)
  7990. have-zero end links link c)
  7991. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  7992. (push (match-string 0 zero) links)
  7993. (setq cnt (1- cnt) have-zero t))
  7994. (save-excursion
  7995. (org-back-to-heading t)
  7996. (setq end (save-excursion (outline-next-heading) (point)))
  7997. (while (re-search-forward org-link-any-re end t)
  7998. (push (match-string 0) links))
  7999. (setq links (org-uniquify (reverse links))))
  8000. (cond
  8001. ((null links)
  8002. (message "No links"))
  8003. ((equal (length links) 1)
  8004. (setq link (car links)))
  8005. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  8006. (setq link (nth (if have-zero nth (1- nth)) links)))
  8007. (t ; we have to select a link
  8008. (save-excursion
  8009. (save-window-excursion
  8010. (delete-other-windows)
  8011. (with-output-to-temp-buffer "*Select Link*"
  8012. (dolist (l links)
  8013. (cond
  8014. ((not (string-match org-link-bracket-re l))
  8015. (princ (format "[%c] %s\n" (cl-incf cnt)
  8016. (org-unbracket-string "<" ">" l))))
  8017. ((match-end 2)
  8018. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  8019. (match-string 2 l) (match-string 1 l))))
  8020. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  8021. (match-string 1 l)))))))
  8022. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  8023. (message "Select link to open, RET to open all:")
  8024. (setq c (read-char-exclusive))
  8025. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  8026. (when (equal c ?q) (user-error "Abort"))
  8027. (if (equal c ?\C-m)
  8028. (setq link links)
  8029. (setq nth (- c ?0))
  8030. (when have-zero (setq nth (1+ nth)))
  8031. (unless (and (integerp nth) (>= (length links) nth))
  8032. (user-error "Invalid link selection"))
  8033. (setq link (nth (1- nth) links)))))
  8034. (cons link end)))))
  8035. ;;; File search
  8036. (defun org-do-occur (regexp &optional cleanup)
  8037. "Call the Emacs command `occur'.
  8038. If CLEANUP is non-nil, remove the printout of the regular expression
  8039. in the *Occur* buffer. This is useful if the regex is long and not useful
  8040. to read."
  8041. (occur regexp)
  8042. (when cleanup
  8043. (let ((cwin (selected-window)) win beg end)
  8044. (when (setq win (get-buffer-window "*Occur*"))
  8045. (select-window win))
  8046. (goto-char (point-min))
  8047. (when (re-search-forward "match[a-z]+" nil t)
  8048. (setq beg (match-end 0))
  8049. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  8050. (setq end (1- (match-beginning 0)))))
  8051. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  8052. (goto-char (point-min))
  8053. (select-window cwin))))
  8054. ;;; The Mark Ring
  8055. (defvar org-mark-ring nil
  8056. "Mark ring for positions before jumps in Org mode.")
  8057. (defvar org-mark-ring-last-goto nil
  8058. "Last position in the mark ring used to go back.")
  8059. ;; Fill and close the ring
  8060. (setq org-mark-ring nil)
  8061. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  8062. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  8063. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  8064. org-mark-ring)
  8065. (defun org-mark-ring-push (&optional pos buffer)
  8066. "Put the current position into the mark ring and rotate it.
  8067. Also push position into the Emacs mark ring. If optional
  8068. argument POS and BUFFER are not nil, mark this location instead."
  8069. (interactive)
  8070. (let ((pos (or pos (point)))
  8071. (buffer (or buffer (current-buffer))))
  8072. (with-current-buffer buffer
  8073. (org-with-point-at pos (push-mark nil t)))
  8074. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  8075. (move-marker (car org-mark-ring) pos buffer))
  8076. (message
  8077. (substitute-command-keys
  8078. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  8079. (defun org-mark-ring-goto (&optional n)
  8080. "Jump to the previous position in the mark ring.
  8081. With prefix arg N, jump back that many stored positions. When
  8082. called several times in succession, walk through the entire ring.
  8083. Org mode commands jumping to a different position in the current file,
  8084. or to another Org file, automatically push the old position onto the ring."
  8085. (interactive "p")
  8086. (let (p m)
  8087. (if (eq last-command this-command)
  8088. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  8089. (setq p org-mark-ring))
  8090. (setq org-mark-ring-last-goto p)
  8091. (setq m (car p))
  8092. (pop-to-buffer-same-window (marker-buffer m))
  8093. (goto-char m)
  8094. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  8095. ;;; Following specific links
  8096. (defvar org-agenda-buffer-tmp-name)
  8097. (defvar org-agenda-start-on-weekday)
  8098. (defun org-follow-timestamp-link ()
  8099. "Open an agenda view for the time-stamp date/range at point."
  8100. (cond
  8101. ((org-at-date-range-p t)
  8102. (let ((org-agenda-start-on-weekday)
  8103. (t1 (match-string 1))
  8104. (t2 (match-string 2)) tt1 tt2)
  8105. (setq tt1 (time-to-days (org-time-string-to-time t1))
  8106. tt2 (time-to-days (org-time-string-to-time t2)))
  8107. (let ((org-agenda-buffer-tmp-name
  8108. (format "*Org Agenda(a:%s)"
  8109. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  8110. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  8111. ((org-at-timestamp-p 'lax)
  8112. (let ((org-agenda-buffer-tmp-name
  8113. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  8114. (org-agenda-list nil (time-to-days (org-time-string-to-time
  8115. (substring (match-string 1) 0 10)))
  8116. 1)))
  8117. (t (error "This should not happen"))))
  8118. ;;; Following file links
  8119. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  8120. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  8121. (declare-function mailcap-mime-info
  8122. "mailcap" (string &optional request no-decode))
  8123. (defvar org-wait nil)
  8124. ;;;; Refiling
  8125. (defun org-get-org-file ()
  8126. "Read a filename, with default directory `org-directory'."
  8127. (let ((default (or org-default-notes-file remember-data-file)))
  8128. (read-file-name (format "File name [%s]: " default)
  8129. (file-name-as-directory org-directory)
  8130. default)))
  8131. (defun org-notes-order-reversed-p ()
  8132. "Check if the current file should receive notes in reversed order."
  8133. (cond
  8134. ((not org-reverse-note-order) nil)
  8135. ((eq t org-reverse-note-order) t)
  8136. ((not (listp org-reverse-note-order)) nil)
  8137. (t (catch 'exit
  8138. (dolist (entry org-reverse-note-order)
  8139. (when (string-match (car entry) buffer-file-name)
  8140. (throw 'exit (cdr entry))))))))
  8141. (defvar org-agenda-new-buffers nil
  8142. "Buffers created to visit agenda files.")
  8143. (declare-function org-string-nw-p "org-macs" (s))
  8144. ;;;; Dynamic blocks
  8145. (defun org-find-dblock (name)
  8146. "Find the first dynamic block with name NAME in the buffer.
  8147. If not found, stay at current position and return nil."
  8148. (let ((case-fold-search t) pos)
  8149. (save-excursion
  8150. (goto-char (point-min))
  8151. (setq pos (and (re-search-forward
  8152. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  8153. (match-beginning 0))))
  8154. (when pos (goto-char pos))
  8155. pos))
  8156. (defun org-create-dblock (plist)
  8157. "Create a dynamic block section, with parameters taken from PLIST.
  8158. PLIST must contain a :name entry which is used as the name of the block."
  8159. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  8160. (end-of-line 1)
  8161. (newline))
  8162. (let ((col (current-column))
  8163. (name (plist-get plist :name)))
  8164. (insert "#+BEGIN: " name)
  8165. (while plist
  8166. (if (eq (car plist) :name)
  8167. (setq plist (cddr plist))
  8168. (insert " " (prin1-to-string (pop plist)))))
  8169. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  8170. (beginning-of-line -2)))
  8171. (defun org-prepare-dblock ()
  8172. "Prepare dynamic block for refresh.
  8173. This empties the block, puts the cursor at the insert position and returns
  8174. the property list including an extra property :name with the block name."
  8175. (unless (looking-at org-dblock-start-re)
  8176. (user-error "Not at a dynamic block"))
  8177. (let* ((begdel (1+ (match-end 0)))
  8178. (name (org-no-properties (match-string 1)))
  8179. (params (append (list :name name)
  8180. (read (concat "(" (match-string 3) ")")))))
  8181. (save-excursion
  8182. (beginning-of-line 1)
  8183. (skip-chars-forward " \t")
  8184. (setq params (plist-put params :indentation-column (current-column))))
  8185. (unless (re-search-forward org-dblock-end-re nil t)
  8186. (error "Dynamic block not terminated"))
  8187. (setq params
  8188. (append params
  8189. (list :content (buffer-substring
  8190. begdel (match-beginning 0)))))
  8191. (delete-region begdel (match-beginning 0))
  8192. (goto-char begdel)
  8193. (open-line 1)
  8194. params))
  8195. (defun org-map-dblocks (&optional command)
  8196. "Apply COMMAND to all dynamic blocks in the current buffer.
  8197. If COMMAND is not given, use `org-update-dblock'."
  8198. (let ((cmd (or command 'org-update-dblock)))
  8199. (save-excursion
  8200. (goto-char (point-min))
  8201. (while (re-search-forward org-dblock-start-re nil t)
  8202. (goto-char (match-beginning 0))
  8203. (save-excursion
  8204. (condition-case nil
  8205. (funcall cmd)
  8206. (error (message "Error during update of dynamic block"))))
  8207. (unless (re-search-forward org-dblock-end-re nil t)
  8208. (error "Dynamic block not terminated"))))))
  8209. (defvar org-dynamic-block-alist nil
  8210. "Alist defining all the Org dynamic blocks.
  8211. The key is the dynamic block type name, as a string. The value
  8212. is the function used to insert the dynamic block.
  8213. Use `org-dynamic-block-define' to populate it.")
  8214. (defun org-dynamic-block-function (type)
  8215. "Return function associated to a given dynamic block type.
  8216. TYPE is the dynamic block type, as a string."
  8217. (cdr (assoc type org-dynamic-block-alist)))
  8218. (defun org-dynamic-block-types ()
  8219. "List all defined dynamic block types."
  8220. (mapcar #'car org-dynamic-block-alist))
  8221. (defun org-dynamic-block-define (type func)
  8222. "Define dynamic block TYPE with FUNC.
  8223. TYPE is a string. FUNC is the function creating the dynamic
  8224. block of such type."
  8225. (pcase (assoc type org-dynamic-block-alist)
  8226. (`nil (push (cons type func) org-dynamic-block-alist))
  8227. (def (setcdr def func))))
  8228. (defun org-dynamic-block-insert-dblock (type &optional interactive-p)
  8229. "Insert a dynamic block of type TYPE.
  8230. When used interactively, select the dynamic block types among
  8231. defined types, per `org-dynamic-block-define'. If INTERACTIVE-P
  8232. is non-nil, call the dynamic block function interactively."
  8233. (interactive (list (completing-read "Dynamic block: "
  8234. (org-dynamic-block-types))
  8235. t))
  8236. (pcase (org-dynamic-block-function type)
  8237. (`nil (error "No such dynamic block: %S" type))
  8238. ((and f (pred functionp))
  8239. (if interactive-p (call-interactively f) (funcall f)))
  8240. (_ (error "Invalid function for dynamic block %S" type))))
  8241. (defun org-dblock-update (&optional arg)
  8242. "User command for updating dynamic blocks.
  8243. Update the dynamic block at point. With prefix ARG, update all dynamic
  8244. blocks in the buffer."
  8245. (interactive "P")
  8246. (if arg
  8247. (org-update-all-dblocks)
  8248. (or (looking-at org-dblock-start-re)
  8249. (org-beginning-of-dblock))
  8250. (org-update-dblock)))
  8251. (defun org-update-dblock ()
  8252. "Update the dynamic block at point.
  8253. This means to empty the block, parse for parameters and then call
  8254. the correct writing function."
  8255. (interactive)
  8256. (save-excursion
  8257. (let* ((win (selected-window))
  8258. (pos (point))
  8259. (line (org-current-line))
  8260. (params (org-prepare-dblock))
  8261. (name (plist-get params :name))
  8262. (indent (plist-get params :indentation-column))
  8263. (cmd (intern (concat "org-dblock-write:" name))))
  8264. (message "Updating dynamic block `%s' at line %d..." name line)
  8265. (funcall cmd params)
  8266. (message "Updating dynamic block `%s' at line %d...done" name line)
  8267. (goto-char pos)
  8268. (when (and indent (> indent 0))
  8269. (setq indent (make-string indent ?\ ))
  8270. (save-excursion
  8271. (select-window win)
  8272. (org-beginning-of-dblock)
  8273. (forward-line 1)
  8274. (while (not (looking-at org-dblock-end-re))
  8275. (insert indent)
  8276. (beginning-of-line 2))
  8277. (when (looking-at org-dblock-end-re)
  8278. (and (looking-at "[ \t]+")
  8279. (replace-match ""))
  8280. (insert indent)))))))
  8281. (defun org-beginning-of-dblock ()
  8282. "Find the beginning of the dynamic block at point.
  8283. Error if there is no such block at point."
  8284. (let ((pos (point))
  8285. beg)
  8286. (end-of-line 1)
  8287. (if (and (re-search-backward org-dblock-start-re nil t)
  8288. (setq beg (match-beginning 0))
  8289. (re-search-forward org-dblock-end-re nil t)
  8290. (> (match-end 0) pos))
  8291. (goto-char beg)
  8292. (goto-char pos)
  8293. (error "Not in a dynamic block"))))
  8294. (defun org-update-all-dblocks ()
  8295. "Update all dynamic blocks in the buffer.
  8296. This function can be used in a hook."
  8297. (interactive)
  8298. (when (derived-mode-p 'org-mode)
  8299. (org-map-dblocks 'org-update-dblock)))
  8300. ;;;; Completion
  8301. (declare-function org-export-backend-options "ox" (cl-x) t)
  8302. (defun org-get-export-keywords ()
  8303. "Return a list of all currently understood export keywords.
  8304. Export keywords include options, block names, attributes and
  8305. keywords relative to each registered export back-end."
  8306. (let (keywords)
  8307. (dolist (backend
  8308. (bound-and-true-p org-export-registered-backends)
  8309. (delq nil keywords))
  8310. ;; Back-end name (for keywords, like #+LATEX:)
  8311. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  8312. (dolist (option-entry (org-export-backend-options backend))
  8313. ;; Back-end options.
  8314. (push (nth 1 option-entry) keywords)))))
  8315. (defconst org-options-keywords
  8316. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  8317. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  8318. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  8319. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  8320. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  8321. (defcustom org-structure-template-alist
  8322. '(("a" . "export ascii")
  8323. ("c" . "center")
  8324. ("C" . "comment")
  8325. ("e" . "example")
  8326. ("E" . "export")
  8327. ("h" . "export html")
  8328. ("l" . "export latex")
  8329. ("q" . "quote")
  8330. ("s" . "src")
  8331. ("v" . "verse"))
  8332. "An alist of keys and block types.
  8333. `org-insert-structure-template' will display a menu with this
  8334. list of templates to choose from. The block type is inserted,
  8335. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  8336. The menu keys are defined by the car of each entry in this alist.
  8337. If two entries have the keys \"a\" and \"aa\" respectively, the
  8338. former will be inserted by typing \"a TAB/RET/SPC\" and the
  8339. latter will be inserted by typing \"aa\". If an entry with the
  8340. key \"aab\" is later added, it can be inserted by typing \"ab\".
  8341. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  8342. block can be inserted by pressing TAB after the string \"<KEY\"."
  8343. :group 'org-edit-structure
  8344. :type '(repeat
  8345. (cons (string :tag "Key")
  8346. (string :tag "Template")))
  8347. :package-version '(Org . "9.2"))
  8348. (defun org--check-org-structure-template-alist (&optional checklist)
  8349. "Check whether `org-structure-template-alist' is set up correctly.
  8350. In particular, check if the Org 9.2 format is used as opposed to
  8351. previous format."
  8352. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  8353. (or (eval checklist)
  8354. org-structure-template-alist))))
  8355. (when elm
  8356. (org-display-warning
  8357. (format "
  8358. Please update the entries of `%s'.
  8359. In Org 9.2 the format was changed from something like
  8360. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  8361. to something like
  8362. (\"s\" . \"src\")
  8363. Please refer to the documentation of `org-structure-template-alist'.
  8364. The following entries must be updated:
  8365. %s"
  8366. (or checklist 'org-structure-template-alist)
  8367. (pp-to-string elm))))))
  8368. (defun org--insert-structure-template-mks ()
  8369. "Present `org-structure-template-alist' with `org-mks'.
  8370. Menus are added if keys require more than one keystroke. Tabs
  8371. are added to single key entries when more than one stroke is
  8372. needed. Keys longer than two characters are reduced to two
  8373. characters."
  8374. (org--check-org-structure-template-alist)
  8375. (let* (case-fold-search
  8376. (templates (append org-structure-template-alist
  8377. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  8378. (keys (mapcar #'car templates))
  8379. (start-letters
  8380. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  8381. ;; Sort each element of `org-structure-template-alist' into
  8382. ;; sublists according to the first letter.
  8383. (superlist
  8384. (mapcar (lambda (letter)
  8385. (list letter
  8386. (cl-remove-if-not
  8387. (apply-partially #'string-match-p (concat "^" letter))
  8388. templates :key #'car)))
  8389. start-letters)))
  8390. (org-mks
  8391. (apply #'append
  8392. ;; Make an `org-mks' table. If only one element is
  8393. ;; present in a sublist, make it part of the top-menu,
  8394. ;; otherwise make a submenu according to the starting
  8395. ;; letter and populate it.
  8396. (mapcar (lambda (sublist)
  8397. (if (eq 1 (length (cadr sublist)))
  8398. (mapcar (lambda (elm)
  8399. (list (substring (car elm) 0 1)
  8400. (cdr elm) ""))
  8401. (cadr sublist))
  8402. ;; Create submenu.
  8403. (let* ((topkey (car sublist))
  8404. (elms (cadr sublist))
  8405. (keys (mapcar #'car elms))
  8406. (long (> (length elms) 3)))
  8407. (append
  8408. (list
  8409. ;; Make a description of the submenu.
  8410. (list topkey
  8411. (concat
  8412. (mapconcat #'cdr
  8413. (cl-subseq elms 0 (if long 3 (length elms)))
  8414. ", ")
  8415. (when long ", ..."))))
  8416. ;; List of entries in submenu.
  8417. (cl-mapcar #'list
  8418. (org--insert-structure-template-unique-keys keys)
  8419. (mapcar #'cdr elms)
  8420. (make-list (length elms) ""))))))
  8421. superlist))
  8422. "Select a key\n============"
  8423. "Key: ")))
  8424. (defun org--insert-structure-template-unique-keys (keys)
  8425. "Make a list of unique, two characters long elements from KEYS.
  8426. Elements of length one have a tab appended. Elements of length
  8427. two are kept as is. Longer elements are truncated to length two.
  8428. If an element cannot be made unique, an error is raised."
  8429. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  8430. menu-keys)
  8431. (dolist (key ordered-keys)
  8432. (let ((potential-key
  8433. (cl-case (length key)
  8434. (1 (concat key "\t"))
  8435. (2 key)
  8436. (otherwise
  8437. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  8438. (mapcar (apply-partially #'concat (substring key 0 1))
  8439. (split-string (substring key 1) "" t)))))))
  8440. (if (or (not potential-key) (assoc potential-key menu-keys))
  8441. (user-error "Could not make unique key for %s." key)
  8442. (push (cons potential-key key) menu-keys))))
  8443. (mapcar #'car
  8444. (cl-sort menu-keys #'<
  8445. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8446. (defun org-insert-structure-template (type)
  8447. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8448. Select a block from `org-structure-template-alist' then type
  8449. either RET, TAB or SPC to write the block type. With an active
  8450. region, wrap the region in the block. Otherwise, insert an empty
  8451. block."
  8452. (interactive
  8453. (list (pcase (org--insert-structure-template-mks)
  8454. (`("\t" . ,_) (read-string "Structure type: "))
  8455. (`(,_ ,choice . ,_) choice))))
  8456. (let* ((region? (use-region-p))
  8457. (region-start (and region? (region-beginning)))
  8458. (region-end (and region? (copy-marker (region-end))))
  8459. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8460. (verbatim? (string-match-p
  8461. (concat "\\`" (regexp-opt '("example" "export" "src")))
  8462. type)))
  8463. (when region? (goto-char region-start))
  8464. (let ((column (current-indentation)))
  8465. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8466. (beginning-of-line)
  8467. (insert "\n"))
  8468. (save-excursion
  8469. (indent-to column)
  8470. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  8471. (when region?
  8472. (when verbatim? (org-escape-code-in-region (point) region-end))
  8473. (goto-char region-end)
  8474. ;; Ignore empty lines at the end of the region.
  8475. (skip-chars-backward " \r\t\n")
  8476. (end-of-line))
  8477. (unless (bolp) (insert "\n"))
  8478. (indent-to column)
  8479. (insert (format "#+end_%s" (car (split-string type))))
  8480. (if (looking-at "[ \t]*$") (replace-match "")
  8481. (insert "\n"))
  8482. (when (and (eobp) (not (bolp))) (insert "\n")))
  8483. (if extended? (end-of-line)
  8484. (forward-line)
  8485. (skip-chars-forward " \t")))))
  8486. ;;;; TODO, DEADLINE, Comments
  8487. (defun org-toggle-comment ()
  8488. "Change the COMMENT state of an entry."
  8489. (interactive)
  8490. (save-excursion
  8491. (org-back-to-heading)
  8492. (let ((case-fold-search nil))
  8493. (looking-at org-complex-heading-regexp))
  8494. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8495. (skip-chars-forward " \t")
  8496. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8497. (if (org-in-commented-heading-p t)
  8498. (delete-region (point)
  8499. (progn (search-forward " " (line-end-position) 'move)
  8500. (skip-chars-forward " \t")
  8501. (point)))
  8502. (insert org-comment-string)
  8503. (unless (eolp) (insert " ")))))
  8504. (defvar org-last-todo-state-is-todo nil
  8505. "This is non-nil when the last TODO state change led to a TODO state.
  8506. If the last change removed the TODO tag or switched to DONE, then
  8507. this is nil.")
  8508. (defvar org-todo-setup-filter-hook nil
  8509. "Hook for functions that pre-filter todo specs.
  8510. Each function takes a todo spec and returns either nil or the spec
  8511. transformed into canonical form." )
  8512. (defvar org-todo-get-default-hook nil
  8513. "Hook for functions that get a default item for todo.
  8514. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  8515. nil or a string to be used for the todo mark." )
  8516. (defvar org-agenda-headline-snapshot-before-repeat)
  8517. (defun org-current-effective-time ()
  8518. "Return current time adjusted for `org-extend-today-until' variable."
  8519. (let* ((ct (org-current-time))
  8520. (dct (decode-time ct))
  8521. (ct1
  8522. (cond
  8523. (org-use-last-clock-out-time-as-effective-time
  8524. (or (org-clock-get-last-clock-out-time) ct))
  8525. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8526. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8527. (t ct))))
  8528. ct1))
  8529. (defun org-todo-yesterday (&optional arg)
  8530. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  8531. (interactive "P")
  8532. (if (eq major-mode 'org-agenda-mode)
  8533. (apply 'org-agenda-todo-yesterday arg)
  8534. (let* ((org-use-effective-time t)
  8535. (hour (nth 2 (decode-time (org-current-time))))
  8536. (org-extend-today-until (1+ hour)))
  8537. (org-todo arg))))
  8538. (defvar org-block-entry-blocking ""
  8539. "First entry preventing the TODO state change.")
  8540. (defun org-cancel-repeater ()
  8541. "Cancel a repeater by setting its numeric value to zero."
  8542. (interactive)
  8543. (save-excursion
  8544. (org-back-to-heading t)
  8545. (let ((bound1 (point))
  8546. (bound0 (save-excursion (outline-next-heading) (point))))
  8547. (when (and (re-search-forward
  8548. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  8549. org-deadline-time-regexp "\\)\\|\\("
  8550. org-ts-regexp "\\)")
  8551. bound0 t)
  8552. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  8553. bound1 t))
  8554. (replace-match "0" t nil nil 1)))))
  8555. (defvar org-state)
  8556. (defvar org-blocked-by-checkboxes)
  8557. (defun org-todo (&optional arg)
  8558. "Change the TODO state of an item.
  8559. The state of an item is given by a keyword at the start of the heading,
  8560. like
  8561. *** TODO Write paper
  8562. *** DONE Call mom
  8563. The different keywords are specified in the variable `org-todo-keywords'.
  8564. By default the available states are \"TODO\" and \"DONE\". So, for this
  8565. example: when the item starts with TODO, it is changed to DONE.
  8566. When it starts with DONE, the DONE is removed. And when neither TODO nor
  8567. DONE are present, add TODO at the beginning of the heading.
  8568. You can set up single-character keys to fast-select the new state. See the
  8569. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  8570. With `\\[universal-argument]' prefix ARG, force logging the state change \
  8571. and take a
  8572. logging note.
  8573. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  8574. next set of TODO \
  8575. keywords (nextset).
  8576. Another way to achieve this is `S-C-<right>'.
  8577. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8578. prefix, circumvent any state blocking.
  8579. With numeric prefix arg, switch to the Nth state.
  8580. With a numeric prefix arg of 0, inhibit note taking for the change.
  8581. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  8582. When called through ELisp, arg is also interpreted in the following way:
  8583. `none' -> empty state
  8584. \"\" -> switch to empty state
  8585. `done' -> switch to DONE
  8586. `nextset' -> switch to the next set of keywords
  8587. `previousset' -> switch to the previous set of keywords
  8588. \"WAITING\" -> switch to the specified keyword, but only if it
  8589. really is a member of `org-todo-keywords'."
  8590. (interactive "P")
  8591. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8592. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8593. 'region-start-level 'region))
  8594. org-loop-over-headlines-in-active-region)
  8595. (org-map-entries
  8596. (lambda () (org-todo arg))
  8597. nil cl
  8598. (when (org-invisible-p) (org-end-of-subtree nil t))))
  8599. (when (equal arg '(16)) (setq arg 'nextset))
  8600. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  8601. (let ((org-blocker-hook org-blocker-hook)
  8602. commentp
  8603. case-fold-search)
  8604. (when (equal arg '(64))
  8605. (setq arg nil org-blocker-hook nil))
  8606. (when (and org-blocker-hook
  8607. (or org-inhibit-blocking
  8608. (org-entry-get nil "NOBLOCKING")))
  8609. (setq org-blocker-hook nil))
  8610. (save-excursion
  8611. (catch 'exit
  8612. (org-back-to-heading t)
  8613. (when (org-in-commented-heading-p t)
  8614. (org-toggle-comment)
  8615. (setq commentp t))
  8616. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  8617. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  8618. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  8619. (let* ((match-data (match-data))
  8620. (startpos (copy-marker (line-beginning-position)))
  8621. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  8622. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  8623. (org-log-done org-log-done)
  8624. (org-log-repeat org-log-repeat)
  8625. (org-todo-log-states org-todo-log-states)
  8626. (org-inhibit-logging
  8627. (if (equal arg 0)
  8628. (progn (setq arg nil) 'note) org-inhibit-logging))
  8629. (this (match-string 1))
  8630. (hl-pos (match-beginning 0))
  8631. (head (org-get-todo-sequence-head this))
  8632. (ass (assoc head org-todo-kwd-alist))
  8633. (interpret (nth 1 ass))
  8634. (done-word (nth 3 ass))
  8635. (final-done-word (nth 4 ass))
  8636. (org-last-state (or this ""))
  8637. (completion-ignore-case t)
  8638. (member (member this org-todo-keywords-1))
  8639. (tail (cdr member))
  8640. (org-state (cond
  8641. ((eq arg 'right)
  8642. ;; Next state
  8643. (if this
  8644. (if tail (car tail) nil)
  8645. (car org-todo-keywords-1)))
  8646. ((eq arg 'left)
  8647. ;; Previous state
  8648. (unless (equal member org-todo-keywords-1)
  8649. (if this
  8650. (nth (- (length org-todo-keywords-1)
  8651. (length tail) 2)
  8652. org-todo-keywords-1)
  8653. (org-last org-todo-keywords-1))))
  8654. (arg
  8655. ;; User or caller requests a specific state.
  8656. (cond
  8657. ((equal arg "") nil)
  8658. ((eq arg 'none) nil)
  8659. ((eq arg 'done) (or done-word (car org-done-keywords)))
  8660. ((eq arg 'nextset)
  8661. (or (car (cdr (member head org-todo-heads)))
  8662. (car org-todo-heads)))
  8663. ((eq arg 'previousset)
  8664. (let ((org-todo-heads (reverse org-todo-heads)))
  8665. (or (car (cdr (member head org-todo-heads)))
  8666. (car org-todo-heads))))
  8667. ((car (member arg org-todo-keywords-1)))
  8668. ((stringp arg)
  8669. (user-error "State `%s' not valid in this file" arg))
  8670. ((nth (1- (prefix-numeric-value arg))
  8671. org-todo-keywords-1))))
  8672. ((and org-todo-key-trigger org-use-fast-todo-selection)
  8673. ;; Use fast selection.
  8674. (org-fast-todo-selection this))
  8675. ((null member) (or head (car org-todo-keywords-1)))
  8676. ((equal this final-done-word) nil) ;-> make empty
  8677. ((null tail) nil) ;-> first entry
  8678. ((memq interpret '(type priority))
  8679. (if (eq this-command last-command)
  8680. (car tail)
  8681. (if (> (length tail) 0)
  8682. (or done-word (car org-done-keywords))
  8683. nil)))
  8684. (t
  8685. (car tail))))
  8686. (org-state (or
  8687. (run-hook-with-args-until-success
  8688. 'org-todo-get-default-hook org-state org-last-state)
  8689. org-state))
  8690. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  8691. (change-plist (list :type 'todo-state-change :from this :to org-state
  8692. :position startpos))
  8693. dolog now-done-p)
  8694. (when org-blocker-hook
  8695. (let (org-blocked-by-checkboxes block-reason)
  8696. (setq org-last-todo-state-is-todo
  8697. (not (member this org-done-keywords)))
  8698. (unless (save-excursion
  8699. (save-match-data
  8700. (org-with-wide-buffer
  8701. (run-hook-with-args-until-failure
  8702. 'org-blocker-hook change-plist))))
  8703. (setq block-reason (if org-blocked-by-checkboxes
  8704. "contained checkboxes"
  8705. (format "\"%s\"" org-block-entry-blocking)))
  8706. (if (called-interactively-p 'interactive)
  8707. (user-error "TODO state change from %s to %s blocked (by %s)"
  8708. this org-state block-reason)
  8709. ;; Fail silently.
  8710. (message "TODO state change from %s to %s blocked (by %s)"
  8711. this org-state block-reason)
  8712. (throw 'exit nil)))))
  8713. (store-match-data match-data)
  8714. (replace-match next t t)
  8715. (cond ((and org-state (equal this org-state))
  8716. (message "TODO state was already %s" (org-trim next)))
  8717. ((not (pos-visible-in-window-p hl-pos))
  8718. (message "TODO state changed to %s" (org-trim next))))
  8719. (unless head
  8720. (setq head (org-get-todo-sequence-head org-state)
  8721. ass (assoc head org-todo-kwd-alist)
  8722. interpret (nth 1 ass)
  8723. done-word (nth 3 ass)
  8724. final-done-word (nth 4 ass)))
  8725. (when (memq arg '(nextset previousset))
  8726. (message "Keyword-Set %d/%d: %s"
  8727. (- (length org-todo-sets) -1
  8728. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  8729. (length org-todo-sets)
  8730. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  8731. (setq org-last-todo-state-is-todo
  8732. (not (member org-state org-done-keywords)))
  8733. (setq now-done-p (and (member org-state org-done-keywords)
  8734. (not (member this org-done-keywords))))
  8735. (and logging (org-local-logging logging))
  8736. (when (or (and (or org-todo-log-states org-log-done)
  8737. (not (eq org-inhibit-logging t))
  8738. (not (memq arg '(nextset previousset))))
  8739. force-log)
  8740. ;; We need to look at recording a time and note.
  8741. (setq dolog (or (if force-log 'note)
  8742. (nth 1 (assoc org-state org-todo-log-states))
  8743. (nth 2 (assoc this org-todo-log-states))))
  8744. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  8745. (setq dolog 'time))
  8746. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  8747. (and org-state
  8748. (member org-state org-not-done-keywords)
  8749. (not (member this org-not-done-keywords))))
  8750. ;; This is now a todo state and was not one before
  8751. ;; If there was a CLOSED time stamp, get rid of it.
  8752. (org-add-planning-info nil nil 'closed))
  8753. (when (and now-done-p org-log-done)
  8754. ;; It is now done, and it was not done before.
  8755. (org-add-planning-info 'closed (org-current-effective-time))
  8756. (when (and (not dolog) (eq 'note org-log-done))
  8757. (org-add-log-setup 'done org-state this 'note)))
  8758. (when (and org-state dolog)
  8759. ;; This is a non-nil state, and we need to log it.
  8760. (org-add-log-setup 'state org-state this dolog)))
  8761. ;; Fixup tag positioning.
  8762. (org-todo-trigger-tag-changes org-state)
  8763. (when org-auto-align-tags (org-align-tags))
  8764. (when org-provide-todo-statistics
  8765. (org-update-parent-todo-statistics))
  8766. (when (bound-and-true-p org-clock-out-when-done)
  8767. (org-clock-out-if-current))
  8768. (run-hooks 'org-after-todo-state-change-hook)
  8769. (when (and arg (not (member org-state org-done-keywords)))
  8770. (setq head (org-get-todo-sequence-head org-state)))
  8771. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  8772. ;; Do we need to trigger a repeat?
  8773. (when now-done-p
  8774. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  8775. ;; This is for the agenda, take a snapshot of the headline.
  8776. (save-match-data
  8777. (setq org-agenda-headline-snapshot-before-repeat
  8778. (org-get-heading))))
  8779. (org-auto-repeat-maybe org-state))
  8780. ;; Fixup cursor location if close to the keyword.
  8781. (when (and (outline-on-heading-p)
  8782. (not (bolp))
  8783. (save-excursion (beginning-of-line 1)
  8784. (looking-at org-todo-line-regexp))
  8785. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  8786. (goto-char (or (match-end 2) (match-end 1)))
  8787. (and (looking-at " ")
  8788. (not (looking-at " *:"))
  8789. (just-one-space)))
  8790. (when org-trigger-hook
  8791. (save-excursion
  8792. (run-hook-with-args 'org-trigger-hook change-plist)))
  8793. (when commentp (org-toggle-comment))))))))
  8794. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  8795. "Block turning an entry into a TODO, using the hierarchy.
  8796. This checks whether the current task should be blocked from state
  8797. changes. Such blocking occurs when:
  8798. 1. The task has children which are not all in a completed state.
  8799. 2. A task has a parent with the property :ORDERED:, and there
  8800. are siblings prior to the current task with incomplete
  8801. status.
  8802. 3. The parent of the task is blocked because it has siblings that should
  8803. be done first, or is child of a block grandparent TODO entry."
  8804. (if (not org-enforce-todo-dependencies)
  8805. t ; if locally turned off don't block
  8806. (catch 'dont-block
  8807. ;; If this is not a todo state change, or if this entry is already DONE,
  8808. ;; do not block
  8809. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8810. (member (plist-get change-plist :from)
  8811. (cons 'done org-done-keywords))
  8812. (member (plist-get change-plist :to)
  8813. (cons 'todo org-not-done-keywords))
  8814. (not (plist-get change-plist :to)))
  8815. (throw 'dont-block t))
  8816. ;; If this task has children, and any are undone, it's blocked
  8817. (save-excursion
  8818. (org-back-to-heading t)
  8819. (let ((this-level (funcall outline-level)))
  8820. (outline-next-heading)
  8821. (let ((child-level (funcall outline-level)))
  8822. (while (and (not (eobp))
  8823. (> child-level this-level))
  8824. ;; this todo has children, check whether they are all
  8825. ;; completed
  8826. (when (and (not (org-entry-is-done-p))
  8827. (org-entry-is-todo-p))
  8828. (setq org-block-entry-blocking (org-get-heading))
  8829. (throw 'dont-block nil))
  8830. (outline-next-heading)
  8831. (setq child-level (funcall outline-level))))))
  8832. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  8833. ;; any previous siblings are undone, it's blocked
  8834. (save-excursion
  8835. (org-back-to-heading t)
  8836. (let* ((pos (point))
  8837. (parent-pos (and (org-up-heading-safe) (point)))
  8838. (case-fold-search nil))
  8839. (unless parent-pos (throw 'dont-block t)) ; no parent
  8840. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8841. (forward-line 1)
  8842. (re-search-forward org-not-done-heading-regexp pos t))
  8843. (setq org-block-entry-blocking (match-string 0))
  8844. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  8845. ;; Search further up the hierarchy, to see if an ancestor is blocked
  8846. (while t
  8847. (goto-char parent-pos)
  8848. (unless (looking-at org-not-done-heading-regexp)
  8849. (throw 'dont-block t)) ; do not block, parent is not a TODO
  8850. (setq pos (point))
  8851. (setq parent-pos (and (org-up-heading-safe) (point)))
  8852. (unless parent-pos (throw 'dont-block t)) ; no parent
  8853. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8854. (forward-line 1)
  8855. (re-search-forward org-not-done-heading-regexp pos t)
  8856. (setq org-block-entry-blocking (org-get-heading)))
  8857. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  8858. (defcustom org-track-ordered-property-with-tag nil
  8859. "Should the ORDERED property also be shown as a tag?
  8860. The ORDERED property decides if an entry should require subtasks to be
  8861. completed in sequence. Since a property is not very visible, setting
  8862. this option means that toggling the ORDERED property with the command
  8863. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  8864. not relevant for the behavior, but it makes things more visible.
  8865. Note that toggling the tag with tags commands will not change the property
  8866. and therefore not influence behavior!
  8867. This can be t, meaning the tag ORDERED should be used. It can also be a
  8868. string to select a different tag for this task."
  8869. :group 'org-todo
  8870. :type '(choice
  8871. (const :tag "No tracking" nil)
  8872. (const :tag "Track with ORDERED tag" t)
  8873. (string :tag "Use other tag")))
  8874. (defun org-toggle-ordered-property ()
  8875. "Toggle the ORDERED property of the current entry.
  8876. For better visibility, you can track the value of this property with a tag.
  8877. See variable `org-track-ordered-property-with-tag'."
  8878. (interactive)
  8879. (let* ((t1 org-track-ordered-property-with-tag)
  8880. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  8881. (save-excursion
  8882. (org-back-to-heading)
  8883. (if (org-entry-get nil "ORDERED")
  8884. (progn
  8885. (org-delete-property "ORDERED")
  8886. (and tag (org-toggle-tag tag 'off))
  8887. (message "Subtasks can be completed in arbitrary order"))
  8888. (org-entry-put nil "ORDERED" "t")
  8889. (and tag (org-toggle-tag tag 'on))
  8890. (message "Subtasks must be completed in sequence")))))
  8891. (defun org-block-todo-from-checkboxes (change-plist)
  8892. "Block turning an entry into a TODO, using checkboxes.
  8893. This checks whether the current task should be blocked from state
  8894. changes because there are unchecked boxes in this entry."
  8895. (if (not org-enforce-todo-checkbox-dependencies)
  8896. t ; if locally turned off don't block
  8897. (catch 'dont-block
  8898. ;; If this is not a todo state change, or if this entry is already DONE,
  8899. ;; do not block
  8900. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8901. (member (plist-get change-plist :from)
  8902. (cons 'done org-done-keywords))
  8903. (member (plist-get change-plist :to)
  8904. (cons 'todo org-not-done-keywords))
  8905. (not (plist-get change-plist :to)))
  8906. (throw 'dont-block t))
  8907. ;; If this task has checkboxes that are not checked, it's blocked
  8908. (save-excursion
  8909. (org-back-to-heading t)
  8910. (let ((beg (point)) end)
  8911. (outline-next-heading)
  8912. (setq end (point))
  8913. (goto-char beg)
  8914. (when (org-list-search-forward
  8915. (concat (org-item-beginning-re)
  8916. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  8917. "\\[[- ]\\]")
  8918. end t)
  8919. (when (boundp 'org-blocked-by-checkboxes)
  8920. (setq org-blocked-by-checkboxes t))
  8921. (throw 'dont-block nil))))
  8922. t))) ; do not block
  8923. (defun org-entry-blocked-p ()
  8924. "Non-nil if entry at point is blocked."
  8925. (and (not (org-entry-get nil "NOBLOCKING"))
  8926. (member (org-entry-get nil "TODO") org-not-done-keywords)
  8927. (not (run-hook-with-args-until-failure
  8928. 'org-blocker-hook
  8929. (list :type 'todo-state-change
  8930. :position (point)
  8931. :from 'todo
  8932. :to 'done)))))
  8933. (defun org-update-statistics-cookies (all)
  8934. "Update the statistics cookie, either from TODO or from checkboxes.
  8935. This should be called with the cursor in a line with a statistics
  8936. cookie. When called with a \\[universal-argument] prefix, update
  8937. all statistics cookies in the buffer."
  8938. (interactive "P")
  8939. (if all
  8940. (progn
  8941. (org-update-checkbox-count 'all)
  8942. (org-map-entries 'org-update-parent-todo-statistics))
  8943. (if (not (org-at-heading-p))
  8944. (org-update-checkbox-count)
  8945. (let ((pos (point-marker))
  8946. end l1 l2)
  8947. (ignore-errors (org-back-to-heading t))
  8948. (if (not (org-at-heading-p))
  8949. (org-update-checkbox-count)
  8950. (setq l1 (org-outline-level))
  8951. (setq end (save-excursion
  8952. (outline-next-heading)
  8953. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  8954. (point)))
  8955. (if (and (save-excursion
  8956. (re-search-forward
  8957. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  8958. (not (save-excursion (re-search-forward
  8959. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  8960. (org-update-checkbox-count)
  8961. (if (and l2 (> l2 l1))
  8962. (progn
  8963. (goto-char end)
  8964. (org-update-parent-todo-statistics))
  8965. (goto-char pos)
  8966. (beginning-of-line 1)
  8967. (while (re-search-forward
  8968. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  8969. (point-at-eol) t)
  8970. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  8971. (goto-char pos)
  8972. (move-marker pos nil)))))
  8973. (defvar org-entry-property-inherited-from) ;; defined below
  8974. (defun org-update-parent-todo-statistics ()
  8975. "Update any statistics cookie in the parent of the current headline.
  8976. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  8977. the entire subtree and this will travel up the hierarchy and update
  8978. statistics everywhere."
  8979. (let* ((prop (save-excursion (org-up-heading-safe)
  8980. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  8981. (recursive (or (not org-hierarchical-todo-statistics)
  8982. (and prop (string-match "\\<recursive\\>" prop))))
  8983. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  8984. 0))
  8985. (first t)
  8986. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  8987. level ltoggle l1 new ndel
  8988. (cnt-all 0) (cnt-done 0) is-percent kwd
  8989. checkbox-beg cookie-present)
  8990. (catch 'exit
  8991. (save-excursion
  8992. (beginning-of-line 1)
  8993. (setq ltoggle (funcall outline-level))
  8994. ;; Three situations are to consider:
  8995. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  8996. ;; to the top-level ancestor on the headline;
  8997. ;; 2. If parent has "recursive" property, repeat up to the
  8998. ;; headline setting that property, taking inheritance into
  8999. ;; account;
  9000. ;; 3. Else, move up to direct parent and proceed only once.
  9001. (while (and (setq level (org-up-heading-safe))
  9002. (or recursive first)
  9003. (>= (point) lim))
  9004. (setq first nil cookie-present nil)
  9005. (unless (and level
  9006. (not (string-match
  9007. "\\<checkbox\\>"
  9008. (downcase (or (org-entry-get nil "COOKIE_DATA")
  9009. "")))))
  9010. (throw 'exit nil))
  9011. (while (re-search-forward box-re (point-at-eol) t)
  9012. (setq cnt-all 0 cnt-done 0 cookie-present t)
  9013. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  9014. (save-match-data
  9015. (unless (outline-next-heading) (throw 'exit nil))
  9016. (while (and (looking-at org-complex-heading-regexp)
  9017. (> (setq l1 (length (match-string 1))) level))
  9018. (setq kwd (and (or recursive (= l1 ltoggle))
  9019. (match-string 2)))
  9020. (if (or (eq org-provide-todo-statistics 'all-headlines)
  9021. (and (eq org-provide-todo-statistics t)
  9022. (or (member kwd org-done-keywords)))
  9023. (and (listp org-provide-todo-statistics)
  9024. (stringp (car org-provide-todo-statistics))
  9025. (or (member kwd org-provide-todo-statistics)
  9026. (member kwd org-done-keywords)))
  9027. (and (listp org-provide-todo-statistics)
  9028. (listp (car org-provide-todo-statistics))
  9029. (or (member kwd (car org-provide-todo-statistics))
  9030. (and (member kwd org-done-keywords)
  9031. (member kwd (cadr org-provide-todo-statistics))))))
  9032. (setq cnt-all (1+ cnt-all))
  9033. (and (eq org-provide-todo-statistics t)
  9034. kwd
  9035. (setq cnt-all (1+ cnt-all))))
  9036. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  9037. (member kwd org-done-keywords))
  9038. (and (listp org-provide-todo-statistics)
  9039. (listp (car org-provide-todo-statistics))
  9040. (member kwd org-done-keywords)
  9041. (member kwd (cadr org-provide-todo-statistics)))
  9042. (and (listp org-provide-todo-statistics)
  9043. (stringp (car org-provide-todo-statistics))
  9044. (member kwd org-done-keywords)))
  9045. (setq cnt-done (1+ cnt-done)))
  9046. (outline-next-heading)))
  9047. (setq new
  9048. (if is-percent
  9049. (format "[%d%%]" (floor (* 100.0 cnt-done)
  9050. (max 1 cnt-all)))
  9051. (format "[%d/%d]" cnt-done cnt-all))
  9052. ndel (- (match-end 0) checkbox-beg))
  9053. (goto-char checkbox-beg)
  9054. (insert new)
  9055. (delete-region (point) (+ (point) ndel))
  9056. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  9057. (when cookie-present
  9058. (run-hook-with-args 'org-after-todo-statistics-hook
  9059. cnt-done (- cnt-all cnt-done))))))
  9060. (run-hooks 'org-todo-statistics-hook)))
  9061. (defvar org-after-todo-statistics-hook nil
  9062. "Hook that is called after a TODO statistics cookie has been updated.
  9063. Each function is called with two arguments: the number of not-done entries
  9064. and the number of done entries.
  9065. For example, the following function, when added to this hook, will switch
  9066. an entry to DONE when all children are done, and back to TODO when new
  9067. entries are set to a TODO status. Note that this hook is only called
  9068. when there is a statistics cookie in the headline!
  9069. (defun org-summary-todo (n-done n-not-done)
  9070. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  9071. (let (org-log-done org-log-states) ; turn off logging
  9072. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))")
  9073. (defvar org-todo-statistics-hook nil
  9074. "Hook that is run whenever Org thinks TODO statistics should be updated.
  9075. This hook runs even if there is no statistics cookie present, in which case
  9076. `org-after-todo-statistics-hook' would not run.")
  9077. (defun org-todo-trigger-tag-changes (state)
  9078. "Apply the changes defined in `org-todo-state-tags-triggers'."
  9079. (let ((l org-todo-state-tags-triggers)
  9080. changes)
  9081. (when (or (not state) (equal state ""))
  9082. (setq changes (append changes (cdr (assoc "" l)))))
  9083. (when (and (stringp state) (> (length state) 0))
  9084. (setq changes (append changes (cdr (assoc state l)))))
  9085. (when (member state org-not-done-keywords)
  9086. (setq changes (append changes (cdr (assq 'todo l)))))
  9087. (when (member state org-done-keywords)
  9088. (setq changes (append changes (cdr (assq 'done l)))))
  9089. (dolist (c changes)
  9090. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  9091. (defun org-local-logging (value)
  9092. "Get logging settings from a property VALUE."
  9093. ;; Directly set the variables, they are already local.
  9094. (setq org-log-done nil
  9095. org-log-repeat nil
  9096. org-todo-log-states nil)
  9097. (dolist (w (split-string value))
  9098. (let (a)
  9099. (cond
  9100. ((setq a (assoc w org-startup-options))
  9101. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  9102. (set (nth 1 a) (nth 2 a))))
  9103. ((setq a (org-extract-log-state-settings w))
  9104. (and (member (car a) org-todo-keywords-1)
  9105. (push a org-todo-log-states)))))))
  9106. (defun org-get-todo-sequence-head (kwd)
  9107. "Return the head of the TODO sequence to which KWD belongs.
  9108. If KWD is not set, check if there is a text property remembering the
  9109. right sequence."
  9110. (let (p)
  9111. (cond
  9112. ((not kwd)
  9113. (or (get-text-property (point-at-bol) 'org-todo-head)
  9114. (progn
  9115. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  9116. nil (point-at-eol)))
  9117. (get-text-property p 'org-todo-head))))
  9118. ((not (member kwd org-todo-keywords-1))
  9119. (car org-todo-keywords-1))
  9120. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  9121. (defun org-fast-todo-selection (&optional current-state)
  9122. "Fast TODO keyword selection with single keys.
  9123. Returns the new TODO keyword, or nil if no state change should occur.
  9124. When CURRENT-STATE is given and selection letters are not unique globally,
  9125. prefer a state in the current sequence over on in another sequence."
  9126. (let* ((fulltable org-todo-key-alist)
  9127. (head (org-get-todo-sequence-head current-state))
  9128. (done-keywords org-done-keywords) ;; needed for the faces.
  9129. (maxlen (apply 'max (mapcar
  9130. (lambda (x)
  9131. (if (stringp (car x)) (string-width (car x)) 0))
  9132. fulltable)))
  9133. (expert (equal org-use-fast-todo-selection 'expert))
  9134. (prompt "")
  9135. (fwidth (+ maxlen 3 1 3))
  9136. (ncol (/ (- (window-width) 4) fwidth))
  9137. tg cnt e c tbl subtable
  9138. groups ingroup in-current-sequence)
  9139. (save-excursion
  9140. (save-window-excursion
  9141. (if expert
  9142. (set-buffer (get-buffer-create " *Org todo*"))
  9143. (delete-other-windows)
  9144. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  9145. (org-switch-to-buffer-other-window " *Org todo*"))
  9146. (erase-buffer)
  9147. (setq-local org-done-keywords done-keywords)
  9148. (setq tbl fulltable cnt 0)
  9149. (while (setq e (pop tbl))
  9150. (cond
  9151. ((equal e '(:startgroup))
  9152. (push '() groups) (setq ingroup t)
  9153. (unless (= cnt 0)
  9154. (setq cnt 0)
  9155. (insert "\n"))
  9156. (setq prompt (concat prompt "{"))
  9157. (insert "{ "))
  9158. ((equal e '(:endgroup))
  9159. (setq ingroup nil cnt 0 in-current-sequence nil)
  9160. (setq prompt (concat prompt "}"))
  9161. (insert "}\n"))
  9162. ((equal e '(:newline))
  9163. (unless (= cnt 0)
  9164. (setq cnt 0)
  9165. (insert "\n")
  9166. (setq e (car tbl))
  9167. (while (equal (car tbl) '(:newline))
  9168. (insert "\n")
  9169. (setq tbl (cdr tbl)))))
  9170. (t
  9171. (setq tg (car e) c (cdr e))
  9172. (if (equal tg head) (setq in-current-sequence t))
  9173. (when ingroup (push tg (car groups)))
  9174. (when in-current-sequence (push e subtable))
  9175. (setq tg (org-add-props tg nil 'face
  9176. (org-get-todo-face tg)))
  9177. (when (and (= cnt 0) (not ingroup)) (insert " "))
  9178. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  9179. (insert "[" c "] " tg (make-string
  9180. (- fwidth 4 (length tg)) ?\ ))
  9181. (when (and (= (setq cnt (1+ cnt)) ncol)
  9182. ;; Avoid lines with just a closing delimiter.
  9183. (not (equal (car tbl) '(:endgroup))))
  9184. (insert "\n")
  9185. (when ingroup (insert " "))
  9186. (setq cnt 0)))))
  9187. (insert "\n")
  9188. (goto-char (point-min))
  9189. (unless expert (org-fit-window-to-buffer))
  9190. (message (concat "[a-z..]:Set [SPC]:clear"
  9191. (if expert (concat "\n" prompt) "")))
  9192. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  9193. (setq subtable (nreverse subtable))
  9194. (cond
  9195. ((or (= c ?\C-g)
  9196. (and (= c ?q) (not (rassoc c fulltable))))
  9197. (setq quit-flag t))
  9198. ((= c ?\ ) nil)
  9199. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  9200. tg (car e))
  9201. tg)
  9202. (t (setq quit-flag t)))))))
  9203. (defun org-entry-is-todo-p ()
  9204. (member (org-get-todo-state) org-not-done-keywords))
  9205. (defun org-entry-is-done-p ()
  9206. (member (org-get-todo-state) org-done-keywords))
  9207. (defun org-get-todo-state ()
  9208. "Return the TODO keyword of the current subtree."
  9209. (save-excursion
  9210. (org-back-to-heading t)
  9211. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9212. (match-end 2)
  9213. (match-string 2))))
  9214. (defun org-at-date-range-p (&optional inactive-ok)
  9215. "Non-nil if point is inside a date range.
  9216. When optional argument INACTIVE-OK is non-nil, also consider
  9217. inactive time ranges.
  9218. When this function returns a non-nil value, match data is set
  9219. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  9220. on INACTIVE-OK."
  9221. (interactive)
  9222. (save-excursion
  9223. (catch 'exit
  9224. (let ((pos (point)))
  9225. (skip-chars-backward "^[<\r\n")
  9226. (skip-chars-backward "<[")
  9227. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9228. (>= (match-end 0) pos)
  9229. (throw 'exit t))
  9230. (skip-chars-backward "^<[\r\n")
  9231. (skip-chars-backward "<[")
  9232. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9233. (>= (match-end 0) pos)
  9234. (throw 'exit t)))
  9235. nil)))
  9236. (defun org-get-repeat (&optional timestamp)
  9237. "Check if there is a time-stamp with repeater in this entry.
  9238. Return the repeater, as a string, or nil. Also return nil when
  9239. this function is called before first heading.
  9240. When optional argument TIMESTAMP is a string, extract the
  9241. repeater from there instead."
  9242. (save-match-data
  9243. (cond (timestamp
  9244. (and (string-match org-repeat-re timestamp)
  9245. (match-string-no-properties 1 timestamp)))
  9246. ((org-before-first-heading-p) nil)
  9247. (t
  9248. (save-excursion
  9249. (org-back-to-heading t)
  9250. (let ((end (org-entry-end-position)))
  9251. (catch :repeat
  9252. (while (re-search-forward org-repeat-re end t)
  9253. (when (save-match-data (org-at-timestamp-p 'agenda))
  9254. (throw :repeat (match-string-no-properties 1)))))))))))
  9255. (defvar org-last-changed-timestamp)
  9256. (defvar org-last-inserted-timestamp)
  9257. (defvar org-log-post-message)
  9258. (defvar org-log-note-purpose)
  9259. (defvar org-log-note-how nil)
  9260. (defvar org-log-note-extra)
  9261. (defun org-auto-repeat-maybe (done-word)
  9262. "Check if the current headline contains a repeated time-stamp.
  9263. If yes, set TODO state back to what it was and change the base date
  9264. of repeating deadline/scheduled time stamps to new date.
  9265. This function is run automatically after each state change to a DONE state."
  9266. (let* ((repeat (org-get-repeat))
  9267. (aa (assoc org-last-state org-todo-kwd-alist))
  9268. (interpret (nth 1 aa))
  9269. (head (nth 2 aa))
  9270. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  9271. (msg "Entry repeats: ")
  9272. (org-log-done nil)
  9273. (org-todo-log-states nil)
  9274. (end (copy-marker (org-entry-end-position))))
  9275. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  9276. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  9277. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  9278. (and (stringp org-todo-repeat-to-state)
  9279. org-todo-repeat-to-state)
  9280. (and org-todo-repeat-to-state org-last-state))))
  9281. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  9282. to-state)
  9283. ((eq interpret 'type) org-last-state)
  9284. (head)
  9285. (t 'none))))
  9286. (org-back-to-heading t)
  9287. (org-add-planning-info nil nil 'closed)
  9288. ;; When `org-log-repeat' is non-nil or entry contains
  9289. ;; a clock, set LAST_REPEAT property.
  9290. (when (or org-log-repeat
  9291. (catch :clock
  9292. (save-excursion
  9293. (while (re-search-forward org-clock-line-re end t)
  9294. (when (org-at-clock-log-p) (throw :clock t))))))
  9295. (org-entry-put nil "LAST_REPEAT" (format-time-string
  9296. (org-time-stamp-format t t))))
  9297. (when org-log-repeat
  9298. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  9299. (memq 'org-add-log-note post-command-hook))
  9300. ;; We are already setup for some record.
  9301. (when (eq org-log-repeat 'note)
  9302. ;; Make sure we take a note, not only a time stamp.
  9303. (setq org-log-note-how 'note))
  9304. ;; Set up for taking a record.
  9305. (org-add-log-setup 'state
  9306. (or done-word (car org-done-keywords))
  9307. org-last-state
  9308. org-log-repeat)))
  9309. ;; Time-stamps without a repeater are usually skipped. However,
  9310. ;; a SCHEDULED time-stamp without one is removed, as they are no
  9311. ;; longer relevant.
  9312. (save-excursion
  9313. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  9314. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  9315. (org-remove-timestamp-with-keyword org-scheduled-string))))
  9316. ;; Update every time-stamp with a repeater in the entry.
  9317. (let ((planning-re (regexp-opt
  9318. (list org-scheduled-string org-deadline-string))))
  9319. (while (re-search-forward org-repeat-re end t)
  9320. (let* ((ts (match-string 0))
  9321. (type (if (not (org-at-planning-p)) "Plain:"
  9322. (save-excursion
  9323. (re-search-backward
  9324. planning-re (line-beginning-position) t)
  9325. (match-string 0)))))
  9326. (when (and (org-at-timestamp-p 'agenda)
  9327. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  9328. (let ((n (string-to-number (match-string 2 ts)))
  9329. (what (match-string 3 ts)))
  9330. (when (equal what "w") (setq n (* n 7) what "d"))
  9331. (when (and (equal what "h")
  9332. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  9333. ts)))
  9334. (user-error
  9335. "Cannot repeat in %d hour(s) because no hour has been set"
  9336. n))
  9337. ;; Preparation, see if we need to modify the start
  9338. ;; date for the change.
  9339. (when (match-end 1)
  9340. (let ((time (save-match-data (org-time-string-to-time ts)))
  9341. (repeater-type (match-string 1 ts)))
  9342. (cond
  9343. ((equal "." repeater-type)
  9344. ;; Shift starting date to today, or now if
  9345. ;; repeater is by hours.
  9346. (if (equal what "h")
  9347. (org-timestamp-change
  9348. (floor (- (org-time-stamp-to-now ts t)) 60) 'minute)
  9349. (org-timestamp-change
  9350. (- (org-today) (time-to-days time)) 'day)))
  9351. ((equal "+" repeater-type)
  9352. (let ((nshiftmax 10)
  9353. (nshift 0))
  9354. (while (or (= nshift 0)
  9355. (not (org-time-less-p nil time)))
  9356. (when (= nshiftmax (cl-incf nshift))
  9357. (or (y-or-n-p
  9358. (format "%d repeater intervals were not \
  9359. enough to shift date past today. Continue? "
  9360. nshift))
  9361. (user-error "Abort")))
  9362. (org-timestamp-change n (cdr (assoc what whata)))
  9363. (org-in-regexp org-ts-regexp3)
  9364. (setq ts (match-string 1))
  9365. (setq time
  9366. (save-match-data
  9367. (org-time-string-to-time ts)))))
  9368. (org-timestamp-change (- n) (cdr (assoc what whata)))
  9369. ;; Rematch, so that we have everything in place
  9370. ;; for the real shift.
  9371. (org-in-regexp org-ts-regexp3)
  9372. (setq ts (match-string 1))
  9373. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  9374. ts)))))
  9375. (save-excursion
  9376. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  9377. (setq msg
  9378. (concat msg type " " org-last-changed-timestamp " ")))))))
  9379. (run-hooks 'org-todo-repeat-hook)
  9380. (setq org-log-post-message msg)
  9381. (message msg))))
  9382. (defun org-show-todo-tree (arg)
  9383. "Make a compact tree which shows all headlines marked with TODO.
  9384. The tree will show the lines where the regexp matches, and all higher
  9385. headlines above the match.
  9386. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  9387. With a numeric prefix N, construct a sparse tree for the Nth element
  9388. of `org-todo-keywords-1'."
  9389. (interactive "P")
  9390. (let ((case-fold-search nil)
  9391. (kwd-re
  9392. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  9393. ((equal arg '(4))
  9394. (let ((kwd
  9395. (completing-read "Keyword (or KWD1|KWD2|...): "
  9396. (mapcar #'list org-todo-keywords-1))))
  9397. (concat "\\("
  9398. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  9399. "\\)\\>")))
  9400. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  9401. (regexp-quote (nth (1- (prefix-numeric-value arg))
  9402. org-todo-keywords-1)))
  9403. (t (user-error "Invalid prefix argument: %s" arg)))))
  9404. (message "%d TODO entries found"
  9405. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  9406. (defun org--deadline-or-schedule (arg type time)
  9407. "Insert DEADLINE or SCHEDULE information in current entry.
  9408. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  9409. `org-schedule' for information about ARG and TIME arguments."
  9410. (let* ((deadline? (eq type 'deadline))
  9411. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9412. (log (if deadline? org-log-redeadline org-log-reschedule))
  9413. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9414. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9415. ;; Save repeater cookie from either TIME or current scheduled
  9416. ;; time stamp. We are going to insert it back at the end of
  9417. ;; the process.
  9418. (repeater (or (and (org-string-nw-p time)
  9419. ;; We use `org-repeat-re' because we need
  9420. ;; to tell the difference between a real
  9421. ;; repeater and a time delta, e.g. "+2d".
  9422. (string-match org-repeat-re time)
  9423. (match-string 1 time))
  9424. (and (org-string-nw-p old-date)
  9425. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9426. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9427. old-date)
  9428. (match-string 1 old-date)))))
  9429. (pcase arg
  9430. (`(4)
  9431. (if (not old-date)
  9432. (message (if deadline? "Entry had no deadline to remove"
  9433. "Entry was not scheduled"))
  9434. (when (and old-date log)
  9435. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9436. nil old-date log))
  9437. (org-remove-timestamp-with-keyword keyword)
  9438. (message (if deadline? "Entry no longer has a deadline."
  9439. "Entry is no longer scheduled."))))
  9440. (`(16)
  9441. (save-excursion
  9442. (org-back-to-heading t)
  9443. (let ((regexp (if deadline? org-deadline-time-regexp
  9444. org-scheduled-time-regexp)))
  9445. (if (not (re-search-forward regexp (line-end-position 2) t))
  9446. (user-error (if deadline? "No deadline information to update"
  9447. "No scheduled information to update"))
  9448. (let* ((rpl0 (match-string 1))
  9449. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9450. (msg (if deadline? "Warn starting from" "Delay until")))
  9451. (replace-match
  9452. (concat keyword
  9453. " <" rpl
  9454. (format " -%dd"
  9455. (abs (- (time-to-days
  9456. (save-match-data
  9457. (org-read-date
  9458. nil t nil msg old-date-time)))
  9459. (time-to-days old-date-time))))
  9460. ">") t t))))))
  9461. (_
  9462. (org-add-planning-info type time 'closed)
  9463. (when (and old-date
  9464. log
  9465. (not (equal old-date org-last-inserted-timestamp)))
  9466. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9467. org-last-inserted-timestamp
  9468. old-date
  9469. log))
  9470. (when repeater
  9471. (save-excursion
  9472. (org-back-to-heading t)
  9473. (when (re-search-forward
  9474. (concat keyword " " org-last-inserted-timestamp)
  9475. (line-end-position 2)
  9476. t)
  9477. (goto-char (1- (match-end 0)))
  9478. (insert " " repeater)
  9479. (setq org-last-inserted-timestamp
  9480. (concat (substring org-last-inserted-timestamp 0 -1)
  9481. " " repeater
  9482. (substring org-last-inserted-timestamp -1))))))
  9483. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9484. org-last-inserted-timestamp)))))
  9485. (defun org-deadline (arg &optional time)
  9486. "Insert a \"DEADLINE:\" string with a timestamp to make a deadline.
  9487. When called interactively, this command pops up the Emacs calendar to let
  9488. the user select a date.
  9489. With one universal prefix argument, remove any deadline from the item.
  9490. With two universal prefix arguments, prompt for a warning delay.
  9491. With argument TIME, set the deadline at the corresponding date. TIME
  9492. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9493. (interactive "P")
  9494. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9495. (org-map-entries
  9496. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9497. nil
  9498. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9499. 'region-start-level
  9500. 'region)
  9501. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9502. (org--deadline-or-schedule arg 'deadline time)))
  9503. (defun org-schedule (arg &optional time)
  9504. "Insert a \"SCHEDULED:\" string with a timestamp to schedule an item.
  9505. When called interactively, this command pops up the Emacs calendar to let
  9506. the user select a date.
  9507. With one universal prefix argument, remove any scheduling date from the item.
  9508. With two universal prefix arguments, prompt for a delay cookie.
  9509. With argument TIME, scheduled at the corresponding date. TIME can
  9510. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9511. (interactive "P")
  9512. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9513. (org-map-entries
  9514. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9515. nil
  9516. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9517. 'region-start-level
  9518. 'region)
  9519. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9520. (org--deadline-or-schedule arg 'scheduled time)))
  9521. (defun org-get-scheduled-time (pom &optional inherit)
  9522. "Get the scheduled time as a time tuple, of a format suitable
  9523. for calling org-schedule with, or if there is no scheduling,
  9524. returns nil."
  9525. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9526. (when time
  9527. (org-time-string-to-time time))))
  9528. (defun org-get-deadline-time (pom &optional inherit)
  9529. "Get the deadline as a time tuple, of a format suitable for
  9530. calling org-deadline with, or if there is no scheduling, returns
  9531. nil."
  9532. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9533. (when time
  9534. (org-time-string-to-time time))))
  9535. (defun org-remove-timestamp-with-keyword (keyword)
  9536. "Remove all time stamps with KEYWORD in the current entry."
  9537. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  9538. beg)
  9539. (save-excursion
  9540. (org-back-to-heading t)
  9541. (setq beg (point))
  9542. (outline-next-heading)
  9543. (while (re-search-backward re beg t)
  9544. (replace-match "")
  9545. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  9546. (equal (char-before) ?\ ))
  9547. (backward-delete-char 1)
  9548. (when (string-match "^[ \t]*$" (buffer-substring
  9549. (point-at-bol) (point-at-eol)))
  9550. (delete-region (point-at-bol)
  9551. (min (point-max) (1+ (point-at-eol))))))))))
  9552. (defvar org-time-was-given) ; dynamically scoped parameter
  9553. (defvar org-end-time-was-given) ; dynamically scoped parameter
  9554. (defun org-at-planning-p ()
  9555. "Non-nil when point is on a planning info line."
  9556. ;; This is as accurate and faster than `org-element-at-point' since
  9557. ;; planning info location is fixed in the section.
  9558. (org-with-wide-buffer
  9559. (beginning-of-line)
  9560. (and (looking-at-p org-planning-line-re)
  9561. (eq (point)
  9562. (ignore-errors
  9563. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  9564. (org-back-to-heading t)
  9565. (org-with-limited-levels (org-back-to-heading t)))
  9566. (line-beginning-position 2))))))
  9567. (defun org-add-planning-info (what &optional time &rest remove)
  9568. "Insert new timestamp with keyword in the planning line.
  9569. WHAT indicates what kind of time stamp to add. It is a symbol
  9570. among `closed', `deadline', `scheduled' and nil. TIME indicates
  9571. the time to use. If none is given, the user is prompted for
  9572. a date. REMOVE indicates what kind of entries to remove. An old
  9573. WHAT entry will also be removed."
  9574. (let (org-time-was-given org-end-time-was-given default-time default-input)
  9575. (when (and (memq what '(scheduled deadline))
  9576. (or (not time)
  9577. (and (stringp time)
  9578. (string-match "^[-+]+[0-9]" time))))
  9579. ;; Try to get a default date/time from existing timestamp
  9580. (save-excursion
  9581. (org-back-to-heading t)
  9582. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  9583. (when (re-search-forward (if (eq what 'scheduled)
  9584. org-scheduled-time-regexp
  9585. org-deadline-time-regexp)
  9586. end t)
  9587. (setq ts (match-string 1)
  9588. default-time (org-time-string-to-time ts)
  9589. default-input (and ts (org-get-compact-tod ts)))))))
  9590. (when what
  9591. (setq time
  9592. (if (stringp time)
  9593. ;; This is a string (relative or absolute), set
  9594. ;; proper date.
  9595. (apply #'encode-time
  9596. (org-read-date-analyze
  9597. time default-time (decode-time default-time)))
  9598. ;; If necessary, get the time from the user
  9599. (or time (org-read-date nil 'to-time nil
  9600. (cl-case what
  9601. (deadline "DEADLINE")
  9602. (scheduled "SCHEDULED")
  9603. (otherwise nil))
  9604. default-time default-input)))))
  9605. (org-with-wide-buffer
  9606. (org-back-to-heading t)
  9607. (let ((planning? (save-excursion
  9608. (forward-line)
  9609. (looking-at-p org-planning-line-re))))
  9610. (cond
  9611. (planning?
  9612. (forward-line)
  9613. ;; Move to current indentation.
  9614. (skip-chars-forward " \t")
  9615. ;; Check if we have to remove something.
  9616. (dolist (type (if what (cons what remove) remove))
  9617. (save-excursion
  9618. (when (re-search-forward
  9619. (cl-case type
  9620. (closed org-closed-time-regexp)
  9621. (deadline org-deadline-time-regexp)
  9622. (scheduled org-scheduled-time-regexp)
  9623. (otherwise (error "Invalid planning type: %s" type)))
  9624. (line-end-position)
  9625. t)
  9626. ;; Delete until next keyword or end of line.
  9627. (delete-region
  9628. (match-beginning 0)
  9629. (if (re-search-forward org-keyword-time-not-clock-regexp
  9630. (line-end-position)
  9631. t)
  9632. (match-beginning 0)
  9633. (line-end-position))))))
  9634. ;; If there is nothing more to add and no more keyword is
  9635. ;; left, remove the line completely.
  9636. (if (and (looking-at-p "[ \t]*$") (not what))
  9637. (delete-region (line-end-position 0)
  9638. (line-end-position))
  9639. ;; If we removed last keyword, do not leave trailing white
  9640. ;; space at the end of line.
  9641. (let ((p (point)))
  9642. (save-excursion
  9643. (end-of-line)
  9644. (unless (= (skip-chars-backward " \t" p) 0)
  9645. (delete-region (point) (line-end-position)))))))
  9646. (what
  9647. (end-of-line)
  9648. (insert "\n")
  9649. (when org-adapt-indentation
  9650. (indent-to-column (1+ (org-outline-level)))))
  9651. (t nil)))
  9652. (when what
  9653. ;; Insert planning keyword.
  9654. (insert (cl-case what
  9655. (closed org-closed-string)
  9656. (deadline org-deadline-string)
  9657. (scheduled org-scheduled-string)
  9658. (otherwise (error "Invalid planning type: %s" what)))
  9659. " ")
  9660. ;; Insert associated timestamp.
  9661. (let ((ts (org-insert-time-stamp
  9662. time
  9663. (or org-time-was-given
  9664. (and (eq what 'closed) org-log-done-with-time))
  9665. (eq what 'closed)
  9666. nil nil (list org-end-time-was-given))))
  9667. (unless (eolp) (insert " "))
  9668. ts)))))
  9669. (defvar org-log-note-marker (make-marker)
  9670. "Marker pointing at the entry where the note is to be inserted.")
  9671. (defvar org-log-note-purpose nil)
  9672. (defvar org-log-note-state nil)
  9673. (defvar org-log-note-previous-state nil)
  9674. (defvar org-log-note-extra nil)
  9675. (defvar org-log-note-window-configuration nil)
  9676. (defvar org-log-note-return-to (make-marker))
  9677. (defvar org-log-note-effective-time nil
  9678. "Remembered current time.
  9679. So that dynamically scoped `org-extend-today-until' affects
  9680. timestamps in state change log.")
  9681. (defvar org-log-post-message nil
  9682. "Message to be displayed after a log note has been stored.
  9683. The auto-repeater uses this.")
  9684. (defun org-add-note ()
  9685. "Add a note to the current entry.
  9686. This is done in the same way as adding a state change note."
  9687. (interactive)
  9688. (org-add-log-setup 'note))
  9689. (defun org-log-beginning (&optional create)
  9690. "Return expected start of log notes in current entry.
  9691. When optional argument CREATE is non-nil, the function creates
  9692. a drawer to store notes, if necessary. Returned position ignores
  9693. narrowing."
  9694. (org-with-wide-buffer
  9695. (let ((drawer (org-log-into-drawer)))
  9696. (cond
  9697. (drawer
  9698. (org-end-of-meta-data)
  9699. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  9700. (end (if (org-at-heading-p) (point)
  9701. (save-excursion (outline-next-heading) (point))))
  9702. (case-fold-search t))
  9703. (catch 'exit
  9704. ;; Try to find existing drawer.
  9705. (while (re-search-forward regexp end t)
  9706. (let ((element (org-element-at-point)))
  9707. (when (eq (org-element-type element) 'drawer)
  9708. (let ((cend (org-element-property :contents-end element)))
  9709. (when (and (not org-log-states-order-reversed) cend)
  9710. (goto-char cend)))
  9711. (throw 'exit nil))))
  9712. ;; No drawer found. Create one, if permitted.
  9713. (when create
  9714. (unless (bolp) (insert "\n"))
  9715. (let ((beg (point)))
  9716. (insert ":" drawer ":\n:END:\n")
  9717. (org-indent-region beg (point))
  9718. (org-flag-region (line-end-position -1) (1- (point)) t 'outline))
  9719. (end-of-line -1)))))
  9720. (t
  9721. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  9722. (skip-chars-forward " \t\n")
  9723. (beginning-of-line)
  9724. (unless org-log-states-order-reversed
  9725. (org-skip-over-state-notes)
  9726. (skip-chars-backward " \t\n")
  9727. (forward-line)))))
  9728. (if (bolp) (point) (line-beginning-position 2))))
  9729. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  9730. "Set up the post command hook to take a note.
  9731. If this is about to TODO state change, the new state is expected in STATE.
  9732. HOW is an indicator what kind of note should be created.
  9733. EXTRA is additional text that will be inserted into the notes buffer."
  9734. (move-marker org-log-note-marker (point))
  9735. (setq org-log-note-purpose purpose
  9736. org-log-note-state state
  9737. org-log-note-previous-state prev-state
  9738. org-log-note-how how
  9739. org-log-note-extra extra
  9740. org-log-note-effective-time (org-current-effective-time))
  9741. (add-hook 'post-command-hook 'org-add-log-note 'append))
  9742. (defun org-skip-over-state-notes ()
  9743. "Skip past the list of State notes in an entry."
  9744. (when (ignore-errors (goto-char (org-in-item-p)))
  9745. (let* ((struct (org-list-struct))
  9746. (prevs (org-list-prevs-alist struct))
  9747. (regexp
  9748. (concat "[ \t]*- +"
  9749. (replace-regexp-in-string
  9750. " +" " +"
  9751. (org-replace-escapes
  9752. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  9753. `(("%d" . ,org-ts-regexp-inactive)
  9754. ("%D" . ,org-ts-regexp)
  9755. ("%s" . "\\(?:\"\\S-+\"\\)?")
  9756. ("%S" . "\\(?:\"\\S-+\"\\)?")
  9757. ("%t" . ,org-ts-regexp-inactive)
  9758. ("%T" . ,org-ts-regexp)
  9759. ("%u" . ".*?")
  9760. ("%U" . ".*?")))))))
  9761. (while (looking-at-p regexp)
  9762. (goto-char (or (org-list-get-next-item (point) struct prevs)
  9763. (org-list-get-item-end (point) struct)))))))
  9764. (defun org-add-log-note (&optional _purpose)
  9765. "Pop up a window for taking a note, and add this note later."
  9766. (remove-hook 'post-command-hook 'org-add-log-note)
  9767. (setq org-log-note-window-configuration (current-window-configuration))
  9768. (delete-other-windows)
  9769. (move-marker org-log-note-return-to (point))
  9770. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  9771. (goto-char org-log-note-marker)
  9772. (org-switch-to-buffer-other-window "*Org Note*")
  9773. (erase-buffer)
  9774. (if (memq org-log-note-how '(time state))
  9775. (org-store-log-note)
  9776. (let ((org-inhibit-startup t)) (org-mode))
  9777. (insert (format "# Insert note for %s.
  9778. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  9779. (cl-case org-log-note-purpose
  9780. (clock-out "stopped clock")
  9781. (done "closed todo item")
  9782. (reschedule "rescheduling")
  9783. (delschedule "no longer scheduled")
  9784. (redeadline "changing deadline")
  9785. (deldeadline "removing deadline")
  9786. (refile "refiling")
  9787. (note "this entry")
  9788. (state
  9789. (format "state change from \"%s\" to \"%s\""
  9790. (or org-log-note-previous-state "")
  9791. (or org-log-note-state "")))
  9792. (t (error "This should not happen")))))
  9793. (when org-log-note-extra (insert org-log-note-extra))
  9794. (setq-local org-finish-function 'org-store-log-note)
  9795. (run-hooks 'org-log-buffer-setup-hook)))
  9796. (defvar org-note-abort nil) ; dynamically scoped
  9797. (defun org-store-log-note ()
  9798. "Finish taking a log note, and insert it to where it belongs."
  9799. (let ((txt (prog1 (buffer-string)
  9800. (kill-buffer)))
  9801. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  9802. lines)
  9803. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  9804. (setq txt (replace-match "" t t txt)))
  9805. (when (string-match "\\s-+\\'" txt)
  9806. (setq txt (replace-match "" t t txt)))
  9807. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  9808. (when (org-string-nw-p note)
  9809. (setq note
  9810. (org-replace-escapes
  9811. note
  9812. (list (cons "%u" (user-login-name))
  9813. (cons "%U" user-full-name)
  9814. (cons "%t" (format-time-string
  9815. (org-time-stamp-format 'long 'inactive)
  9816. org-log-note-effective-time))
  9817. (cons "%T" (format-time-string
  9818. (org-time-stamp-format 'long nil)
  9819. org-log-note-effective-time))
  9820. (cons "%d" (format-time-string
  9821. (org-time-stamp-format nil 'inactive)
  9822. org-log-note-effective-time))
  9823. (cons "%D" (format-time-string
  9824. (org-time-stamp-format nil nil)
  9825. org-log-note-effective-time))
  9826. (cons "%s" (cond
  9827. ((not org-log-note-state) "")
  9828. ((string-match-p org-ts-regexp
  9829. org-log-note-state)
  9830. (format "\"[%s]\""
  9831. (substring org-log-note-state 1 -1)))
  9832. (t (format "\"%s\"" org-log-note-state))))
  9833. (cons "%S"
  9834. (cond
  9835. ((not org-log-note-previous-state) "")
  9836. ((string-match-p org-ts-regexp
  9837. org-log-note-previous-state)
  9838. (format "\"[%s]\""
  9839. (substring
  9840. org-log-note-previous-state 1 -1)))
  9841. (t (format "\"%s\""
  9842. org-log-note-previous-state)))))))
  9843. (when lines (setq note (concat note " \\\\")))
  9844. (push note lines))
  9845. (when (and lines (not org-note-abort))
  9846. (with-current-buffer (marker-buffer org-log-note-marker)
  9847. (org-with-wide-buffer
  9848. ;; Find location for the new note.
  9849. (goto-char org-log-note-marker)
  9850. (set-marker org-log-note-marker nil)
  9851. ;; Note associated to a clock is to be located right after
  9852. ;; the clock. Do not move point.
  9853. (unless (eq org-log-note-purpose 'clock-out)
  9854. (goto-char (org-log-beginning t)))
  9855. ;; Make sure point is at the beginning of an empty line.
  9856. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  9857. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  9858. ;; In an existing list, add a new item at the top level.
  9859. ;; Otherwise, indent line like a regular one.
  9860. (let ((itemp (org-in-item-p)))
  9861. (if itemp
  9862. (indent-line-to
  9863. (let ((struct (save-excursion
  9864. (goto-char itemp) (org-list-struct))))
  9865. (org-list-get-ind (org-list-get-top-point struct) struct)))
  9866. (org-indent-line)))
  9867. (insert (org-list-bullet-string "-") (pop lines))
  9868. (let ((ind (org-list-item-body-column (line-beginning-position))))
  9869. (dolist (line lines)
  9870. (insert "\n")
  9871. (indent-line-to ind)
  9872. (insert line)))
  9873. (message "Note stored")
  9874. (org-back-to-heading t))
  9875. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  9876. ;; from within `org-add-log-note' because `buffer-undo-list'
  9877. ;; is then modified outside of `org-with-remote-undo'.
  9878. (when (eq this-command 'org-agenda-todo)
  9879. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  9880. ;; Don't add undo information when called from `org-agenda-todo'.
  9881. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  9882. (set-window-configuration org-log-note-window-configuration)
  9883. (with-current-buffer (marker-buffer org-log-note-return-to)
  9884. (goto-char org-log-note-return-to))
  9885. (move-marker org-log-note-return-to nil)
  9886. (when org-log-post-message (message "%s" org-log-post-message))))
  9887. (defun org-remove-empty-drawer-at (pos)
  9888. "Remove an empty drawer at position POS.
  9889. POS may also be a marker."
  9890. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  9891. (org-with-wide-buffer
  9892. (goto-char pos)
  9893. (let ((drawer (org-element-at-point)))
  9894. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  9895. (not (org-element-property :contents-begin drawer)))
  9896. (delete-region (org-element-property :begin drawer)
  9897. (progn (goto-char (org-element-property :end drawer))
  9898. (skip-chars-backward " \r\t\n")
  9899. (forward-line)
  9900. (point))))))))
  9901. (defvar org-ts-type nil)
  9902. (defun org-sparse-tree (&optional arg type)
  9903. "Create a sparse tree, prompt for the details.
  9904. This command can create sparse trees. You first need to select the type
  9905. of match used to create the tree:
  9906. t Show all TODO entries.
  9907. T Show entries with a specific TODO keyword.
  9908. m Show entries selected by a tags/property match.
  9909. p Enter a property name and its value (both with completion on existing
  9910. names/values) and show entries with that property.
  9911. r Show entries matching a regular expression (`/' can be used as well).
  9912. b Show deadlines and scheduled items before a date.
  9913. a Show deadlines and scheduled items after a date.
  9914. d Show deadlines due within `org-deadline-warning-days'.
  9915. D Show deadlines and scheduled items between a date range."
  9916. (interactive "P")
  9917. (setq type (or type org-sparse-tree-default-date-type))
  9918. (setq org-ts-type type)
  9919. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  9920. [d]eadlines [b]efore-date [a]fter-date [D]ates range
  9921. [c]ycle through date types: %s"
  9922. (cl-case type
  9923. (all "all timestamps")
  9924. (scheduled "only scheduled")
  9925. (deadline "only deadline")
  9926. (active "only active timestamps")
  9927. (inactive "only inactive timestamps")
  9928. (closed "with a closed time-stamp")
  9929. (otherwise "scheduled/deadline")))
  9930. (let ((answer (read-char-exclusive)))
  9931. (cl-case answer
  9932. (?c
  9933. (org-sparse-tree
  9934. arg
  9935. (cadr
  9936. (memq type '(nil all scheduled deadline active inactive closed)))))
  9937. (?d (call-interactively 'org-check-deadlines))
  9938. (?b (call-interactively 'org-check-before-date))
  9939. (?a (call-interactively 'org-check-after-date))
  9940. (?D (call-interactively 'org-check-dates-range))
  9941. (?t (call-interactively 'org-show-todo-tree))
  9942. (?T (org-show-todo-tree '(4)))
  9943. (?m (call-interactively 'org-match-sparse-tree))
  9944. ((?p ?P)
  9945. (let* ((kwd (completing-read
  9946. "Property: " (mapcar #'list (org-buffer-property-keys))))
  9947. (value (completing-read
  9948. "Value: " (mapcar #'list (org-property-values kwd)))))
  9949. (unless (string-match "\\`{.*}\\'" value)
  9950. (setq value (concat "\"" value "\"")))
  9951. (org-match-sparse-tree arg (concat kwd "=" value))))
  9952. ((?r ?R ?/) (call-interactively 'org-occur))
  9953. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  9954. (defvar-local org-occur-highlights nil
  9955. "List of overlays used for occur matches.")
  9956. (defvar-local org-occur-parameters nil
  9957. "Parameters of the active org-occur calls.
  9958. This is a list, each call to org-occur pushes as cons cell,
  9959. containing the regular expression and the callback, onto the list.
  9960. The list can contain several entries if `org-occur' has been called
  9961. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  9962. will only contain one set of parameters. When the highlights are
  9963. removed (for example with `C-c C-c', or with the next edit (depending
  9964. on `org-remove-highlights-with-change'), this variable is emptied
  9965. as well.")
  9966. (defun org-occur (regexp &optional keep-previous callback)
  9967. "Make a compact tree showing all matches of REGEXP.
  9968. The tree will show the lines where the regexp matches, and any other context
  9969. defined in `org-show-context-detail', which see.
  9970. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  9971. done by a previous call to `org-occur' will be kept, to allow stacking of
  9972. calls to this command.
  9973. Optional argument CALLBACK can be a function of no argument. In this case,
  9974. it is called with point at the end of the match, match data being set
  9975. accordingly. Current match is shown only if the return value is non-nil.
  9976. The function must neither move point nor alter narrowing."
  9977. (interactive "sRegexp: \nP")
  9978. (when (equal regexp "")
  9979. (user-error "Regexp cannot be empty"))
  9980. (unless keep-previous
  9981. (org-remove-occur-highlights nil nil t))
  9982. (push (cons regexp callback) org-occur-parameters)
  9983. (let ((cnt 0))
  9984. (save-excursion
  9985. (goto-char (point-min))
  9986. (when (or (not keep-previous) ; do not want to keep
  9987. (not org-occur-highlights)) ; no previous matches
  9988. ;; hide everything
  9989. (org-overview))
  9990. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  9991. (isearch-no-upper-case-p regexp t)
  9992. org-occur-case-fold-search)))
  9993. (while (re-search-forward regexp nil t)
  9994. (when (or (not callback)
  9995. (save-match-data (funcall callback)))
  9996. (setq cnt (1+ cnt))
  9997. (when org-highlight-sparse-tree-matches
  9998. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  9999. (org-show-context 'occur-tree)))))
  10000. (when org-remove-highlights-with-change
  10001. (add-hook 'before-change-functions 'org-remove-occur-highlights
  10002. nil 'local))
  10003. (unless org-sparse-tree-open-archived-trees
  10004. (org-hide-archived-subtrees (point-min) (point-max)))
  10005. (run-hooks 'org-occur-hook)
  10006. (when (called-interactively-p 'interactive)
  10007. (message "%d match(es) for regexp %s" cnt regexp))
  10008. cnt))
  10009. (defun org-occur-next-match (&optional n _reset)
  10010. "Function for `next-error-function' to find sparse tree matches.
  10011. N is the number of matches to move, when negative move backwards.
  10012. This function always goes back to the starting point when no
  10013. match is found."
  10014. (let* ((limit (if (< n 0) (point-min) (point-max)))
  10015. (search-func (if (< n 0)
  10016. 'previous-single-char-property-change
  10017. 'next-single-char-property-change))
  10018. (n (abs n))
  10019. (pos (point))
  10020. p1)
  10021. (catch 'exit
  10022. (while (setq p1 (funcall search-func (point) 'org-type))
  10023. (when (equal p1 limit)
  10024. (goto-char pos)
  10025. (user-error "No more matches"))
  10026. (when (equal (get-char-property p1 'org-type) 'org-occur)
  10027. (setq n (1- n))
  10028. (when (= n 0)
  10029. (goto-char p1)
  10030. (throw 'exit (point))))
  10031. (goto-char p1))
  10032. (goto-char p1)
  10033. (user-error "No more matches"))))
  10034. (defun org-highlight-new-match (beg end)
  10035. "Highlight from BEG to END and mark the highlight is an occur headline."
  10036. (let ((ov (make-overlay beg end)))
  10037. (overlay-put ov 'face 'secondary-selection)
  10038. (overlay-put ov 'org-type 'org-occur)
  10039. (push ov org-occur-highlights)))
  10040. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  10041. "Remove the occur highlights from the buffer.
  10042. BEG and END are ignored. If NOREMOVE is nil, remove this function
  10043. from the `before-change-functions' in the current buffer."
  10044. (interactive)
  10045. (unless org-inhibit-highlight-removal
  10046. (mapc #'delete-overlay org-occur-highlights)
  10047. (setq org-occur-highlights nil)
  10048. (setq org-occur-parameters nil)
  10049. (unless noremove
  10050. (remove-hook 'before-change-functions
  10051. 'org-remove-occur-highlights 'local))))
  10052. ;;;; Priorities
  10053. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  10054. "Regular expression matching the priority indicator.
  10055. A priority indicator can be e.g. [#A] or [#1].
  10056. This regular expression matches these groups:
  10057. 0 : the whole match, e.g. \"TODO [#A] Hack\"
  10058. 1 : the priority cookie, e.g. \"[#A]\"
  10059. 2 : the value of the priority cookie, e.g. \"A\".")
  10060. (defun org-priority-up ()
  10061. "Increase the priority of the current item."
  10062. (interactive)
  10063. (org-priority 'up))
  10064. (defun org-priority-down ()
  10065. "Decrease the priority of the current item."
  10066. (interactive)
  10067. (org-priority 'down))
  10068. (defun org-priority (&optional action show)
  10069. "Change the priority of an item.
  10070. When called interactively with a `\\[universal-argument]' prefix,
  10071. show the priority in the minibuffer instead of changing it.
  10072. When called programmatically, ACTION can be `set', `up', `down',
  10073. or a character."
  10074. (interactive "P")
  10075. (when show
  10076. ;; Deprecation warning inserted for Org 9.2; once enough time has
  10077. ;; passed the SHOW argument should be removed.
  10078. (warn "`org-priority' called with deprecated SHOW argument"))
  10079. (if (equal action '(4))
  10080. (org-priority-show)
  10081. (unless org-priority-enable-commands
  10082. (user-error "Priority commands are disabled"))
  10083. (setq action (or action 'set))
  10084. (let ((nump (< org-priority-lowest 65))
  10085. current new news have remove)
  10086. (save-excursion
  10087. (org-back-to-heading t)
  10088. (when (looking-at org-priority-regexp)
  10089. (let ((ms (match-string 2)))
  10090. (setq current (org-priority-to-value ms)
  10091. have t)))
  10092. (cond
  10093. ((eq action 'remove)
  10094. (setq remove t new ?\ ))
  10095. ((or (eq action 'set)
  10096. (integerp action))
  10097. (if (not (eq action 'set))
  10098. (setq new action)
  10099. (setq
  10100. new
  10101. (if nump
  10102. (string-to-number
  10103. (read-string (format "Priority %s-%s, SPC to remove: "
  10104. (number-to-string org-priority-highest)
  10105. (number-to-string org-priority-lowest))))
  10106. (progn (message "Priority %c-%c, SPC to remove: "
  10107. org-priority-highest org-priority-lowest)
  10108. (save-match-data
  10109. (setq new (read-char-exclusive)))))))
  10110. (when (and (= (upcase org-priority-highest) org-priority-highest)
  10111. (= (upcase org-priority-lowest) org-priority-lowest))
  10112. (setq new (upcase new)))
  10113. (cond ((equal new ?\s) (setq remove t))
  10114. ((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  10115. (user-error
  10116. (if nump
  10117. "Priority must be between `%s' and `%s'"
  10118. "Priority must be between `%c' and `%c'")
  10119. org-priority-highest org-priority-lowest))))
  10120. ((eq action 'up)
  10121. (setq new (if have
  10122. (1- current) ; normal cycling
  10123. ;; last priority was empty
  10124. (if (eq last-command this-command)
  10125. org-priority-lowest ; wrap around empty to lowest
  10126. ;; default
  10127. (if org-priority-start-cycle-with-default
  10128. org-priority-default
  10129. (1- org-priority-default))))))
  10130. ((eq action 'down)
  10131. (setq new (if have
  10132. (1+ current) ; normal cycling
  10133. ;; last priority was empty
  10134. (if (eq last-command this-command)
  10135. org-priority-highest ; wrap around empty to highest
  10136. ;; default
  10137. (if org-priority-start-cycle-with-default
  10138. org-priority-default
  10139. (1+ org-priority-default))))))
  10140. (t (user-error "Invalid action")))
  10141. (when (or (< (upcase new) org-priority-highest)
  10142. (> (upcase new) org-priority-lowest))
  10143. (if (and (memq action '(up down))
  10144. (not have) (not (eq last-command this-command)))
  10145. ;; `new' is from default priority
  10146. (error
  10147. "The default can not be set, see `org-priority-default' why")
  10148. ;; normal cycling: `new' is beyond highest/lowest priority
  10149. ;; and is wrapped around to the empty priority
  10150. (setq remove t)))
  10151. ;; Numerical priorities are limited to 64, beyond that number,
  10152. ;; assume the priority cookie is a character.
  10153. (setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  10154. (if have
  10155. (if remove
  10156. (replace-match "" t t nil 1)
  10157. (replace-match news t t nil 2))
  10158. (if remove
  10159. (user-error "No priority cookie found in line")
  10160. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  10161. (if (match-end 2)
  10162. (progn
  10163. (goto-char (match-end 2))
  10164. (insert " [#" news "]"))
  10165. (goto-char (match-beginning 3))
  10166. (insert "[#" news "] "))))
  10167. (org-align-tags))
  10168. (if remove
  10169. (message "Priority removed")
  10170. (message "Priority of current item set to %s" news)))))
  10171. (defalias 'org-show-priority 'org-priority-show)
  10172. (defun org-priority-show ()
  10173. "Show the priority of the current item.
  10174. This priority is composed of the main priority given with the [#A] cookies,
  10175. and by additional input from the age of a schedules or deadline entry."
  10176. (interactive)
  10177. (let ((pri (if (eq major-mode 'org-agenda-mode)
  10178. (org-get-at-bol 'priority)
  10179. (save-excursion
  10180. (save-match-data
  10181. (beginning-of-line)
  10182. (and (looking-at org-heading-regexp)
  10183. (org-get-priority (match-string 0))))))))
  10184. (message "Priority is %d" (if pri pri -1000))))
  10185. (defun org-get-priority (s)
  10186. "Find priority cookie and return priority.
  10187. S is a string against which you can match `org-priority-regexp'.
  10188. If `org-priority-get-priority-function' is set to a custom
  10189. function, use it. Otherwise process S and output the priority
  10190. value, an integer."
  10191. (save-match-data
  10192. (if (functionp org-priority-get-priority-function)
  10193. (funcall org-priority-get-priority-function s)
  10194. (if (not (string-match org-priority-regexp s))
  10195. (* 1000 (- org-priority-lowest org-priority-default))
  10196. (* 1000 (- org-priority-lowest
  10197. (org-priority-to-value (match-string 2 s))))))))
  10198. ;;;; Tags
  10199. (defvar org-agenda-archives-mode)
  10200. (defvar org-map-continue-from nil
  10201. "Position from where mapping should continue.
  10202. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  10203. (defvar org-scanner-tags nil
  10204. "The current tag list while the tags scanner is running.")
  10205. (defvar org-trust-scanner-tags nil
  10206. "Should `org-get-tags' use the tags for the scanner.
  10207. This is for internal dynamical scoping only.
  10208. When this is non-nil, the function `org-get-tags' will return the value
  10209. of `org-scanner-tags' instead of building the list by itself. This
  10210. can lead to large speed-ups when the tags scanner is used in a file with
  10211. many entries, and when the list of tags is retrieved, for example to
  10212. obtain a list of properties. Building the tags list for each entry in such
  10213. a file becomes an N^2 operation - but with this variable set, it scales
  10214. as N.")
  10215. (defvar org--matcher-tags-todo-only nil)
  10216. (defun org-scan-tags (action matcher todo-only &optional start-level)
  10217. "Scan headline tags with inheritance and produce output ACTION.
  10218. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  10219. or `agenda' to produce an entry list for an agenda view. It can also be
  10220. a Lisp form or a function that should be called at each matched headline, in
  10221. this case the return value is a list of all return values from these calls.
  10222. MATCHER is a function accepting three arguments, returning
  10223. a non-nil value whenever a given set of tags qualifies a headline
  10224. for inclusion. See `org-make-tags-matcher' for more information.
  10225. As a special case, it can also be set to t (respectively nil) in
  10226. order to match all (respectively none) headline.
  10227. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  10228. included in the output.
  10229. START-LEVEL can be a string with asterisks, reducing the scope to
  10230. headlines matching this string."
  10231. (require 'org-agenda)
  10232. (let* ((re (concat "^"
  10233. (if start-level
  10234. ;; Get the correct level to match
  10235. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  10236. org-outline-regexp)
  10237. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  10238. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  10239. (props (list 'face 'default
  10240. 'done-face 'org-agenda-done
  10241. 'undone-face 'default
  10242. 'mouse-face 'highlight
  10243. 'org-not-done-regexp org-not-done-regexp
  10244. 'org-todo-regexp org-todo-regexp
  10245. 'org-complex-heading-regexp org-complex-heading-regexp
  10246. 'help-echo
  10247. (format "mouse-2 or RET jump to Org file %S"
  10248. (abbreviate-file-name
  10249. (or (buffer-file-name (buffer-base-buffer))
  10250. (buffer-name (buffer-base-buffer)))))))
  10251. (org-map-continue-from nil)
  10252. lspos tags tags-list
  10253. (tags-alist (list (cons 0 org-file-tags)))
  10254. (llast 0) rtn rtn1 level category i txt
  10255. todo marker entry priority
  10256. ts-date ts-date-type ts-date-pair)
  10257. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  10258. (setq action (list 'lambda nil action)))
  10259. (save-excursion
  10260. (goto-char (point-min))
  10261. (when (eq action 'sparse-tree)
  10262. (org-overview)
  10263. (org-remove-occur-highlights))
  10264. (while (let (case-fold-search)
  10265. (re-search-forward re nil t))
  10266. (setq org-map-continue-from nil)
  10267. (catch :skip
  10268. ;; Ignore closing parts of inline tasks.
  10269. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  10270. (throw :skip t))
  10271. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  10272. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  10273. (goto-char (setq lspos (match-beginning 0)))
  10274. (setq level (org-reduced-level (org-outline-level))
  10275. category (org-get-category))
  10276. (when (eq action 'agenda)
  10277. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  10278. ts-date (car ts-date-pair)
  10279. ts-date-type (cdr ts-date-pair)))
  10280. (setq i llast llast level)
  10281. ;; remove tag lists from same and sublevels
  10282. (while (>= i level)
  10283. (when (setq entry (assoc i tags-alist))
  10284. (setq tags-alist (delete entry tags-alist)))
  10285. (setq i (1- i)))
  10286. ;; add the next tags
  10287. (when tags
  10288. (setq tags (org-split-string tags ":")
  10289. tags-alist
  10290. (cons (cons level tags) tags-alist)))
  10291. ;; compile tags for current headline
  10292. (setq tags-list
  10293. (if org-use-tag-inheritance
  10294. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10295. tags)
  10296. org-scanner-tags tags-list)
  10297. (when org-use-tag-inheritance
  10298. (setcdr (car tags-alist)
  10299. (mapcar (lambda (x)
  10300. (setq x (copy-sequence x))
  10301. (org-add-prop-inherited x))
  10302. (cdar tags-alist))))
  10303. (when (and tags org-use-tag-inheritance
  10304. (or (not (eq t org-use-tag-inheritance))
  10305. org-tags-exclude-from-inheritance))
  10306. ;; Selective inheritance, remove uninherited ones.
  10307. (setcdr (car tags-alist)
  10308. (org-remove-uninherited-tags (cdar tags-alist))))
  10309. (when (and
  10310. ;; eval matcher only when the todo condition is OK
  10311. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10312. (if (functionp matcher)
  10313. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10314. (funcall matcher todo tags-list level))
  10315. matcher))
  10316. ;; Call the skipper, but return t if it does not
  10317. ;; skip, so that the `and' form continues evaluating.
  10318. (progn
  10319. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10320. t)
  10321. ;; Check if timestamps are deselecting this entry
  10322. (or (not todo-only)
  10323. (and (member todo org-todo-keywords-1)
  10324. (or (not org-agenda-tags-todo-honor-ignore-options)
  10325. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10326. ;; select this headline
  10327. (cond
  10328. ((eq action 'sparse-tree)
  10329. (and org-highlight-sparse-tree-matches
  10330. (org-get-heading) (match-end 0)
  10331. (org-highlight-new-match
  10332. (match-beginning 1) (match-end 1)))
  10333. (org-show-context 'tags-tree))
  10334. ((eq action 'agenda)
  10335. (setq txt (org-agenda-format-item
  10336. ""
  10337. (concat
  10338. (if (eq org-tags-match-list-sublevels 'indented)
  10339. (make-string (1- level) ?.) "")
  10340. (org-get-heading))
  10341. (make-string level ?\s)
  10342. category
  10343. tags-list)
  10344. priority (org-get-priority txt))
  10345. (goto-char lspos)
  10346. (setq marker (org-agenda-new-marker))
  10347. (org-add-props txt props
  10348. 'org-marker marker 'org-hd-marker marker 'org-category category
  10349. 'todo-state todo
  10350. 'ts-date ts-date
  10351. 'priority priority
  10352. 'type (concat "tagsmatch" ts-date-type))
  10353. (push txt rtn))
  10354. ((functionp action)
  10355. (setq org-map-continue-from nil)
  10356. (save-excursion
  10357. (setq rtn1 (funcall action))
  10358. (push rtn1 rtn)))
  10359. (t (user-error "Invalid action")))
  10360. ;; if we are to skip sublevels, jump to end of subtree
  10361. (unless org-tags-match-list-sublevels
  10362. (org-end-of-subtree t)
  10363. (backward-char 1))))
  10364. ;; Get the correct position from where to continue
  10365. (if org-map-continue-from
  10366. (goto-char org-map-continue-from)
  10367. (and (= (point) lspos) (end-of-line 1)))))
  10368. (when (and (eq action 'sparse-tree)
  10369. (not org-sparse-tree-open-archived-trees))
  10370. (org-hide-archived-subtrees (point-min) (point-max)))
  10371. (nreverse rtn)))
  10372. (defun org-remove-uninherited-tags (tags)
  10373. "Remove all tags that are not inherited from the list TAGS."
  10374. (cond
  10375. ((eq org-use-tag-inheritance t)
  10376. (if org-tags-exclude-from-inheritance
  10377. (org-delete-all org-tags-exclude-from-inheritance tags)
  10378. tags))
  10379. ((not org-use-tag-inheritance) nil)
  10380. ((stringp org-use-tag-inheritance)
  10381. (delq nil (mapcar
  10382. (lambda (x)
  10383. (if (and (string-match org-use-tag-inheritance x)
  10384. (not (member x org-tags-exclude-from-inheritance)))
  10385. x nil))
  10386. tags)))
  10387. ((listp org-use-tag-inheritance)
  10388. (delq nil (mapcar
  10389. (lambda (x)
  10390. (if (member x org-use-tag-inheritance) x nil))
  10391. tags)))))
  10392. (defun org-match-sparse-tree (&optional todo-only match)
  10393. "Create a sparse tree according to tags string MATCH.
  10394. MATCH is a string with match syntax. It can contain a selection
  10395. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10396. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10397. those. See the manual for details.
  10398. If optional argument TODO-ONLY is non-nil, only select lines that
  10399. are also TODO tasks."
  10400. (interactive "P")
  10401. (org-agenda-prepare-buffers (list (current-buffer)))
  10402. (let ((org--matcher-tags-todo-only todo-only))
  10403. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match t))
  10404. org--matcher-tags-todo-only)))
  10405. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10406. (defvar org-cached-props nil)
  10407. (defun org-cached-entry-get (pom property)
  10408. (if (or (eq t org-use-property-inheritance)
  10409. (and (stringp org-use-property-inheritance)
  10410. (let ((case-fold-search t))
  10411. (string-match-p org-use-property-inheritance property)))
  10412. (and (listp org-use-property-inheritance)
  10413. (member-ignore-case property org-use-property-inheritance)))
  10414. ;; Caching is not possible, check it directly.
  10415. (org-entry-get pom property 'inherit)
  10416. ;; Get all properties, so we can do complicated checks easily.
  10417. (cdr (assoc-string property
  10418. (or org-cached-props
  10419. (setq org-cached-props (org-entry-properties pom)))
  10420. t))))
  10421. (defun org-global-tags-completion-table (&optional files)
  10422. "Return the list of all tags in all agenda buffer/files.
  10423. Optional FILES argument is a list of files which can be used
  10424. instead of the agenda files."
  10425. (save-excursion
  10426. (org-uniquify
  10427. (delq nil
  10428. (apply #'append
  10429. (mapcar
  10430. (lambda (file)
  10431. (set-buffer (find-file-noselect file))
  10432. (org--tag-add-to-alist
  10433. (org-get-buffer-tags)
  10434. (mapcar (lambda (x)
  10435. (and (stringp (car-safe x))
  10436. (list (car-safe x))))
  10437. org-current-tag-alist)))
  10438. (if (car-safe files) files
  10439. (org-agenda-files))))))))
  10440. (defun org-make-tags-matcher (match &optional only-local-tags)
  10441. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10442. Returns a cons of the selection string MATCH and a function
  10443. implementing the matcher.
  10444. The matcher is to be called at an Org entry, with point on the
  10445. headline, and returns non-nil if the entry matches the selection
  10446. string MATCH. It must be called with three arguments: the TODO
  10447. keyword at the entry (or nil if none), the list of all tags at
  10448. the entry including inherited ones and the reduced level of the
  10449. headline. Additionally, the category of the entry, if any, must
  10450. be specified as the text property `org-category' on the headline.
  10451. This function sets the variable `org--matcher-tags-todo-only' to
  10452. a non-nil value if the matcher restricts matching to TODO
  10453. entries, otherwise it is not touched.
  10454. When ONLY-LOCAL-TAGS is non-nil, ignore the global tag completion
  10455. table, only get buffer tags.
  10456. See also `org-scan-tags'."
  10457. (unless match
  10458. ;; Get a new match request, with completion against the global
  10459. ;; tags table and the local tags in current buffer.
  10460. (let ((org-last-tags-completion-table
  10461. (org--tag-add-to-alist
  10462. (org-get-buffer-tags)
  10463. (unless only-local-tags
  10464. (org-global-tags-completion-table)))))
  10465. (setq match
  10466. (completing-read
  10467. "Match: "
  10468. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10469. (let ((match0 match)
  10470. (re (concat
  10471. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10472. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10473. "\\([<>=]\\{1,2\\}\\)"
  10474. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10475. "\\|" org-tag-re "\\)"))
  10476. (start 0)
  10477. tagsmatch todomatch tagsmatcher todomatcher)
  10478. ;; Expand group tags.
  10479. (setq match (org-tags-expand match))
  10480. ;; Check if there is a TODO part of this match, which would be the
  10481. ;; part after a "/". To make sure that this slash is not part of
  10482. ;; a property value to be matched against, we also check that
  10483. ;; there is no / after that slash. First, find the last slash.
  10484. (let ((s 0))
  10485. (while (string-match "/+" match s)
  10486. (setq start (match-beginning 0))
  10487. (setq s (match-end 0))))
  10488. (if (and (string-match "/+" match start)
  10489. (not (string-match-p "\"" match start)))
  10490. ;; Match contains also a TODO-matching request.
  10491. (progn
  10492. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10493. (setq todomatch (substring match (match-end 0)))
  10494. (when (string-prefix-p "!" todomatch)
  10495. (setq org--matcher-tags-todo-only t)
  10496. (setq todomatch (substring todomatch 1)))
  10497. (when (string-match "\\`\\s-*\\'" todomatch)
  10498. (setq todomatch nil)))
  10499. ;; Only matching tags.
  10500. (setq tagsmatch match)
  10501. (setq todomatch nil))
  10502. ;; Make the tags matcher.
  10503. (when (org-string-nw-p tagsmatch)
  10504. (let ((orlist nil)
  10505. (orterms (org-split-string tagsmatch "|"))
  10506. term)
  10507. (while (setq term (pop orterms))
  10508. (while (and (equal (substring term -1) "\\") orterms)
  10509. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10510. (while (string-match re term)
  10511. (let* ((rest (substring term (match-end 0)))
  10512. (minus (and (match-end 1)
  10513. (equal (match-string 1 term) "-")))
  10514. (tag (save-match-data
  10515. (replace-regexp-in-string
  10516. "\\\\-" "-" (match-string 2 term))))
  10517. (regexp (eq (string-to-char tag) ?{))
  10518. (levelp (match-end 4))
  10519. (propp (match-end 5))
  10520. (mm
  10521. (cond
  10522. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10523. (levelp
  10524. `(,(org-op-to-function (match-string 3 term))
  10525. level
  10526. ,(string-to-number (match-string 4 term))))
  10527. (propp
  10528. (let* ((gv (pcase (upcase (match-string 5 term))
  10529. ("CATEGORY"
  10530. '(get-text-property (point) 'org-category))
  10531. ("TODO" 'todo)
  10532. (p `(org-cached-entry-get nil ,p))))
  10533. (pv (match-string 7 term))
  10534. (regexp (eq (string-to-char pv) ?{))
  10535. (strp (eq (string-to-char pv) ?\"))
  10536. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10537. (po (org-op-to-function (match-string 6 term)
  10538. (if timep 'time strp))))
  10539. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10540. (when timep (setq pv (org-matcher-time pv)))
  10541. (cond ((and regexp (eq po '/=))
  10542. `(not (string-match ,pv (or ,gv ""))))
  10543. (regexp `(string-match ,pv (or ,gv "")))
  10544. (strp `(,po (or ,gv "") ,pv))
  10545. (t
  10546. `(,po
  10547. (string-to-number (or ,gv ""))
  10548. ,(string-to-number pv))))))
  10549. (t `(member ,tag tags-list)))))
  10550. (push (if minus `(not ,mm) mm) tagsmatcher)
  10551. (setq term rest)))
  10552. (push `(and ,@tagsmatcher) orlist)
  10553. (setq tagsmatcher nil))
  10554. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10555. ;; Make the TODO matcher.
  10556. (when (org-string-nw-p todomatch)
  10557. (let ((orlist nil))
  10558. (dolist (term (org-split-string todomatch "|"))
  10559. (while (string-match re term)
  10560. (let* ((minus (and (match-end 1)
  10561. (equal (match-string 1 term) "-")))
  10562. (kwd (match-string 2 term))
  10563. (regexp (eq (string-to-char kwd) ?{))
  10564. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10565. `(equal todo ,kwd))))
  10566. (push (if minus `(not ,mm) mm) todomatcher))
  10567. (setq term (substring term (match-end 0))))
  10568. (push (if (> (length todomatcher) 1)
  10569. (cons 'and todomatcher)
  10570. (car todomatcher))
  10571. orlist)
  10572. (setq todomatcher nil))
  10573. (setq todomatcher (cons 'or orlist))))
  10574. ;; Return the string and function of the matcher. If no
  10575. ;; tags-specific or todo-specific matcher exists, match
  10576. ;; everything.
  10577. (let ((matcher (if (and tagsmatcher todomatcher)
  10578. `(and ,tagsmatcher ,todomatcher)
  10579. (or tagsmatcher todomatcher t))))
  10580. (when org--matcher-tags-todo-only
  10581. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10582. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10583. (defun org--tags-expand-group (group tag-groups expanded)
  10584. "Recursively expand all tags in GROUP, according to TAG-GROUPS.
  10585. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10586. an accumulator used in recursive calls."
  10587. (dolist (tag group)
  10588. (unless (member tag expanded)
  10589. (let ((group (assoc tag tag-groups)))
  10590. (push tag expanded)
  10591. (when group
  10592. (setq expanded
  10593. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10594. expanded)
  10595. (defun org-tags-expand (match &optional single-as-list downcased)
  10596. "Expand group tags in MATCH.
  10597. This replaces every group tag in MATCH with a regexp tag search.
  10598. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10599. will be replaced like this:
  10600. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10601. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10602. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10603. Replacing by a regexp preserves the structure of the match.
  10604. E.g., this expansion
  10605. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10606. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10607. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10608. A group tag in MATCH can contain regular expressions of its own.
  10609. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10610. will be replaced like this:
  10611. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10612. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10613. assumed to be a single group tag, and the function will return
  10614. the list of tags in this group.
  10615. When DOWNCASED is non-nil, expand downcased TAGS."
  10616. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10617. (let ((tag-groups
  10618. (let ((g (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10619. (if (not downcased) g
  10620. (mapcar (lambda (s) (mapcar #'downcase s)) g)))))
  10621. (cond
  10622. (single-as-list (org--tags-expand-group
  10623. (list (if downcased (downcase match) match))
  10624. tag-groups nil))
  10625. (org-group-tags
  10626. (let* ((case-fold-search t)
  10627. (tag-syntax org-mode-syntax-table)
  10628. (group-keys (mapcar #'car tag-groups))
  10629. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  10630. (return-match (if downcased (downcase match) match)))
  10631. ;; Mark regexp-expressions in the match-expression so that we
  10632. ;; do not replace them later on.
  10633. (let ((s 0))
  10634. (while (string-match "{.+?}" return-match s)
  10635. (setq s (match-end 0))
  10636. (add-text-properties
  10637. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  10638. ;; @ and _ are allowed as word-components in tags.
  10639. (modify-syntax-entry ?@ "w" tag-syntax)
  10640. (modify-syntax-entry ?_ "w" tag-syntax)
  10641. ;; For each tag token found in MATCH, compute a regexp and it
  10642. (with-syntax-table tag-syntax
  10643. (replace-regexp-in-string
  10644. key-regexp
  10645. (lambda (m)
  10646. (if (get-text-property (match-beginning 2) 'regexp m)
  10647. m ;regexp tag: ignore
  10648. (let* ((operator (match-string 1 m))
  10649. (tag-token (let ((tag (match-string 2 m)))
  10650. (list (if downcased (downcase tag) tag))))
  10651. regexp-tags regular-tags)
  10652. ;; Partition tags between regexp and regular tags.
  10653. ;; Remove curly bracket syntax from regexp tags.
  10654. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  10655. (save-match-data
  10656. (if (string-match "{\\(.+?\\)}" tag)
  10657. (push (match-string 1 tag) regexp-tags)
  10658. (push tag regular-tags))))
  10659. ;; Replace tag token by the appropriate regexp.
  10660. ;; Regular tags need to be regexp-quoted, whereas
  10661. ;; regexp-tags are inserted as-is.
  10662. (let ((regular (regexp-opt regular-tags))
  10663. (regexp (mapconcat #'identity regexp-tags "\\|")))
  10664. (concat operator
  10665. (cond
  10666. ((null regular-tags) (format "{%s}" regexp))
  10667. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  10668. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  10669. return-match
  10670. t t))))
  10671. (t match))))
  10672. (defun org-op-to-function (op &optional stringp)
  10673. "Turn an operator into the appropriate function."
  10674. (setq op
  10675. (cond
  10676. ((equal op "<" ) '(< org-string< org-time<))
  10677. ((equal op ">" ) '(> org-string> org-time>))
  10678. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  10679. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  10680. ((member op '("=" "==")) '(= string= org-time=))
  10681. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  10682. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  10683. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  10684. (defvar org-tags-overlay (make-overlay 1 1))
  10685. (delete-overlay org-tags-overlay)
  10686. (defun org-add-prop-inherited (s)
  10687. (add-text-properties 0 (length s) '(inherited t) s)
  10688. s)
  10689. (defun org-toggle-tag (tag &optional onoff)
  10690. "Toggle the tag TAG for the current line.
  10691. If ONOFF is `on' or `off', don't toggle but set to this state."
  10692. (save-excursion
  10693. (org-back-to-heading t)
  10694. (let ((current
  10695. ;; Reverse the tags list so any new tag is appended to the
  10696. ;; current list of tags.
  10697. (nreverse (org-get-tags nil t)))
  10698. res)
  10699. (pcase onoff
  10700. (`off (setq current (delete tag current)))
  10701. ((or `on (guard (not (member tag current))))
  10702. (setq res t)
  10703. (cl-pushnew tag current :test #'equal))
  10704. (_ (setq current (delete tag current))))
  10705. (org-set-tags (nreverse current))
  10706. res)))
  10707. (defun org--align-tags-here (to-col)
  10708. "Align tags on the current headline to TO-COL.
  10709. Assume point is on a headline. Preserve point when aligning
  10710. tags."
  10711. (when (org-match-line org-tag-line-re)
  10712. (let* ((tags-start (match-beginning 1))
  10713. (blank-start (save-excursion
  10714. (goto-char tags-start)
  10715. (skip-chars-backward " \t")
  10716. (point)))
  10717. (new (max (if (>= to-col 0) to-col
  10718. (- (abs to-col) (string-width (match-string 1))))
  10719. ;; Introduce at least one space after the heading
  10720. ;; or the stars.
  10721. (save-excursion
  10722. (goto-char blank-start)
  10723. (1+ (current-column)))))
  10724. (current
  10725. (save-excursion (goto-char tags-start) (current-column)))
  10726. (origin (point-marker))
  10727. (column (current-column))
  10728. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  10729. (when (/= new current)
  10730. (delete-region blank-start tags-start)
  10731. (goto-char blank-start)
  10732. (let ((indent-tabs-mode nil)) (indent-to new))
  10733. ;; Try to move back to original position. If point was in the
  10734. ;; blanks before the tags, ORIGIN marker is of no use because
  10735. ;; it now points to BLANK-START. Use COLUMN instead.
  10736. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  10737. (defun org-set-tags-command (&optional arg)
  10738. "Set the tags for the current visible entry.
  10739. When called with `\\[universal-argument]' prefix argument ARG, \
  10740. realign all tags
  10741. in the current buffer.
  10742. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  10743. unconditionally do not
  10744. offer the fast tag selection interface.
  10745. If a region is active, set tags in the region according to the
  10746. setting of `org-loop-over-headlines-in-active-region'.
  10747. This function is for interactive use only;
  10748. in Lisp code use `org-set-tags' instead."
  10749. (interactive "P")
  10750. (let ((org-use-fast-tag-selection
  10751. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  10752. (cond
  10753. ((equal '(4) arg) (org-align-tags t))
  10754. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10755. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  10756. (org-map-entries
  10757. #'org-set-tags-command
  10758. nil
  10759. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10760. 'region-start-level
  10761. 'region)
  10762. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  10763. (t
  10764. (save-excursion
  10765. (org-back-to-heading)
  10766. (let* ((all-tags (org-get-tags))
  10767. (table (setq org-last-tags-completion-table
  10768. (org--tag-add-to-alist
  10769. (and org-complete-tags-always-offer-all-agenda-tags
  10770. (org-global-tags-completion-table
  10771. (org-agenda-files)))
  10772. (or org-current-tag-alist (org-get-buffer-tags)))))
  10773. (current-tags
  10774. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  10775. all-tags))
  10776. (inherited-tags
  10777. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  10778. all-tags))
  10779. (tags
  10780. (replace-regexp-in-string
  10781. ;; Ignore all forbidden characters in tags.
  10782. "[^[:alnum:]_@#%]+" ":"
  10783. (if (or (eq t org-use-fast-tag-selection)
  10784. (and org-use-fast-tag-selection
  10785. (delq nil (mapcar #'cdr table))))
  10786. (org-fast-tag-selection
  10787. current-tags
  10788. inherited-tags
  10789. table
  10790. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  10791. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  10792. (org-trim (completing-read
  10793. "Tags: "
  10794. #'org-tags-completion-function
  10795. nil nil (org-make-tag-string current-tags)
  10796. 'org-tags-history)))))))
  10797. (org-set-tags tags)))))
  10798. ;; `save-excursion' may not replace the point at the right
  10799. ;; position.
  10800. (when (and (save-excursion (skip-chars-backward "*") (bolp))
  10801. (looking-at-p " "))
  10802. (forward-char))))
  10803. (defun org-align-tags (&optional all)
  10804. "Align tags in current entry.
  10805. When optional argument ALL is non-nil, align all tags in the
  10806. visible part of the buffer."
  10807. (let ((get-indent-column
  10808. (lambda ()
  10809. (let ((offset (if (bound-and-true-p org-indent-mode)
  10810. (* (1- org-indent-indentation-per-level)
  10811. (1- (org-current-level)))
  10812. 0)))
  10813. (+ org-tags-column
  10814. (if (> org-tags-column 0) (- offset) offset))))))
  10815. (if (and (not all) (org-at-heading-p))
  10816. (org--align-tags-here (funcall get-indent-column))
  10817. (save-excursion
  10818. (if all
  10819. (progn
  10820. (goto-char (point-min))
  10821. (while (re-search-forward org-tag-line-re nil t)
  10822. (org--align-tags-here (funcall get-indent-column))))
  10823. (org-back-to-heading t)
  10824. (org--align-tags-here (funcall get-indent-column)))))))
  10825. (defun org-set-tags (tags)
  10826. "Set the tags of the current entry to TAGS, replacing current tags.
  10827. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  10828. If TAGS is nil or the empty string, all tags are removed.
  10829. This function assumes point is on a headline."
  10830. (org-with-wide-buffer
  10831. (let ((tags (pcase tags
  10832. ((pred listp) tags)
  10833. ((pred stringp) (split-string (org-trim tags) ":" t))
  10834. (_ (error "Invalid tag specification: %S" tags))))
  10835. (old-tags (org-get-tags nil t))
  10836. (tags-change? nil))
  10837. (when (functionp org-tags-sort-function)
  10838. (setq tags (sort tags org-tags-sort-function)))
  10839. (setq tags-change? (not (equal tags old-tags)))
  10840. (when tags-change?
  10841. ;; Delete previous tags and any trailing white space.
  10842. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  10843. (line-end-position)))
  10844. (skip-chars-backward " \t")
  10845. (delete-region (point) (line-end-position))
  10846. ;; Deleting white spaces may break an otherwise empty headline.
  10847. ;; Re-introduce one space in this case.
  10848. (unless (org-at-heading-p) (insert " "))
  10849. (when tags
  10850. (save-excursion (insert " " (org-make-tag-string tags)))
  10851. ;; When text is being inserted on an invisible region
  10852. ;; boundary, it can be inadvertently sucked into
  10853. ;; invisibility.
  10854. (unless (org-invisible-p (line-beginning-position))
  10855. (org-flag-region (point) (line-end-position) nil 'outline))))
  10856. ;; Align tags, if any.
  10857. (when tags (org-align-tags))
  10858. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  10859. (defun org-change-tag-in-region (beg end tag off)
  10860. "Add or remove TAG for each entry in the region.
  10861. This works in the agenda, and also in an Org buffer."
  10862. (interactive
  10863. (list (region-beginning) (region-end)
  10864. (let ((org-last-tags-completion-table
  10865. (if (derived-mode-p 'org-mode)
  10866. (org--tag-add-to-alist
  10867. (org-get-buffer-tags)
  10868. (org-global-tags-completion-table))
  10869. (org-global-tags-completion-table))))
  10870. (completing-read
  10871. "Tag: " 'org-tags-completion-function nil nil nil
  10872. 'org-tags-history))
  10873. (progn
  10874. (message "[s]et or [r]emove? ")
  10875. (equal (read-char-exclusive) ?r))))
  10876. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10877. (let ((agendap (equal major-mode 'org-agenda-mode))
  10878. l1 l2 m buf pos newhead (cnt 0))
  10879. (goto-char end)
  10880. (setq l2 (1- (org-current-line)))
  10881. (goto-char beg)
  10882. (setq l1 (org-current-line))
  10883. (cl-loop for l from l1 to l2 do
  10884. (org-goto-line l)
  10885. (setq m (get-text-property (point) 'org-hd-marker))
  10886. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  10887. (and agendap m))
  10888. (setq buf (if agendap (marker-buffer m) (current-buffer))
  10889. pos (if agendap m (point)))
  10890. (with-current-buffer buf
  10891. (save-excursion
  10892. (save-restriction
  10893. (goto-char pos)
  10894. (setq cnt (1+ cnt))
  10895. (org-toggle-tag tag (if off 'off 'on))
  10896. (setq newhead (org-get-heading)))))
  10897. (and agendap (org-agenda-change-all-lines newhead m))))
  10898. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  10899. (defun org-tags-completion-function (string _predicate &optional flag)
  10900. "Complete tag STRING.
  10901. FLAG specifies the type of completion operation to perform. This
  10902. function is passed as a collection function to `completing-read',
  10903. which see."
  10904. (let ((completion-ignore-case nil) ;tags are case-sensitive
  10905. (confirm (lambda (x) (stringp (car x))))
  10906. (prefix ""))
  10907. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  10908. (setq prefix (match-string 1 string))
  10909. (setq string (match-string 2 string)))
  10910. (pcase flag
  10911. (`t (all-completions string org-last-tags-completion-table confirm))
  10912. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  10913. (`nil
  10914. (pcase (try-completion string org-last-tags-completion-table confirm)
  10915. ((and completion (pred stringp))
  10916. (concat prefix
  10917. completion
  10918. (if (and org-add-colon-after-tag-completion
  10919. (assoc completion org-last-tags-completion-table))
  10920. ":"
  10921. "")))
  10922. (completion completion)))
  10923. (_ nil))))
  10924. (defun org-fast-tag-insert (kwd tags face &optional end)
  10925. "Insert KWD, and the TAGS, the latter with face FACE.
  10926. Also insert END."
  10927. (insert (format "%-12s" (concat kwd ":"))
  10928. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  10929. (or end "")))
  10930. (defun org-fast-tag-show-exit (flag)
  10931. (save-excursion
  10932. (org-goto-line 3)
  10933. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  10934. (replace-match ""))
  10935. (when flag
  10936. (end-of-line 1)
  10937. (org-move-to-column (- (window-width) 19) t)
  10938. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  10939. (defun org-set-current-tags-overlay (current prefix)
  10940. "Add an overlay to CURRENT tag with PREFIX."
  10941. (let ((s (org-make-tag-string current)))
  10942. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  10943. (org-overlay-display org-tags-overlay (concat prefix s))))
  10944. (defvar org-last-tag-selection-key nil)
  10945. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  10946. "Fast tag selection with single keys.
  10947. CURRENT is the current list of tags in the headline, INHERITED is the
  10948. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  10949. possibly with grouping information. TODO-TABLE is a similar table with
  10950. TODO keywords, should these have keys assigned to them.
  10951. If the keys are nil, a-z are automatically assigned.
  10952. Returns the new tags string, or nil to not change the current settings."
  10953. (let* ((fulltable (append table todo-table))
  10954. (maxlen (if (null fulltable) 0
  10955. (apply #'max
  10956. (mapcar (lambda (x)
  10957. (if (stringp (car x)) (string-width (car x))
  10958. 0))
  10959. fulltable))))
  10960. (buf (current-buffer))
  10961. (expert (eq org-fast-tag-selection-single-key 'expert))
  10962. (buffer-tags nil)
  10963. (fwidth (+ maxlen 3 1 3))
  10964. (ncol (/ (- (window-width) 4) fwidth))
  10965. (i-face 'org-done)
  10966. (c-face 'org-todo)
  10967. tg cnt e c char c1 c2 ntable tbl rtn
  10968. ov-start ov-end ov-prefix
  10969. (exit-after-next org-fast-tag-selection-single-key)
  10970. (done-keywords org-done-keywords)
  10971. groups ingroup intaggroup)
  10972. (save-excursion
  10973. (beginning-of-line)
  10974. (if (looking-at org-tag-line-re)
  10975. (setq ov-start (match-beginning 1)
  10976. ov-end (match-end 1)
  10977. ov-prefix "")
  10978. (setq ov-start (1- (point-at-eol))
  10979. ov-end (1+ ov-start))
  10980. (skip-chars-forward "^\n\r")
  10981. (setq ov-prefix
  10982. (concat
  10983. (buffer-substring (1- (point)) (point))
  10984. (if (> (current-column) org-tags-column)
  10985. " "
  10986. (make-string (- org-tags-column (current-column)) ?\ ))))))
  10987. (move-overlay org-tags-overlay ov-start ov-end)
  10988. (save-excursion
  10989. (save-window-excursion
  10990. (if expert
  10991. (set-buffer (get-buffer-create " *Org tags*"))
  10992. (delete-other-windows)
  10993. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  10994. (org-switch-to-buffer-other-window " *Org tags*"))
  10995. (erase-buffer)
  10996. (setq-local org-done-keywords done-keywords)
  10997. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  10998. (org-fast-tag-insert "Current" current c-face "\n\n")
  10999. (org-fast-tag-show-exit exit-after-next)
  11000. (org-set-current-tags-overlay current ov-prefix)
  11001. (setq tbl fulltable char ?a cnt 0)
  11002. (while (setq e (pop tbl))
  11003. (cond
  11004. ((eq (car e) :startgroup)
  11005. (push '() groups) (setq ingroup t)
  11006. (unless (zerop cnt)
  11007. (setq cnt 0)
  11008. (insert "\n"))
  11009. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  11010. ((eq (car e) :endgroup)
  11011. (setq ingroup nil cnt 0)
  11012. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  11013. ((eq (car e) :startgrouptag)
  11014. (setq intaggroup t)
  11015. (unless (zerop cnt)
  11016. (setq cnt 0)
  11017. (insert "\n"))
  11018. (insert "[ "))
  11019. ((eq (car e) :endgrouptag)
  11020. (setq intaggroup nil cnt 0)
  11021. (insert "]\n"))
  11022. ((equal e '(:newline))
  11023. (unless (zerop cnt)
  11024. (setq cnt 0)
  11025. (insert "\n")
  11026. (setq e (car tbl))
  11027. (while (equal (car tbl) '(:newline))
  11028. (insert "\n")
  11029. (setq tbl (cdr tbl)))))
  11030. ((equal e '(:grouptags)) (insert " : "))
  11031. (t
  11032. (setq tg (copy-sequence (car e)) c2 nil)
  11033. (if (cdr e)
  11034. (setq c (cdr e))
  11035. ;; automatically assign a character.
  11036. (setq c1 (string-to-char
  11037. (downcase (substring
  11038. tg (if (= (string-to-char tg) ?@) 1 0)))))
  11039. (if (or (rassoc c1 ntable) (rassoc c1 table))
  11040. (while (or (rassoc char ntable) (rassoc char table))
  11041. (setq char (1+ char)))
  11042. (setq c2 c1))
  11043. (setq c (or c2 char)))
  11044. (when ingroup (push tg (car groups)))
  11045. (setq tg (org-add-props tg nil 'face
  11046. (cond
  11047. ((not (assoc tg table))
  11048. (org-get-todo-face tg))
  11049. ((member tg current) c-face)
  11050. ((member tg inherited) i-face))))
  11051. (when (equal (caar tbl) :grouptags)
  11052. (org-add-props tg nil 'face 'org-tag-group))
  11053. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  11054. (insert "[" c "] " tg (make-string
  11055. (- fwidth 4 (length tg)) ?\ ))
  11056. (push (cons tg c) ntable)
  11057. (when (= (cl-incf cnt) ncol)
  11058. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  11059. (insert "\n")
  11060. (when (or ingroup intaggroup) (insert " ")))
  11061. (setq cnt 0)))))
  11062. (setq ntable (nreverse ntable))
  11063. (insert "\n")
  11064. (goto-char (point-min))
  11065. (unless expert (org-fit-window-to-buffer))
  11066. (setq rtn
  11067. (catch 'exit
  11068. (while t
  11069. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  11070. (if (not groups) "no " "")
  11071. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  11072. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11073. (setq org-last-tag-selection-key c)
  11074. (cond
  11075. ((= c ?\r) (throw 'exit t))
  11076. ((= c ?!)
  11077. (setq groups (not groups))
  11078. (goto-char (point-min))
  11079. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  11080. ((= c ?\C-c)
  11081. (if (not expert)
  11082. (org-fast-tag-show-exit
  11083. (setq exit-after-next (not exit-after-next)))
  11084. (setq expert nil)
  11085. (delete-other-windows)
  11086. (set-window-buffer (split-window-vertically) " *Org tags*")
  11087. (org-switch-to-buffer-other-window " *Org tags*")
  11088. (org-fit-window-to-buffer)))
  11089. ((or (= c ?\C-g)
  11090. (and (= c ?q) (not (rassoc c ntable))))
  11091. (delete-overlay org-tags-overlay)
  11092. (setq quit-flag t))
  11093. ((= c ?\ )
  11094. (setq current nil)
  11095. (when exit-after-next (setq exit-after-next 'now)))
  11096. ((= c ?\t)
  11097. (condition-case nil
  11098. (setq tg (completing-read
  11099. "Tag: "
  11100. (or buffer-tags
  11101. (with-current-buffer buf
  11102. (setq buffer-tags
  11103. (org-get-buffer-tags))))))
  11104. (quit (setq tg "")))
  11105. (when (string-match "\\S-" tg)
  11106. (cl-pushnew (list tg) buffer-tags :test #'equal)
  11107. (if (member tg current)
  11108. (setq current (delete tg current))
  11109. (push tg current)))
  11110. (when exit-after-next (setq exit-after-next 'now)))
  11111. ((setq e (rassoc c todo-table) tg (car e))
  11112. (with-current-buffer buf
  11113. (save-excursion (org-todo tg)))
  11114. (when exit-after-next (setq exit-after-next 'now)))
  11115. ((setq e (rassoc c ntable) tg (car e))
  11116. (if (member tg current)
  11117. (setq current (delete tg current))
  11118. (cl-loop for g in groups do
  11119. (when (member tg g)
  11120. (dolist (x g) (setq current (delete x current)))))
  11121. (push tg current))
  11122. (when exit-after-next (setq exit-after-next 'now))))
  11123. ;; Create a sorted list
  11124. (setq current
  11125. (sort current
  11126. (lambda (a b)
  11127. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  11128. (when (eq exit-after-next 'now) (throw 'exit t))
  11129. (goto-char (point-min))
  11130. (beginning-of-line 2)
  11131. (delete-region (point) (point-at-eol))
  11132. (org-fast-tag-insert "Current" current c-face)
  11133. (org-set-current-tags-overlay current ov-prefix)
  11134. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  11135. (while (re-search-forward tag-re nil t)
  11136. (let ((tag (match-string 1)))
  11137. (add-text-properties
  11138. (match-beginning 1) (match-end 1)
  11139. (list 'face
  11140. (cond
  11141. ((member tag current) c-face)
  11142. ((member tag inherited) i-face)
  11143. (t (get-text-property (match-beginning 1) '
  11144. face))))))))
  11145. (goto-char (point-min)))))
  11146. (delete-overlay org-tags-overlay)
  11147. (if rtn
  11148. (mapconcat 'identity current ":")
  11149. nil)))))
  11150. (defun org-make-tag-string (tags)
  11151. "Return string associated to TAGS.
  11152. TAGS is a list of strings."
  11153. (if (null tags) ""
  11154. (format ":%s:" (mapconcat #'identity tags ":"))))
  11155. (defun org--get-local-tags ()
  11156. "Return list of tags for the current headline.
  11157. Assume point is at the beginning of the headline."
  11158. (and (looking-at org-tag-line-re)
  11159. (split-string (match-string-no-properties 2) ":" t)))
  11160. (defun org-get-tags (&optional pos local)
  11161. "Get the list of tags specified in the current headline.
  11162. When argument POS is non-nil, retrieve tags for headline at POS.
  11163. According to `org-use-tag-inheritance', tags may be inherited
  11164. from parent headlines, and from the whole document, through
  11165. `org-file-tags'. In this case, the returned list of tags
  11166. contains tags in this order: file tags, tags inherited from
  11167. parent headlines, local tags. If a tag appears multiple times,
  11168. only the most local tag is returned.
  11169. However, when optional argument LOCAL is non-nil, only return
  11170. tags specified at the headline.
  11171. Inherited tags have the `inherited' text property."
  11172. (if (and org-trust-scanner-tags
  11173. (or (not pos) (eq pos (point)))
  11174. (not local))
  11175. org-scanner-tags
  11176. (org-with-point-at (or pos (point))
  11177. (unless (org-before-first-heading-p)
  11178. (org-back-to-heading t)
  11179. (let ((ltags (org--get-local-tags)) itags)
  11180. (if (or local (not org-use-tag-inheritance)) ltags
  11181. (while (org-up-heading-safe)
  11182. (setq itags (nconc (mapcar #'org-add-prop-inherited
  11183. (org--get-local-tags))
  11184. itags)))
  11185. (setq itags (append org-file-tags itags))
  11186. (nreverse
  11187. (delete-dups
  11188. (nreverse (nconc (org-remove-uninherited-tags itags) ltags))))))))))
  11189. (defun org-get-buffer-tags ()
  11190. "Get a table of all tags used in the buffer, for completion."
  11191. (org-with-point-at 1
  11192. (let (tags)
  11193. (while (re-search-forward org-tag-line-re nil t)
  11194. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  11195. tags)))
  11196. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  11197. ;;;; The mapping API
  11198. (defvar org-agenda-skip-comment-trees)
  11199. (defvar org-agenda-skip-function)
  11200. (defun org-map-entries (func &optional match scope &rest skip)
  11201. "Call FUNC at each headline selected by MATCH in SCOPE.
  11202. FUNC is a function or a lisp form. The function will be called without
  11203. arguments, with the cursor positioned at the beginning of the headline.
  11204. The return values of all calls to the function will be collected and
  11205. returned as a list.
  11206. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  11207. does not need to preserve point. After evaluation, the cursor will be
  11208. moved to the end of the line (presumably of the headline of the
  11209. processed entry) and search continues from there. Under some
  11210. circumstances, this may not produce the wanted results. For example,
  11211. if you have removed (e.g. archived) the current (sub)tree it could
  11212. mean that the next entry will be skipped entirely. In such cases, you
  11213. can specify the position from where search should continue by making
  11214. FUNC set the variable `org-map-continue-from' to the desired buffer
  11215. position.
  11216. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  11217. Only headlines that are matched by this query will be considered during
  11218. the iteration. When MATCH is nil or t, all headlines will be
  11219. visited by the iteration.
  11220. SCOPE determines the scope of this command. It can be any of:
  11221. nil The current buffer, respecting the restriction if any
  11222. tree The subtree started with the entry at point
  11223. region The entries within the active region, if any
  11224. region-start-level
  11225. The entries within the active region, but only those at
  11226. the same level than the first one.
  11227. file The current buffer, without restriction
  11228. file-with-archives
  11229. The current buffer, and any archives associated with it
  11230. agenda All agenda files
  11231. agenda-with-archives
  11232. All agenda files with any archive files associated with them
  11233. \(file1 file2 ...)
  11234. If this is a list, all files in the list will be scanned
  11235. The remaining args are treated as settings for the skipping facilities of
  11236. the scanner. The following items can be given here:
  11237. archive skip trees with the archive tag
  11238. comment skip trees with the COMMENT keyword
  11239. function or Emacs Lisp form:
  11240. will be used as value for `org-agenda-skip-function', so
  11241. whenever the function returns a position, FUNC will not be
  11242. called for that entry and search will continue from the
  11243. position returned
  11244. If your function needs to retrieve the tags including inherited tags
  11245. at the *current* entry, you can use the value of the variable
  11246. `org-scanner-tags' which will be much faster than getting the value
  11247. with `org-get-tags'. If your function gets properties with
  11248. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  11249. to t around the call to `org-entry-properties' to get the same speedup.
  11250. Note that if your function moves around to retrieve tags and properties at
  11251. a *different* entry, you cannot use these techniques."
  11252. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  11253. (not (org-region-active-p)))
  11254. (let* ((org-agenda-archives-mode nil) ; just to make sure
  11255. (org-agenda-skip-archived-trees (memq 'archive skip))
  11256. (org-agenda-skip-comment-trees (memq 'comment skip))
  11257. (org-agenda-skip-function
  11258. (car (org-delete-all '(comment archive) skip)))
  11259. (org-tags-match-list-sublevels t)
  11260. (start-level (eq scope 'region-start-level))
  11261. matcher res
  11262. org-todo-keywords-for-agenda
  11263. org-done-keywords-for-agenda
  11264. org-todo-keyword-alist-for-agenda
  11265. org-tag-alist-for-agenda
  11266. org--matcher-tags-todo-only)
  11267. (cond
  11268. ((eq match t) (setq matcher t))
  11269. ((eq match nil) (setq matcher t))
  11270. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  11271. (save-excursion
  11272. (save-restriction
  11273. (cond ((eq scope 'tree)
  11274. (org-back-to-heading t)
  11275. (org-narrow-to-subtree)
  11276. (setq scope nil))
  11277. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11278. (org-region-active-p))
  11279. ;; If needed, set start-level to a string like "2"
  11280. (when start-level
  11281. (save-excursion
  11282. (goto-char (region-beginning))
  11283. (unless (org-at-heading-p) (outline-next-heading))
  11284. (setq start-level (org-current-level))))
  11285. (narrow-to-region (region-beginning)
  11286. (save-excursion
  11287. (goto-char (region-end))
  11288. (unless (and (bolp) (org-at-heading-p))
  11289. (outline-next-heading))
  11290. (point)))
  11291. (setq scope nil)))
  11292. (if (not scope)
  11293. (progn
  11294. (org-agenda-prepare-buffers
  11295. (and buffer-file-name (list buffer-file-name)))
  11296. (setq res
  11297. (org-scan-tags
  11298. func matcher org--matcher-tags-todo-only start-level)))
  11299. ;; Get the right scope
  11300. (cond
  11301. ((and scope (listp scope) (symbolp (car scope)))
  11302. (setq scope (eval scope)))
  11303. ((eq scope 'agenda)
  11304. (setq scope (org-agenda-files t)))
  11305. ((eq scope 'agenda-with-archives)
  11306. (setq scope (org-agenda-files t))
  11307. (setq scope (org-add-archive-files scope)))
  11308. ((eq scope 'file)
  11309. (setq scope (and buffer-file-name (list buffer-file-name))))
  11310. ((eq scope 'file-with-archives)
  11311. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11312. (org-agenda-prepare-buffers scope)
  11313. (dolist (file scope)
  11314. (with-current-buffer (org-find-base-buffer-visiting file)
  11315. (org-with-wide-buffer
  11316. (goto-char (point-min))
  11317. (setq res
  11318. (append
  11319. res
  11320. (org-scan-tags
  11321. func matcher org--matcher-tags-todo-only)))))))))
  11322. res)))
  11323. ;;; Properties API
  11324. (defconst org-special-properties
  11325. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11326. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11327. "The special properties valid in Org mode.
  11328. These are properties that are not defined in the property drawer,
  11329. but in some other way.")
  11330. (defconst org-default-properties
  11331. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11332. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11333. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11334. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11335. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11336. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11337. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  11338. "Some properties that are used by Org mode for various purposes.
  11339. Being in this list makes sure that they are offered for completion.")
  11340. (defun org--valid-property-p (property)
  11341. "Non-nil when string PROPERTY is a valid property name."
  11342. (not
  11343. (or (equal property "")
  11344. (string-match-p "\\s-" property))))
  11345. (defun org--update-property-plist (key val props)
  11346. "Associate KEY to VAL in alist PROPS.
  11347. Modifications are made by side-effect. Return new alist."
  11348. (let* ((appending (string= (substring key -1) "+"))
  11349. (key (if appending (substring key 0 -1) key))
  11350. (old (assoc-string key props t)))
  11351. (if (not old) (cons (cons key val) props)
  11352. (setcdr old (if appending (concat (cdr old) " " val) val))
  11353. props)))
  11354. (defun org-get-property-block (&optional beg force)
  11355. "Return the (beg . end) range of the body of the property drawer.
  11356. BEG is the beginning of the current subtree or the beginning of
  11357. the document if before the first headline. If it is not given,
  11358. it will be found. If the drawer does not exist, create it if
  11359. FORCE is non-nil, or return nil."
  11360. (org-with-wide-buffer
  11361. (let ((beg (cond (beg (goto-char beg))
  11362. ((or (not (featurep 'org-inlinetask))
  11363. (org-inlinetask-in-task-p))
  11364. (org-back-to-heading-or-point-min t) (point))
  11365. (t (org-with-limited-levels
  11366. (org-back-to-heading-or-point-min t))
  11367. (point)))))
  11368. ;; Move point to its position according to its positional rules.
  11369. (cond ((org-before-first-heading-p)
  11370. (while (and (org-at-comment-p) (bolp)) (forward-line)))
  11371. (t (forward-line)
  11372. (when (looking-at-p org-planning-line-re) (forward-line))))
  11373. (cond ((looking-at org-property-drawer-re)
  11374. (forward-line)
  11375. (cons (point) (progn (goto-char (match-end 0))
  11376. (line-beginning-position))))
  11377. (force
  11378. (goto-char beg)
  11379. (org-insert-property-drawer)
  11380. (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  11381. (line-beginning-position))))
  11382. (cons pos pos)))))))
  11383. (defun org-at-property-drawer-p ()
  11384. "Non-nil when point is at the first line of a property drawer."
  11385. (org-with-wide-buffer
  11386. (beginning-of-line)
  11387. (and (looking-at org-property-drawer-re)
  11388. (or (bobp)
  11389. (progn
  11390. (forward-line -1)
  11391. (cond ((org-at-heading-p))
  11392. ((looking-at org-planning-line-re)
  11393. (forward-line -1)
  11394. (org-at-heading-p))
  11395. ((looking-at org-comment-regexp)
  11396. (forward-line -1)
  11397. (while (and (not (bobp)) (looking-at org-comment-regexp))
  11398. (forward-line -1))
  11399. (looking-at org-comment-regexp))
  11400. (t nil)))))))
  11401. (defun org-at-property-p ()
  11402. "Non-nil when point is inside a property drawer.
  11403. See `org-property-re' for match data, if applicable."
  11404. (save-excursion
  11405. (beginning-of-line)
  11406. (and (looking-at org-property-re)
  11407. (let ((property-drawer (save-match-data (org-get-property-block))))
  11408. (and property-drawer
  11409. (>= (point) (car property-drawer))
  11410. (< (point) (cdr property-drawer)))))))
  11411. (defun org-property-action ()
  11412. "Do an action on properties."
  11413. (interactive)
  11414. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11415. (let ((c (read-char-exclusive)))
  11416. (cl-case c
  11417. (?s (call-interactively #'org-set-property))
  11418. (?d (call-interactively #'org-delete-property))
  11419. (?D (call-interactively #'org-delete-property-globally))
  11420. (?c (call-interactively #'org-compute-property-at-point))
  11421. (otherwise (user-error "No such property action %c" c)))))
  11422. (defun org-inc-effort ()
  11423. "Increment the value of the effort property in the current entry."
  11424. (interactive)
  11425. (org-set-effort t))
  11426. (defvar org-clock-effort) ; Defined in org-clock.el.
  11427. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11428. (defun org-set-effort (&optional increment value)
  11429. "Set the effort property of the current entry.
  11430. If INCREMENT is non-nil, set the property to the next allowed
  11431. value. Otherwise, if optional argument VALUE is provided, use
  11432. it. Eventually, prompt for the new value if none of the previous
  11433. variables is set."
  11434. (interactive "P")
  11435. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11436. (current (org-entry-get nil org-effort-property))
  11437. (value
  11438. (cond
  11439. (increment
  11440. (unless allowed (user-error "Allowed effort values are not set"))
  11441. (or (cl-caadr (member (list current) allowed))
  11442. (user-error "Unknown value %S among allowed values" current)))
  11443. (value
  11444. (if (stringp value) value
  11445. (error "Invalid effort value: %S" value)))
  11446. (t
  11447. (let ((must-match
  11448. (and allowed
  11449. (not (get-text-property 0 'org-unrestricted
  11450. (caar allowed))))))
  11451. (completing-read "Effort: " allowed nil must-match))))))
  11452. ;; Test whether the value can be interpreted as a duration before
  11453. ;; inserting it in the buffer:
  11454. (org-duration-to-minutes value)
  11455. ;; Maybe update the effort value:
  11456. (unless (equal current value)
  11457. (org-entry-put nil org-effort-property value))
  11458. (org-refresh-property '((effort . identity)
  11459. (effort-minutes . org-duration-to-minutes))
  11460. value)
  11461. (when (equal (org-get-heading t t t t)
  11462. (bound-and-true-p org-clock-current-task))
  11463. (setq org-clock-effort value)
  11464. (org-clock-update-mode-line))
  11465. (message "%s is now %s" org-effort-property value)))
  11466. (defun org-entry-properties (&optional pom which)
  11467. "Get all properties of the current entry.
  11468. When POM is a buffer position, get all properties from the entry
  11469. there instead.
  11470. This includes the TODO keyword, the tags, time strings for
  11471. deadline, scheduled, and clocking, and any additional properties
  11472. defined in the entry.
  11473. If WHICH is nil or `all', get all properties. If WHICH is
  11474. `special' or `standard', only get that subclass. If WHICH is
  11475. a string, only get that property.
  11476. Return value is an alist. Keys are properties, as upcased
  11477. strings."
  11478. (org-with-point-at pom
  11479. (when (and (derived-mode-p 'org-mode)
  11480. (org-back-to-heading-or-point-min t))
  11481. (catch 'exit
  11482. (let* ((beg (point))
  11483. (specific (and (stringp which) (upcase which)))
  11484. (which (cond ((not specific) which)
  11485. ((member specific org-special-properties) 'special)
  11486. (t 'standard)))
  11487. props)
  11488. ;; Get the special properties, like TODO and TAGS.
  11489. (when (memq which '(nil all special))
  11490. (when (or (not specific) (string= specific "CLOCKSUM"))
  11491. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11492. (when clocksum
  11493. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11494. props)))
  11495. (when specific (throw 'exit props)))
  11496. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11497. (let ((clocksumt (get-text-property (point)
  11498. :org-clock-minutes-today)))
  11499. (when clocksumt
  11500. (push (cons "CLOCKSUM_T"
  11501. (org-duration-from-minutes clocksumt))
  11502. props)))
  11503. (when specific (throw 'exit props)))
  11504. (when (or (not specific) (string= specific "ITEM"))
  11505. (let ((case-fold-search nil))
  11506. (when (looking-at org-complex-heading-regexp)
  11507. (push (cons "ITEM"
  11508. (let ((title (match-string-no-properties 4)))
  11509. (if (org-string-nw-p title)
  11510. (org-remove-tabs title)
  11511. "")))
  11512. props)))
  11513. (when specific (throw 'exit props)))
  11514. (when (or (not specific) (string= specific "TODO"))
  11515. (let ((case-fold-search nil))
  11516. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11517. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11518. (when specific (throw 'exit props)))
  11519. (when (or (not specific) (string= specific "PRIORITY"))
  11520. (push (cons "PRIORITY"
  11521. (if (looking-at org-priority-regexp)
  11522. (match-string-no-properties 2)
  11523. (char-to-string org-priority-default)))
  11524. props)
  11525. (when specific (throw 'exit props)))
  11526. (when (or (not specific) (string= specific "FILE"))
  11527. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11528. props)
  11529. (when specific (throw 'exit props)))
  11530. (when (or (not specific) (string= specific "TAGS"))
  11531. (let ((tags (org-get-tags nil t)))
  11532. (when tags
  11533. (push (cons "TAGS" (org-make-tag-string tags))
  11534. props)))
  11535. (when specific (throw 'exit props)))
  11536. (when (or (not specific) (string= specific "ALLTAGS"))
  11537. (let ((tags (org-get-tags)))
  11538. (when tags
  11539. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11540. props)))
  11541. (when specific (throw 'exit props)))
  11542. (when (or (not specific) (string= specific "BLOCKED"))
  11543. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11544. (when specific (throw 'exit props)))
  11545. (when (or (not specific)
  11546. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11547. (forward-line)
  11548. (when (looking-at-p org-planning-line-re)
  11549. (end-of-line)
  11550. (let ((bol (line-beginning-position))
  11551. ;; Backward compatibility: time keywords used to
  11552. ;; be configurable (before 8.3). Make sure we
  11553. ;; get the correct keyword.
  11554. (key-assoc `(("CLOSED" . ,org-closed-string)
  11555. ("DEADLINE" . ,org-deadline-string)
  11556. ("SCHEDULED" . ,org-scheduled-string))))
  11557. (dolist (pair (if specific (list (assoc specific key-assoc))
  11558. key-assoc))
  11559. (save-excursion
  11560. (when (search-backward (cdr pair) bol t)
  11561. (goto-char (match-end 0))
  11562. (skip-chars-forward " \t")
  11563. (and (looking-at org-ts-regexp-both)
  11564. (push (cons (car pair)
  11565. (match-string-no-properties 0))
  11566. props)))))))
  11567. (when specific (throw 'exit props)))
  11568. (when (or (not specific)
  11569. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11570. (let ((find-ts
  11571. (lambda (end ts)
  11572. ;; Fix next time-stamp before END. TS is the
  11573. ;; list of time-stamps found so far.
  11574. (let ((ts ts)
  11575. (regexp (cond
  11576. ((string= specific "TIMESTAMP")
  11577. org-ts-regexp)
  11578. ((string= specific "TIMESTAMP_IA")
  11579. org-ts-regexp-inactive)
  11580. ((assoc "TIMESTAMP_IA" ts)
  11581. org-ts-regexp)
  11582. ((assoc "TIMESTAMP" ts)
  11583. org-ts-regexp-inactive)
  11584. (t org-ts-regexp-both))))
  11585. (catch 'next
  11586. (while (re-search-forward regexp end t)
  11587. (backward-char)
  11588. (let ((object (org-element-context)))
  11589. ;; Accept to match timestamps in node
  11590. ;; properties, too.
  11591. (when (memq (org-element-type object)
  11592. '(node-property timestamp))
  11593. (let ((type
  11594. (org-element-property :type object)))
  11595. (cond
  11596. ((and (memq type '(active active-range))
  11597. (not (equal specific "TIMESTAMP_IA")))
  11598. (unless (assoc "TIMESTAMP" ts)
  11599. (push (cons "TIMESTAMP"
  11600. (org-element-property
  11601. :raw-value object))
  11602. ts)
  11603. (when specific (throw 'exit ts))))
  11604. ((and (memq type '(inactive inactive-range))
  11605. (not (string= specific "TIMESTAMP")))
  11606. (unless (assoc "TIMESTAMP_IA" ts)
  11607. (push (cons "TIMESTAMP_IA"
  11608. (org-element-property
  11609. :raw-value object))
  11610. ts)
  11611. (when specific (throw 'exit ts))))))
  11612. ;; Both timestamp types are found,
  11613. ;; move to next part.
  11614. (when (= (length ts) 2) (throw 'next ts)))))
  11615. ts)))))
  11616. (goto-char beg)
  11617. ;; First look for timestamps within headline.
  11618. (let ((ts (funcall find-ts (line-end-position) nil)))
  11619. (if (= (length ts) 2) (setq props (nconc ts props))
  11620. ;; Then find timestamps in the section, skipping
  11621. ;; planning line.
  11622. (let ((end (save-excursion (outline-next-heading))))
  11623. (forward-line)
  11624. (when (looking-at-p org-planning-line-re) (forward-line))
  11625. (setq props (nconc (funcall find-ts end ts) props))))))))
  11626. ;; Get the standard properties, like :PROP:.
  11627. (when (memq which '(nil all standard))
  11628. ;; If we are looking after a specific property, delegate
  11629. ;; to `org-entry-get', which is faster. However, make an
  11630. ;; exception for "CATEGORY", since it can be also set
  11631. ;; through keywords (i.e. #+CATEGORY).
  11632. (if (and specific (not (equal specific "CATEGORY")))
  11633. (let ((value (org-entry-get beg specific nil t)))
  11634. (throw 'exit (and value (list (cons specific value)))))
  11635. (let ((range (org-get-property-block beg)))
  11636. (when range
  11637. (let ((end (cdr range)) seen-base)
  11638. (goto-char (car range))
  11639. ;; Unlike to `org--update-property-plist', we
  11640. ;; handle the case where base values is found
  11641. ;; after its extension. We also forbid standard
  11642. ;; properties to be named as special properties.
  11643. (while (re-search-forward org-property-re end t)
  11644. (let* ((key (upcase (match-string-no-properties 2)))
  11645. (extendp (string-match-p "\\+\\'" key))
  11646. (key-base (if extendp (substring key 0 -1) key))
  11647. (value (match-string-no-properties 3)))
  11648. (cond
  11649. ((member-ignore-case key-base org-special-properties))
  11650. (extendp
  11651. (setq props
  11652. (org--update-property-plist key value props)))
  11653. ((member key seen-base))
  11654. (t (push key seen-base)
  11655. (let ((p (assoc-string key props t)))
  11656. (if p (setcdr p (concat value " " (cdr p)))
  11657. (push (cons key value) props))))))))))))
  11658. (unless (assoc "CATEGORY" props)
  11659. (push (cons "CATEGORY" (org-get-category beg)) props)
  11660. (when (string= specific "CATEGORY") (throw 'exit props)))
  11661. ;; Return value.
  11662. props)))))
  11663. (defun org--property-local-values (property literal-nil)
  11664. "Return value for PROPERTY in current entry.
  11665. Value is a list whose car is the base value for PROPERTY and cdr
  11666. a list of accumulated values. Return nil if neither is found in
  11667. the entry. Also return nil when PROPERTY is set to \"nil\",
  11668. unless LITERAL-NIL is non-nil."
  11669. (let ((range (org-get-property-block)))
  11670. (when range
  11671. (goto-char (car range))
  11672. (let* ((case-fold-search t)
  11673. (end (cdr range))
  11674. (value
  11675. ;; Base value.
  11676. (save-excursion
  11677. (let ((v (and (re-search-forward
  11678. (org-re-property property nil t) end t)
  11679. (match-string-no-properties 3))))
  11680. (list (if literal-nil v (org-not-nil v)))))))
  11681. ;; Find additional values.
  11682. (let* ((property+ (org-re-property (concat property "+") nil t)))
  11683. (while (re-search-forward property+ end t)
  11684. (push (match-string-no-properties 3) value)))
  11685. ;; Return final values.
  11686. (and (not (equal value '(nil))) (nreverse value))))))
  11687. (defun org--property-global-or-keyword-value (property literal-nil)
  11688. "Return value for PROPERTY as defined by global properties or by keyword.
  11689. Return value is a string. Return nil if property is not set
  11690. globally or by keyword. Also return nil when PROPERTY is set to
  11691. \"nil\", unless LITERAL-NIL is non-nil."
  11692. (let ((global
  11693. (cdr (or (assoc-string property org-keyword-properties t)
  11694. (assoc-string property org-global-properties t)
  11695. (assoc-string property org-global-properties-fixed t)))))
  11696. (if literal-nil global (org-not-nil global))))
  11697. (defun org-entry-get (pom property &optional inherit literal-nil)
  11698. "Get value of PROPERTY for entry or content at point-or-marker POM.
  11699. If INHERIT is non-nil and the entry does not have the property,
  11700. then also check higher levels of the hierarchy. If INHERIT is
  11701. the symbol `selective', use inheritance only if the setting in
  11702. `org-use-property-inheritance' selects PROPERTY for inheritance.
  11703. If the property is present but empty, the return value is the
  11704. empty string. If the property is not present at all, nil is
  11705. returned. In any other case, return the value as a string.
  11706. Search is case-insensitive.
  11707. If LITERAL-NIL is set, return the string value \"nil\" as
  11708. a string, do not interpret it as the list atom nil. This is used
  11709. for inheritance when a \"nil\" value can supersede a non-nil
  11710. value higher up the hierarchy."
  11711. (org-with-point-at pom
  11712. (cond
  11713. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  11714. ;; We need a special property. Use `org-entry-properties' to
  11715. ;; retrieve it, but specify the wanted property.
  11716. (cdr (assoc-string property (org-entry-properties nil property))))
  11717. ((and inherit
  11718. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  11719. (org-entry-get-with-inheritance property literal-nil))
  11720. (t
  11721. (let* ((local (org--property-local-values property literal-nil))
  11722. (value (and local (mapconcat #'identity (delq nil local) " "))))
  11723. (if literal-nil value (org-not-nil value)))))))
  11724. (defun org-property-or-variable-value (var &optional inherit)
  11725. "Check if there is a property fixing the value of VAR.
  11726. If yes, return this value. If not, return the current value of the variable."
  11727. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  11728. (if (and prop (stringp prop) (string-match "\\S-" prop))
  11729. (read prop)
  11730. (symbol-value var))))
  11731. (defun org-entry-delete (pom property)
  11732. "Delete PROPERTY from entry at point-or-marker POM.
  11733. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  11734. non-nil when a property was removed."
  11735. (org-with-point-at pom
  11736. (pcase (org-get-property-block)
  11737. (`(,begin . ,origin)
  11738. (let* ((end (copy-marker origin))
  11739. (re (org-re-property
  11740. (concat (regexp-quote property) "\\+?") t t)))
  11741. (goto-char begin)
  11742. (while (re-search-forward re end t)
  11743. (delete-region (match-beginning 0) (line-beginning-position 2)))
  11744. ;; If drawer is empty, remove it altogether.
  11745. (when (= begin end)
  11746. (delete-region (line-beginning-position 0)
  11747. (line-beginning-position 2)))
  11748. ;; Return non-nil if some property was removed.
  11749. (prog1 (/= end origin) (set-marker end nil))))
  11750. (_ nil))))
  11751. ;; Multi-values properties are properties that contain multiple values
  11752. ;; These values are assumed to be single words, separated by whitespace.
  11753. (defun org-entry-add-to-multivalued-property (pom property value)
  11754. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  11755. (let* ((old (org-entry-get pom property))
  11756. (values (and old (split-string old))))
  11757. (setq value (org-entry-protect-space value))
  11758. (unless (member value values)
  11759. (setq values (append values (list value)))
  11760. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11761. (defun org-entry-remove-from-multivalued-property (pom property value)
  11762. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  11763. (let* ((old (org-entry-get pom property))
  11764. (values (and old (split-string old))))
  11765. (setq value (org-entry-protect-space value))
  11766. (when (member value values)
  11767. (setq values (delete value values))
  11768. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11769. (defun org-entry-member-in-multivalued-property (pom property value)
  11770. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  11771. (let* ((old (org-entry-get pom property))
  11772. (values (and old (split-string old))))
  11773. (setq value (org-entry-protect-space value))
  11774. (member value values)))
  11775. (defun org-entry-get-multivalued-property (pom property)
  11776. "Return a list of values in a multivalued property."
  11777. (let* ((value (org-entry-get pom property))
  11778. (values (and value (split-string value))))
  11779. (mapcar #'org-entry-restore-space values)))
  11780. (defun org-entry-put-multivalued-property (pom property &rest values)
  11781. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  11782. VALUES should be a list of strings. Spaces will be protected."
  11783. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  11784. (let* ((value (org-entry-get pom property))
  11785. (values (and value (split-string value))))
  11786. (mapcar #'org-entry-restore-space values)))
  11787. (defun org-entry-protect-space (s)
  11788. "Protect spaces and newline in string S."
  11789. (while (string-match " " s)
  11790. (setq s (replace-match "%20" t t s)))
  11791. (while (string-match "\n" s)
  11792. (setq s (replace-match "%0A" t t s)))
  11793. s)
  11794. (defun org-entry-restore-space (s)
  11795. "Restore spaces and newline in string S."
  11796. (while (string-match "%20" s)
  11797. (setq s (replace-match " " t t s)))
  11798. (while (string-match "%0A" s)
  11799. (setq s (replace-match "\n" t t s)))
  11800. s)
  11801. (defvar org-entry-property-inherited-from (make-marker)
  11802. "Marker pointing to the entry from where a property was inherited.
  11803. Each call to `org-entry-get-with-inheritance' will set this marker to the
  11804. location of the entry where the inheritance search matched. If there was
  11805. no match, the marker will point nowhere.
  11806. Note that also `org-entry-get' calls this function, if the INHERIT flag
  11807. is set.")
  11808. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  11809. "Get PROPERTY of entry or content at point, search higher levels if needed.
  11810. The search will stop at the first ancestor which has the property defined.
  11811. If the value found is \"nil\", return nil to show that the property
  11812. should be considered as undefined (this is the meaning of nil here).
  11813. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  11814. (move-marker org-entry-property-inherited-from nil)
  11815. (org-with-wide-buffer
  11816. (let (value)
  11817. (catch 'exit
  11818. (while t
  11819. (let ((v (org--property-local-values property literal-nil)))
  11820. (when v
  11821. (setq value
  11822. (concat (mapconcat #'identity (delq nil v) " ")
  11823. (and value " ")
  11824. value)))
  11825. (cond
  11826. ((car v)
  11827. (org-back-to-heading-or-point-min t)
  11828. (move-marker org-entry-property-inherited-from (point))
  11829. (throw 'exit nil))
  11830. ((org-up-heading-or-point-min))
  11831. (t
  11832. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11833. (cond ((not global))
  11834. (value (setq value (concat global " " value)))
  11835. (t (setq value global))))
  11836. (throw 'exit nil))))))
  11837. (if literal-nil value (org-not-nil value)))))
  11838. (defvar org-property-changed-functions nil
  11839. "Hook called when the value of a property has changed.
  11840. Each hook function should accept two arguments, the name of the property
  11841. and the new value.")
  11842. (defun org-entry-put (pom property value)
  11843. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  11844. If the value is nil, it is converted to the empty string. If it
  11845. is not a string, an error is raised. Also raise an error on
  11846. invalid property names.
  11847. PROPERTY can be any regular property (see
  11848. `org-special-properties'). It can also be \"TODO\",
  11849. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  11850. For the last two properties, VALUE may have any of the special
  11851. values \"earlier\" and \"later\". The function then increases or
  11852. decreases scheduled or deadline date by one day."
  11853. (cond ((null value) (setq value ""))
  11854. ((not (stringp value)) (error "Properties values should be strings"))
  11855. ((not (org--valid-property-p property))
  11856. (user-error "Invalid property name: \"%s\"" property)))
  11857. (org-with-point-at pom
  11858. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11859. (org-back-to-heading-or-point-min t)
  11860. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11861. (let ((beg (point)))
  11862. (cond
  11863. ((equal property "TODO")
  11864. (cond ((not (org-string-nw-p value)) (setq value 'none))
  11865. ((not (member value org-todo-keywords-1))
  11866. (user-error "\"%s\" is not a valid TODO state" value)))
  11867. (org-todo value)
  11868. (org-align-tags))
  11869. ((equal property "PRIORITY")
  11870. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  11871. (org-align-tags))
  11872. ((equal property "SCHEDULED")
  11873. (forward-line)
  11874. (if (and (looking-at-p org-planning-line-re)
  11875. (re-search-forward
  11876. org-scheduled-time-regexp (line-end-position) t))
  11877. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11878. ((string= value "later") (org-timestamp-change 1 'day))
  11879. ((string= value "") (org-schedule '(4)))
  11880. (t (org-schedule nil value)))
  11881. (if (member value '("earlier" "later" ""))
  11882. (call-interactively #'org-schedule)
  11883. (org-schedule nil value))))
  11884. ((equal property "DEADLINE")
  11885. (forward-line)
  11886. (if (and (looking-at-p org-planning-line-re)
  11887. (re-search-forward
  11888. org-deadline-time-regexp (line-end-position) t))
  11889. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11890. ((string= value "later") (org-timestamp-change 1 'day))
  11891. ((string= value "") (org-deadline '(4)))
  11892. (t (org-deadline nil value)))
  11893. (if (member value '("earlier" "later" ""))
  11894. (call-interactively #'org-deadline)
  11895. (org-deadline nil value))))
  11896. ((member property org-special-properties)
  11897. (error "The %s property cannot be set with `org-entry-put'" property))
  11898. (t
  11899. (let* ((range (org-get-property-block beg 'force))
  11900. (end (cdr range))
  11901. (case-fold-search t))
  11902. (goto-char (car range))
  11903. (if (re-search-forward (org-re-property property nil t) end t)
  11904. (progn (delete-region (match-beginning 0) (match-end 0))
  11905. (goto-char (match-beginning 0)))
  11906. (goto-char end)
  11907. (insert "\n")
  11908. (backward-char))
  11909. (insert ":" property ":")
  11910. (when value (insert " " value))
  11911. (org-indent-line)))))
  11912. (run-hook-with-args 'org-property-changed-functions property value)))
  11913. (defun org-buffer-property-keys (&optional specials defaults columns)
  11914. "Get all property keys in the current buffer.
  11915. When SPECIALS is non-nil, also list the special properties that
  11916. reflect things like tags and TODO state.
  11917. When DEFAULTS is non-nil, also include properties that has
  11918. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  11919. DESCRIPTION, LOCATION, and LOGGING and others.
  11920. When COLUMNS in non-nil, also include property names given in
  11921. COLUMN formats in the current buffer."
  11922. (let ((case-fold-search t)
  11923. (props (append
  11924. (and specials org-special-properties)
  11925. (and defaults (cons org-effort-property org-default-properties))
  11926. ;; Get property names from #+PROPERTY keywords as well
  11927. (mapcar (lambda (s)
  11928. (nth 0 (split-string s)))
  11929. (cdar (org-collect-keywords '("PROPERTY")))))))
  11930. (org-with-wide-buffer
  11931. (goto-char (point-min))
  11932. (while (re-search-forward org-property-start-re nil t)
  11933. (catch :skip
  11934. (let ((range (org-get-property-block)))
  11935. (unless range (throw :skip nil))
  11936. (goto-char (car range))
  11937. (let ((begin (car range))
  11938. (end (cdr range)))
  11939. ;; Make sure that found property block is not located
  11940. ;; before current point, as it would generate an infloop.
  11941. ;; It can happen, for example, in the following
  11942. ;; situation:
  11943. ;;
  11944. ;; * Headline
  11945. ;; :PROPERTIES:
  11946. ;; ...
  11947. ;; :END:
  11948. ;; *************** Inlinetask
  11949. ;; #+BEGIN_EXAMPLE
  11950. ;; :PROPERTIES:
  11951. ;; #+END_EXAMPLE
  11952. ;;
  11953. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  11954. (while (< (point) end)
  11955. (let ((p (progn (looking-at org-property-re)
  11956. (match-string-no-properties 2))))
  11957. ;; Only add true property name, not extension symbol.
  11958. (push (if (not (string-match-p "\\+\\'" p)) p
  11959. (substring p 0 -1))
  11960. props))
  11961. (forward-line))))
  11962. (outline-next-heading)))
  11963. (when columns
  11964. (goto-char (point-min))
  11965. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  11966. (let ((element (org-element-at-point)))
  11967. (when (memq (org-element-type element) '(keyword node-property))
  11968. (let ((value (org-element-property :value element))
  11969. (start 0))
  11970. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  11971. \\(?:{[^}]+}\\)?"
  11972. value start)
  11973. (setq start (match-end 0))
  11974. (let ((p (match-string-no-properties 1 value)))
  11975. (unless (member-ignore-case p org-special-properties)
  11976. (push p props))))))))))
  11977. (sort (delete-dups
  11978. (append props
  11979. ;; for each xxx_ALL property, make sure the bare
  11980. ;; xxx property is also included
  11981. (delq nil (mapcar (lambda (p)
  11982. (and (string-match-p "._ALL\\'" p)
  11983. (substring p 0 -4)))
  11984. props))))
  11985. (lambda (a b) (string< (upcase a) (upcase b))))))
  11986. (defun org-property-values (key)
  11987. "List all non-nil values of property KEY in current buffer."
  11988. (org-with-wide-buffer
  11989. (goto-char (point-min))
  11990. (let ((case-fold-search t)
  11991. (re (org-re-property key))
  11992. values)
  11993. (while (re-search-forward re nil t)
  11994. (push (org-entry-get (point) key) values))
  11995. (delete-dups values))))
  11996. (defun org-insert-property-drawer ()
  11997. "Insert a property drawer into the current entry.
  11998. Do nothing if the drawer already exists. The newly created
  11999. drawer is immediately hidden."
  12000. (org-with-wide-buffer
  12001. ;; Set point to the position where the drawer should be inserted.
  12002. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12003. (org-back-to-heading-or-point-min t)
  12004. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  12005. (if (org-before-first-heading-p)
  12006. (while (and (org-at-comment-p) (bolp)) (forward-line))
  12007. (progn
  12008. (forward-line)
  12009. (when (looking-at-p org-planning-line-re) (forward-line))))
  12010. (unless (looking-at-p org-property-drawer-re)
  12011. ;; Make sure we start editing a line from current entry, not from
  12012. ;; next one. It prevents extending text properties or overlays
  12013. ;; belonging to the latter.
  12014. (when (and (bolp) (> (point) (point-min))) (backward-char))
  12015. (let ((begin (if (bobp) (point) (1+ (point))))
  12016. (inhibit-read-only t))
  12017. (unless (bobp) (insert "\n"))
  12018. (insert ":PROPERTIES:\n:END:")
  12019. (org-flag-region (line-end-position 0) (point) t 'outline)
  12020. (when (or (eobp) (= begin (point-min))) (insert "\n"))
  12021. (org-indent-region begin (point))))))
  12022. (defun org-insert-drawer (&optional arg drawer)
  12023. "Insert a drawer at point.
  12024. When optional argument ARG is non-nil, insert a property drawer.
  12025. Optional argument DRAWER, when non-nil, is a string representing
  12026. drawer's name. Otherwise, the user is prompted for a name.
  12027. If a region is active, insert the drawer around that region
  12028. instead.
  12029. Point is left between drawer's boundaries."
  12030. (interactive "P")
  12031. (let* ((drawer (if arg "PROPERTIES"
  12032. (or drawer (read-from-minibuffer "Drawer: ")))))
  12033. (cond
  12034. ;; With C-u, fall back on `org-insert-property-drawer'
  12035. (arg (org-insert-property-drawer))
  12036. ;; Check validity of suggested drawer's name.
  12037. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  12038. (user-error "Invalid drawer name"))
  12039. ;; With an active region, insert a drawer at point.
  12040. ((not (org-region-active-p))
  12041. (progn
  12042. (unless (bolp) (insert "\n"))
  12043. (insert (format ":%s:\n\n:END:\n" drawer))
  12044. (forward-line -2)))
  12045. ;; Otherwise, insert the drawer at point
  12046. (t
  12047. (let ((rbeg (region-beginning))
  12048. (rend (copy-marker (region-end))))
  12049. (unwind-protect
  12050. (progn
  12051. (goto-char rbeg)
  12052. (beginning-of-line)
  12053. (when (save-excursion
  12054. (re-search-forward org-outline-regexp-bol rend t))
  12055. (user-error "Drawers cannot contain headlines"))
  12056. ;; Position point at the beginning of the first
  12057. ;; non-blank line in region. Insert drawer's opening
  12058. ;; there, then indent it.
  12059. (org-skip-whitespace)
  12060. (beginning-of-line)
  12061. (insert ":" drawer ":\n")
  12062. (forward-line -1)
  12063. (indent-for-tab-command)
  12064. ;; Move point to the beginning of the first blank line
  12065. ;; after the last non-blank line in region. Insert
  12066. ;; drawer's closing, then indent it.
  12067. (goto-char rend)
  12068. (skip-chars-backward " \r\t\n")
  12069. (insert "\n:END:")
  12070. (deactivate-mark t)
  12071. (indent-for-tab-command)
  12072. (unless (eolp) (insert "\n")))
  12073. ;; Clear marker, whatever the outcome of insertion is.
  12074. (set-marker rend nil)))))))
  12075. (defvar org-property-set-functions-alist nil
  12076. "Property set function alist.
  12077. Each entry should have the following format:
  12078. (PROPERTY . READ-FUNCTION)
  12079. The read function will be called with the same argument as
  12080. `org-completing-read'.")
  12081. (defun org-set-property-function (property)
  12082. "Get the function that should be used to set PROPERTY.
  12083. This is computed according to `org-property-set-functions-alist'."
  12084. (or (cdr (assoc property org-property-set-functions-alist))
  12085. 'org-completing-read))
  12086. (defun org-read-property-value (property &optional pom)
  12087. "Read value for PROPERTY, as a string.
  12088. When optional argument POM is non-nil, completion uses additional
  12089. information, i.e., allowed or existing values at point or marker
  12090. POM."
  12091. (let* ((completion-ignore-case t)
  12092. (allowed
  12093. (or (org-property-get-allowed-values nil property 'table)
  12094. (and pom (org-property-get-allowed-values pom property 'table))))
  12095. (current (org-entry-get nil property))
  12096. (prompt (format "%s value%s: "
  12097. property
  12098. (if (org-string-nw-p current)
  12099. (format " [%s]" current)
  12100. "")))
  12101. (set-function (org-set-property-function property)))
  12102. (org-trim
  12103. (if allowed
  12104. (funcall set-function
  12105. prompt allowed nil
  12106. (not (get-text-property 0 'org-unrestricted (caar allowed))))
  12107. (let ((all (mapcar #'list
  12108. (append (org-property-values property)
  12109. (and pom
  12110. (org-with-point-at pom
  12111. (org-property-values property)))))))
  12112. (funcall set-function prompt all nil nil "" nil current))))))
  12113. (defvar org-last-set-property nil)
  12114. (defvar org-last-set-property-value nil)
  12115. (defun org-read-property-name ()
  12116. "Read a property name."
  12117. (let ((completion-ignore-case t)
  12118. (default-prop (or (and (org-at-property-p)
  12119. (match-string-no-properties 2))
  12120. org-last-set-property)))
  12121. (org-completing-read
  12122. (concat "Property"
  12123. (if default-prop (concat " [" default-prop "]") "")
  12124. ": ")
  12125. (mapcar #'list (org-buffer-property-keys nil t t))
  12126. nil nil nil nil default-prop)))
  12127. (defun org-set-property-and-value (use-last)
  12128. "Allow to set [PROPERTY]: [value] direction from prompt.
  12129. When use-default, don't even ask, just use the last
  12130. \"[PROPERTY]: [value]\" string from the history."
  12131. (interactive "P")
  12132. (let* ((completion-ignore-case t)
  12133. (pv (or (and use-last org-last-set-property-value)
  12134. (org-completing-read
  12135. "Enter a \"[Property]: [value]\" pair: "
  12136. nil nil nil nil nil
  12137. org-last-set-property-value)))
  12138. prop val)
  12139. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  12140. (setq prop (match-string 1 pv)
  12141. val (match-string 2 pv))
  12142. (org-set-property prop val))))
  12143. (defun org-set-property (property value)
  12144. "In the current entry, set PROPERTY to VALUE.
  12145. When called interactively, this will prompt for a property name, offering
  12146. completion on existing and default properties. And then it will prompt
  12147. for a value, offering completion either on allowed values (via an inherited
  12148. xxx_ALL property) or on existing values in other instances of this property
  12149. in the current file.
  12150. Throw an error when trying to set a property with an invalid name."
  12151. (interactive (list nil nil))
  12152. (let ((property (or property (org-read-property-name))))
  12153. ;; `org-entry-put' also makes the following check, but this one
  12154. ;; avoids polluting `org-last-set-property' and
  12155. ;; `org-last-set-property-value' needlessly.
  12156. (unless (org--valid-property-p property)
  12157. (user-error "Invalid property name: \"%s\"" property))
  12158. (let ((value (or value (org-read-property-value property)))
  12159. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  12160. (setq org-last-set-property property)
  12161. (setq org-last-set-property-value (concat property ": " value))
  12162. ;; Possibly postprocess the inserted value:
  12163. (when fn (setq value (funcall fn value)))
  12164. (unless (equal (org-entry-get nil property) value)
  12165. (org-entry-put nil property value)))))
  12166. (defun org-find-property (property &optional value)
  12167. "Find first entry in buffer that sets PROPERTY.
  12168. When optional argument VALUE is non-nil, only consider an entry
  12169. if it contains PROPERTY set to this value. If PROPERTY should be
  12170. explicitly set to nil, use string \"nil\" for VALUE.
  12171. Return position where the entry begins, or nil if there is no
  12172. such entry. If narrowing is in effect, only search the visible
  12173. part of the buffer."
  12174. (save-excursion
  12175. (goto-char (point-min))
  12176. (let ((case-fold-search t)
  12177. (re (org-re-property property nil (not value) value)))
  12178. (catch 'exit
  12179. (while (re-search-forward re nil t)
  12180. (when (if value (org-at-property-p)
  12181. (org-entry-get (point) property nil t))
  12182. (throw 'exit (progn (org-back-to-heading-or-point-min t)
  12183. (point)))))))))
  12184. (defun org-delete-property (property)
  12185. "In the current entry, delete PROPERTY."
  12186. (interactive
  12187. (let* ((completion-ignore-case t)
  12188. (cat (org-entry-get (point) "CATEGORY"))
  12189. (props0 (org-entry-properties nil 'standard))
  12190. (props (if cat props0
  12191. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  12192. (prop (if (< 1 (length props))
  12193. (completing-read "Property: " props nil t)
  12194. (caar props))))
  12195. (list prop)))
  12196. (if (not property)
  12197. (message "No property to delete in this entry")
  12198. (org-entry-delete nil property)
  12199. (message "Property \"%s\" deleted" property)))
  12200. (defun org-delete-property-globally (property)
  12201. "Remove PROPERTY globally, from all entries.
  12202. This function ignores narrowing, if any."
  12203. (interactive
  12204. (let* ((completion-ignore-case t)
  12205. (prop (completing-read
  12206. "Globally remove property: "
  12207. (mapcar #'list (org-buffer-property-keys)))))
  12208. (list prop)))
  12209. (org-with-wide-buffer
  12210. (goto-char (point-min))
  12211. (let ((count 0)
  12212. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  12213. (while (re-search-forward re nil t)
  12214. (when (org-entry-delete (point) property) (cl-incf count)))
  12215. (message "Property \"%s\" removed from %d entries" property count))))
  12216. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  12217. (defun org-compute-property-at-point ()
  12218. "Compute the property at point.
  12219. This looks for an enclosing column format, extracts the operator and
  12220. then applies it to the property in the column format's scope."
  12221. (interactive)
  12222. (unless (org-at-property-p)
  12223. (user-error "Not at a property"))
  12224. (let ((prop (match-string-no-properties 2)))
  12225. (org-columns-get-format-and-top-level)
  12226. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  12227. (user-error "No operator defined for property %s" prop))
  12228. (org-columns-compute prop)))
  12229. (defvar org-property-allowed-value-functions nil
  12230. "Hook for functions supplying allowed values for a specific property.
  12231. The functions must take a single argument, the name of the property, and
  12232. return a flat list of allowed values. If \":ETC\" is one of
  12233. the values, this means that these values are intended as defaults for
  12234. completion, but that other values should be allowed too.
  12235. The functions must return nil if they are not responsible for this
  12236. property.")
  12237. (defun org-property-get-allowed-values (pom property &optional table)
  12238. "Get allowed values for the property PROPERTY.
  12239. When TABLE is non-nil, return an alist that can directly be used for
  12240. completion."
  12241. (let (vals)
  12242. (cond
  12243. ((equal property "TODO")
  12244. (setq vals (org-with-point-at pom
  12245. (append org-todo-keywords-1 '("")))))
  12246. ((equal property "PRIORITY")
  12247. (let ((n org-priority-lowest))
  12248. (while (>= n org-priority-highest)
  12249. (push (char-to-string n) vals)
  12250. (setq n (1- n)))))
  12251. ((equal property "CATEGORY"))
  12252. ((member property org-special-properties))
  12253. ((setq vals (run-hook-with-args-until-success
  12254. 'org-property-allowed-value-functions property)))
  12255. (t
  12256. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  12257. (when (and vals (string-match "\\S-" vals))
  12258. (setq vals (car (read-from-string (concat "(" vals ")"))))
  12259. (setq vals (mapcar (lambda (x)
  12260. (cond ((stringp x) x)
  12261. ((numberp x) (number-to-string x))
  12262. ((symbolp x) (symbol-name x))
  12263. (t "???")))
  12264. vals)))))
  12265. (when (member ":ETC" vals)
  12266. (setq vals (remove ":ETC" vals))
  12267. (org-add-props (car vals) '(org-unrestricted t)))
  12268. (if table (mapcar 'list vals) vals)))
  12269. (defun org-property-previous-allowed-value (&optional _previous)
  12270. "Switch to the next allowed value for this property."
  12271. (interactive)
  12272. (org-property-next-allowed-value t))
  12273. (defun org-property-next-allowed-value (&optional previous)
  12274. "Switch to the next allowed value for this property."
  12275. (interactive)
  12276. (unless (org-at-property-p)
  12277. (user-error "Not at a property"))
  12278. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  12279. (key (match-string 2))
  12280. (value (match-string 3))
  12281. (allowed (or (org-property-get-allowed-values (point) key)
  12282. (and (member value '("[ ]" "[-]" "[X]"))
  12283. '("[ ]" "[X]"))))
  12284. (heading (save-match-data (nth 4 (org-heading-components))))
  12285. nval)
  12286. (unless allowed
  12287. (user-error "Allowed values for this property have not been defined"))
  12288. (when previous (setq allowed (reverse allowed)))
  12289. (when (member value allowed)
  12290. (setq nval (car (cdr (member value allowed)))))
  12291. (setq nval (or nval (car allowed)))
  12292. (when (equal nval value)
  12293. (user-error "Only one allowed value for this property"))
  12294. (org-at-property-p)
  12295. (replace-match (concat " :" key ": " nval) t t)
  12296. (org-indent-line)
  12297. (beginning-of-line 1)
  12298. (skip-chars-forward " \t")
  12299. (when (equal prop org-effort-property)
  12300. (org-refresh-property
  12301. '((effort . identity)
  12302. (effort-minutes . org-duration-to-minutes))
  12303. nval)
  12304. (when (string= org-clock-current-task heading)
  12305. (setq org-clock-effort nval)
  12306. (org-clock-update-mode-line)))
  12307. (run-hook-with-args 'org-property-changed-functions key nval)))
  12308. (defun org-find-olp (path &optional this-buffer)
  12309. "Return a marker pointing to the entry at outline path OLP.
  12310. If anything goes wrong, throw an error, and if you need to do
  12311. something based on this error, you can catch it with
  12312. `condition-case'.
  12313. If THIS-BUFFER is set, the outline path does not contain a file,
  12314. only headings."
  12315. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12316. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12317. (level 1)
  12318. (lmin 1)
  12319. (lmax 1)
  12320. end found flevel)
  12321. (unless buffer (error "File not found :%s" file))
  12322. (with-current-buffer buffer
  12323. (unless (derived-mode-p 'org-mode)
  12324. (error "Buffer %s needs to be in Org mode" buffer))
  12325. (org-with-wide-buffer
  12326. (goto-char (point-min))
  12327. (dolist (heading path)
  12328. (let ((re (format org-complex-heading-regexp-format
  12329. (regexp-quote heading)))
  12330. (cnt 0))
  12331. (while (re-search-forward re end t)
  12332. (setq level (- (match-end 1) (match-beginning 1)))
  12333. (when (and (>= level lmin) (<= level lmax))
  12334. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12335. (when (= cnt 0)
  12336. (error "Heading not found on level %d: %s" lmax heading))
  12337. (when (> cnt 1)
  12338. (error "Heading not unique on level %d: %s" lmax heading))
  12339. (goto-char found)
  12340. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12341. (setq end (save-excursion (org-end-of-subtree t t)))))
  12342. (when (org-at-heading-p)
  12343. (point-marker))))))
  12344. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12345. "Find node HEADING in BUFFER.
  12346. Return a marker to the heading if it was found, or nil if not.
  12347. If POS-ONLY is set, return just the position instead of a marker.
  12348. The heading text must match exact, but it may have a TODO keyword,
  12349. a priority cookie and tags in the standard locations."
  12350. (with-current-buffer (or buffer (current-buffer))
  12351. (org-with-wide-buffer
  12352. (goto-char (point-min))
  12353. (let (case-fold-search)
  12354. (when (re-search-forward
  12355. (format org-complex-heading-regexp-format
  12356. (regexp-quote heading)) nil t)
  12357. (if pos-only
  12358. (match-beginning 0)
  12359. (move-marker (make-marker) (match-beginning 0))))))))
  12360. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12361. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12362. When the target headline is found, return a marker to this location."
  12363. (let ((files (directory-files (or dir default-directory)
  12364. t "\\`[^.#].*\\.org\\'"))
  12365. visiting m buffer)
  12366. (catch 'found
  12367. (dolist (file files)
  12368. (message "trying %s" file)
  12369. (setq visiting (org-find-base-buffer-visiting file))
  12370. (setq buffer (or visiting (find-file-noselect file)))
  12371. (setq m (org-find-exact-headline-in-buffer
  12372. heading buffer))
  12373. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12374. (and m (throw 'found m))))))
  12375. (defun org-find-entry-with-id (ident)
  12376. "Locate the entry that contains the ID property with exact value IDENT.
  12377. IDENT can be a string, a symbol or a number, this function will search for
  12378. the string representation of it.
  12379. Return the position where this entry starts, or nil if there is no such entry."
  12380. (interactive "sID: ")
  12381. (let ((id (cond
  12382. ((stringp ident) ident)
  12383. ((symbolp ident) (symbol-name ident))
  12384. ((numberp ident) (number-to-string ident))
  12385. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12386. (org-with-wide-buffer (org-find-property "ID" id))))
  12387. ;;;; Timestamps
  12388. (defvar org-last-changed-timestamp nil)
  12389. (defvar org-last-inserted-timestamp nil
  12390. "The last time stamp inserted with `org-insert-time-stamp'.")
  12391. (defun org-time-stamp (arg &optional inactive)
  12392. "Prompt for a date/time and insert a time stamp.
  12393. If the user specifies a time like HH:MM or if this command is
  12394. called with at least one prefix argument, the time stamp contains
  12395. the date and the time. Otherwise, only the date is included.
  12396. All parts of a date not specified by the user are filled in from
  12397. the timestamp at point, if any, or the current date/time
  12398. otherwise.
  12399. If there is already a timestamp at the cursor, it is replaced.
  12400. With two universal prefix arguments, insert an active timestamp
  12401. with the current time without prompting the user.
  12402. When called from lisp, the timestamp is inactive if INACTIVE is
  12403. non-nil."
  12404. (interactive "P")
  12405. (let* ((ts (cond
  12406. ((org-at-date-range-p t)
  12407. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12408. ((org-at-timestamp-p 'lax) (match-string 0))))
  12409. ;; Default time is either the timestamp at point or today.
  12410. ;; When entering a range, only the range start is considered.
  12411. (default-time (and ts (org-time-string-to-time ts)))
  12412. (default-input (and ts (org-get-compact-tod ts)))
  12413. (repeater (and ts
  12414. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12415. (match-string 0 ts)))
  12416. org-time-was-given
  12417. org-end-time-was-given
  12418. (time
  12419. (if (equal arg '(16)) (current-time)
  12420. ;; Preserve `this-command' and `last-command'.
  12421. (let ((this-command this-command)
  12422. (last-command last-command))
  12423. (org-read-date
  12424. arg 'totime nil nil default-time default-input
  12425. inactive)))))
  12426. (cond
  12427. ((and ts
  12428. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12429. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12430. (insert "--")
  12431. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12432. (ts
  12433. ;; Make sure we're on a timestamp. When in the middle of a date
  12434. ;; range, move arbitrarily to range end.
  12435. (unless (org-at-timestamp-p 'lax)
  12436. (skip-chars-forward "-")
  12437. (org-at-timestamp-p 'lax))
  12438. (replace-match "")
  12439. (setq org-last-changed-timestamp
  12440. (org-insert-time-stamp
  12441. time (or org-time-was-given arg)
  12442. inactive nil nil (list org-end-time-was-given)))
  12443. (when repeater
  12444. (backward-char)
  12445. (insert " " repeater)
  12446. (setq org-last-changed-timestamp
  12447. (concat (substring org-last-inserted-timestamp 0 -1)
  12448. " " repeater ">")))
  12449. (message "Timestamp updated"))
  12450. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12451. (t (org-insert-time-stamp
  12452. time (or org-time-was-given arg) inactive nil nil
  12453. (list org-end-time-was-given))))))
  12454. ;; FIXME: can we use this for something else, like computing time differences?
  12455. (defun org-get-compact-tod (s)
  12456. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12457. (let* ((t1 (match-string 1 s))
  12458. (h1 (string-to-number (match-string 2 s)))
  12459. (m1 (string-to-number (match-string 3 s)))
  12460. (t2 (and (match-end 4) (match-string 5 s)))
  12461. (h2 (and t2 (string-to-number (match-string 6 s))))
  12462. (m2 (and t2 (string-to-number (match-string 7 s))))
  12463. dh dm)
  12464. (if (not t2)
  12465. t1
  12466. (setq dh (- h2 h1) dm (- m2 m1))
  12467. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12468. (concat t1 "+" (number-to-string dh)
  12469. (and (/= 0 dm) (format ":%02d" dm)))))))
  12470. (defun org-time-stamp-inactive (&optional arg)
  12471. "Insert an inactive time stamp.
  12472. An inactive time stamp is enclosed in square brackets instead of
  12473. angle brackets. It is inactive in the sense that it does not
  12474. trigger agenda entries. So these are more for recording a
  12475. certain time/date.
  12476. If the user specifies a time like HH:MM or if this command is called with
  12477. at least one prefix argument, the time stamp contains the date and the time.
  12478. Otherwise, only the date is included.
  12479. When called with two universal prefix arguments, insert an inactive time stamp
  12480. with the current time without prompting the user."
  12481. (interactive "P")
  12482. (org-time-stamp arg 'inactive))
  12483. (defvar org-date-ovl (make-overlay 1 1))
  12484. (overlay-put org-date-ovl 'face 'org-date-selected)
  12485. (delete-overlay org-date-ovl)
  12486. (defvar org-ans1) ; dynamically scoped parameter
  12487. (defvar org-ans2) ; dynamically scoped parameter
  12488. (defvar org-plain-time-of-day-regexp) ; defined below
  12489. (defvar org-overriding-default-time nil) ; dynamically scoped
  12490. (defvar org-read-date-overlay nil)
  12491. (defvar org-read-date-history nil)
  12492. (defvar org-read-date-final-answer nil)
  12493. (defvar org-read-date-analyze-futurep nil)
  12494. (defvar org-read-date-analyze-forced-year nil)
  12495. (defvar org-read-date-inactive)
  12496. (defvar org-def)
  12497. (defvar org-defdecode)
  12498. (defvar org-with-time)
  12499. (defvar calendar-setup) ; Dynamically scoped.
  12500. (defun org-read-date (&optional with-time to-time from-string prompt
  12501. default-time default-input inactive)
  12502. "Read a date, possibly a time, and make things smooth for the user.
  12503. The prompt will suggest to enter an ISO date, but you can also enter anything
  12504. which will at least partially be understood by `parse-time-string'.
  12505. Unrecognized parts of the date will default to the current day, month, year,
  12506. hour and minute. If this command is called to replace a timestamp at point,
  12507. or to enter the second timestamp of a range, the default time is taken
  12508. from the existing stamp. Furthermore, the command prefers the future,
  12509. so if you are giving a date where the year is not given, and the day-month
  12510. combination is already past in the current year, it will assume you
  12511. mean next year. For details, see the manual. A few examples:
  12512. 3-2-5 --> 2003-02-05
  12513. feb 15 --> currentyear-02-15
  12514. 2/15 --> currentyear-02-15
  12515. sep 12 9 --> 2009-09-12
  12516. 12:45 --> today 12:45
  12517. 22 sept 0:34 --> currentyear-09-22 0:34
  12518. 12 --> currentyear-currentmonth-12
  12519. Fri --> nearest Friday after today
  12520. -Tue --> last Tuesday
  12521. etc.
  12522. Furthermore you can specify a relative date by giving, as the *first* thing
  12523. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12524. change in days weeks, months, years.
  12525. With a single plus or minus, the date is relative to today. With a double
  12526. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12527. +4d --> four days from today
  12528. +4 --> same as above
  12529. +2w --> two weeks from today
  12530. ++5 --> five days from default date
  12531. The function understands only English month and weekday abbreviations.
  12532. While prompting, a calendar is popped up - you can also select the
  12533. date with the mouse (button 1). The calendar shows a period of three
  12534. months. To scroll it to other months, use the keys `>' and `<'.
  12535. If you don't like the calendar, turn it off with
  12536. (setq org-read-date-popup-calendar nil)
  12537. With optional argument TO-TIME, the date will immediately be converted
  12538. to an internal time.
  12539. With an optional argument WITH-TIME, the prompt will suggest to
  12540. also insert a time. Note that when WITH-TIME is not set, you can
  12541. still enter a time, and this function will inform the calling routine
  12542. about this change. The calling routine may then choose to change the
  12543. format used to insert the time stamp into the buffer to include the time.
  12544. With optional argument FROM-STRING, read from this string instead from
  12545. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12546. the time/date that is used for everything that is not specified by the
  12547. user."
  12548. (require 'parse-time)
  12549. (let* ((org-with-time with-time)
  12550. (org-time-stamp-rounding-minutes
  12551. (if (equal org-with-time '(16))
  12552. '(0 0)
  12553. org-time-stamp-rounding-minutes))
  12554. (ct (org-current-time))
  12555. (org-def (or org-overriding-default-time default-time ct))
  12556. (org-defdecode (decode-time org-def))
  12557. (cur-frame (selected-frame))
  12558. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12559. (calendar-setup
  12560. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12561. (calendar-move-hook nil)
  12562. (calendar-view-diary-initially-flag nil)
  12563. (calendar-view-holidays-initially-flag nil)
  12564. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12565. ;; Rationalize `org-def' and `org-defdecode', if required.
  12566. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12567. (setf (nth 2 org-defdecode) -1)
  12568. (setf (nth 1 org-defdecode) 59)
  12569. (setq org-def (apply #'encode-time org-defdecode))
  12570. (setq org-defdecode (decode-time org-def)))
  12571. (let* ((timestr (format-time-string
  12572. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12573. org-def))
  12574. (prompt (concat (if prompt (concat prompt " ") "")
  12575. (format "Date+time [%s]: " timestr))))
  12576. (cond
  12577. (from-string (setq ans from-string))
  12578. (org-read-date-popup-calendar
  12579. (save-excursion
  12580. (save-window-excursion
  12581. (calendar)
  12582. (when (eq calendar-setup 'calendar-only)
  12583. (setq cal-frame
  12584. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12585. (select-frame cal-frame))
  12586. (org-eval-in-calendar '(setq cursor-type nil) t)
  12587. (unwind-protect
  12588. (progn
  12589. (calendar-forward-day (- (time-to-days org-def)
  12590. (calendar-absolute-from-gregorian
  12591. (calendar-current-date))))
  12592. (org-eval-in-calendar nil t)
  12593. (let* ((old-map (current-local-map))
  12594. (map (copy-keymap calendar-mode-map))
  12595. (minibuffer-local-map
  12596. (copy-keymap org-read-date-minibuffer-local-map)))
  12597. (org-defkey map (kbd "RET") 'org-calendar-select)
  12598. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12599. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12600. (unwind-protect
  12601. (progn
  12602. (use-local-map map)
  12603. (setq org-read-date-inactive inactive)
  12604. (add-hook 'post-command-hook 'org-read-date-display)
  12605. (setq org-ans0
  12606. (read-string prompt
  12607. default-input
  12608. 'org-read-date-history
  12609. nil))
  12610. ;; org-ans0: from prompt
  12611. ;; org-ans1: from mouse click
  12612. ;; org-ans2: from calendar motion
  12613. (setq ans
  12614. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12615. (remove-hook 'post-command-hook 'org-read-date-display)
  12616. (use-local-map old-map)
  12617. (when org-read-date-overlay
  12618. (delete-overlay org-read-date-overlay)
  12619. (setq org-read-date-overlay nil)))))
  12620. (bury-buffer "*Calendar*")
  12621. (when cal-frame
  12622. (delete-frame cal-frame)
  12623. (select-frame-set-input-focus cur-frame))))))
  12624. (t ; Naked prompt only
  12625. (unwind-protect
  12626. (setq ans (read-string prompt default-input
  12627. 'org-read-date-history timestr))
  12628. (when org-read-date-overlay
  12629. (delete-overlay org-read-date-overlay)
  12630. (setq org-read-date-overlay nil))))))
  12631. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12632. (when org-read-date-analyze-forced-year
  12633. (message "Year was forced into %s"
  12634. (if org-read-date-force-compatible-dates
  12635. "compatible range (1970-2037)"
  12636. "range representable on this machine"))
  12637. (ding))
  12638. (setq final (apply #'encode-time final))
  12639. (setq org-read-date-final-answer ans)
  12640. (if to-time
  12641. final
  12642. ;; This round-trip gets rid of 34th of August and stuff like that....
  12643. (setq final (decode-time final))
  12644. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12645. (format "%04d-%02d-%02d %02d:%02d"
  12646. (nth 5 final) (nth 4 final) (nth 3 final)
  12647. (nth 2 final) (nth 1 final))
  12648. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12649. (defun org-read-date-display ()
  12650. "Display the current date prompt interpretation in the minibuffer."
  12651. (when org-read-date-display-live
  12652. (when org-read-date-overlay
  12653. (delete-overlay org-read-date-overlay))
  12654. (when (minibufferp (current-buffer))
  12655. (save-excursion
  12656. (end-of-line 1)
  12657. (while (not (equal (buffer-substring
  12658. (max (point-min) (- (point) 4)) (point))
  12659. " "))
  12660. (insert " ")))
  12661. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  12662. " " (or org-ans1 org-ans2)))
  12663. (org-end-time-was-given nil)
  12664. (f (org-read-date-analyze ans org-def org-defdecode))
  12665. (fmts (if org-display-custom-times
  12666. org-time-stamp-custom-formats
  12667. org-time-stamp-formats))
  12668. (fmt (if (or org-with-time
  12669. (and (boundp 'org-time-was-given) org-time-was-given))
  12670. (cdr fmts)
  12671. (car fmts)))
  12672. (txt (format-time-string fmt (apply #'encode-time f)))
  12673. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  12674. (txt (concat "=> " txt)))
  12675. (when (and org-end-time-was-given
  12676. (string-match org-plain-time-of-day-regexp txt))
  12677. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  12678. org-end-time-was-given
  12679. (substring txt (match-end 0)))))
  12680. (when org-read-date-analyze-futurep
  12681. (setq txt (concat txt " (=>F)")))
  12682. (setq org-read-date-overlay
  12683. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  12684. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  12685. (defun org-read-date-analyze (ans def defdecode)
  12686. "Analyze the combined answer of the date prompt."
  12687. ;; FIXME: cleanup and comment
  12688. (let ((org-def def)
  12689. (org-defdecode defdecode)
  12690. (nowdecode (decode-time))
  12691. delta deltan deltaw deltadef year month day
  12692. hour minute second wday pm h2 m2 tl wday1
  12693. iso-year iso-weekday iso-week iso-date futurep kill-year)
  12694. (setq org-read-date-analyze-futurep nil
  12695. org-read-date-analyze-forced-year nil)
  12696. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  12697. (setq ans "+0"))
  12698. (when (setq delta (org-read-date-get-relative ans nil org-def))
  12699. (setq ans (replace-match "" t t ans)
  12700. deltan (car delta)
  12701. deltaw (nth 1 delta)
  12702. deltadef (nth 2 delta)))
  12703. ;; Check if there is an iso week date in there. If yes, store the
  12704. ;; info and postpone interpreting it until the rest of the parsing
  12705. ;; is done.
  12706. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  12707. (setq iso-year (when (match-end 1)
  12708. (org-small-year-to-year
  12709. (string-to-number (match-string 1 ans))))
  12710. iso-weekday (when (match-end 3)
  12711. (string-to-number (match-string 3 ans)))
  12712. iso-week (string-to-number (match-string 2 ans)))
  12713. (setq ans (replace-match "" t t ans)))
  12714. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  12715. (when (string-match
  12716. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  12717. (setq year (if (match-end 2)
  12718. (string-to-number (match-string 2 ans))
  12719. (progn (setq kill-year t)
  12720. (string-to-number (format-time-string "%Y"))))
  12721. month (string-to-number (match-string 3 ans))
  12722. day (string-to-number (match-string 4 ans)))
  12723. (setq year (org-small-year-to-year year))
  12724. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12725. t nil ans)))
  12726. ;; Help matching dotted european dates
  12727. (when (string-match
  12728. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  12729. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  12730. (setq kill-year t)
  12731. (string-to-number (format-time-string "%Y")))
  12732. day (string-to-number (match-string 1 ans))
  12733. month (string-to-number (match-string 2 ans))
  12734. ans (replace-match (format "%04d-%02d-%02d" year month day)
  12735. t nil ans)))
  12736. ;; Help matching american dates, like 5/30 or 5/30/7
  12737. (when (string-match
  12738. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  12739. (setq year (if (match-end 4)
  12740. (string-to-number (match-string 4 ans))
  12741. (progn (setq kill-year t)
  12742. (string-to-number (format-time-string "%Y"))))
  12743. month (string-to-number (match-string 1 ans))
  12744. day (string-to-number (match-string 2 ans)))
  12745. (setq year (org-small-year-to-year year))
  12746. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12747. t nil ans)))
  12748. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  12749. ;; If there is a time with am/pm, and *no* time without it, we convert
  12750. ;; so that matching will be successful.
  12751. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12752. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12753. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  12754. (setq hour (string-to-number (match-string 1 ans))
  12755. minute (if (match-end 3)
  12756. (string-to-number (match-string 3 ans))
  12757. 0)
  12758. pm (equal ?p
  12759. (string-to-char (downcase (match-string 4 ans)))))
  12760. (if (and (= hour 12) (not pm))
  12761. (setq hour 0)
  12762. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  12763. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12764. t t ans))))
  12765. ;; Check if a time range is given as a duration
  12766. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  12767. (setq hour (string-to-number (match-string 1 ans))
  12768. h2 (+ hour (string-to-number (match-string 3 ans)))
  12769. minute (string-to-number (match-string 2 ans))
  12770. m2 (+ minute (if (match-end 5) (string-to-number
  12771. (match-string 5 ans))0)))
  12772. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  12773. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  12774. t t ans)))
  12775. ;; Check if there is a time range
  12776. (when (boundp 'org-end-time-was-given)
  12777. (setq org-time-was-given nil)
  12778. (when (and (string-match org-plain-time-of-day-regexp ans)
  12779. (match-end 8))
  12780. (setq org-end-time-was-given (match-string 8 ans))
  12781. (setq ans (concat (substring ans 0 (match-beginning 7))
  12782. (substring ans (match-end 7))))))
  12783. (setq tl (parse-time-string ans)
  12784. day (or (nth 3 tl) (nth 3 org-defdecode))
  12785. month
  12786. (cond ((nth 4 tl))
  12787. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  12788. ;; Day was specified. Make sure DAY+MONTH
  12789. ;; combination happens in the future.
  12790. ((nth 3 tl)
  12791. (setq futurep t)
  12792. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  12793. (nth 4 nowdecode)))
  12794. (t (nth 4 org-defdecode)))
  12795. year
  12796. (cond ((and (not kill-year) (nth 5 tl)))
  12797. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  12798. ;; Month was guessed in the future and is at least
  12799. ;; equal to NOWDECODE's. Fix year accordingly.
  12800. (futurep
  12801. (if (or (> month (nth 4 nowdecode))
  12802. (>= day (nth 3 nowdecode)))
  12803. (nth 5 nowdecode)
  12804. (1+ (nth 5 nowdecode))))
  12805. ;; Month was specified. Make sure MONTH+YEAR
  12806. ;; combination happens in the future.
  12807. ((nth 4 tl)
  12808. (setq futurep t)
  12809. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  12810. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  12811. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  12812. (t (nth 5 nowdecode))))
  12813. (t (nth 5 org-defdecode)))
  12814. hour (or (nth 2 tl) (nth 2 org-defdecode))
  12815. minute (or (nth 1 tl) (nth 1 org-defdecode))
  12816. second (or (nth 0 tl) 0)
  12817. wday (nth 6 tl))
  12818. (when (and (eq org-read-date-prefer-future 'time)
  12819. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  12820. (equal day (nth 3 nowdecode))
  12821. (equal month (nth 4 nowdecode))
  12822. (equal year (nth 5 nowdecode))
  12823. (nth 2 tl)
  12824. (or (< (nth 2 tl) (nth 2 nowdecode))
  12825. (and (= (nth 2 tl) (nth 2 nowdecode))
  12826. (nth 1 tl)
  12827. (< (nth 1 tl) (nth 1 nowdecode)))))
  12828. (setq day (1+ day)
  12829. futurep t))
  12830. ;; Special date definitions below
  12831. (cond
  12832. (iso-week
  12833. ;; There was an iso week
  12834. (require 'cal-iso)
  12835. (setq futurep nil)
  12836. (setq year (or iso-year year)
  12837. day (or iso-weekday wday 1)
  12838. wday nil ; to make sure that the trigger below does not match
  12839. iso-date (calendar-gregorian-from-absolute
  12840. (calendar-iso-to-absolute
  12841. (list iso-week day year))))
  12842. ; FIXME: Should we also push ISO weeks into the future?
  12843. ; (when (and org-read-date-prefer-future
  12844. ; (not iso-year)
  12845. ; (< (calendar-absolute-from-gregorian iso-date)
  12846. ; (time-to-days nil)))
  12847. ; (setq year (1+ year)
  12848. ; iso-date (calendar-gregorian-from-absolute
  12849. ; (calendar-iso-to-absolute
  12850. ; (list iso-week day year)))))
  12851. (setq month (car iso-date)
  12852. year (nth 2 iso-date)
  12853. day (nth 1 iso-date)))
  12854. (deltan
  12855. (setq futurep nil)
  12856. (unless deltadef
  12857. (let ((now (decode-time)))
  12858. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  12859. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  12860. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  12861. ((equal deltaw "m") (setq month (+ month deltan)))
  12862. ((equal deltaw "y") (setq year (+ year deltan)))))
  12863. ((and wday (not (nth 3 tl)))
  12864. ;; Weekday was given, but no day, so pick that day in the week
  12865. ;; on or after the derived date.
  12866. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  12867. (unless (equal wday wday1)
  12868. (setq day (+ day (% (- wday wday1 -7) 7))))))
  12869. (when (and (boundp 'org-time-was-given)
  12870. (nth 2 tl))
  12871. (setq org-time-was-given t))
  12872. (when (< year 100) (setq year (+ 2000 year)))
  12873. ;; Check of the date is representable
  12874. (if org-read-date-force-compatible-dates
  12875. (progn
  12876. (when (< year 1970)
  12877. (setq year 1970 org-read-date-analyze-forced-year t))
  12878. (when (> year 2037)
  12879. (setq year 2037 org-read-date-analyze-forced-year t)))
  12880. (condition-case nil
  12881. (ignore (encode-time second minute hour day month year))
  12882. (error
  12883. (setq year (nth 5 org-defdecode))
  12884. (setq org-read-date-analyze-forced-year t))))
  12885. (setq org-read-date-analyze-futurep futurep)
  12886. (list second minute hour day month year)))
  12887. (defvar parse-time-weekdays)
  12888. (defun org-read-date-get-relative (s today default)
  12889. "Check string S for special relative date string.
  12890. TODAY and DEFAULT are internal times, for today and for a default.
  12891. Return shift list (N what def-flag)
  12892. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  12893. N is the number of WHATs to shift.
  12894. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  12895. the DEFAULT date rather than TODAY."
  12896. (require 'parse-time)
  12897. (when (and
  12898. (string-match
  12899. (concat
  12900. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  12901. "\\([0-9]+\\)?"
  12902. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  12903. "\\([ \t]\\|$\\)") s)
  12904. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  12905. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  12906. (string-to-char (substring (match-string 1 s) -1))
  12907. ?+))
  12908. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  12909. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  12910. (what (if (match-end 3) (match-string 3 s) "d"))
  12911. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  12912. (date (if rel default today))
  12913. (wday (nth 6 (decode-time date)))
  12914. delta)
  12915. (if wday1
  12916. (progn
  12917. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  12918. (when (= delta 0) (setq delta 7))
  12919. (when (= dir ?-)
  12920. (setq delta (- delta 7))
  12921. (when (= delta 0) (setq delta -7)))
  12922. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  12923. (list delta "d" rel))
  12924. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  12925. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  12926. "Turn a user-specified date into the internal representation.
  12927. The internal representation needed by the calendar is (month day year).
  12928. This is a wrapper to handle the brain-dead convention in calendar that
  12929. user function argument order change dependent on argument order."
  12930. (pcase calendar-date-style
  12931. (`american (list arg1 arg2 arg3))
  12932. (`european (list arg2 arg1 arg3))
  12933. (`iso (list arg2 arg3 arg1))))
  12934. (defun org-eval-in-calendar (form &optional keepdate)
  12935. "Eval FORM in the calendar window and return to current window.
  12936. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  12937. (let ((sf (selected-frame))
  12938. (sw (selected-window)))
  12939. (select-window (get-buffer-window "*Calendar*" t))
  12940. (eval form)
  12941. (when (and (not keepdate) (calendar-cursor-to-date))
  12942. (let* ((date (calendar-cursor-to-date))
  12943. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12944. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  12945. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  12946. (select-window sw)
  12947. (select-frame-set-input-focus sf)))
  12948. (defun org-calendar-select ()
  12949. "Return to `org-read-date' with the date currently selected.
  12950. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12951. (interactive)
  12952. (when (calendar-cursor-to-date)
  12953. (let* ((date (calendar-cursor-to-date))
  12954. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12955. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12956. (when (active-minibuffer-window) (exit-minibuffer))))
  12957. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  12958. "Insert a date stamp for the date given by the internal TIME.
  12959. See `format-time-string' for the format of TIME.
  12960. WITH-HM means use the stamp format that includes the time of the day.
  12961. INACTIVE means use square brackets instead of angular ones, so that the
  12962. stamp will not contribute to the agenda.
  12963. PRE and POST are optional strings to be inserted before and after the
  12964. stamp.
  12965. The command returns the inserted time stamp."
  12966. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  12967. stamp)
  12968. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  12969. (insert-before-markers (or pre ""))
  12970. (when (listp extra)
  12971. (setq extra (car extra))
  12972. (if (and (stringp extra)
  12973. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  12974. (setq extra (format "-%02d:%02d"
  12975. (string-to-number (match-string 1 extra))
  12976. (string-to-number (match-string 2 extra))))
  12977. (setq extra nil)))
  12978. (when extra
  12979. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  12980. (insert-before-markers (setq stamp (format-time-string fmt time)))
  12981. (insert-before-markers (or post ""))
  12982. (setq org-last-inserted-timestamp stamp)))
  12983. (defun org-toggle-time-stamp-overlays ()
  12984. "Toggle the use of custom time stamp formats."
  12985. (interactive)
  12986. (setq org-display-custom-times (not org-display-custom-times))
  12987. (unless org-display-custom-times
  12988. (let ((p (point-min)) (bmp (buffer-modified-p)))
  12989. (while (setq p (next-single-property-change p 'display))
  12990. (when (and (get-text-property p 'display)
  12991. (eq (get-text-property p 'face) 'org-date))
  12992. (remove-text-properties
  12993. p (setq p (next-single-property-change p 'display))
  12994. '(display t))))
  12995. (set-buffer-modified-p bmp)))
  12996. (org-restart-font-lock)
  12997. (setq org-table-may-need-update t)
  12998. (if org-display-custom-times
  12999. (message "Time stamps are overlaid with custom format")
  13000. (message "Time stamp overlays removed")))
  13001. (defun org-display-custom-time (beg end)
  13002. "Overlay modified time stamp format over timestamp between BEG and END."
  13003. (let* ((ts (buffer-substring beg end))
  13004. t1 with-hm tf time str (off 0))
  13005. (save-match-data
  13006. (setq t1 (org-parse-time-string ts t))
  13007. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  13008. (setq off (- (match-end 0) (match-beginning 0)))))
  13009. (setq end (- end off))
  13010. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  13011. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  13012. time (org-fix-decoded-time t1)
  13013. str (org-add-props
  13014. (format-time-string
  13015. (substring tf 1 -1) (apply 'encode-time time))
  13016. nil 'mouse-face 'highlight))
  13017. (put-text-property beg end 'display str)))
  13018. (defun org-fix-decoded-time (time)
  13019. "Set 0 instead of nil for the first 6 elements of time.
  13020. Don't touch the rest."
  13021. (let ((n 0))
  13022. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  13023. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  13024. "Difference between TIMESTAMP-STRING and now in days.
  13025. If SECONDS is non-nil, return the difference in seconds."
  13026. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  13027. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  13028. (funcall fdiff nil))))
  13029. (defun org-deadline-close-p (timestamp-string &optional ndays)
  13030. "Is the time in TIMESTAMP-STRING close to the current date?"
  13031. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  13032. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  13033. (not (org-entry-is-done-p))))
  13034. (defun org-get-wdays (ts &optional delay zero-delay)
  13035. "Get the deadline lead time appropriate for timestring TS.
  13036. When DELAY is non-nil, get the delay time for scheduled items
  13037. instead of the deadline lead time. When ZERO-DELAY is non-nil
  13038. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  13039. don't try to find the delay cookie in the scheduled timestamp."
  13040. (let ((tv (if delay org-scheduled-delay-days
  13041. org-deadline-warning-days)))
  13042. (cond
  13043. ((or (and delay (< tv 0))
  13044. (and delay zero-delay (<= tv 0))
  13045. (and (not delay) (<= tv 0)))
  13046. ;; Enforce this value no matter what
  13047. (- tv))
  13048. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  13049. ;; lead time is specified.
  13050. (floor (* (string-to-number (match-string 1 ts))
  13051. (cdr (assoc (match-string 2 ts)
  13052. '(("d" . 1) ("w" . 7)
  13053. ("m" . 30.4) ("y" . 365.25)
  13054. ("h" . 0.041667)))))))
  13055. ;; go for the default.
  13056. (t tv))))
  13057. (defun org-calendar-select-mouse (ev)
  13058. "Return to `org-read-date' with the date currently selected.
  13059. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13060. (interactive "e")
  13061. (mouse-set-point ev)
  13062. (when (calendar-cursor-to-date)
  13063. (let* ((date (calendar-cursor-to-date))
  13064. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13065. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13066. (when (active-minibuffer-window) (exit-minibuffer))))
  13067. (defun org-check-deadlines (ndays)
  13068. "Check if there are any deadlines due or past due.
  13069. A deadline is considered due if it happens within `org-deadline-warning-days'
  13070. days from today's date. If the deadline appears in an entry marked DONE,
  13071. it is not shown. A numeric prefix argument NDAYS can be used to test that
  13072. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  13073. are shown."
  13074. (interactive "P")
  13075. (let* ((org-warn-days
  13076. (cond
  13077. ((equal ndays '(4)) 100000)
  13078. (ndays (prefix-numeric-value ndays))
  13079. (t (abs org-deadline-warning-days))))
  13080. (case-fold-search nil)
  13081. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  13082. (callback
  13083. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  13084. (message "%d deadlines past-due or due within %d days"
  13085. (org-occur regexp nil callback)
  13086. org-warn-days)))
  13087. (defsubst org-re-timestamp (type)
  13088. "Return a regexp for timestamp TYPE.
  13089. Allowed values for TYPE are:
  13090. all: all timestamps
  13091. active: only active timestamps (<...>)
  13092. inactive: only inactive timestamps ([...])
  13093. scheduled: only scheduled timestamps
  13094. deadline: only deadline timestamps
  13095. closed: only closed time-stamps
  13096. When TYPE is nil, fall back on returning a regexp that matches
  13097. both scheduled and deadline timestamps."
  13098. (cl-case type
  13099. (all org-ts-regexp-both)
  13100. (active org-ts-regexp)
  13101. (inactive org-ts-regexp-inactive)
  13102. (scheduled org-scheduled-time-regexp)
  13103. (deadline org-deadline-time-regexp)
  13104. (closed org-closed-time-regexp)
  13105. (otherwise
  13106. (concat "\\<"
  13107. (regexp-opt (list org-deadline-string org-scheduled-string))
  13108. " *<\\([^>]+\\)>"))))
  13109. (defun org-check-before-date (d)
  13110. "Check if there are deadlines or scheduled entries before date D."
  13111. (interactive (list (org-read-date)))
  13112. (let* ((case-fold-search nil)
  13113. (regexp (org-re-timestamp org-ts-type))
  13114. (ts-type org-ts-type)
  13115. (callback
  13116. (lambda ()
  13117. (let ((match (match-string 1)))
  13118. (and (if (memq ts-type '(active inactive all))
  13119. (eq (org-element-type (save-excursion
  13120. (backward-char)
  13121. (org-element-context)))
  13122. 'timestamp)
  13123. (org-at-planning-p))
  13124. (time-less-p
  13125. (org-time-string-to-time match)
  13126. (org-time-string-to-time d)))))))
  13127. (message "%d entries before %s"
  13128. (org-occur regexp nil callback)
  13129. d)))
  13130. (defun org-check-after-date (d)
  13131. "Check if there are deadlines or scheduled entries after date D."
  13132. (interactive (list (org-read-date)))
  13133. (let* ((case-fold-search nil)
  13134. (regexp (org-re-timestamp org-ts-type))
  13135. (ts-type org-ts-type)
  13136. (callback
  13137. (lambda ()
  13138. (let ((match (match-string 1)))
  13139. (and (if (memq ts-type '(active inactive all))
  13140. (eq (org-element-type (save-excursion
  13141. (backward-char)
  13142. (org-element-context)))
  13143. 'timestamp)
  13144. (org-at-planning-p))
  13145. (not (time-less-p
  13146. (org-time-string-to-time match)
  13147. (org-time-string-to-time d))))))))
  13148. (message "%d entries after %s"
  13149. (org-occur regexp nil callback)
  13150. d)))
  13151. (defun org-check-dates-range (start-date end-date)
  13152. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  13153. (interactive (list (org-read-date nil nil nil "Range starts")
  13154. (org-read-date nil nil nil "Range end")))
  13155. (let ((case-fold-search nil)
  13156. (regexp (org-re-timestamp org-ts-type))
  13157. (callback
  13158. (let ((type org-ts-type))
  13159. (lambda ()
  13160. (let ((match (match-string 1)))
  13161. (and
  13162. (if (memq type '(active inactive all))
  13163. (eq (org-element-type (save-excursion
  13164. (backward-char)
  13165. (org-element-context)))
  13166. 'timestamp)
  13167. (org-at-planning-p))
  13168. (not (time-less-p
  13169. (org-time-string-to-time match)
  13170. (org-time-string-to-time start-date)))
  13171. (time-less-p
  13172. (org-time-string-to-time match)
  13173. (org-time-string-to-time end-date))))))))
  13174. (message "%d entries between %s and %s"
  13175. (org-occur regexp nil callback) start-date end-date)))
  13176. (defun org-evaluate-time-range (&optional to-buffer)
  13177. "Evaluate a time range by computing the difference between start and end.
  13178. Normally the result is just printed in the echo area, but with prefix arg
  13179. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  13180. If the time range is actually in a table, the result is inserted into the
  13181. next column.
  13182. For time difference computation, a year is assumed to be exactly 365
  13183. days in order to avoid rounding problems."
  13184. (interactive "P")
  13185. (or
  13186. (org-clock-update-time-maybe)
  13187. (save-excursion
  13188. (unless (org-at-date-range-p t)
  13189. (goto-char (point-at-bol))
  13190. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  13191. (unless (org-at-date-range-p t)
  13192. (user-error "Not at a time-stamp range, and none found in current line")))
  13193. (let* ((ts1 (match-string 1))
  13194. (ts2 (match-string 2))
  13195. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  13196. (match-end (match-end 0))
  13197. (time1 (org-time-string-to-time ts1))
  13198. (time2 (org-time-string-to-time ts2))
  13199. (diff (abs (float-time (time-subtract time2 time1))))
  13200. (negative (time-less-p time2 time1))
  13201. ;; (ys (floor (* 365 24 60 60)))
  13202. (ds (* 24 60 60))
  13203. (hs (* 60 60))
  13204. (fy "%dy %dd %02d:%02d")
  13205. (fy1 "%dy %dd")
  13206. (fd "%dd %02d:%02d")
  13207. (fd1 "%dd")
  13208. (fh "%02d:%02d")
  13209. y d h m align)
  13210. (if havetime
  13211. (setq ; y (floor diff ys) diff (mod diff ys)
  13212. y 0
  13213. d (floor diff ds) diff (mod diff ds)
  13214. h (floor diff hs) diff (mod diff hs)
  13215. m (floor diff 60))
  13216. (setq ; y (floor diff ys) diff (mod diff ys)
  13217. y 0
  13218. d (round diff ds)
  13219. h 0 m 0))
  13220. (if (not to-buffer)
  13221. (message "%s" (org-make-tdiff-string y d h m))
  13222. (if (org-at-table-p)
  13223. (progn
  13224. (goto-char match-end)
  13225. (setq align t)
  13226. (and (looking-at " *|") (goto-char (match-end 0))))
  13227. (goto-char match-end))
  13228. (when (looking-at
  13229. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  13230. (replace-match ""))
  13231. (when negative (insert " -"))
  13232. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  13233. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  13234. (insert " " (format fh h m))))
  13235. (when align (org-table-align))
  13236. (message "Time difference inserted")))))
  13237. (defun org-make-tdiff-string (y d h m)
  13238. (let ((fmt "")
  13239. (l nil))
  13240. (when (> y 0)
  13241. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  13242. (push y l))
  13243. (when (> d 0)
  13244. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  13245. (push d l))
  13246. (when (> h 0)
  13247. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  13248. (push h l))
  13249. (when (> m 0)
  13250. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  13251. (push m l))
  13252. (apply 'format fmt (nreverse l))))
  13253. (defun org-time-string-to-time (s)
  13254. "Convert timestamp string S into internal time."
  13255. (apply #'encode-time (org-parse-time-string s)))
  13256. (defun org-time-string-to-seconds (s)
  13257. "Convert a timestamp string S into a number of seconds."
  13258. (float-time (org-time-string-to-time s)))
  13259. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  13260. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  13261. "Convert time stamp S to an absolute day number.
  13262. If DAYNR in non-nil, and there is a specifier for a cyclic time
  13263. stamp, get the closest date to DAYNR. If PREFER is
  13264. `past' (respectively `future') return a date past (respectively
  13265. after) or equal to DAYNR.
  13266. POS is the location of time stamp S, as a buffer position in
  13267. BUFFER.
  13268. Diary sexp timestamps are matched against DAYNR, when non-nil.
  13269. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  13270. signaled."
  13271. (cond
  13272. ((string-match "\\`%%\\((.*)\\)" s)
  13273. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13274. ;; only able to match individual dates. If it fails, raise an
  13275. ;; error.
  13276. (if (and daynr
  13277. (org-diary-sexp-entry
  13278. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13279. daynr
  13280. (signal 'org-diary-sexp-no-match (list s))))
  13281. (daynr (org-closest-date s daynr prefer))
  13282. (t (time-to-days
  13283. (condition-case errdata
  13284. (org-time-string-to-time s)
  13285. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13286. s
  13287. (if (not (and buffer pos)) ""
  13288. (format-message " at %d in buffer `%s'" pos buffer))
  13289. (cdr errdata))))))))
  13290. (defun org-days-to-iso-week (days)
  13291. "Return the ISO week number."
  13292. (require 'cal-iso)
  13293. (car (calendar-iso-from-absolute days)))
  13294. (defun org-small-year-to-year (year)
  13295. "Convert 2-digit years into 4-digit years.
  13296. YEAR is expanded into one of the 30 next years, if possible, or
  13297. into a past one. Any year larger than 99 is returned unchanged."
  13298. (if (>= year 100) year
  13299. (let* ((current (string-to-number (format-time-string "%Y")))
  13300. (century (/ current 100))
  13301. (offset (- year (% current 100))))
  13302. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13303. ((> offset -70) (+ (* century 100) year))
  13304. (t (+ (* (1+ century) 100) year))))))
  13305. (defun org-time-from-absolute (d)
  13306. "Return the time corresponding to date D.
  13307. D may be an absolute day number, or a calendar-type list (month day year)."
  13308. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13309. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13310. (defvar org-agenda-current-date)
  13311. (defun org-calendar-holiday ()
  13312. "List of holidays, for Diary display in Org mode."
  13313. (require 'holidays)
  13314. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13315. (and hl (mapconcat #'identity hl "; "))))
  13316. (defun org-diary-sexp-entry (sexp entry d)
  13317. "Process a SEXP diary ENTRY for date D."
  13318. (require 'diary-lib)
  13319. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13320. ;; dynamically.
  13321. (let* ((sexp `(let ((entry ,entry)
  13322. (date ',d))
  13323. ,(car (read-from-string sexp))))
  13324. (result (if calendar-debug-sexp (eval sexp)
  13325. (condition-case nil
  13326. (eval sexp)
  13327. (error
  13328. (beep)
  13329. (message "Bad sexp at line %d in %s: %s"
  13330. (org-current-line)
  13331. (buffer-file-name) sexp)
  13332. (sleep-for 2))))))
  13333. (cond ((stringp result) (split-string result "; "))
  13334. ((and (consp result)
  13335. (not (consp (cdr result)))
  13336. (stringp (cdr result))) (cdr result))
  13337. ((and (consp result)
  13338. (stringp (car result))) result)
  13339. (result entry))))
  13340. (defun org-diary-to-ical-string (frombuf)
  13341. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13342. This uses the icalendar.el library."
  13343. (let* ((tmpdir temporary-file-directory)
  13344. (tmpfile (make-temp-name
  13345. (expand-file-name "orgics" tmpdir)))
  13346. buf rtn b e)
  13347. (with-current-buffer frombuf
  13348. (icalendar-export-region (point-min) (point-max) tmpfile)
  13349. (setq buf (find-buffer-visiting tmpfile))
  13350. (set-buffer buf)
  13351. (goto-char (point-min))
  13352. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13353. (setq b (match-beginning 0)))
  13354. (goto-char (point-max))
  13355. (when (re-search-backward "^END:VEVENT" nil t)
  13356. (setq e (match-end 0)))
  13357. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13358. (kill-buffer buf)
  13359. (delete-file tmpfile)
  13360. rtn))
  13361. (defun org-closest-date (start current prefer)
  13362. "Return closest date to CURRENT starting from START.
  13363. CURRENT and START are both time stamps.
  13364. When PREFER is `past', return a date that is either CURRENT or
  13365. past. When PREFER is `future', return a date that is either
  13366. CURRENT or future.
  13367. Only time stamps with a repeater are modified. Any other time
  13368. stamp stay unchanged. In any case, return value is an absolute
  13369. day number."
  13370. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13371. ;; No repeater. Do not shift time stamp.
  13372. (time-to-days (org-time-string-to-time start))
  13373. (let ((value (string-to-number (match-string 1 start)))
  13374. (type (match-string 2 start)))
  13375. (if (= 0 value)
  13376. ;; Repeater with a 0-value is considered as void.
  13377. (time-to-days (org-time-string-to-time start))
  13378. (let* ((base (org-date-to-gregorian start))
  13379. (target (org-date-to-gregorian current))
  13380. (sday (calendar-absolute-from-gregorian base))
  13381. (cday (calendar-absolute-from-gregorian target))
  13382. n1 n2)
  13383. ;; If START is already past CURRENT, just return START.
  13384. (if (<= cday sday) sday
  13385. ;; Compute closest date before (N1) and closest date past
  13386. ;; (N2) CURRENT.
  13387. (pcase type
  13388. ("h"
  13389. (let ((missing-hours
  13390. (mod (+ (- (* 24 (- cday sday))
  13391. (nth 2 (org-parse-time-string start)))
  13392. org-extend-today-until)
  13393. value)))
  13394. (setf n1 (if (= missing-hours 0) cday
  13395. (- cday (1+ (/ missing-hours 24)))))
  13396. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13397. ((or "d" "w")
  13398. (let ((value (if (equal type "w") (* 7 value) value)))
  13399. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13400. (setf n2 (+ n1 value))))
  13401. ("m"
  13402. (let* ((add-months
  13403. (lambda (d n)
  13404. ;; Add N months to gregorian date D, i.e.,
  13405. ;; a list (MONTH DAY YEAR). Return a valid
  13406. ;; gregorian date.
  13407. (let ((m (+ (nth 0 d) n)))
  13408. (list (mod m 12)
  13409. (nth 1 d)
  13410. (+ (/ m 12) (nth 2 d))))))
  13411. (months ; Complete months to TARGET.
  13412. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13413. (- (nth 0 target) (nth 0 base))
  13414. ;; If START's day is greater than
  13415. ;; TARGET's, remove incomplete month.
  13416. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13417. value)
  13418. value))
  13419. (before (funcall add-months base months)))
  13420. (setf n1 (calendar-absolute-from-gregorian before))
  13421. (setf n2
  13422. (calendar-absolute-from-gregorian
  13423. (funcall add-months before value)))))
  13424. (_
  13425. (let* ((d (nth 1 base))
  13426. (m (nth 0 base))
  13427. (y (nth 2 base))
  13428. (years ; Complete years to TARGET.
  13429. (* (/ (- (nth 2 target)
  13430. y
  13431. ;; If START's month and day are
  13432. ;; greater than TARGET's, remove
  13433. ;; incomplete year.
  13434. (if (or (> (nth 0 target) m)
  13435. (and (= (nth 0 target) m)
  13436. (> (nth 1 target) d)))
  13437. 0
  13438. 1))
  13439. value)
  13440. value))
  13441. (before (list m d (+ y years))))
  13442. (setf n1 (calendar-absolute-from-gregorian before))
  13443. (setf n2 (calendar-absolute-from-gregorian
  13444. (list m d (+ (nth 2 before) value)))))))
  13445. ;; Handle PREFER parameter, if any.
  13446. (cond
  13447. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13448. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13449. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13450. (defun org-date-to-gregorian (d)
  13451. "Turn any specification of date D into a Gregorian date for the calendar."
  13452. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13453. ((and (listp d) (= (length d) 3)) d)
  13454. ((stringp d)
  13455. (let ((d (org-parse-time-string d)))
  13456. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13457. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13458. (defun org-timestamp-up (&optional arg)
  13459. "Increase the date item at the cursor by one.
  13460. If the cursor is on the year, change the year. If it is on the month,
  13461. the day or the time, change that. If the cursor is on the enclosing
  13462. bracket, change the timestamp type.
  13463. With prefix ARG, change by that many units."
  13464. (interactive "p")
  13465. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13466. (defun org-timestamp-down (&optional arg)
  13467. "Decrease the date item at the cursor by one.
  13468. If the cursor is on the year, change the year. If it is on the month,
  13469. the day or the time, change that. If the cursor is on the enclosing
  13470. bracket, change the timestamp type.
  13471. With prefix ARG, change by that many units."
  13472. (interactive "p")
  13473. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13474. (defun org-timestamp-up-day (&optional arg)
  13475. "Increase the date in the time stamp by one day.
  13476. With prefix ARG, change that many days."
  13477. (interactive "p")
  13478. (if (and (not (org-at-timestamp-p 'lax))
  13479. (org-at-heading-p))
  13480. (org-todo 'up)
  13481. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13482. (defun org-timestamp-down-day (&optional arg)
  13483. "Decrease the date in the time stamp by one day.
  13484. With prefix ARG, change that many days."
  13485. (interactive "p")
  13486. (if (and (not (org-at-timestamp-p 'lax))
  13487. (org-at-heading-p))
  13488. (org-todo 'down)
  13489. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13490. (defun org-at-timestamp-p (&optional extended)
  13491. "Non-nil if point is inside a timestamp.
  13492. By default, the function only consider syntactically valid active
  13493. timestamps. However, the caller may have a broader definition
  13494. for timestamps. As a consequence, optional argument EXTENDED can
  13495. be set to the following values
  13496. `inactive'
  13497. Include also syntactically valid inactive timestamps.
  13498. `agenda'
  13499. Include timestamps allowed in Agenda, i.e., those in
  13500. properties drawers, planning lines and clock lines.
  13501. `lax'
  13502. Ignore context. The function matches any part of the
  13503. document looking like a timestamp. This includes comments,
  13504. example blocks...
  13505. For backward-compatibility with Org 9.0, every other non-nil
  13506. value is equivalent to `inactive'.
  13507. When at a timestamp, return the position of the point as a symbol
  13508. among `bracket', `after', `year', `month', `hour', `minute',
  13509. `day' or a number of character from the last know part of the
  13510. time stamp.
  13511. When matching, the match groups are the following:
  13512. group 1: year
  13513. group 2: month
  13514. group 3: day number
  13515. group 4: day name
  13516. group 5: hours, if any
  13517. group 6: minutes, if any"
  13518. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  13519. (pos (point))
  13520. (match?
  13521. (let ((boundaries (org-in-regexp regexp)))
  13522. (save-match-data
  13523. (cond ((null boundaries) nil)
  13524. ((eq extended 'lax) t)
  13525. (t
  13526. (or (and (eq extended 'agenda)
  13527. (or (org-at-planning-p)
  13528. (org-at-property-p)
  13529. (and (bound-and-true-p
  13530. org-agenda-include-inactive-timestamps)
  13531. (org-at-clock-log-p))))
  13532. (eq 'timestamp
  13533. (save-excursion
  13534. (when (= pos (cdr boundaries)) (forward-char -1))
  13535. (org-element-type (org-element-context)))))))))))
  13536. (cond
  13537. ((not match?) nil)
  13538. ((= pos (match-beginning 0)) 'bracket)
  13539. ;; Distinguish location right before the closing bracket from
  13540. ;; right after it.
  13541. ((= pos (1- (match-end 0))) 'bracket)
  13542. ((= pos (match-end 0)) 'after)
  13543. ((org-pos-in-match-range pos 2) 'year)
  13544. ((org-pos-in-match-range pos 3) 'month)
  13545. ((org-pos-in-match-range pos 7) 'hour)
  13546. ((org-pos-in-match-range pos 8) 'minute)
  13547. ((or (org-pos-in-match-range pos 4)
  13548. (org-pos-in-match-range pos 5)) 'day)
  13549. ((and (> pos (or (match-end 8) (match-end 5)))
  13550. (< pos (match-end 0)))
  13551. (- pos (or (match-end 8) (match-end 5))))
  13552. (t 'day))))
  13553. (defun org-toggle-timestamp-type ()
  13554. "Toggle the type (<active> or [inactive]) of a time stamp."
  13555. (interactive)
  13556. (when (org-at-timestamp-p 'lax)
  13557. (let ((beg (match-beginning 0)) (end (match-end 0))
  13558. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13559. (save-excursion
  13560. (goto-char beg)
  13561. (while (re-search-forward "[][<>]" end t)
  13562. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13563. t t)))
  13564. (message "Timestamp is now %sactive"
  13565. (if (equal (char-after beg) ?<) "" "in")))))
  13566. (defun org-at-clock-log-p ()
  13567. "Non-nil if point is on a clock log line."
  13568. (and (org-match-line org-clock-line-re)
  13569. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13570. (defvar org-clock-history) ; defined in org-clock.el
  13571. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13572. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13573. "Change the date in the time stamp at point.
  13574. The date is changed by N times WHAT. WHAT can be `day', `month',
  13575. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13576. position in the timestamp determines what is changed.
  13577. When optional argument UPDOWN is non-nil, minutes are rounded
  13578. according to `org-time-stamp-rounding-minutes'.
  13579. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13580. \"--2d\"."
  13581. (let ((origin (point))
  13582. (timestamp? (org-at-timestamp-p 'lax))
  13583. origin-cat
  13584. with-hm inactive
  13585. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13586. extra rem
  13587. ts time time0 fixnext clrgx)
  13588. (unless timestamp? (user-error "Not at a timestamp"))
  13589. (if (and (not what) (eq timestamp? 'bracket))
  13590. (org-toggle-timestamp-type)
  13591. ;; Point isn't on brackets. Remember the part of the time-stamp
  13592. ;; the point was in. Indeed, size of time-stamps may change,
  13593. ;; but point must be kept in the same category nonetheless.
  13594. (setq origin-cat timestamp?)
  13595. (when (and (not what) (not (eq timestamp? 'day))
  13596. org-display-custom-times
  13597. (get-text-property (point) 'display)
  13598. (not (get-text-property (1- (point)) 'display)))
  13599. (setq timestamp? 'day))
  13600. (setq timestamp? (or what timestamp?)
  13601. inactive (= (char-after (match-beginning 0)) ?\[)
  13602. ts (match-string 0))
  13603. (replace-match "")
  13604. (when (string-match
  13605. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13606. ts)
  13607. (setq extra (match-string 1 ts))
  13608. (when suppress-tmp-delay
  13609. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13610. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13611. (setq with-hm t))
  13612. (setq time0 (org-parse-time-string ts))
  13613. (when (and updown
  13614. (eq timestamp? 'minute)
  13615. (not current-prefix-arg))
  13616. ;; This looks like s-up and s-down. Change by one rounding step.
  13617. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13618. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13619. (setcar (cdr time0) (+ (nth 1 time0)
  13620. (if (> n 0) (- rem) (- dm rem))))))
  13621. (setq time
  13622. (apply #'encode-time
  13623. (or (car time0) 0)
  13624. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13625. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13626. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13627. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13628. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13629. (nthcdr 6 time0)))
  13630. (when (and (memq timestamp? '(hour minute))
  13631. extra
  13632. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13633. (setq extra (org-modify-ts-extra
  13634. extra
  13635. (if (eq timestamp? 'hour) 2 5)
  13636. n dm)))
  13637. (when (integerp timestamp?)
  13638. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13639. (when (eq what 'calendar)
  13640. (let ((cal-date (org-get-date-from-calendar)))
  13641. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13642. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13643. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13644. (setcar time0 (or (car time0) 0))
  13645. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13646. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13647. (setq time (apply 'encode-time time0))))
  13648. ;; Insert the new time-stamp, and ensure point stays in the same
  13649. ;; category as before (i.e. not after the last position in that
  13650. ;; category).
  13651. (let ((pos (point)))
  13652. ;; Stay before inserted string. `save-excursion' is of no use.
  13653. (setq org-last-changed-timestamp
  13654. (org-insert-time-stamp time with-hm inactive nil nil extra))
  13655. (goto-char pos))
  13656. (save-match-data
  13657. (looking-at org-ts-regexp3)
  13658. (goto-char
  13659. (pcase origin-cat
  13660. ;; `day' category ends before `hour' if any, or at the end
  13661. ;; of the day name.
  13662. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  13663. (`hour (min (match-end 7) origin))
  13664. (`minute (min (1- (match-end 8)) origin))
  13665. ((pred integerp) (min (1- (match-end 0)) origin))
  13666. ;; Point was right after the time-stamp. However, the
  13667. ;; time-stamp length might have changed, so refer to
  13668. ;; (match-end 0) instead.
  13669. (`after (match-end 0))
  13670. ;; `year' and `month' have both fixed size: point couldn't
  13671. ;; have moved into another part.
  13672. (_ origin))))
  13673. ;; Update clock if on a CLOCK line.
  13674. (org-clock-update-time-maybe)
  13675. ;; Maybe adjust the closest clock in `org-clock-history'
  13676. (when org-clock-adjust-closest
  13677. (if (not (and (org-at-clock-log-p)
  13678. (< 1 (length (delq nil (mapcar 'marker-position
  13679. org-clock-history))))))
  13680. (message "No clock to adjust")
  13681. (cond ((save-excursion ; fix previous clock?
  13682. (re-search-backward org-ts-regexp0 nil t)
  13683. (looking-back (concat org-clock-string " \\[")
  13684. (line-beginning-position)))
  13685. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  13686. ((save-excursion ; fix next clock?
  13687. (re-search-backward org-ts-regexp0 nil t)
  13688. (looking-at (concat org-ts-regexp0 "\\] =>")))
  13689. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  13690. (save-window-excursion
  13691. ;; Find closest clock to point, adjust the previous/next one in history
  13692. (let* ((p (save-excursion (org-back-to-heading t)))
  13693. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  13694. (clfixnth
  13695. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  13696. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  13697. (if (not clfixpos)
  13698. (message "No clock to adjust")
  13699. (save-excursion
  13700. (org-goto-marker-or-bmk clfixpos)
  13701. (org-show-subtree)
  13702. (when (re-search-forward clrgx nil t)
  13703. (goto-char (match-beginning 1))
  13704. (let (org-clock-adjust-closest)
  13705. (org-timestamp-change n timestamp? updown))
  13706. (message "Clock adjusted in %s for heading: %s"
  13707. (file-name-nondirectory (buffer-file-name))
  13708. (org-get-heading t t)))))))))
  13709. ;; Try to recenter the calendar window, if any.
  13710. (when (and org-calendar-follow-timestamp-change
  13711. (get-buffer-window "*Calendar*" t)
  13712. (memq timestamp? '(day month year)))
  13713. (org-recenter-calendar (time-to-days time))))))
  13714. (defun org-modify-ts-extra (s pos n dm)
  13715. "Change the different parts of the lead-time and repeat fields in timestamp."
  13716. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  13717. ng h m new rem)
  13718. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  13719. (cond
  13720. ((or (org-pos-in-match-range pos 2)
  13721. (org-pos-in-match-range pos 3))
  13722. (setq m (string-to-number (match-string 3 s))
  13723. h (string-to-number (match-string 2 s)))
  13724. (if (org-pos-in-match-range pos 2)
  13725. (setq h (+ h n))
  13726. (setq n (* dm (with-no-warnings (cl-signum n))))
  13727. (unless (= 0 (setq rem (% m dm)))
  13728. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  13729. (setq m (+ m n)))
  13730. (when (< m 0) (setq m (+ m 60) h (1- h)))
  13731. (when (> m 59) (setq m (- m 60) h (1+ h)))
  13732. (setq h (mod h 24))
  13733. (setq ng 1 new (format "-%02d:%02d" h m)))
  13734. ((org-pos-in-match-range pos 6)
  13735. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  13736. ((org-pos-in-match-range pos 5)
  13737. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  13738. ((org-pos-in-match-range pos 9)
  13739. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  13740. ((org-pos-in-match-range pos 8)
  13741. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  13742. (when ng
  13743. (setq s (concat
  13744. (substring s 0 (match-beginning ng))
  13745. new
  13746. (substring s (match-end ng))))))
  13747. s))
  13748. (defun org-recenter-calendar (d)
  13749. "If the calendar is visible, recenter it to date D."
  13750. (let ((cwin (get-buffer-window "*Calendar*" t)))
  13751. (when cwin
  13752. (let ((calendar-move-hook nil))
  13753. (with-selected-window cwin
  13754. (calendar-goto-date
  13755. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  13756. (defun org-goto-calendar (&optional arg)
  13757. "Go to the Emacs calendar at the current date.
  13758. If there is a time stamp in the current line, go to that date.
  13759. A prefix ARG can be used to force the current date."
  13760. (interactive "P")
  13761. (let ((calendar-move-hook nil)
  13762. (calendar-view-holidays-initially-flag nil)
  13763. (calendar-view-diary-initially-flag nil)
  13764. diff)
  13765. (when (or (org-at-timestamp-p 'lax)
  13766. (org-match-line (concat ".*" org-ts-regexp)))
  13767. (let ((d1 (time-to-days nil))
  13768. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  13769. (setq diff (- d2 d1))))
  13770. (calendar)
  13771. (calendar-goto-today)
  13772. (when (and diff (not arg)) (calendar-forward-day diff))))
  13773. (defun org-get-date-from-calendar ()
  13774. "Return a list (month day year) of date at point in calendar."
  13775. (with-current-buffer "*Calendar*"
  13776. (save-match-data
  13777. (calendar-cursor-to-date))))
  13778. (defun org-date-from-calendar ()
  13779. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  13780. If there is already a time stamp at the cursor position, update it."
  13781. (interactive)
  13782. (if (org-at-timestamp-p 'lax)
  13783. (org-timestamp-change 0 'calendar)
  13784. (let ((cal-date (org-get-date-from-calendar)))
  13785. (org-insert-time-stamp
  13786. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  13787. (defcustom org-image-actual-width t
  13788. "When non-nil, use the actual width of images when inlining them.
  13789. When set to a number, use imagemagick (when available) to set the
  13790. image's width to this value.
  13791. When set to a number in a list, try to get the width from any
  13792. #+ATTR.* keyword if it matches a width specification like
  13793. #+ATTR_HTML: :width 300px
  13794. and fall back on that number if none is found.
  13795. When set to nil, try to get the width from an #+ATTR.* keyword
  13796. and fall back on the original width if none is found.
  13797. When set to any other non-nil value, always use the image width.
  13798. This requires Emacs >= 24.1, built with imagemagick support."
  13799. :group 'org-appearance
  13800. :version "24.4"
  13801. :package-version '(Org . "8.0")
  13802. :type '(choice
  13803. (const :tag "Use the image width" t)
  13804. (integer :tag "Use a number of pixels")
  13805. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  13806. (const :tag "Use #+ATTR* or don't resize" nil)))
  13807. (defcustom org-agenda-inhibit-startup nil
  13808. "Inhibit startup when preparing agenda buffers.
  13809. When this variable is t, the initialization of the Org agenda
  13810. buffers is inhibited: e.g. the visibility state is not set, the
  13811. tables are not re-aligned, etc."
  13812. :type 'boolean
  13813. :version "24.3"
  13814. :group 'org-agenda)
  13815. (defcustom org-agenda-ignore-properties nil
  13816. "Avoid updating text properties when building the agenda.
  13817. Properties are used to prepare buffers for effort estimates,
  13818. appointments, statistics and subtree-local categories.
  13819. If you don't use these in the agenda, you can add them to this
  13820. list and agenda building will be a bit faster.
  13821. The value is a list, with zero or more of the symbols `effort', `appt',
  13822. `stats' or `category'."
  13823. :type '(set :greedy t
  13824. (const effort)
  13825. (const appt)
  13826. (const stats)
  13827. (const category))
  13828. :version "26.1"
  13829. :package-version '(Org . "8.3")
  13830. :group 'org-agenda)
  13831. ;;;; Files
  13832. (defun org-save-all-org-buffers ()
  13833. "Save all Org buffers without user confirmation."
  13834. (interactive)
  13835. (message "Saving all Org buffers...")
  13836. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  13837. (when (featurep 'org-id) (org-id-locations-save))
  13838. (message "Saving all Org buffers... done"))
  13839. (defun org-revert-all-org-buffers ()
  13840. "Revert all Org buffers.
  13841. Prompt for confirmation when there are unsaved changes.
  13842. Be sure you know what you are doing before letting this function
  13843. overwrite your changes.
  13844. This function is useful in a setup where one tracks Org files
  13845. with a version control system, to revert on one machine after pulling
  13846. changes from another. I believe the procedure must be like this:
  13847. 1. M-x org-save-all-org-buffers
  13848. 2. Pull changes from the other machine, resolve conflicts
  13849. 3. M-x org-revert-all-org-buffers"
  13850. (interactive)
  13851. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  13852. (user-error "Abort"))
  13853. (save-excursion
  13854. (save-window-excursion
  13855. (dolist (b (buffer-list))
  13856. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  13857. (with-current-buffer b buffer-file-name))
  13858. (pop-to-buffer-same-window b)
  13859. (revert-buffer t 'no-confirm)))
  13860. (when (and (featurep 'org-id) org-id-track-globally)
  13861. (org-id-locations-load)))))
  13862. ;;;; Agenda files
  13863. ;;;###autoload
  13864. (defun org-switchb (&optional arg)
  13865. "Switch between Org buffers.
  13866. With `\\[universal-argument]' prefix, restrict available buffers to files.
  13867. With `\\[universal-argument] \\[universal-argument]' \
  13868. prefix, restrict available buffers to agenda files."
  13869. (interactive "P")
  13870. (let ((blist (org-buffer-list
  13871. (cond ((equal arg '(4)) 'files)
  13872. ((equal arg '(16)) 'agenda)))))
  13873. (pop-to-buffer-same-window
  13874. (completing-read "Org buffer: "
  13875. (mapcar #'list (mapcar #'buffer-name blist))
  13876. nil t))))
  13877. (defun org-buffer-list (&optional predicate exclude-tmp)
  13878. "Return a list of Org buffers.
  13879. PREDICATE can be `export', `files' or `agenda'.
  13880. export restrict the list to Export buffers.
  13881. files restrict the list to buffers visiting Org files.
  13882. agenda restrict the list to buffers visiting agenda files.
  13883. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  13884. (let* ((bfn nil)
  13885. (agenda-files (and (eq predicate 'agenda)
  13886. (mapcar 'file-truename (org-agenda-files t))))
  13887. (filter
  13888. (cond
  13889. ((eq predicate 'files)
  13890. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  13891. ((eq predicate 'export)
  13892. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  13893. ((eq predicate 'agenda)
  13894. (lambda (b)
  13895. (with-current-buffer b
  13896. (and (derived-mode-p 'org-mode)
  13897. (setq bfn (buffer-file-name b))
  13898. (member (file-truename bfn) agenda-files)))))
  13899. (t (lambda (b) (with-current-buffer b
  13900. (or (derived-mode-p 'org-mode)
  13901. (string-match "\\*Org .*Export"
  13902. (buffer-name b)))))))))
  13903. (delq nil
  13904. (mapcar
  13905. (lambda(b)
  13906. (if (and (funcall filter b)
  13907. (or (not exclude-tmp)
  13908. (not (string-match "tmp" (buffer-name b)))))
  13909. b
  13910. nil))
  13911. (buffer-list)))))
  13912. (defun org-agenda-files (&optional unrestricted archives)
  13913. "Get the list of agenda files.
  13914. Optional UNRESTRICTED means return the full list even if a restriction
  13915. is currently in place.
  13916. When ARCHIVES is t, include all archive files that are really being
  13917. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  13918. `org-agenda-archives-mode' is t."
  13919. (let ((files
  13920. (cond
  13921. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  13922. ((stringp org-agenda-files) (org-read-agenda-file-list))
  13923. ((listp org-agenda-files) org-agenda-files)
  13924. (t (error "Invalid value of `org-agenda-files'")))))
  13925. (setq files (apply 'append
  13926. (mapcar (lambda (f)
  13927. (if (file-directory-p f)
  13928. (directory-files
  13929. f t org-agenda-file-regexp)
  13930. (list f)))
  13931. files)))
  13932. (when org-agenda-skip-unavailable-files
  13933. (setq files (delq nil
  13934. (mapcar (function
  13935. (lambda (file)
  13936. (and (file-readable-p file) file)))
  13937. files))))
  13938. (when (or (eq archives t)
  13939. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  13940. (setq files (org-add-archive-files files)))
  13941. files))
  13942. (defun org-agenda-file-p (&optional file)
  13943. "Return non-nil, if FILE is an agenda file.
  13944. If FILE is omitted, use the file associated with the current
  13945. buffer."
  13946. (let ((fname (or file (buffer-file-name))))
  13947. (and fname
  13948. (member (file-truename fname)
  13949. (mapcar #'file-truename (org-agenda-files t))))))
  13950. (defun org-edit-agenda-file-list ()
  13951. "Edit the list of agenda files.
  13952. Depending on setup, this either uses customize to edit the variable
  13953. `org-agenda-files', or it visits the file that is holding the list. In the
  13954. latter case, the buffer is set up in a way that saving it automatically kills
  13955. the buffer and restores the previous window configuration."
  13956. (interactive)
  13957. (if (stringp org-agenda-files)
  13958. (let ((cw (current-window-configuration)))
  13959. (find-file org-agenda-files)
  13960. (setq-local org-window-configuration cw)
  13961. (add-hook 'after-save-hook
  13962. (lambda ()
  13963. (set-window-configuration
  13964. (prog1 org-window-configuration
  13965. (kill-buffer (current-buffer))))
  13966. (org-install-agenda-files-menu)
  13967. (message "New agenda file list installed"))
  13968. nil 'local)
  13969. (message "%s" (substitute-command-keys
  13970. "Edit list and finish with \\[save-buffer]")))
  13971. (customize-variable 'org-agenda-files)))
  13972. (defun org-store-new-agenda-file-list (list)
  13973. "Set new value for the agenda file list and save it correctly."
  13974. (if (stringp org-agenda-files)
  13975. (let ((fe (org-read-agenda-file-list t)) b u)
  13976. (while (setq b (find-buffer-visiting org-agenda-files))
  13977. (kill-buffer b))
  13978. (with-temp-file org-agenda-files
  13979. (insert
  13980. (mapconcat
  13981. (lambda (f) ;; Keep un-expanded entries.
  13982. (if (setq u (assoc f fe))
  13983. (cdr u)
  13984. f))
  13985. list "\n")
  13986. "\n")))
  13987. (let ((org-mode-hook nil) (org-inhibit-startup t)
  13988. (org-insert-mode-line-in-empty-file nil))
  13989. (setq org-agenda-files list)
  13990. (customize-save-variable 'org-agenda-files org-agenda-files))))
  13991. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  13992. "Read the list of agenda files from a file.
  13993. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  13994. filenames, used by `org-store-new-agenda-file-list' to write back
  13995. un-expanded file names."
  13996. (when (file-directory-p org-agenda-files)
  13997. (error "`org-agenda-files' cannot be a single directory"))
  13998. (when (stringp org-agenda-files)
  13999. (with-temp-buffer
  14000. (insert-file-contents org-agenda-files)
  14001. (mapcar
  14002. (lambda (f)
  14003. (let ((e (expand-file-name (substitute-in-file-name f)
  14004. org-directory)))
  14005. (if pair-with-expansion
  14006. (cons e f)
  14007. e)))
  14008. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  14009. ;;;###autoload
  14010. (defun org-cycle-agenda-files ()
  14011. "Cycle through the files in `org-agenda-files'.
  14012. If the current buffer visits an agenda file, find the next one in the list.
  14013. If the current buffer does not, find the first agenda file."
  14014. (interactive)
  14015. (let* ((fs (or (org-agenda-files t)
  14016. (user-error "No agenda files")))
  14017. (files (copy-sequence fs))
  14018. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  14019. file)
  14020. (when tcf
  14021. (while (and (setq file (pop files))
  14022. (not (equal (file-truename file) tcf)))))
  14023. (find-file (car (or files fs)))
  14024. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  14025. (defun org-agenda-file-to-front (&optional to-end)
  14026. "Move/add the current file to the top of the agenda file list.
  14027. If the file is not present in the list, it is added to the front. If it is
  14028. present, it is moved there. With optional argument TO-END, add/move to the
  14029. end of the list."
  14030. (interactive "P")
  14031. (let ((org-agenda-skip-unavailable-files nil)
  14032. (file-alist (mapcar (lambda (x)
  14033. (cons (file-truename x) x))
  14034. (org-agenda-files t)))
  14035. (ctf (file-truename
  14036. (or buffer-file-name
  14037. (user-error "Please save the current buffer to a file"))))
  14038. x had)
  14039. (setq x (assoc ctf file-alist) had x)
  14040. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  14041. (if to-end
  14042. (setq file-alist (append (delq x file-alist) (list x)))
  14043. (setq file-alist (cons x (delq x file-alist))))
  14044. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  14045. (org-install-agenda-files-menu)
  14046. (message "File %s to %s of agenda file list"
  14047. (if had "moved" "added") (if to-end "end" "front"))))
  14048. (defun org-remove-file (&optional file)
  14049. "Remove current file from the list of files in variable `org-agenda-files'.
  14050. These are the files which are being checked for agenda entries.
  14051. Optional argument FILE means use this file instead of the current."
  14052. (interactive)
  14053. (let* ((org-agenda-skip-unavailable-files nil)
  14054. (file (or file buffer-file-name
  14055. (user-error "Current buffer does not visit a file")))
  14056. (true-file (file-truename file))
  14057. (afile (abbreviate-file-name file))
  14058. (files (delq nil (mapcar
  14059. (lambda (x)
  14060. (unless (equal true-file
  14061. (file-truename x))
  14062. x))
  14063. (org-agenda-files t)))))
  14064. (if (not (= (length files) (length (org-agenda-files t))))
  14065. (progn
  14066. (org-store-new-agenda-file-list files)
  14067. (org-install-agenda-files-menu)
  14068. (message "Removed from Org Agenda list: %s" afile))
  14069. (message "File was not in list: %s (not removed)" afile))))
  14070. (defun org-file-menu-entry (file)
  14071. (vector file (list 'find-file file) t))
  14072. (defun org-check-agenda-file (file)
  14073. "Make sure FILE exists. If not, ask user what to do."
  14074. (unless (file-exists-p file)
  14075. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  14076. (abbreviate-file-name file))
  14077. (let ((r (downcase (read-char-exclusive))))
  14078. (cond
  14079. ((equal r ?r)
  14080. (org-remove-file file)
  14081. (throw 'nextfile t))
  14082. (t (user-error "Abort"))))))
  14083. (defun org-get-agenda-file-buffer (file)
  14084. "Get an agenda buffer visiting FILE.
  14085. If the buffer needs to be created, add it to the list of buffers
  14086. which might be released later."
  14087. (let ((buf (org-find-base-buffer-visiting file)))
  14088. (if buf
  14089. buf ; just return it
  14090. ;; Make a new buffer and remember it
  14091. (setq buf (find-file-noselect file))
  14092. (when buf (push buf org-agenda-new-buffers))
  14093. buf)))
  14094. (defun org-release-buffers (blist)
  14095. "Release all buffers in list, asking the user for confirmation when needed.
  14096. When a buffer is unmodified, it is just killed. When modified, it is saved
  14097. \(if the user agrees) and then killed."
  14098. (let (file)
  14099. (dolist (buf blist)
  14100. (setq file (buffer-file-name buf))
  14101. (when (and (buffer-modified-p buf)
  14102. file
  14103. (y-or-n-p (format "Save file %s? " file)))
  14104. (with-current-buffer buf (save-buffer)))
  14105. (kill-buffer buf))))
  14106. (defun org-agenda-prepare-buffers (files)
  14107. "Create buffers for all agenda files, protect archived trees and comments."
  14108. (interactive)
  14109. (let ((pa '(:org-archived t))
  14110. (pc '(:org-comment t))
  14111. (pall '(:org-archived t :org-comment t))
  14112. (inhibit-read-only t)
  14113. (org-inhibit-startup org-agenda-inhibit-startup)
  14114. (rea (org-make-tag-string (list org-archive-tag)))
  14115. re pos)
  14116. (setq org-tag-alist-for-agenda nil
  14117. org-tag-groups-alist-for-agenda nil)
  14118. (save-excursion
  14119. (save-restriction
  14120. (dolist (file files)
  14121. (catch 'nextfile
  14122. (if (bufferp file)
  14123. (set-buffer file)
  14124. (org-check-agenda-file file)
  14125. (set-buffer (org-get-agenda-file-buffer file)))
  14126. (widen)
  14127. (org-set-regexps-and-options 'tags-only)
  14128. (setq pos (point))
  14129. (or (memq 'category org-agenda-ignore-properties)
  14130. (org-refresh-category-properties))
  14131. (or (memq 'stats org-agenda-ignore-properties)
  14132. (org-refresh-stats-properties))
  14133. (or (memq 'effort org-agenda-ignore-properties)
  14134. (org-refresh-effort-properties))
  14135. (or (memq 'appt org-agenda-ignore-properties)
  14136. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  14137. (setq org-todo-keywords-for-agenda
  14138. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  14139. (setq org-done-keywords-for-agenda
  14140. (append org-done-keywords-for-agenda org-done-keywords))
  14141. (setq org-todo-keyword-alist-for-agenda
  14142. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  14143. (setq org-tag-alist-for-agenda
  14144. (org--tag-add-to-alist
  14145. org-tag-alist-for-agenda
  14146. org-current-tag-alist))
  14147. ;; Merge current file's tag groups into global
  14148. ;; `org-tag-groups-alist-for-agenda'.
  14149. (when org-group-tags
  14150. (dolist (alist org-tag-groups-alist)
  14151. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  14152. (if old
  14153. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  14154. (push alist org-tag-groups-alist-for-agenda)))))
  14155. (with-silent-modifications
  14156. (save-excursion
  14157. (remove-text-properties (point-min) (point-max) pall)
  14158. (when org-agenda-skip-archived-trees
  14159. (goto-char (point-min))
  14160. (while (re-search-forward rea nil t)
  14161. (when (org-at-heading-p t)
  14162. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  14163. (goto-char (point-min))
  14164. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  14165. (while (re-search-forward re nil t)
  14166. (when (save-match-data (org-in-commented-heading-p t))
  14167. (add-text-properties
  14168. (match-beginning 0) (org-end-of-subtree t) pc)))))
  14169. (goto-char pos)))))
  14170. (setq org-todo-keywords-for-agenda
  14171. (org-uniquify org-todo-keywords-for-agenda))
  14172. (setq org-todo-keyword-alist-for-agenda
  14173. (org-uniquify org-todo-keyword-alist-for-agenda))))
  14174. ;;;; CDLaTeX minor mode
  14175. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  14176. "Keymap for the minor `org-cdlatex-mode'.")
  14177. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  14178. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  14179. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  14180. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  14181. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  14182. (defvar org-cdlatex-texmathp-advice-is-done nil
  14183. "Flag remembering if we have applied the advice to texmathp already.")
  14184. (define-minor-mode org-cdlatex-mode
  14185. "Toggle the minor `org-cdlatex-mode'.
  14186. This mode supports entering LaTeX environment and math in LaTeX fragments
  14187. in Org mode.
  14188. \\{org-cdlatex-mode-map}"
  14189. nil " OCDL" nil
  14190. (when org-cdlatex-mode
  14191. (require 'cdlatex)
  14192. (run-hooks 'cdlatex-mode-hook)
  14193. (cdlatex-compute-tables))
  14194. (unless org-cdlatex-texmathp-advice-is-done
  14195. (setq org-cdlatex-texmathp-advice-is-done t)
  14196. (defadvice texmathp (around org-math-always-on activate)
  14197. "Always return t in Org buffers.
  14198. This is because we want to insert math symbols without dollars even outside
  14199. the LaTeX math segments. If Org mode thinks that point is actually inside
  14200. an embedded LaTeX fragment, let `texmathp' do its job.
  14201. `\\[org-cdlatex-mode-map]'"
  14202. (interactive)
  14203. (let (p)
  14204. (cond
  14205. ((not (derived-mode-p 'org-mode)) ad-do-it)
  14206. ((eq this-command 'cdlatex-math-symbol)
  14207. (setq ad-return-value t
  14208. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  14209. (t
  14210. (let ((p (org-inside-LaTeX-fragment-p)))
  14211. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  14212. (setq ad-return-value t
  14213. texmathp-why '("Org mode embedded math" . 0))
  14214. (when p ad-do-it)))))))))
  14215. (defun turn-on-org-cdlatex ()
  14216. "Unconditionally turn on `org-cdlatex-mode'."
  14217. (org-cdlatex-mode 1))
  14218. (defun org-try-cdlatex-tab ()
  14219. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  14220. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  14221. - inside a LaTeX fragment, or
  14222. - after the first word in a line, where an abbreviation expansion could
  14223. insert a LaTeX environment."
  14224. (when org-cdlatex-mode
  14225. (cond
  14226. ;; Before any word on the line: No expansion possible.
  14227. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  14228. ;; Just after first word on the line: Expand it. Make sure it
  14229. ;; cannot happen on headlines, though.
  14230. ((save-excursion
  14231. (skip-chars-backward "a-zA-Z0-9*")
  14232. (skip-chars-backward " \t")
  14233. (and (bolp) (not (org-at-heading-p))))
  14234. (cdlatex-tab) t)
  14235. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  14236. (defun org-cdlatex-underscore-caret (&optional _arg)
  14237. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  14238. Revert to the normal definition outside of these fragments."
  14239. (interactive "P")
  14240. (if (org-inside-LaTeX-fragment-p)
  14241. (call-interactively 'cdlatex-sub-superscript)
  14242. (let (org-cdlatex-mode)
  14243. (call-interactively (key-binding (vector last-input-event))))))
  14244. (defun org-cdlatex-math-modify (&optional _arg)
  14245. "Execute `cdlatex-math-modify' in LaTeX fragments.
  14246. Revert to the normal definition outside of these fragments."
  14247. (interactive "P")
  14248. (if (org-inside-LaTeX-fragment-p)
  14249. (call-interactively 'cdlatex-math-modify)
  14250. (let (org-cdlatex-mode)
  14251. (call-interactively (key-binding (vector last-input-event))))))
  14252. (defun org-cdlatex-environment-indent (&optional environment item)
  14253. "Execute `cdlatex-environment' and indent the inserted environment.
  14254. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  14255. The inserted environment is indented to current indentation
  14256. unless point is at the beginning of the line, in which the
  14257. environment remains unintended."
  14258. (interactive)
  14259. ;; cdlatex-environment always return nil. Therefore, capture output
  14260. ;; first and determine if an environment was selected.
  14261. (let* ((beg (point-marker))
  14262. (end (copy-marker (point) t))
  14263. (inserted (progn
  14264. (ignore-errors (cdlatex-environment environment item))
  14265. (< beg end)))
  14266. ;; Figure out how many lines to move forward after the
  14267. ;; environment has been inserted.
  14268. (lines (when inserted
  14269. (save-excursion
  14270. (- (cl-loop while (< beg (point))
  14271. with x = 0
  14272. do (forward-line -1)
  14273. (cl-incf x)
  14274. finally return x)
  14275. (if (progn (goto-char beg)
  14276. (and (progn (skip-chars-forward " \t") (eolp))
  14277. (progn (skip-chars-backward " \t") (bolp))))
  14278. 1 0)))))
  14279. (env (org-trim (delete-and-extract-region beg end))))
  14280. (when inserted
  14281. ;; Get indentation of next line unless at column 0.
  14282. (let ((ind (if (bolp) 0
  14283. (save-excursion
  14284. (org-return t)
  14285. (prog1 (current-indentation)
  14286. (when (progn (skip-chars-forward " \t") (eolp))
  14287. (delete-region beg (point)))))))
  14288. (bol (progn (skip-chars-backward " \t") (bolp))))
  14289. ;; Insert a newline before environment unless at column zero
  14290. ;; to "escape" the current line. Insert a newline if
  14291. ;; something is one the same line as \end{ENVIRONMENT}.
  14292. (insert
  14293. (concat (unless bol "\n") env
  14294. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14295. (unless (zerop ind)
  14296. (save-excursion
  14297. (goto-char beg)
  14298. (while (< (point) end)
  14299. (unless (eolp) (indent-line-to ind))
  14300. (forward-line))))
  14301. (goto-char beg)
  14302. (forward-line lines)
  14303. (indent-line-to ind)))
  14304. (set-marker beg nil)
  14305. (set-marker end nil)))
  14306. ;;;; LaTeX fragments
  14307. (defun org-inside-LaTeX-fragment-p ()
  14308. "Test if point is inside a LaTeX fragment.
  14309. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14310. sequence appearing also before point.
  14311. Even though the matchers for math are configurable, this function assumes
  14312. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14313. delimiters are skipped when they have been removed by customization.
  14314. The return value is nil, or a cons cell with the delimiter and the
  14315. position of this delimiter.
  14316. This function does a reasonably good job, but can locally be fooled by
  14317. for example currency specifications. For example it will assume being in
  14318. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14319. fragments that are properly closed, but during editing, we have to live
  14320. with the uncertainty caused by missing closing delimiters. This function
  14321. looks only before point, not after."
  14322. (catch 'exit
  14323. (let ((pos (point))
  14324. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14325. (lim (progn
  14326. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil
  14327. 'move)
  14328. (point)))
  14329. dd-on str (start 0) m re)
  14330. (goto-char pos)
  14331. (when dodollar
  14332. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14333. re (nth 1 (assoc "$" org-latex-regexps)))
  14334. (while (string-match re str start)
  14335. (cond
  14336. ((= (match-end 0) (length str))
  14337. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14338. ((= (match-end 0) (- (length str) 5))
  14339. (throw 'exit nil))
  14340. (t (setq start (match-end 0))))))
  14341. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14342. (goto-char pos)
  14343. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14344. (and (match-beginning 2) (throw 'exit nil))
  14345. ;; count $$
  14346. (while (re-search-backward "\\$\\$" lim t)
  14347. (setq dd-on (not dd-on)))
  14348. (goto-char pos)
  14349. (when dd-on (cons "$$" m))))))
  14350. (defun org-inside-latex-macro-p ()
  14351. "Is point inside a LaTeX macro or its arguments?"
  14352. (save-match-data
  14353. (org-in-regexp
  14354. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14355. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14356. "Build an overlay between BEG and END using IMAGE file.
  14357. Argument IMAGETYPE is the extension of the displayed image,
  14358. as a string. It defaults to \"png\"."
  14359. (let ((ov (make-overlay beg end))
  14360. (imagetype (or (intern imagetype) 'png)))
  14361. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14362. (overlay-put ov 'evaporate t)
  14363. (overlay-put ov
  14364. 'modification-hooks
  14365. (list (lambda (o _flag _beg _end &optional _l)
  14366. (delete-overlay o))))
  14367. (overlay-put ov
  14368. 'display
  14369. (list 'image :type imagetype :file image :ascent 'center))))
  14370. (defun org-clear-latex-preview (&optional beg end)
  14371. "Remove all overlays with LaTeX fragment images in current buffer.
  14372. When optional arguments BEG and END are non-nil, remove all
  14373. overlays between them instead. Return a non-nil value when some
  14374. overlays were removed, nil otherwise."
  14375. (let ((overlays
  14376. (cl-remove-if-not
  14377. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14378. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14379. (mapc #'delete-overlay overlays)
  14380. overlays))
  14381. (defun org--latex-preview-region (beg end)
  14382. "Preview LaTeX fragments between BEG and END.
  14383. BEG and END are buffer positions."
  14384. (let ((file (buffer-file-name (buffer-base-buffer))))
  14385. (save-excursion
  14386. (org-format-latex
  14387. (concat org-preview-latex-image-directory "org-ltximg")
  14388. beg end
  14389. ;; Emacs cannot overlay images from remote hosts. Create it in
  14390. ;; `temporary-file-directory' instead.
  14391. (if (or (not file) (file-remote-p file))
  14392. temporary-file-directory
  14393. default-directory)
  14394. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14395. (defun org-latex-preview (&optional arg)
  14396. "Toggle preview of the LaTeX fragment at point.
  14397. If the cursor is on a LaTeX fragment, create the image and
  14398. overlay it over the source code, if there is none. Remove it
  14399. otherwise. If there is no fragment at point, display images for
  14400. all fragments in the current section.
  14401. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14402. for all fragments
  14403. in the current section.
  14404. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14405. argument ARG, display image for all
  14406. fragments in the buffer.
  14407. With a `\\[universal-argument] \\[universal-argument] \
  14408. \\[universal-argument]' prefix argument ARG, clear image for all
  14409. fragments in the buffer."
  14410. (interactive "P")
  14411. (cond
  14412. ((not (display-graphic-p)) nil)
  14413. ;; Clear whole buffer.
  14414. ((equal arg '(64))
  14415. (org-clear-latex-preview (point-min) (point-max))
  14416. (message "LaTeX previews removed from buffer"))
  14417. ;; Preview whole buffer.
  14418. ((equal arg '(16))
  14419. (message "Creating LaTeX previews in buffer...")
  14420. (org--latex-preview-region (point-min) (point-max))
  14421. (message "Creating LaTeX previews in buffer... done."))
  14422. ;; Clear current section.
  14423. ((equal arg '(4))
  14424. (org-clear-latex-preview
  14425. (if (org-before-first-heading-p) (point-min)
  14426. (save-excursion
  14427. (org-with-limited-levels (org-back-to-heading t) (point))))
  14428. (org-with-limited-levels (org-entry-end-position))))
  14429. ;; Toggle preview on LaTeX code at point.
  14430. ((let ((datum (org-element-context)))
  14431. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14432. (let ((beg (org-element-property :begin datum))
  14433. (end (org-element-property :end datum)))
  14434. (if (org-clear-latex-preview beg end)
  14435. (message "LaTeX preview removed")
  14436. (message "Creating LaTeX preview...")
  14437. (org--latex-preview-region beg end)
  14438. (message "Creating LaTeX preview... done."))
  14439. t))))
  14440. ;; Preview current section.
  14441. (t
  14442. (let ((beg (if (org-before-first-heading-p) (point-min)
  14443. (save-excursion
  14444. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14445. (end (org-with-limited-levels (org-entry-end-position))))
  14446. (message "Creating LaTeX previews in section...")
  14447. (org--latex-preview-region beg end)
  14448. (message "Creating LaTeX previews in section... done.")))))
  14449. (defun org-format-latex
  14450. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14451. "Replace LaTeX fragments with links to an image.
  14452. The function takes care of creating the replacement image.
  14453. Only consider fragments between BEG and END when those are
  14454. provided.
  14455. When optional argument OVERLAYS is non-nil, display the image on
  14456. top of the fragment instead of replacing it.
  14457. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14458. Some of the options can be changed using the variable
  14459. `org-format-latex-options', which see."
  14460. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14461. (unless (eq processing-type 'verbatim)
  14462. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14463. (cnt 0)
  14464. checkdir-flag)
  14465. (goto-char (or beg (point-min)))
  14466. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14467. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14468. (overlay-recenter (or end (point-max))))
  14469. (while (re-search-forward math-regexp end t)
  14470. (unless (and overlays
  14471. (eq (get-char-property (point) 'org-overlay-type)
  14472. 'org-latex-overlay))
  14473. (let* ((context (org-element-context))
  14474. (type (org-element-type context)))
  14475. (when (memq type '(latex-environment latex-fragment))
  14476. (let ((block-type (eq type 'latex-environment))
  14477. (value (org-element-property :value context))
  14478. (beg (org-element-property :begin context))
  14479. (end (save-excursion
  14480. (goto-char (org-element-property :end context))
  14481. (skip-chars-backward " \r\t\n")
  14482. (point))))
  14483. (cond
  14484. ((eq processing-type 'mathjax)
  14485. ;; Prepare for MathJax processing.
  14486. (if (not (string-match "\\`\\$\\$?" value))
  14487. (goto-char end)
  14488. (delete-region beg end)
  14489. (if (string= (match-string 0 value) "$$")
  14490. (insert "\\[" (substring value 2 -2) "\\]")
  14491. (insert "\\(" (substring value 1 -1) "\\)"))))
  14492. ((eq processing-type 'html)
  14493. (goto-char beg)
  14494. (delete-region beg end)
  14495. (insert (org-format-latex-as-html value)))
  14496. ((assq processing-type org-preview-latex-process-alist)
  14497. ;; Process to an image.
  14498. (cl-incf cnt)
  14499. (goto-char beg)
  14500. (let* ((processing-info
  14501. (cdr (assq processing-type org-preview-latex-process-alist)))
  14502. (face (face-at-point))
  14503. ;; Get the colors from the face at point.
  14504. (fg
  14505. (let ((color (plist-get org-format-latex-options
  14506. :foreground)))
  14507. (if (and forbuffer (eq color 'auto))
  14508. (face-attribute face :foreground nil 'default)
  14509. color)))
  14510. (bg
  14511. (let ((color (plist-get org-format-latex-options
  14512. :background)))
  14513. (if (and forbuffer (eq color 'auto))
  14514. (face-attribute face :background nil 'default)
  14515. color)))
  14516. (hash (sha1 (prin1-to-string
  14517. (list org-format-latex-header
  14518. org-latex-default-packages-alist
  14519. org-latex-packages-alist
  14520. org-format-latex-options
  14521. forbuffer value fg bg))))
  14522. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14523. (absprefix (expand-file-name prefix dir))
  14524. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14525. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14526. (sep (and block-type "\n\n"))
  14527. (link (concat sep "[[file:" linkfile "]]" sep))
  14528. (options
  14529. (org-combine-plists
  14530. org-format-latex-options
  14531. `(:foreground ,fg :background ,bg))))
  14532. (when msg (message msg cnt))
  14533. (unless checkdir-flag ; Ensure the directory exists.
  14534. (setq checkdir-flag t)
  14535. (let ((todir (file-name-directory absprefix)))
  14536. (unless (file-directory-p todir)
  14537. (make-directory todir t))))
  14538. (unless (file-exists-p movefile)
  14539. (org-create-formula-image
  14540. value movefile options forbuffer processing-type))
  14541. (if overlays
  14542. (progn
  14543. (dolist (o (overlays-in beg end))
  14544. (when (eq (overlay-get o 'org-overlay-type)
  14545. 'org-latex-overlay)
  14546. (delete-overlay o)))
  14547. (org--make-preview-overlay beg end movefile imagetype)
  14548. (goto-char end))
  14549. (delete-region beg end)
  14550. (insert
  14551. (org-add-props link
  14552. (list 'org-latex-src
  14553. (replace-regexp-in-string "\"" "" value)
  14554. 'org-latex-src-embed-type
  14555. (if block-type 'paragraph 'character)))))))
  14556. ((eq processing-type 'mathml)
  14557. ;; Process to MathML.
  14558. (unless (org-format-latex-mathml-available-p)
  14559. (user-error "LaTeX to MathML converter not configured"))
  14560. (cl-incf cnt)
  14561. (when msg (message msg cnt))
  14562. (goto-char beg)
  14563. (delete-region beg end)
  14564. (insert (org-format-latex-as-mathml
  14565. value block-type prefix dir)))
  14566. (t
  14567. (error "Unknown conversion process %s for LaTeX fragments"
  14568. processing-type)))))))))))
  14569. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14570. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14571. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14572. successful, return the portion between \"<math...> </math>\"
  14573. elements otherwise return nil. When MATHML-FILE is specified,
  14574. write the results in to that file. When invoked as an
  14575. interactive command, prompt for LATEX-FRAG, with initial value
  14576. set to the current active region and echo the results for user
  14577. inspection."
  14578. (interactive (list (let ((frag (when (org-region-active-p)
  14579. (buffer-substring-no-properties
  14580. (region-beginning) (region-end)))))
  14581. (read-string "LaTeX Fragment: " frag nil frag))))
  14582. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14583. (let* ((tmp-in-file
  14584. (let ((file (file-relative-name
  14585. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14586. (write-region latex-frag nil file)
  14587. file))
  14588. (tmp-out-file (file-relative-name
  14589. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14590. (cmd (format-spec
  14591. org-latex-to-mathml-convert-command
  14592. `((?j . ,(and org-latex-to-mathml-jar-file
  14593. (shell-quote-argument
  14594. (expand-file-name
  14595. org-latex-to-mathml-jar-file))))
  14596. (?I . ,(shell-quote-argument tmp-in-file))
  14597. (?i . ,latex-frag)
  14598. (?o . ,(shell-quote-argument tmp-out-file)))))
  14599. mathml shell-command-output)
  14600. (when (called-interactively-p 'any)
  14601. (unless (org-format-latex-mathml-available-p)
  14602. (user-error "LaTeX to MathML converter not configured")))
  14603. (message "Running %s" cmd)
  14604. (setq shell-command-output (shell-command-to-string cmd))
  14605. (setq mathml
  14606. (when (file-readable-p tmp-out-file)
  14607. (with-current-buffer (find-file-noselect tmp-out-file t)
  14608. (goto-char (point-min))
  14609. (when (re-search-forward
  14610. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14611. (regexp-quote
  14612. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14613. nil t)
  14614. (prog1 (match-string 0) (kill-buffer))))))
  14615. (cond
  14616. (mathml
  14617. (setq mathml
  14618. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14619. (when mathml-file
  14620. (write-region mathml nil mathml-file))
  14621. (when (called-interactively-p 'any)
  14622. (message mathml)))
  14623. ((warn "LaTeX to MathML conversion failed")
  14624. (message shell-command-output)))
  14625. (delete-file tmp-in-file)
  14626. (when (file-exists-p tmp-out-file)
  14627. (delete-file tmp-out-file))
  14628. mathml))
  14629. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14630. prefix &optional dir)
  14631. "Use `org-create-math-formula' but check local cache first."
  14632. (let* ((absprefix (expand-file-name prefix dir))
  14633. (print-length nil) (print-level nil)
  14634. (formula-id (concat
  14635. "formula-"
  14636. (sha1
  14637. (prin1-to-string
  14638. (list latex-frag
  14639. org-latex-to-mathml-convert-command)))))
  14640. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14641. (formula-cache-dir (file-name-directory formula-cache)))
  14642. (unless (file-directory-p formula-cache-dir)
  14643. (make-directory formula-cache-dir t))
  14644. (unless (file-exists-p formula-cache)
  14645. (org-create-math-formula latex-frag formula-cache))
  14646. (if (file-exists-p formula-cache)
  14647. ;; Successful conversion. Return the link to MathML file.
  14648. (org-add-props
  14649. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14650. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14651. 'org-latex-src-embed-type (if latex-frag-type
  14652. 'paragraph 'character)))
  14653. ;; Failed conversion. Return the LaTeX fragment verbatim
  14654. latex-frag)))
  14655. (defun org-format-latex-as-html (latex-fragment)
  14656. "Convert LATEX-FRAGMENT to HTML.
  14657. This uses `org-latex-to-html-convert-command', which see."
  14658. (let ((cmd (format-spec org-latex-to-html-convert-command
  14659. `((?i . ,latex-fragment)))))
  14660. (message "Running %s" cmd)
  14661. (shell-command-to-string cmd)))
  14662. (defun org--get-display-dpi ()
  14663. "Get the DPI of the display.
  14664. The function assumes that the display has the same pixel width in
  14665. the horizontal and vertical directions."
  14666. (if (display-graphic-p)
  14667. (round (/ (display-pixel-height)
  14668. (/ (display-mm-height) 25.4)))
  14669. (error "Attempt to calculate the dpi of a non-graphic display")))
  14670. (defun org-create-formula-image
  14671. (string tofile options buffer &optional processing-type)
  14672. "Create an image from LaTeX source using external processes.
  14673. The LaTeX STRING is saved to a temporary LaTeX file, then
  14674. converted to an image file by process PROCESSING-TYPE defined in
  14675. `org-preview-latex-process-alist'. A nil value defaults to
  14676. `org-preview-latex-default-process'.
  14677. The generated image file is eventually moved to TOFILE.
  14678. The OPTIONS argument controls the size, foreground color and
  14679. background color of the generated image.
  14680. When BUFFER non-nil, this function is used for LaTeX previewing.
  14681. Otherwise, it is used to deal with LaTeX snippets showed in
  14682. a HTML file."
  14683. (let* ((processing-type (or processing-type
  14684. org-preview-latex-default-process))
  14685. (processing-info
  14686. (cdr (assq processing-type org-preview-latex-process-alist)))
  14687. (programs (plist-get processing-info :programs))
  14688. (error-message (or (plist-get processing-info :message) ""))
  14689. (image-input-type (plist-get processing-info :image-input-type))
  14690. (image-output-type (plist-get processing-info :image-output-type))
  14691. (post-clean (or (plist-get processing-info :post-clean)
  14692. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  14693. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  14694. (latex-header
  14695. (or (plist-get processing-info :latex-header)
  14696. (org-latex-make-preamble
  14697. (org-export-get-environment (org-export-get-backend 'latex))
  14698. org-format-latex-header
  14699. 'snippet)))
  14700. (latex-compiler (plist-get processing-info :latex-compiler))
  14701. (image-converter (plist-get processing-info :image-converter))
  14702. (tmpdir temporary-file-directory)
  14703. (texfilebase (make-temp-name
  14704. (expand-file-name "orgtex" tmpdir)))
  14705. (texfile (concat texfilebase ".tex"))
  14706. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  14707. '(1.0 . 1.0)))
  14708. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  14709. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  14710. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  14711. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  14712. "Black"))
  14713. (bg (or (plist-get options (if buffer :background :html-background))
  14714. "Transparent"))
  14715. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  14716. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  14717. (dolist (program programs)
  14718. (org-check-external-command program error-message))
  14719. (if (eq fg 'default)
  14720. (setq fg (org-latex-color :foreground))
  14721. (setq fg (org-latex-color-format fg)))
  14722. (if (eq bg 'default)
  14723. (setq bg (org-latex-color :background))
  14724. (setq bg (org-latex-color-format
  14725. (if (string= bg "Transparent") "white" bg))))
  14726. ;; Remove TeX \par at end of snippet to avoid trailing space.
  14727. (if (string-suffix-p string "\n")
  14728. (aset string (1- (length string)) ?%)
  14729. (setq string (concat string "%")))
  14730. (with-temp-file texfile
  14731. (insert latex-header)
  14732. (insert "\n\\begin{document}\n"
  14733. "\\definecolor{fg}{rgb}{" fg "}%\n"
  14734. "\\definecolor{bg}{rgb}{" bg "}%\n"
  14735. "\n\\pagecolor{bg}%\n"
  14736. "\n{\\color{fg}\n"
  14737. string
  14738. "\n}\n"
  14739. "\n\\end{document}\n"))
  14740. (let* ((err-msg (format "Please adjust `%s' part of \
  14741. `org-preview-latex-process-alist'."
  14742. processing-type))
  14743. (image-input-file
  14744. (org-compile-file
  14745. texfile latex-compiler image-input-type err-msg log-buf))
  14746. (image-output-file
  14747. (org-compile-file
  14748. image-input-file image-converter image-output-type err-msg log-buf
  14749. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  14750. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  14751. (copy-file image-output-file tofile 'replace)
  14752. (dolist (e post-clean)
  14753. (when (file-exists-p (concat texfilebase e))
  14754. (delete-file (concat texfilebase e))))
  14755. image-output-file)))
  14756. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  14757. "Fill a LaTeX header template TPL.
  14758. In the template, the following place holders will be recognized:
  14759. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  14760. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  14761. [PACKAGES] \\usepackage statements for PKG
  14762. [NO-PACKAGES] do not include PKG
  14763. [EXTRA] the string EXTRA
  14764. [NO-EXTRA] do not include EXTRA
  14765. For backward compatibility, if both the positive and the negative place
  14766. holder is missing, the positive one (without the \"NO-\") will be
  14767. assumed to be present at the end of the template.
  14768. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  14769. EXTRA is a string.
  14770. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  14771. (let (rpl (end ""))
  14772. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  14773. (setq rpl (if (or (match-end 1) (not def-pkg))
  14774. "" (org-latex-packages-to-string def-pkg snippets-p t))
  14775. tpl (replace-match rpl t t tpl))
  14776. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  14777. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  14778. (setq rpl (if (or (match-end 1) (not pkg))
  14779. "" (org-latex-packages-to-string pkg snippets-p t))
  14780. tpl (replace-match rpl t t tpl))
  14781. (when pkg (setq end
  14782. (concat end "\n"
  14783. (org-latex-packages-to-string pkg snippets-p)))))
  14784. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  14785. (setq rpl (if (or (match-end 1) (not extra))
  14786. "" (concat extra "\n"))
  14787. tpl (replace-match rpl t t tpl))
  14788. (when (and extra (string-match "\\S-" extra))
  14789. (setq end (concat end "\n" extra))))
  14790. (if (string-match "\\S-" end)
  14791. (concat tpl "\n" end)
  14792. tpl)))
  14793. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  14794. "Turn an alist of packages into a string with the \\usepackage macros."
  14795. (setq pkg (mapconcat (lambda(p)
  14796. (cond
  14797. ((stringp p) p)
  14798. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  14799. (format "%% Package %s omitted" (cadr p)))
  14800. ((equal "" (car p))
  14801. (format "\\usepackage{%s}" (cadr p)))
  14802. (t
  14803. (format "\\usepackage[%s]{%s}"
  14804. (car p) (cadr p)))))
  14805. pkg
  14806. "\n"))
  14807. (if newline (concat pkg "\n") pkg))
  14808. (defun org-dvipng-color (attr)
  14809. "Return a RGB color specification for dvipng."
  14810. (org-dvipng-color-format (face-attribute 'default attr nil)))
  14811. (defun org-dvipng-color-format (color-name)
  14812. "Convert COLOR-NAME to a RGB color value for dvipng."
  14813. (apply #'format "rgb %s %s %s"
  14814. (mapcar 'org-normalize-color
  14815. (color-values color-name))))
  14816. (defun org-latex-color (attr)
  14817. "Return a RGB color for the LaTeX color package."
  14818. (org-latex-color-format (face-attribute 'default attr nil)))
  14819. (defun org-latex-color-format (color-name)
  14820. "Convert COLOR-NAME to a RGB color value."
  14821. (apply #'format "%s,%s,%s"
  14822. (mapcar 'org-normalize-color
  14823. (color-values color-name))))
  14824. (defun org-normalize-color (value)
  14825. "Return string to be used as color value for an RGB component."
  14826. (format "%g" (/ value 65535.0)))
  14827. ;; Image display
  14828. (defvar-local org-inline-image-overlays nil)
  14829. (defun org-toggle-inline-images (&optional include-linked)
  14830. "Toggle the display of inline images.
  14831. INCLUDE-LINKED is passed to `org-display-inline-images'."
  14832. (interactive "P")
  14833. (if org-inline-image-overlays
  14834. (progn
  14835. (org-remove-inline-images)
  14836. (when (called-interactively-p 'interactive)
  14837. (message "Inline image display turned off")))
  14838. (org-display-inline-images include-linked)
  14839. (when (called-interactively-p 'interactive)
  14840. (message (if org-inline-image-overlays
  14841. (format "%d images displayed inline"
  14842. (length org-inline-image-overlays))
  14843. "No images to display inline")))))
  14844. (defun org-redisplay-inline-images ()
  14845. "Assure display of inline images and refresh them."
  14846. (interactive)
  14847. (org-toggle-inline-images)
  14848. (unless org-inline-image-overlays
  14849. (org-toggle-inline-images)))
  14850. ;; For without-x builds.
  14851. (declare-function image-refresh "image" (spec &optional frame))
  14852. (defcustom org-display-remote-inline-images 'skip
  14853. "How to display remote inline images.
  14854. Possible values of this option are:
  14855. skip Don't display remote images.
  14856. download Always download and display remote images.
  14857. cache Display remote images, and open them in separate buffers
  14858. for caching. Silently update the image buffer when a file
  14859. change is detected."
  14860. :group 'org-appearance
  14861. :package-version '(Org . "9.4")
  14862. :type '(choice
  14863. (const :tag "Ignore remote images" skip)
  14864. (const :tag "Always display remote images" download)
  14865. (const :tag "Display and silently update remote images" cache))
  14866. :safe #'symbolp)
  14867. (defun org--create-inline-image (file width)
  14868. "Create image located at FILE, or return nil.
  14869. WIDTH is the width of the image. The image may not be created
  14870. according to the value of `org-display-remote-inline-images'."
  14871. (let* ((remote? (file-remote-p file))
  14872. (file-or-data
  14873. (pcase org-display-remote-inline-images
  14874. ((guard (not remote?)) file)
  14875. (`download (with-temp-buffer
  14876. (set-buffer-multibyte nil)
  14877. (insert-file-contents-literally file)
  14878. (buffer-string)))
  14879. (`cache (let ((revert-without-query '(".")))
  14880. (with-current-buffer (find-file-noselect file)
  14881. (buffer-string))))
  14882. (`skip nil)
  14883. (other
  14884. (message "Invalid value of `org-display-remote-inline-images': %S"
  14885. other)
  14886. nil))))
  14887. (when file-or-data
  14888. (create-image file-or-data
  14889. (and (image-type-available-p 'imagemagick)
  14890. width
  14891. 'imagemagick)
  14892. remote?
  14893. :width width))))
  14894. (defun org-display-inline-images (&optional include-linked refresh beg end)
  14895. "Display inline images.
  14896. An inline image is a link which follows either of these
  14897. conventions:
  14898. 1. Its path is a file with an extension matching return value
  14899. from `image-file-name-regexp' and it has no contents.
  14900. 2. Its description consists in a single link of the previous
  14901. type. In this case, that link must be a well-formed plain
  14902. or angle link, i.e., it must have an explicit \"file\" type.
  14903. Equip each image with the key-map `image-map'.
  14904. When optional argument INCLUDE-LINKED is non-nil, also links with
  14905. a text description part will be inlined. This can be nice for
  14906. a quick look at those images, but it does not reflect what
  14907. exported files will look like.
  14908. When optional argument REFRESH is non-nil, refresh existing
  14909. images between BEG and END. This will create new image displays
  14910. only if necessary.
  14911. BEG and END define the considered part. They default to the
  14912. buffer boundaries with possible narrowing."
  14913. (interactive "P")
  14914. (when (display-graphic-p)
  14915. (unless refresh
  14916. (org-remove-inline-images)
  14917. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  14918. (let ((end (or end (point-max))))
  14919. (org-with-point-at (or beg (point-min))
  14920. (let* ((case-fold-search t)
  14921. (file-extension-re (image-file-name-regexp))
  14922. (link-abbrevs (mapcar #'car
  14923. (append org-link-abbrev-alist-local
  14924. org-link-abbrev-alist)))
  14925. ;; Check absolute, relative file names and explicit
  14926. ;; "file:" links. Also check link abbreviations since
  14927. ;; some might expand to "file" links.
  14928. (file-types-re
  14929. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  14930. (if (not link-abbrevs) ""
  14931. (concat "\\|" (regexp-opt link-abbrevs))))))
  14932. (while (re-search-forward file-types-re end t)
  14933. (let* ((link (org-element-lineage
  14934. (save-match-data (org-element-context))
  14935. '(link) t))
  14936. (linktype (org-element-property :type link))
  14937. (inner-start (match-beginning 1))
  14938. (path
  14939. (cond
  14940. ;; No link at point; no inline image.
  14941. ((not link) nil)
  14942. ;; File link without a description. Also handle
  14943. ;; INCLUDE-LINKED here since it should have
  14944. ;; precedence over the next case. I.e., if link
  14945. ;; contains filenames in both the path and the
  14946. ;; description, prioritize the path only when
  14947. ;; INCLUDE-LINKED is non-nil.
  14948. ((or (not (org-element-property :contents-begin link))
  14949. include-linked)
  14950. (and (or (equal "file" linktype)
  14951. (equal "attachment" linktype))
  14952. (org-element-property :path link)))
  14953. ;; Link with a description. Check if description
  14954. ;; is a filename. Even if Org doesn't have syntax
  14955. ;; for those -- clickable image -- constructs, fake
  14956. ;; them, as in `org-export-insert-image-links'.
  14957. ((not inner-start) nil)
  14958. (t
  14959. (org-with-point-at inner-start
  14960. (and (looking-at
  14961. (if (char-equal ?< (char-after inner-start))
  14962. org-link-angle-re
  14963. org-link-plain-re))
  14964. ;; File name must fill the whole
  14965. ;; description.
  14966. (= (org-element-property :contents-end link)
  14967. (match-end 0))
  14968. (match-string 2)))))))
  14969. (when (and path (string-match-p file-extension-re path))
  14970. (let ((file (if (equal "attachment" linktype)
  14971. (progn
  14972. (require 'org-attach)
  14973. (ignore-errors (org-attach-expand path)))
  14974. (expand-file-name path))))
  14975. (when (and file (file-exists-p file))
  14976. (let ((width
  14977. ;; Apply `org-image-actual-width' specifications.
  14978. (cond
  14979. ((eq org-image-actual-width t) nil)
  14980. ((listp org-image-actual-width)
  14981. (or
  14982. ;; First try to find a width among
  14983. ;; attributes associated to the paragraph
  14984. ;; containing link.
  14985. (pcase (org-element-lineage link '(paragraph))
  14986. (`nil nil)
  14987. (p
  14988. (let* ((case-fold-search t)
  14989. (end (org-element-property :post-affiliated p))
  14990. (re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"))
  14991. (when (org-with-point-at
  14992. (org-element-property :begin p)
  14993. (re-search-forward re end t))
  14994. (string-to-number (match-string 1))))))
  14995. ;; Otherwise, fall-back to provided number.
  14996. (car org-image-actual-width)))
  14997. ((numberp org-image-actual-width)
  14998. org-image-actual-width)
  14999. (t nil)))
  15000. (old (get-char-property-and-overlay
  15001. (org-element-property :begin link)
  15002. 'org-image-overlay)))
  15003. (if (and (car-safe old) refresh)
  15004. (image-refresh (overlay-get (cdr old) 'display))
  15005. (let ((image (org--create-inline-image file width)))
  15006. (when image
  15007. (let ((ov (make-overlay
  15008. (org-element-property :begin link)
  15009. (progn
  15010. (goto-char
  15011. (org-element-property :end link))
  15012. (skip-chars-backward " \t")
  15013. (point)))))
  15014. (overlay-put ov 'display image)
  15015. (overlay-put ov 'face 'default)
  15016. (overlay-put ov 'org-image-overlay t)
  15017. (overlay-put
  15018. ov 'modification-hooks
  15019. (list 'org-display-inline-remove-overlay))
  15020. (when (<= 26 emacs-major-version)
  15021. (cl-assert (boundp 'image-map))
  15022. (overlay-put ov 'keymap image-map))
  15023. (push ov org-inline-image-overlays))))))))))))))))
  15024. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  15025. "Remove inline-display overlay if a corresponding region is modified."
  15026. (let ((inhibit-modification-hooks t))
  15027. (when (and ov after)
  15028. (delete ov org-inline-image-overlays)
  15029. (delete-overlay ov))))
  15030. (defun org-remove-inline-images ()
  15031. "Remove inline display of images."
  15032. (interactive)
  15033. (mapc #'delete-overlay org-inline-image-overlays)
  15034. (setq org-inline-image-overlays nil))
  15035. (defvar org-self-insert-command-undo-counter 0)
  15036. (defvar org-speed-command nil)
  15037. (defun org-self-insert-command (N)
  15038. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  15039. If the cursor is in a table looking at whitespace, the whitespace is
  15040. overwritten, and the table is not marked as requiring realignment."
  15041. (interactive "p")
  15042. (org-check-before-invisible-edit 'insert)
  15043. (cond
  15044. ((and org-use-speed-commands
  15045. (let ((kv (this-command-keys-vector)))
  15046. (setq org-speed-command
  15047. (run-hook-with-args-until-success
  15048. 'org-speed-command-hook
  15049. (make-string 1 (aref kv (1- (length kv))))))))
  15050. (cond
  15051. ((commandp org-speed-command)
  15052. (setq this-command org-speed-command)
  15053. (call-interactively org-speed-command))
  15054. ((functionp org-speed-command)
  15055. (funcall org-speed-command))
  15056. ((and org-speed-command (listp org-speed-command))
  15057. (eval org-speed-command))
  15058. (t (let (org-use-speed-commands)
  15059. (call-interactively 'org-self-insert-command)))))
  15060. ((and
  15061. (= N 1)
  15062. (not (org-region-active-p))
  15063. (org-at-table-p)
  15064. (progn
  15065. ;; Check if we blank the field, and if that triggers align.
  15066. (and (featurep 'org-table)
  15067. org-table-auto-blank-field
  15068. (memq last-command
  15069. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  15070. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  15071. ;; Got extra space, this field does not determine
  15072. ;; column width.
  15073. (let (org-table-may-need-update) (org-table-blank-field))
  15074. ;; No extra space, this field may determine column
  15075. ;; width.
  15076. (org-table-blank-field)))
  15077. t)
  15078. (looking-at "[^|\n]* |"))
  15079. ;; There is room for insertion without re-aligning the table.
  15080. (self-insert-command N)
  15081. (org-table-with-shrunk-field
  15082. (save-excursion
  15083. (skip-chars-forward "^|")
  15084. ;; Do not delete last space, which is
  15085. ;; `org-table-separator-space', but the regular space before
  15086. ;; it.
  15087. (delete-region (- (point) 2) (1- (point))))))
  15088. (t
  15089. (setq org-table-may-need-update t)
  15090. (self-insert-command N)
  15091. (org-fix-tags-on-the-fly)
  15092. (when org-self-insert-cluster-for-undo
  15093. (if (not (eq last-command 'org-self-insert-command))
  15094. (setq org-self-insert-command-undo-counter 1)
  15095. (if (>= org-self-insert-command-undo-counter 20)
  15096. (setq org-self-insert-command-undo-counter 1)
  15097. (and (> org-self-insert-command-undo-counter 0)
  15098. buffer-undo-list (listp buffer-undo-list)
  15099. (not (cadr buffer-undo-list)) ; remove nil entry
  15100. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  15101. (setq org-self-insert-command-undo-counter
  15102. (1+ org-self-insert-command-undo-counter))))))))
  15103. (defun org-check-before-invisible-edit (kind)
  15104. "Check if editing kind KIND would be dangerous with invisible text around.
  15105. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  15106. ;; First, try to get out of here as quickly as possible, to reduce overhead
  15107. (when (and org-catch-invisible-edits
  15108. (or (not (boundp 'visible-mode)) (not visible-mode))
  15109. (or (get-char-property (point) 'invisible)
  15110. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  15111. ;; OK, we need to take a closer look. Do not consider
  15112. ;; invisibility obtained through text properties (e.g., link
  15113. ;; fontification), as it cannot be toggled.
  15114. (let* ((invisible-at-point
  15115. (pcase (get-char-property-and-overlay (point) 'invisible)
  15116. (`(,_ . ,(and (pred overlayp) o)) o)))
  15117. ;; Assume that point cannot land in the middle of an
  15118. ;; overlay, or between two overlays.
  15119. (invisible-before-point
  15120. (and (not invisible-at-point)
  15121. (not (bobp))
  15122. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  15123. (`(,_ . ,(and (pred overlayp) o)) o))))
  15124. (border-and-ok-direction
  15125. (or
  15126. ;; Check if we are acting predictably before invisible
  15127. ;; text.
  15128. (and invisible-at-point
  15129. (memq kind '(insert delete-backward)))
  15130. ;; Check if we are acting predictably after invisible text
  15131. ;; This works not well, and I have turned it off. It seems
  15132. ;; better to always show and stop after invisible text.
  15133. ;; (and (not invisible-at-point) invisible-before-point
  15134. ;; (memq kind '(insert delete)))
  15135. )))
  15136. (when (or invisible-at-point invisible-before-point)
  15137. (when (eq org-catch-invisible-edits 'error)
  15138. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  15139. (if (and org-custom-properties-overlays
  15140. (y-or-n-p "Display invisible properties in this buffer? "))
  15141. (org-toggle-custom-properties-visibility)
  15142. ;; Make the area visible
  15143. (save-excursion
  15144. (when invisible-before-point
  15145. (goto-char
  15146. (previous-single-char-property-change (point) 'invisible)))
  15147. ;; Remove whatever overlay is currently making yet-to-be
  15148. ;; edited text invisible. Also remove nested invisibility
  15149. ;; related overlays.
  15150. (delete-overlay (or invisible-at-point invisible-before-point))
  15151. (let ((origin (if invisible-at-point (point) (1- (point)))))
  15152. (while (pcase (get-char-property-and-overlay origin 'invisible)
  15153. (`(,_ . ,(and (pred overlayp) o))
  15154. (delete-overlay o)
  15155. t)))))
  15156. (cond
  15157. ((eq org-catch-invisible-edits 'show)
  15158. ;; That's it, we do the edit after showing
  15159. (message
  15160. "Unfolding invisible region around point before editing")
  15161. (sit-for 1))
  15162. ((and (eq org-catch-invisible-edits 'smart)
  15163. border-and-ok-direction)
  15164. (message "Unfolding invisible region around point before editing"))
  15165. (t
  15166. ;; Don't do the edit, make the user repeat it in full visibility
  15167. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  15168. (defun org-fix-tags-on-the-fly ()
  15169. "Align tags in headline at point.
  15170. Unlike `org-align-tags', this function does nothing if point is
  15171. either not currently on a tagged headline or on a tag."
  15172. (when (and (org-match-line org-tag-line-re)
  15173. (< (point) (match-beginning 1)))
  15174. (org-align-tags)))
  15175. (defun org-delete-backward-char (N)
  15176. "Like `delete-backward-char', insert whitespace at field end in tables.
  15177. When deleting backwards, in tables this function will insert whitespace in
  15178. front of the next \"|\" separator, to keep the table aligned. The table will
  15179. still be marked for re-alignment if the field did fill the entire column,
  15180. because, in this case the deletion might narrow the column."
  15181. (interactive "p")
  15182. (save-match-data
  15183. (org-check-before-invisible-edit 'delete-backward)
  15184. (if (and (= N 1)
  15185. (not overwrite-mode)
  15186. (not (org-region-active-p))
  15187. (not (eq (char-before) ?|))
  15188. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  15189. (looking-at-p ".*?|")
  15190. (org-at-table-p))
  15191. (progn (forward-char -1) (org-delete-char 1))
  15192. (backward-delete-char N)
  15193. (org-fix-tags-on-the-fly))))
  15194. (defun org-delete-char (N)
  15195. "Like `delete-char', but insert whitespace at field end in tables.
  15196. When deleting characters, in tables this function will insert whitespace in
  15197. front of the next \"|\" separator, to keep the table aligned. The table will
  15198. still be marked for re-alignment if the field did fill the entire column,
  15199. because, in this case the deletion might narrow the column."
  15200. (interactive "p")
  15201. (save-match-data
  15202. (org-check-before-invisible-edit 'delete)
  15203. (cond
  15204. ((or (/= N 1)
  15205. (eq (char-after) ?|)
  15206. (save-excursion (skip-chars-backward " \t") (bolp))
  15207. (not (org-at-table-p)))
  15208. (delete-char N)
  15209. (org-fix-tags-on-the-fly))
  15210. ((looking-at ".\\(.*?\\)|")
  15211. (let* ((update? org-table-may-need-update)
  15212. (noalign (looking-at-p ".*? |")))
  15213. (delete-char 1)
  15214. (org-table-with-shrunk-field
  15215. (save-excursion
  15216. ;; Last space is `org-table-separator-space', so insert
  15217. ;; a regular one before it instead.
  15218. (goto-char (- (match-end 0) 2))
  15219. (insert " ")))
  15220. ;; If there were two spaces at the end, this field does not
  15221. ;; determine the width of the column.
  15222. (when noalign (setq org-table-may-need-update update?))))
  15223. (t
  15224. (delete-char N)))))
  15225. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  15226. (put 'org-self-insert-command 'delete-selection
  15227. (lambda ()
  15228. (not (run-hook-with-args-until-success
  15229. 'self-insert-uses-region-functions))))
  15230. (put 'orgtbl-self-insert-command 'delete-selection
  15231. (lambda ()
  15232. (not (run-hook-with-args-until-success
  15233. 'self-insert-uses-region-functions))))
  15234. (put 'org-delete-char 'delete-selection 'supersede)
  15235. (put 'org-delete-backward-char 'delete-selection 'supersede)
  15236. (put 'org-yank 'delete-selection 'yank)
  15237. ;; Make `flyspell-mode' delay after some commands
  15238. (put 'org-self-insert-command 'flyspell-delayed t)
  15239. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  15240. (put 'org-delete-char 'flyspell-delayed t)
  15241. (put 'org-delete-backward-char 'flyspell-delayed t)
  15242. ;; Make pabbrev-mode expand after Org mode commands
  15243. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  15244. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  15245. (defun org-transpose-words ()
  15246. "Transpose words for Org.
  15247. This uses the `org-mode-transpose-word-syntax-table' syntax
  15248. table, which interprets characters in `org-emphasis-alist' as
  15249. word constituents."
  15250. (interactive)
  15251. (with-syntax-table org-mode-transpose-word-syntax-table
  15252. (call-interactively 'transpose-words)))
  15253. (defvar org-ctrl-c-ctrl-c-hook nil
  15254. "Hook for functions attaching themselves to `C-c C-c'.
  15255. This can be used to add additional functionality to the `C-c C-c'
  15256. key which executes context-dependent commands. This hook is run
  15257. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  15258. run after the last test.
  15259. Each function will be called with no arguments. The function
  15260. must check if the context is appropriate for it to act. If yes,
  15261. it should do its thing and then return a non-nil value. If the
  15262. context is wrong, just do nothing and return nil.")
  15263. (defvar org-ctrl-c-ctrl-c-final-hook nil
  15264. "Hook for functions attaching themselves to `C-c C-c'.
  15265. This can be used to add additional functionality to the `C-c C-c'
  15266. key which executes context-dependent commands. This hook is run
  15267. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  15268. before the first test.
  15269. Each function will be called with no arguments. The function
  15270. must check if the context is appropriate for it to act. If yes,
  15271. it should do its thing and then return a non-nil value. If the
  15272. context is wrong, just do nothing and return nil.")
  15273. (defvar org-tab-first-hook nil
  15274. "Hook for functions to attach themselves to TAB.
  15275. See `org-ctrl-c-ctrl-c-hook' for more information.
  15276. This hook runs as the first action when TAB is pressed, even before
  15277. `org-cycle' messes around with the `outline-regexp' to cater for
  15278. inline tasks and plain list item folding.
  15279. If any function in this hook returns t, any other actions that
  15280. would have been caused by TAB (such as table field motion or visibility
  15281. cycling) will not occur.")
  15282. (defvar org-tab-after-check-for-table-hook nil
  15283. "Hook for functions to attach themselves to TAB.
  15284. See `org-ctrl-c-ctrl-c-hook' for more information.
  15285. This hook runs after it has been established that the cursor is not in a
  15286. table, but before checking if the cursor is in a headline or if global cycling
  15287. should be done.
  15288. If any function in this hook returns t, not other actions like visibility
  15289. cycling will be done.")
  15290. (defvar org-tab-after-check-for-cycling-hook nil
  15291. "Hook for functions to attach themselves to TAB.
  15292. See `org-ctrl-c-ctrl-c-hook' for more information.
  15293. This hook runs after it has been established that not table field motion and
  15294. not visibility should be done because of current context. This is probably
  15295. the place where a package like yasnippets can hook in.")
  15296. (defvar org-tab-before-tab-emulation-hook nil
  15297. "Hook for functions to attach themselves to TAB.
  15298. See `org-ctrl-c-ctrl-c-hook' for more information.
  15299. This hook runs after every other options for TAB have been exhausted, but
  15300. before indentation and \t insertion takes place.")
  15301. (defvar org-metaleft-hook nil
  15302. "Hook for functions attaching themselves to `M-left'.
  15303. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15304. (defvar org-metaright-hook nil
  15305. "Hook for functions attaching themselves to `M-right'.
  15306. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15307. (defvar org-metaup-hook nil
  15308. "Hook for functions attaching themselves to `M-up'.
  15309. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15310. (defvar org-metadown-hook nil
  15311. "Hook for functions attaching themselves to `M-down'.
  15312. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15313. (defvar org-shiftmetaleft-hook nil
  15314. "Hook for functions attaching themselves to `M-S-left'.
  15315. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15316. (defvar org-shiftmetaright-hook nil
  15317. "Hook for functions attaching themselves to `M-S-right'.
  15318. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15319. (defvar org-shiftmetaup-hook nil
  15320. "Hook for functions attaching themselves to `M-S-up'.
  15321. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15322. (defvar org-shiftmetadown-hook nil
  15323. "Hook for functions attaching themselves to `M-S-down'.
  15324. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15325. (defvar org-metareturn-hook nil
  15326. "Hook for functions attaching themselves to `M-RET'.
  15327. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15328. (defvar org-shiftup-hook nil
  15329. "Hook for functions attaching themselves to `S-up'.
  15330. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15331. (defvar org-shiftup-final-hook nil
  15332. "Hook for functions attaching themselves to `S-up'.
  15333. This one runs after all other options except shift-select have been excluded.
  15334. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15335. (defvar org-shiftdown-hook nil
  15336. "Hook for functions attaching themselves to `S-down'.
  15337. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15338. (defvar org-shiftdown-final-hook nil
  15339. "Hook for functions attaching themselves to `S-down'.
  15340. This one runs after all other options except shift-select have been excluded.
  15341. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15342. (defvar org-shiftleft-hook nil
  15343. "Hook for functions attaching themselves to `S-left'.
  15344. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15345. (defvar org-shiftleft-final-hook nil
  15346. "Hook for functions attaching themselves to `S-left'.
  15347. This one runs after all other options except shift-select have been excluded.
  15348. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15349. (defvar org-shiftright-hook nil
  15350. "Hook for functions attaching themselves to `S-right'.
  15351. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15352. (defvar org-shiftright-final-hook nil
  15353. "Hook for functions attaching themselves to `S-right'.
  15354. This one runs after all other options except shift-select have been excluded.
  15355. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15356. (defun org-modifier-cursor-error ()
  15357. "Throw an error, a modified cursor command was applied in wrong context."
  15358. (user-error "This command is active in special context like tables, headlines or items"))
  15359. (defun org-shiftselect-error ()
  15360. "Throw an error because Shift-Cursor command was applied in wrong context."
  15361. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15362. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15363. (user-error "This command works only in special context like headlines or timestamps")))
  15364. (defun org-call-for-shift-select (cmd)
  15365. (let ((this-command-keys-shift-translated t))
  15366. (call-interactively cmd)))
  15367. (defun org-shifttab (&optional arg)
  15368. "Global visibility cycling or move to previous table field.
  15369. Call `org-table-previous-field' within a table.
  15370. When ARG is nil, cycle globally through visibility states.
  15371. When ARG is a numeric prefix, show contents of this level."
  15372. (interactive "P")
  15373. (cond
  15374. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15375. ((integerp arg)
  15376. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15377. (message "Content view to level: %d" arg)
  15378. (org-content (prefix-numeric-value arg2))
  15379. (org-cycle-show-empty-lines t)
  15380. (setq org-cycle-global-status 'overview)))
  15381. (t (call-interactively 'org-global-cycle))))
  15382. (defun org-shiftmetaleft ()
  15383. "Promote subtree or delete table column.
  15384. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15385. `org-table-delete-column', depending on context. See the
  15386. individual commands for more information."
  15387. (interactive)
  15388. (cond
  15389. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15390. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15391. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15392. ((if (not (org-region-active-p)) (org-at-item-p)
  15393. (save-excursion (goto-char (region-beginning))
  15394. (org-at-item-p)))
  15395. (call-interactively 'org-outdent-item-tree))
  15396. (t (org-modifier-cursor-error))))
  15397. (defun org-shiftmetaright ()
  15398. "Demote subtree or insert table column.
  15399. Calls `org-demote-subtree', `org-indent-item-tree', or
  15400. `org-table-insert-column', depending on context. See the
  15401. individual commands for more information."
  15402. (interactive)
  15403. (cond
  15404. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15405. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15406. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15407. ((if (not (org-region-active-p)) (org-at-item-p)
  15408. (save-excursion (goto-char (region-beginning))
  15409. (org-at-item-p)))
  15410. (call-interactively 'org-indent-item-tree))
  15411. (t (org-modifier-cursor-error))))
  15412. (defun org-shiftmetaup (&optional _arg)
  15413. "Drag the line at point up.
  15414. In a table, kill the current row.
  15415. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15416. but also adjust the previous clocked item in the clock history.
  15417. Everywhere else, drag the line at point up."
  15418. (interactive "P")
  15419. (cond
  15420. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15421. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15422. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15423. (call-interactively 'org-timestamp-up)))
  15424. (t (call-interactively 'org-drag-line-backward))))
  15425. (defun org-shiftmetadown (&optional _arg)
  15426. "Drag the line at point down.
  15427. In a table, insert an empty row at the current line.
  15428. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15429. but also adjust the previous clocked item in the clock history.
  15430. Everywhere else, drag the line at point down."
  15431. (interactive "P")
  15432. (cond
  15433. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15434. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15435. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15436. (call-interactively 'org-timestamp-down)))
  15437. (t (call-interactively 'org-drag-line-forward))))
  15438. (defsubst org-hidden-tree-error ()
  15439. (user-error
  15440. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15441. (defun org-metaleft (&optional _arg)
  15442. "Promote heading, list item at point or move table column left.
  15443. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15444. depending on context. With no specific context, calls the Emacs
  15445. default `backward-word'. See the individual commands for more
  15446. information.
  15447. This function runs the hook `org-metaleft-hook' as a first step,
  15448. and returns at first non-nil value."
  15449. (interactive "P")
  15450. (cond
  15451. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15452. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15453. ((org-with-limited-levels
  15454. (or (org-at-heading-p)
  15455. (and (org-region-active-p)
  15456. (save-excursion
  15457. (goto-char (region-beginning))
  15458. (org-at-heading-p)))))
  15459. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15460. (call-interactively 'org-do-promote))
  15461. ;; At an inline task.
  15462. ((org-at-heading-p)
  15463. (call-interactively 'org-inlinetask-promote))
  15464. ((or (org-at-item-p)
  15465. (and (org-region-active-p)
  15466. (save-excursion
  15467. (goto-char (region-beginning))
  15468. (org-at-item-p))))
  15469. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15470. (call-interactively 'org-outdent-item))
  15471. (t (call-interactively 'backward-word))))
  15472. (defun org-metaright (&optional _arg)
  15473. "Demote heading, list item at point or move table column right.
  15474. In front of a drawer or a block keyword, indent it correctly.
  15475. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15476. `org-indent-drawer' or `org-indent-block' depending on context.
  15477. With no specific context, calls the Emacs default `forward-word'.
  15478. See the individual commands for more information.
  15479. This function runs the hook `org-metaright-hook' as a first step,
  15480. and returns at first non-nil value."
  15481. (interactive "P")
  15482. (cond
  15483. ((run-hook-with-args-until-success 'org-metaright-hook))
  15484. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15485. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15486. ((org-at-block-p) (call-interactively 'org-indent-block))
  15487. ((org-with-limited-levels
  15488. (or (org-at-heading-p)
  15489. (and (org-region-active-p)
  15490. (save-excursion
  15491. (goto-char (region-beginning))
  15492. (org-at-heading-p)))))
  15493. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15494. (call-interactively 'org-do-demote))
  15495. ;; At an inline task.
  15496. ((org-at-heading-p)
  15497. (call-interactively 'org-inlinetask-demote))
  15498. ((or (org-at-item-p)
  15499. (and (org-region-active-p)
  15500. (save-excursion
  15501. (goto-char (region-beginning))
  15502. (org-at-item-p))))
  15503. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15504. (call-interactively 'org-indent-item))
  15505. (t (call-interactively 'forward-word))))
  15506. (defun org-check-for-hidden (what)
  15507. "Check if there are hidden headlines/items in the current visual line.
  15508. WHAT can be either `headlines' or `items'. If the current line is
  15509. an outline or item heading and it has a folded subtree below it,
  15510. this function returns t, nil otherwise."
  15511. (let ((re (cond
  15512. ((eq what 'headlines) org-outline-regexp-bol)
  15513. ((eq what 'items) (org-item-beginning-re))
  15514. (t (error "This should not happen"))))
  15515. beg end)
  15516. (save-excursion
  15517. (catch 'exit
  15518. (unless (org-region-active-p)
  15519. (setq beg (point-at-bol))
  15520. (beginning-of-line 2)
  15521. (while (and (not (eobp)) ;; this is like `next-line'
  15522. (get-char-property (1- (point)) 'invisible))
  15523. (beginning-of-line 2))
  15524. (setq end (point))
  15525. (goto-char beg)
  15526. (goto-char (point-at-eol))
  15527. (setq end (max end (point)))
  15528. (while (re-search-forward re end t)
  15529. (when (get-char-property (match-beginning 0) 'invisible)
  15530. (throw 'exit t))))
  15531. nil))))
  15532. (defun org-metaup (&optional _arg)
  15533. "Move subtree up or move table row up.
  15534. Calls `org-move-subtree-up' or `org-table-move-row' or
  15535. `org-move-item-up', depending on context. See the individual commands
  15536. for more information."
  15537. (interactive "P")
  15538. (cond
  15539. ((run-hook-with-args-until-success 'org-metaup-hook))
  15540. ((org-region-active-p)
  15541. (let* ((a (save-excursion
  15542. (goto-char (min (region-beginning) (region-end)))
  15543. (line-beginning-position)))
  15544. (b (save-excursion
  15545. (goto-char (max (region-beginning) (region-end)))
  15546. (if (bolp) (1- (point)) (line-end-position))))
  15547. (c (save-excursion
  15548. (goto-char a)
  15549. (move-beginning-of-line 0)
  15550. (point)))
  15551. (d (save-excursion
  15552. (goto-char a)
  15553. (move-end-of-line 0)
  15554. (point))))
  15555. (transpose-regions a b c d)
  15556. (goto-char c)))
  15557. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15558. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15559. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15560. (t (org-drag-element-backward))))
  15561. (defun org-metadown (&optional _arg)
  15562. "Move subtree down or move table row down.
  15563. Calls `org-move-subtree-down' or `org-table-move-row' or
  15564. `org-move-item-down', depending on context. See the individual
  15565. commands for more information."
  15566. (interactive "P")
  15567. (cond
  15568. ((run-hook-with-args-until-success 'org-metadown-hook))
  15569. ((org-region-active-p)
  15570. (let* ((a (save-excursion
  15571. (goto-char (min (region-beginning) (region-end)))
  15572. (line-beginning-position)))
  15573. (b (save-excursion
  15574. (goto-char (max (region-beginning) (region-end)))
  15575. (if (bolp) (1- (point)) (line-end-position))))
  15576. (c (save-excursion
  15577. (goto-char b)
  15578. (move-beginning-of-line (if (bolp) 1 2))
  15579. (point)))
  15580. (d (save-excursion
  15581. (goto-char b)
  15582. (move-end-of-line (if (bolp) 1 2))
  15583. (point))))
  15584. (transpose-regions a b c d)
  15585. (goto-char d)))
  15586. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15587. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15588. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15589. (t (org-drag-element-forward))))
  15590. (defun org-shiftup (&optional arg)
  15591. "Act on current element according to context.
  15592. Call `org-timestamp-up' or `org-priority-up', or
  15593. `org-previous-item', or `org-table-move-cell-up'. See the
  15594. individual commands for more information."
  15595. (interactive "P")
  15596. (cond
  15597. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15598. ((and org-support-shift-select (org-region-active-p))
  15599. (org-call-for-shift-select 'previous-line))
  15600. ((org-at-timestamp-p 'lax)
  15601. (call-interactively (if org-edit-timestamp-down-means-later
  15602. 'org-timestamp-down 'org-timestamp-up)))
  15603. ((and (not (eq org-support-shift-select 'always))
  15604. org-priority-enable-commands
  15605. (org-at-heading-p))
  15606. (call-interactively 'org-priority-up))
  15607. ((and (not org-support-shift-select) (org-at-item-p))
  15608. (call-interactively 'org-previous-item))
  15609. ((org-clocktable-try-shift 'up arg))
  15610. ((and (not (eq org-support-shift-select 'always))
  15611. (org-at-table-p))
  15612. (org-table-move-cell-up))
  15613. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15614. (org-support-shift-select
  15615. (org-call-for-shift-select 'previous-line))
  15616. (t (org-shiftselect-error))))
  15617. (defun org-shiftdown (&optional arg)
  15618. "Act on current element according to context.
  15619. Call `org-timestamp-down' or `org-priority-down', or
  15620. `org-next-item', or `org-table-move-cell-down'. See the
  15621. individual commands for more information."
  15622. (interactive "P")
  15623. (cond
  15624. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15625. ((and org-support-shift-select (org-region-active-p))
  15626. (org-call-for-shift-select 'next-line))
  15627. ((org-at-timestamp-p 'lax)
  15628. (call-interactively (if org-edit-timestamp-down-means-later
  15629. 'org-timestamp-up 'org-timestamp-down)))
  15630. ((and (not (eq org-support-shift-select 'always))
  15631. org-priority-enable-commands
  15632. (org-at-heading-p))
  15633. (call-interactively 'org-priority-down))
  15634. ((and (not org-support-shift-select) (org-at-item-p))
  15635. (call-interactively 'org-next-item))
  15636. ((org-clocktable-try-shift 'down arg))
  15637. ((and (not (eq org-support-shift-select 'always))
  15638. (org-at-table-p))
  15639. (org-table-move-cell-down))
  15640. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15641. (org-support-shift-select
  15642. (org-call-for-shift-select 'next-line))
  15643. (t (org-shiftselect-error))))
  15644. (defun org-shiftright (&optional arg)
  15645. "Act on the current element according to context.
  15646. This does one of the following:
  15647. - switch a timestamp at point one day into the future
  15648. - on a headline, switch to the next TODO keyword
  15649. - on an item, switch entire list to the next bullet type
  15650. - on a property line, switch to the next allowed value
  15651. - on a clocktable definition line, move time block into the future
  15652. - in a table, move a single cell right"
  15653. (interactive "P")
  15654. (cond
  15655. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15656. ((and org-support-shift-select (org-region-active-p))
  15657. (org-call-for-shift-select 'forward-char))
  15658. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15659. ((and (not (eq org-support-shift-select 'always))
  15660. (org-at-heading-p))
  15661. (let ((org-inhibit-logging
  15662. (not org-treat-S-cursor-todo-selection-as-state-change))
  15663. (org-inhibit-blocking
  15664. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15665. (org-call-with-arg 'org-todo 'right)))
  15666. ((or (and org-support-shift-select
  15667. (not (eq org-support-shift-select 'always))
  15668. (org-at-item-bullet-p))
  15669. (and (not org-support-shift-select) (org-at-item-p)))
  15670. (org-call-with-arg 'org-cycle-list-bullet nil))
  15671. ((and (not (eq org-support-shift-select 'always))
  15672. (org-at-property-p))
  15673. (call-interactively 'org-property-next-allowed-value))
  15674. ((org-clocktable-try-shift 'right arg))
  15675. ((and (not (eq org-support-shift-select 'always))
  15676. (org-at-table-p))
  15677. (org-table-move-cell-right))
  15678. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15679. (org-support-shift-select
  15680. (org-call-for-shift-select 'forward-char))
  15681. (t (org-shiftselect-error))))
  15682. (defun org-shiftleft (&optional arg)
  15683. "Act on current element according to context.
  15684. This does one of the following:
  15685. - switch a timestamp at point one day into the past
  15686. - on a headline, switch to the previous TODO keyword.
  15687. - on an item, switch entire list to the previous bullet type
  15688. - on a property line, switch to the previous allowed value
  15689. - on a clocktable definition line, move time block into the past
  15690. - in a table, move a single cell left"
  15691. (interactive "P")
  15692. (cond
  15693. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15694. ((and org-support-shift-select (org-region-active-p))
  15695. (org-call-for-shift-select 'backward-char))
  15696. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  15697. ((and (not (eq org-support-shift-select 'always))
  15698. (org-at-heading-p))
  15699. (let ((org-inhibit-logging
  15700. (not org-treat-S-cursor-todo-selection-as-state-change))
  15701. (org-inhibit-blocking
  15702. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15703. (org-call-with-arg 'org-todo 'left)))
  15704. ((or (and org-support-shift-select
  15705. (not (eq org-support-shift-select 'always))
  15706. (org-at-item-bullet-p))
  15707. (and (not org-support-shift-select) (org-at-item-p)))
  15708. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  15709. ((and (not (eq org-support-shift-select 'always))
  15710. (org-at-property-p))
  15711. (call-interactively 'org-property-previous-allowed-value))
  15712. ((org-clocktable-try-shift 'left arg))
  15713. ((and (not (eq org-support-shift-select 'always))
  15714. (org-at-table-p))
  15715. (org-table-move-cell-left))
  15716. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  15717. (org-support-shift-select
  15718. (org-call-for-shift-select 'backward-char))
  15719. (t (org-shiftselect-error))))
  15720. (defun org-shiftcontrolright ()
  15721. "Switch to next TODO set."
  15722. (interactive)
  15723. (cond
  15724. ((and org-support-shift-select (org-region-active-p))
  15725. (org-call-for-shift-select 'forward-word))
  15726. ((and (not (eq org-support-shift-select 'always))
  15727. (org-at-heading-p))
  15728. (org-call-with-arg 'org-todo 'nextset))
  15729. (org-support-shift-select
  15730. (org-call-for-shift-select 'forward-word))
  15731. (t (org-shiftselect-error))))
  15732. (defun org-shiftcontrolleft ()
  15733. "Switch to previous TODO set."
  15734. (interactive)
  15735. (cond
  15736. ((and org-support-shift-select (org-region-active-p))
  15737. (org-call-for-shift-select 'backward-word))
  15738. ((and (not (eq org-support-shift-select 'always))
  15739. (org-at-heading-p))
  15740. (org-call-with-arg 'org-todo 'previousset))
  15741. (org-support-shift-select
  15742. (org-call-for-shift-select 'backward-word))
  15743. (t (org-shiftselect-error))))
  15744. (defun org-shiftcontrolup (&optional n)
  15745. "Change timestamps synchronously up in CLOCK log lines.
  15746. Optional argument N tells to change by that many units."
  15747. (interactive "P")
  15748. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15749. (let (org-support-shift-select)
  15750. (org-clock-timestamps-up n))
  15751. (user-error "Not at a clock log")))
  15752. (defun org-shiftcontroldown (&optional n)
  15753. "Change timestamps synchronously down in CLOCK log lines.
  15754. Optional argument N tells to change by that many units."
  15755. (interactive "P")
  15756. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15757. (let (org-support-shift-select)
  15758. (org-clock-timestamps-down n))
  15759. (user-error "Not at a clock log")))
  15760. (defun org-increase-number-at-point (&optional inc)
  15761. "Increment the number at point.
  15762. With an optional prefix numeric argument INC, increment using
  15763. this numeric value."
  15764. (interactive "p")
  15765. (if (not (number-at-point))
  15766. (user-error "Not on a number")
  15767. (unless inc (setq inc 1))
  15768. (let ((pos (point))
  15769. (beg (skip-chars-backward "-+^/*0-9eE."))
  15770. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  15771. (setq nap (buffer-substring-no-properties
  15772. (+ pos beg) (+ pos beg end)))
  15773. (delete-region (+ pos beg) (+ pos beg end))
  15774. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  15775. (when (org-at-table-p)
  15776. (org-table-align)
  15777. (org-table-end-of-field 1))))
  15778. (defun org-decrease-number-at-point (&optional inc)
  15779. "Decrement the number at point.
  15780. With an optional prefix numeric argument INC, decrement using
  15781. this numeric value."
  15782. (interactive "p")
  15783. (org-increase-number-at-point (- (or inc 1))))
  15784. (defun org-ctrl-c-ret ()
  15785. "Call `org-table-hline-and-move' or `org-insert-heading'."
  15786. (interactive)
  15787. (cond
  15788. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  15789. (t (call-interactively 'org-insert-heading))))
  15790. (defun org-copy-visible (beg end)
  15791. "Copy the visible parts of the region."
  15792. (interactive "r")
  15793. (let ((result ""))
  15794. (while (/= beg end)
  15795. (when (get-char-property beg 'invisible)
  15796. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  15797. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  15798. (setq result (concat result (buffer-substring beg next)))
  15799. (setq beg next)))
  15800. (setq deactivate-mark t)
  15801. (kill-new result)
  15802. (message "Visible strings have been copied to the kill ring.")))
  15803. (defun org-copy-special ()
  15804. "Copy region in table or copy current subtree.
  15805. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  15806. context. See the individual commands for more information."
  15807. (interactive)
  15808. (call-interactively
  15809. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  15810. (defun org-cut-special ()
  15811. "Cut region in table or cut current subtree.
  15812. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  15813. context. See the individual commands for more information."
  15814. (interactive)
  15815. (call-interactively
  15816. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  15817. (defun org-paste-special (arg)
  15818. "Paste rectangular region into table, or past subtree relative to level.
  15819. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  15820. See the individual commands for more information."
  15821. (interactive "P")
  15822. (if (org-at-table-p)
  15823. (org-table-paste-rectangle)
  15824. (org-paste-subtree arg)))
  15825. (defun org-edit-special (&optional arg)
  15826. "Call a special editor for the element at point.
  15827. When at a table, call the formula editor with `org-table-edit-formulas'.
  15828. When in a source code block, call `org-edit-src-code'.
  15829. When in a fixed-width region, call `org-edit-fixed-width-region'.
  15830. When in an export block, call `org-edit-export-block'.
  15831. When in a LaTeX environment, call `org-edit-latex-environment'.
  15832. When at an #+INCLUDE keyword, visit the included file.
  15833. When at a footnote reference, call `org-edit-footnote-reference'.
  15834. When at a planning line call, `org-deadline' and/or `org-schedule'.
  15835. When at an active timestamp, call `org-time-stamp'.
  15836. When at an inactive timestamp, call `org-time-stamp-inactive'.
  15837. On a link, call `ffap' to visit the link at point.
  15838. Otherwise, return a user error."
  15839. (interactive "P")
  15840. (let ((element (org-element-at-point)))
  15841. (barf-if-buffer-read-only)
  15842. (pcase (org-element-type element)
  15843. (`src-block
  15844. (if (not arg) (org-edit-src-code)
  15845. (let* ((info (org-babel-get-src-block-info))
  15846. (lang (nth 0 info))
  15847. (params (nth 2 info))
  15848. (session (cdr (assq :session params))))
  15849. (if (not session) (org-edit-src-code)
  15850. ;; At a source block with a session and function called
  15851. ;; with an ARG: switch to the buffer related to the
  15852. ;; inferior process.
  15853. (switch-to-buffer
  15854. (funcall (intern (concat "org-babel-prep-session:" lang))
  15855. session params))))))
  15856. (`keyword
  15857. (unless (member (org-element-property :key element)
  15858. '("INCLUDE" "SETUPFILE"))
  15859. (user-error "No special environment to edit here"))
  15860. (let ((value (org-element-property :value element)))
  15861. (unless (org-string-nw-p value) (user-error "No file to edit"))
  15862. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  15863. (or (match-string 1 value)
  15864. (match-string 0 value)))))
  15865. (when (org-file-url-p file)
  15866. (user-error "Files located with a URL cannot be edited"))
  15867. (org-link-open-from-string
  15868. (format "[[%s]]" (expand-file-name file))))))
  15869. (`table
  15870. (if (eq (org-element-property :type element) 'table.el)
  15871. (org-edit-table.el)
  15872. (call-interactively 'org-table-edit-formulas)))
  15873. ;; Only Org tables contain `table-row' type elements.
  15874. (`table-row (call-interactively 'org-table-edit-formulas))
  15875. (`example-block (org-edit-src-code))
  15876. (`export-block (org-edit-export-block))
  15877. (`fixed-width (org-edit-fixed-width-region))
  15878. (`latex-environment (org-edit-latex-environment))
  15879. (`planning
  15880. (let ((proplist (cadr element)))
  15881. (mapc #'call-interactively
  15882. (remq nil
  15883. (list
  15884. (when (plist-get proplist :deadline) #'org-deadline)
  15885. (when (plist-get proplist :scheduled) #'org-schedule))))))
  15886. (_
  15887. ;; No notable element at point. Though, we may be at a link or
  15888. ;; a footnote reference, which are objects. Thus, scan deeper.
  15889. (let ((context (org-element-context element)))
  15890. (pcase (org-element-type context)
  15891. (`footnote-reference (org-edit-footnote-reference))
  15892. (`inline-src-block (org-edit-inline-src-code))
  15893. (`latex-fragment (org-edit-latex-fragment))
  15894. (`timestamp (if (eq 'inactive (org-element-property :type context))
  15895. (call-interactively #'org-time-stamp-inactive)
  15896. (call-interactively #'org-time-stamp)))
  15897. (`link (call-interactively #'ffap))
  15898. (_ (user-error "No special environment to edit here"))))))))
  15899. (defun org-ctrl-c-ctrl-c (&optional arg)
  15900. "Set tags in headline, or update according to changed information at point.
  15901. This command does many different things, depending on context:
  15902. - If column view is active, in agenda or org buffers, quit it.
  15903. - If there are highlights, remove them.
  15904. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  15905. this is what we do.
  15906. - If the cursor is on a statistics cookie, update it.
  15907. - If the cursor is in a headline, in an agenda or an org buffer,
  15908. prompt for tags and insert them into the current line, aligned
  15909. to `org-tags-column'. When called with prefix arg, realign all
  15910. tags in the current buffer.
  15911. - If the cursor is in one of the special #+KEYWORD lines, this
  15912. triggers scanning the buffer for these lines and updating the
  15913. information.
  15914. - If the cursor is inside a table, realign the table. This command
  15915. works even if the automatic table editor has been turned off.
  15916. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  15917. the entire table.
  15918. - If the cursor is at a footnote reference or definition, jump to
  15919. the corresponding definition or references, respectively.
  15920. - If the cursor is a the beginning of a dynamic block, update it.
  15921. - If the current buffer is a capture buffer, close note and file it.
  15922. - If the cursor is on a <<<target>>>, update radio targets and
  15923. corresponding links in this buffer.
  15924. - If the cursor is on a numbered item in a plain list, renumber the
  15925. ordered list.
  15926. - If the cursor is on a checkbox, toggle it.
  15927. - If the cursor is on a code block, evaluate it. The variable
  15928. `org-confirm-babel-evaluate' can be used to control prompting
  15929. before code block evaluation, by default every code block
  15930. evaluation requires confirmation. Code block evaluation can be
  15931. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  15932. (interactive "P")
  15933. (cond
  15934. ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  15935. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  15936. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  15937. (org-remove-occur-highlights)
  15938. (message "Temporary highlights/overlays removed from current buffer"))
  15939. ((and (local-variable-p 'org-finish-function)
  15940. (fboundp org-finish-function))
  15941. (funcall org-finish-function))
  15942. ((org-babel-hash-at-point))
  15943. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  15944. (t
  15945. (let* ((context
  15946. (org-element-lineage
  15947. (org-element-context)
  15948. ;; Limit to supported contexts.
  15949. '(babel-call clock dynamic-block footnote-definition
  15950. footnote-reference inline-babel-call inline-src-block
  15951. inlinetask item keyword node-property paragraph
  15952. plain-list planning property-drawer radio-target
  15953. src-block statistics-cookie table table-cell table-row
  15954. timestamp)
  15955. t))
  15956. (radio-list-p (org-at-radio-list-p))
  15957. (type (org-element-type context)))
  15958. ;; For convenience: at the first line of a paragraph on the same
  15959. ;; line as an item, apply function on that item instead.
  15960. (when (eq type 'paragraph)
  15961. (let ((parent (org-element-property :parent context)))
  15962. (when (and (eq (org-element-type parent) 'item)
  15963. (= (line-beginning-position)
  15964. (org-element-property :begin parent)))
  15965. (setq context parent)
  15966. (setq type 'item))))
  15967. ;; Act according to type of element or object at point.
  15968. ;;
  15969. ;; Do nothing on a blank line, except if it is contained in
  15970. ;; a source block. Hence, we first check if point is in such
  15971. ;; a block and then if it is at a blank line.
  15972. (pcase type
  15973. ((or `inline-src-block `src-block)
  15974. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  15975. (org-babel-eval-wipe-error-buffer)
  15976. (org-babel-execute-src-block
  15977. current-prefix-arg (org-babel-get-src-block-info nil context))))
  15978. ((guard (org-match-line "[ \t]*$"))
  15979. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  15980. (user-error
  15981. (substitute-command-keys
  15982. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  15983. ((or `babel-call `inline-babel-call)
  15984. (let ((info (org-babel-lob-get-info context)))
  15985. (when info (org-babel-execute-src-block nil info))))
  15986. (`clock (org-clock-update-time-maybe))
  15987. (`dynamic-block
  15988. (save-excursion
  15989. (goto-char (org-element-property :post-affiliated context))
  15990. (org-update-dblock)))
  15991. (`footnote-definition
  15992. (goto-char (org-element-property :post-affiliated context))
  15993. (call-interactively 'org-footnote-action))
  15994. (`footnote-reference (call-interactively #'org-footnote-action))
  15995. ((or `headline `inlinetask)
  15996. (save-excursion (goto-char (org-element-property :begin context))
  15997. (call-interactively #'org-set-tags-command)))
  15998. (`item
  15999. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  16000. ;; unconditionally, whereas `C-u' will toggle its presence.
  16001. ;; Without a universal argument, if the item has a checkbox,
  16002. ;; toggle it. Otherwise repair the list.
  16003. (if (or radio-list-p
  16004. (and (boundp org-list-checkbox-radio-mode)
  16005. org-list-checkbox-radio-mode))
  16006. (org-toggle-radio-button arg)
  16007. (let* ((box (org-element-property :checkbox context))
  16008. (struct (org-element-property :structure context))
  16009. (old-struct (copy-tree struct))
  16010. (parents (org-list-parents-alist struct))
  16011. (prevs (org-list-prevs-alist struct))
  16012. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  16013. (org-list-set-checkbox
  16014. (org-element-property :begin context) struct
  16015. (cond ((equal arg '(16)) "[-]")
  16016. ((and (not box) (equal arg '(4))) "[ ]")
  16017. ((or (not box) (equal arg '(4))) nil)
  16018. ((eq box 'on) "[ ]")
  16019. (t "[X]")))
  16020. ;; Mimic `org-list-write-struct' but with grabbing a return
  16021. ;; value from `org-list-struct-fix-box'.
  16022. (org-list-struct-fix-ind struct parents 2)
  16023. (org-list-struct-fix-item-end struct)
  16024. (org-list-struct-fix-bul struct prevs)
  16025. (org-list-struct-fix-ind struct parents)
  16026. (let ((block-item
  16027. (org-list-struct-fix-box struct parents prevs orderedp)))
  16028. (if (and box (equal struct old-struct))
  16029. (if (equal arg '(16))
  16030. (message "Checkboxes already reset")
  16031. (user-error "Cannot toggle this checkbox: %s"
  16032. (if (eq box 'on)
  16033. "all subitems checked"
  16034. "unchecked subitems")))
  16035. (org-list-struct-apply-struct struct old-struct)
  16036. (org-update-checkbox-count-maybe))
  16037. (when block-item
  16038. (message "Checkboxes were removed due to empty box at line %d"
  16039. (org-current-line block-item)))))))
  16040. (`plain-list
  16041. ;; At a plain list, with a double C-u argument, set
  16042. ;; checkboxes of each item to "[-]", whereas a single one
  16043. ;; will toggle their presence according to the state of the
  16044. ;; first item in the list. Without an argument, repair the
  16045. ;; list.
  16046. (if (or radio-list-p
  16047. (and (boundp org-list-checkbox-radio-mode)
  16048. org-list-checkbox-radio-mode))
  16049. (org-toggle-radio-button arg)
  16050. (let* ((begin (org-element-property :contents-begin context))
  16051. (struct (org-element-property :structure context))
  16052. (old-struct (copy-tree struct))
  16053. (first-box (save-excursion
  16054. (goto-char begin)
  16055. (looking-at org-list-full-item-re)
  16056. (match-string-no-properties 3)))
  16057. (new-box (cond ((equal arg '(16)) "[-]")
  16058. ((equal arg '(4)) (unless first-box "[ ]"))
  16059. ((equal first-box "[X]") "[ ]")
  16060. (t "[X]"))))
  16061. (cond
  16062. (arg
  16063. (dolist (pos
  16064. (org-list-get-all-items
  16065. begin struct (org-list-prevs-alist struct)))
  16066. (org-list-set-checkbox pos struct new-box)))
  16067. ((and first-box (eq (point) begin))
  16068. ;; For convenience, when point is at bol on the first
  16069. ;; item of the list and no argument is provided, simply
  16070. ;; toggle checkbox of that item, if any.
  16071. (org-list-set-checkbox begin struct new-box)))
  16072. (when (equal
  16073. (org-list-write-struct
  16074. struct (org-list-parents-alist struct) old-struct)
  16075. old-struct)
  16076. (message "Cannot update this checkbox"))
  16077. (org-update-checkbox-count-maybe))))
  16078. (`keyword
  16079. (let ((org-inhibit-startup-visibility-stuff t)
  16080. (org-startup-align-all-tables nil))
  16081. (when (boundp 'org-table-coordinate-overlays)
  16082. (mapc #'delete-overlay org-table-coordinate-overlays)
  16083. (setq org-table-coordinate-overlays nil))
  16084. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  16085. (message "Local setup has been refreshed"))
  16086. ((or `property-drawer `node-property)
  16087. (call-interactively #'org-property-action))
  16088. (`radio-target
  16089. (call-interactively #'org-update-radio-target-regexp))
  16090. (`statistics-cookie
  16091. (call-interactively #'org-update-statistics-cookies))
  16092. ((or `table `table-cell `table-row)
  16093. ;; At a table, recalculate every field and align it. Also
  16094. ;; send the table if necessary. If the table has
  16095. ;; a `table.el' type, just give up. At a table row or cell,
  16096. ;; maybe recalculate line but always align table.
  16097. (if (eq (org-element-property :type context) 'table.el)
  16098. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  16099. Use `\\[org-edit-special]' to edit table.el tables"))
  16100. (if (or (eq type 'table)
  16101. ;; Check if point is at a TBLFM line.
  16102. (and (eq type 'table-row)
  16103. (= (point) (org-element-property :end context))))
  16104. (save-excursion
  16105. (if (org-at-TBLFM-p)
  16106. (progn (require 'org-table)
  16107. (org-table-calc-current-TBLFM))
  16108. (goto-char (org-element-property :contents-begin context))
  16109. (org-call-with-arg 'org-table-recalculate (or arg t))
  16110. (orgtbl-send-table 'maybe)))
  16111. (org-table-maybe-eval-formula)
  16112. (cond (arg (call-interactively #'org-table-recalculate))
  16113. ((org-table-maybe-recalculate-line))
  16114. (t (org-table-align))))))
  16115. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  16116. (org-timestamp-change 0 'day))
  16117. ((and `nil (guard (org-at-heading-p)))
  16118. ;; When point is on an unsupported object type, we can miss
  16119. ;; the fact that it also is at a heading. Handle it here.
  16120. (call-interactively #'org-set-tags-command))
  16121. ((guard
  16122. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  16123. (_
  16124. (user-error
  16125. (substitute-command-keys
  16126. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  16127. (defun org-mode-restart ()
  16128. "Restart `org-mode'."
  16129. (interactive)
  16130. (let ((indent-status (bound-and-true-p org-indent-mode)))
  16131. (funcall major-mode)
  16132. (hack-local-variables)
  16133. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  16134. (org-indent-mode -1))
  16135. (org-reset-file-cache))
  16136. (message "%s restarted" major-mode))
  16137. (defun org-flag-above-first-heading (&optional arg)
  16138. "Hide from bob up to the first heading.
  16139. Move point to the beginning of first heading or end of buffer."
  16140. (goto-char (point-min))
  16141. (unless (org-at-heading-p)
  16142. (outline-next-heading))
  16143. (unless (bobp)
  16144. (org-flag-region 1 (1- (point)) (not arg) 'outline)))
  16145. (defun org-show-branches-buffer ()
  16146. "Show all branches in the buffer."
  16147. (org-flag-above-first-heading)
  16148. (outline-hide-sublevels 1)
  16149. (unless (eobp)
  16150. (outline-show-branches)
  16151. (while (outline-get-next-sibling)
  16152. (outline-show-branches)))
  16153. (goto-char (point-min)))
  16154. (defun org-kill-note-or-show-branches ()
  16155. "Abort storing current note, or show just branches."
  16156. (interactive)
  16157. (cond (org-finish-function
  16158. (let ((org-note-abort t)) (funcall org-finish-function)))
  16159. ((org-before-first-heading-p)
  16160. (org-show-branches-buffer)
  16161. (org-hide-archived-subtrees (point-min) (point-max)))
  16162. (t
  16163. (let ((beg (progn (org-back-to-heading) (point)))
  16164. (end (save-excursion (org-end-of-subtree t t) (point))))
  16165. (outline-hide-subtree)
  16166. (outline-show-branches)
  16167. (org-hide-archived-subtrees beg end)))))
  16168. (defun org-delete-indentation (&optional arg)
  16169. "Join current line to previous and fix whitespace at join.
  16170. If previous line is a headline add to headline title. Otherwise
  16171. the function calls `delete-indentation'.
  16172. I.e. with a non-nil optional argument, join the line with the
  16173. following one. If there is a region then join the lines in that
  16174. region."
  16175. (interactive "*P")
  16176. (if (save-excursion
  16177. (beginning-of-line (if arg 1 0))
  16178. (let ((case-fold-search nil))
  16179. (looking-at org-complex-heading-regexp)))
  16180. ;; At headline.
  16181. (let ((tags-column (when (match-beginning 5)
  16182. (save-excursion (goto-char (match-beginning 5))
  16183. (current-column))))
  16184. (string (concat " " (progn (when arg (forward-line 1))
  16185. (org-trim (delete-and-extract-region
  16186. (line-beginning-position)
  16187. (line-end-position)))))))
  16188. (unless (bobp) (delete-region (point) (1- (point))))
  16189. (goto-char (or (match-end 4)
  16190. (match-beginning 5)
  16191. (match-end 0)))
  16192. (skip-chars-backward " \t")
  16193. (save-excursion (insert string))
  16194. ;; Adjust alignment of tags.
  16195. (cond
  16196. ((not tags-column)) ;no tags
  16197. (org-auto-align-tags (org-align-tags))
  16198. (t (org--align-tags-here tags-column)))) ;preserve tags column
  16199. (let ((current-prefix-arg arg))
  16200. (call-interactively #'delete-indentation))))
  16201. (defun org-open-line (n)
  16202. "Insert a new row in tables, call `open-line' elsewhere.
  16203. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  16204. As a special case, when a document starts with a table, allow to
  16205. call `open-line' on the very first character."
  16206. (interactive "*p")
  16207. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  16208. (org-table-insert-row)
  16209. (open-line n)))
  16210. (defun org--newline (indent arg interactive)
  16211. "Call `newline-and-indent' or just `newline'.
  16212. If INDENT is non-nil, call `newline-and-indent' with ARG to
  16213. indent unconditionally; otherwise, call `newline' with ARG and
  16214. INTERACTIVE, which can trigger indentation if
  16215. `electric-indent-mode' is enabled."
  16216. (if indent
  16217. (org-newline-and-indent arg)
  16218. (newline arg interactive)))
  16219. (defun org-return (&optional indent arg interactive)
  16220. "Goto next table row or insert a newline.
  16221. Calls `org-table-next-row' or `newline', depending on context.
  16222. When optional INDENT argument is non-nil, call
  16223. `newline-and-indent' with ARG, otherwise call `newline' with ARG
  16224. and INTERACTIVE.
  16225. When `org-return-follows-link' is non-nil and point is on
  16226. a timestamp or a link, call `org-open-at-point'. However, it
  16227. will not happen if point is in a table or on a \"dead\"
  16228. object (e.g., within a comment). In these case, you need to use
  16229. `org-open-at-point' directly."
  16230. (interactive "i\nP\np")
  16231. (let ((context (if org-return-follows-link (org-element-context)
  16232. (org-element-at-point))))
  16233. (cond
  16234. ;; In a table, call `org-table-next-row'. However, before first
  16235. ;; column or after last one, split the table.
  16236. ((or (and (eq 'table (org-element-type context))
  16237. (not (eq 'table.el (org-element-property :type context)))
  16238. (>= (point) (org-element-property :contents-begin context))
  16239. (< (point) (org-element-property :contents-end context)))
  16240. (org-element-lineage context '(table-row table-cell) t))
  16241. (if (or (looking-at-p "[ \t]*$")
  16242. (save-excursion (skip-chars-backward " \t") (bolp)))
  16243. (insert "\n")
  16244. (org-table-justify-field-maybe)
  16245. (call-interactively #'org-table-next-row)))
  16246. ;; On a link or a timestamp, call `org-open-at-point' if
  16247. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  16248. ;; locations, e.g., in a comment, as `org-open-at-point'.
  16249. ((and org-return-follows-link
  16250. (or (and (eq 'link (org-element-type context))
  16251. ;; Ensure point is not on the white spaces after
  16252. ;; the link.
  16253. (let ((origin (point)))
  16254. (org-with-point-at (org-element-property :end context)
  16255. (skip-chars-backward " \t")
  16256. (> (point) origin))))
  16257. (org-in-regexp org-ts-regexp-both nil t)
  16258. (org-in-regexp org-tsr-regexp-both nil t)
  16259. (org-in-regexp org-link-any-re nil t)))
  16260. (call-interactively #'org-open-at-point))
  16261. ;; Insert newline in heading, but preserve tags.
  16262. ((and (not (bolp))
  16263. (let ((case-fold-search nil))
  16264. (org-match-line org-complex-heading-regexp)))
  16265. ;; At headline. Split line. However, if point is on keyword,
  16266. ;; priority cookie or tags, do not break any of them: add
  16267. ;; a newline after the headline instead.
  16268. (let ((tags-column (and (match-beginning 5)
  16269. (save-excursion (goto-char (match-beginning 5))
  16270. (current-column))))
  16271. (string
  16272. (when (and (match-end 4) (org-point-in-group (point) 4))
  16273. (delete-and-extract-region (point) (match-end 4)))))
  16274. ;; Adjust tag alignment.
  16275. (cond
  16276. ((not (and tags-column string)))
  16277. (org-auto-align-tags (org-align-tags))
  16278. (t (org--align-tags-here tags-column))) ;preserve tags column
  16279. (end-of-line)
  16280. (org-show-entry)
  16281. (org--newline indent arg interactive)
  16282. (when string (save-excursion (insert (org-trim string))))))
  16283. ;; In a list, make sure indenting keeps trailing text within.
  16284. ((and (not (eolp))
  16285. (org-element-lineage context '(item)))
  16286. (let ((trailing-data
  16287. (delete-and-extract-region (point) (line-end-position))))
  16288. (org--newline indent arg interactive)
  16289. (save-excursion (insert trailing-data))))
  16290. (t
  16291. ;; Do not auto-fill when point is in an Org property drawer.
  16292. (let ((auto-fill-function (and (not (org-at-property-p))
  16293. auto-fill-function)))
  16294. (org--newline indent arg interactive))))))
  16295. (defun org-return-and-maybe-indent ()
  16296. "Goto next table row, or insert a newline.
  16297. Call `org-table-next-row' or `org-return', depending on context.
  16298. See the individual commands for more information.
  16299. When inserting a newline, indent the new line if
  16300. `electric-indent-mode' is disabled."
  16301. (interactive)
  16302. (org-return (not electric-indent-mode)))
  16303. (defun org-ctrl-c-tab (&optional arg)
  16304. "Toggle columns width in a table, or show children.
  16305. Call `org-table-toggle-column-width' if point is in a table.
  16306. Otherwise provide a compact view of the children. ARG is the
  16307. level to hide."
  16308. (interactive "p")
  16309. (cond
  16310. ((org-at-table-p)
  16311. (call-interactively #'org-table-toggle-column-width))
  16312. ((org-before-first-heading-p)
  16313. (save-excursion
  16314. (org-flag-above-first-heading)
  16315. (outline-hide-sublevels (or arg 1))))
  16316. (t
  16317. (outline-hide-subtree)
  16318. (org-show-children arg))))
  16319. (defun org-ctrl-c-star ()
  16320. "Compute table, or change heading status of lines.
  16321. Calls `org-table-recalculate' or `org-toggle-heading',
  16322. depending on context."
  16323. (interactive)
  16324. (cond
  16325. ((org-at-table-p)
  16326. (call-interactively 'org-table-recalculate))
  16327. (t
  16328. ;; Convert all lines in region to list items
  16329. (call-interactively 'org-toggle-heading))))
  16330. (defun org-ctrl-c-minus ()
  16331. "Insert separator line in table or modify bullet status of line.
  16332. Also turns a plain line or a region of lines into list items.
  16333. Calls `org-table-insert-hline', `org-toggle-item', or
  16334. `org-cycle-list-bullet', depending on context."
  16335. (interactive)
  16336. (cond
  16337. ((org-at-table-p)
  16338. (call-interactively 'org-table-insert-hline))
  16339. ((org-region-active-p)
  16340. (call-interactively 'org-toggle-item))
  16341. ((org-in-item-p)
  16342. (call-interactively 'org-cycle-list-bullet))
  16343. (t
  16344. (call-interactively 'org-toggle-item))))
  16345. (defun org-toggle-heading (&optional nstars)
  16346. "Convert headings to normal text, or items or text to headings.
  16347. If there is no active region, only convert the current line.
  16348. With a `\\[universal-argument]' prefix, convert the whole list at
  16349. point into heading.
  16350. In a region:
  16351. - If the first non blank line is a headline, remove the stars
  16352. from all headlines in the region.
  16353. - If it is a normal line, turn each and every normal line (i.e.,
  16354. not an heading or an item) in the region into headings. If you
  16355. want to convert only the first line of this region, use one
  16356. universal prefix argument.
  16357. - If it is a plain list item, turn all plain list items into headings.
  16358. When converting a line into a heading, the number of stars is chosen
  16359. such that the lines become children of the current entry. However,
  16360. when a numeric prefix argument is given, its value determines the
  16361. number of stars to add."
  16362. (interactive "P")
  16363. (let ((skip-blanks
  16364. (function
  16365. ;; Return beginning of first non-blank line, starting from
  16366. ;; line at POS.
  16367. (lambda (pos)
  16368. (save-excursion
  16369. (goto-char pos)
  16370. (while (org-at-comment-p) (forward-line))
  16371. (skip-chars-forward " \r\t\n")
  16372. (point-at-bol)))))
  16373. beg end toggled)
  16374. ;; Determine boundaries of changes. If a universal prefix has
  16375. ;; been given, put the list in a region. If region ends at a bol,
  16376. ;; do not consider the last line to be in the region.
  16377. (when (and current-prefix-arg (org-at-item-p))
  16378. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16379. (org-mark-element))
  16380. (if (org-region-active-p)
  16381. (setq beg (funcall skip-blanks (region-beginning))
  16382. end (copy-marker (save-excursion
  16383. (goto-char (region-end))
  16384. (if (bolp) (point) (point-at-eol)))))
  16385. (setq beg (funcall skip-blanks (point-at-bol))
  16386. end (copy-marker (point-at-eol))))
  16387. ;; Ensure inline tasks don't count as headings.
  16388. (org-with-limited-levels
  16389. (save-excursion
  16390. (goto-char beg)
  16391. (cond
  16392. ;; Case 1. Started at an heading: de-star headings.
  16393. ((org-at-heading-p)
  16394. (while (< (point) end)
  16395. (when (org-at-heading-p t)
  16396. (looking-at org-outline-regexp) (replace-match "")
  16397. (setq toggled t))
  16398. (forward-line)))
  16399. ;; Case 2. Started at an item: change items into headlines.
  16400. ;; One star will be added by `org-list-to-subtree'.
  16401. ((org-at-item-p)
  16402. (while (< (point) end)
  16403. (when (org-at-item-p)
  16404. ;; Pay attention to cases when region ends before list.
  16405. (let* ((struct (org-list-struct))
  16406. (list-end
  16407. (min (org-list-get-bottom-point struct) (1+ end))))
  16408. (save-restriction
  16409. (narrow-to-region (point) list-end)
  16410. (insert (org-list-to-subtree
  16411. (org-list-to-lisp t)
  16412. (pcase (org-current-level)
  16413. (`nil 1)
  16414. (l (1+ (org-reduced-level l)))))
  16415. "\n")))
  16416. (setq toggled t))
  16417. (forward-line)))
  16418. ;; Case 3. Started at normal text: make every line an heading,
  16419. ;; skipping headlines and items.
  16420. (t (let* ((stars
  16421. (make-string
  16422. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16423. (add-stars
  16424. (cond (nstars "") ; stars from prefix only
  16425. ((equal stars "") "*") ; before first heading
  16426. (org-odd-levels-only "**") ; inside heading, odd
  16427. (t "*"))) ; inside heading, oddeven
  16428. (rpl (concat stars add-stars " "))
  16429. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16430. (while (< (point) (if (equal nstars '(4)) lend end))
  16431. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16432. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16433. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16434. (forward-line)))))))
  16435. (unless toggled (message "Cannot toggle heading from here"))))
  16436. (defun org-meta-return (&optional arg)
  16437. "Insert a new heading or wrap a region in a table.
  16438. Calls `org-insert-heading', `org-insert-item' or
  16439. `org-table-wrap-region', depending on context. When called with
  16440. an argument, unconditionally call `org-insert-heading'."
  16441. (interactive "P")
  16442. (org-check-before-invisible-edit 'insert)
  16443. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16444. (call-interactively (cond (arg #'org-insert-heading)
  16445. ((org-at-table-p) #'org-table-wrap-region)
  16446. ((org-in-item-p) #'org-insert-item)
  16447. (t #'org-insert-heading)))))
  16448. ;;; Menu entries
  16449. (defsubst org-in-subtree-not-table-p ()
  16450. "Are we in a subtree and not in a table?"
  16451. (and (not (org-before-first-heading-p))
  16452. (not (org-at-table-p))))
  16453. ;; Define the Org mode menus
  16454. (easy-menu-define org-org-menu org-mode-map "Org menu"
  16455. `("Org"
  16456. ("Show/Hide"
  16457. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16458. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16459. ["Sparse Tree..." org-sparse-tree t]
  16460. ["Reveal Context" org-reveal t]
  16461. ["Show All" org-show-all t]
  16462. "--"
  16463. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16464. "--"
  16465. ["New Heading" org-insert-heading t]
  16466. ("Navigate Headings"
  16467. ["Up" outline-up-heading t]
  16468. ["Next" outline-next-visible-heading t]
  16469. ["Previous" outline-previous-visible-heading t]
  16470. ["Next Same Level" outline-forward-same-level t]
  16471. ["Previous Same Level" outline-backward-same-level t]
  16472. "--"
  16473. ["Jump" org-goto t])
  16474. ("Edit Structure"
  16475. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16476. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16477. "--"
  16478. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16479. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16480. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16481. "--"
  16482. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16483. "--"
  16484. ["Copy visible text" org-copy-visible t]
  16485. "--"
  16486. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16487. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16488. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16489. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16490. "--"
  16491. ["Sort Region/Children" org-sort t]
  16492. "--"
  16493. ["Convert to odd levels" org-convert-to-odd-levels t]
  16494. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16495. ("Editing"
  16496. ["Emphasis..." org-emphasize t]
  16497. ["Add block structure" org-insert-structure-template t]
  16498. ["Edit Source Example" org-edit-special t]
  16499. "--"
  16500. ["Footnote new/jump" org-footnote-action t]
  16501. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16502. ("Archive"
  16503. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16504. "--"
  16505. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16506. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16507. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)])
  16508. "--"
  16509. ("Hyperlinks"
  16510. ["Store Link (Global)" org-store-link t]
  16511. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16512. ["Insert Link" org-insert-link t]
  16513. ["Follow Link" org-open-at-point t]
  16514. "--"
  16515. ["Next link" org-next-link t]
  16516. ["Previous link" org-previous-link t]
  16517. "--"
  16518. ["Descriptive Links"
  16519. org-toggle-link-display
  16520. :style radio
  16521. :selected org-descriptive-links
  16522. ]
  16523. ["Literal Links"
  16524. org-toggle-link-display
  16525. :style radio
  16526. :selected (not org-descriptive-links)])
  16527. "--"
  16528. ("TODO Lists"
  16529. ["TODO/DONE/-" org-todo t]
  16530. ("Select keyword"
  16531. ["Next keyword" org-shiftright (org-at-heading-p)]
  16532. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16533. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16534. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16535. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16536. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16537. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16538. "--"
  16539. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16540. :selected org-enforce-todo-dependencies :style toggle :active t]
  16541. "Settings for tree at point"
  16542. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16543. :selected (org-entry-get nil "ORDERED")
  16544. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16545. ["Do Children parallel" org-toggle-ordered-property :style radio
  16546. :selected (not (org-entry-get nil "ORDERED"))
  16547. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16548. "--"
  16549. ["Set Priority" org-priority t]
  16550. ["Priority Up" org-shiftup t]
  16551. ["Priority Down" org-shiftdown t]
  16552. "--"
  16553. ["Get news from all feeds" org-feed-update-all t]
  16554. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16555. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16556. ("TAGS and Properties"
  16557. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16558. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16559. "--"
  16560. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16561. ["Column view of properties" org-columns t]
  16562. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16563. ("Dates and Scheduling"
  16564. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16565. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16566. ("Change Date"
  16567. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16568. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16569. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16570. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16571. ["Compute Time Range" org-evaluate-time-range t]
  16572. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16573. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16574. "--"
  16575. ["Custom time format" org-toggle-time-stamp-overlays
  16576. :style radio :selected org-display-custom-times]
  16577. "--"
  16578. ["Goto Calendar" org-goto-calendar t]
  16579. ["Date from Calendar" org-date-from-calendar t]
  16580. "--"
  16581. ["Start/Restart Timer" org-timer-start t]
  16582. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16583. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16584. ["Insert Timer String" org-timer t]
  16585. ["Insert Timer Item" org-timer-item t])
  16586. ("Logging work"
  16587. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16588. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16589. ["Clock out" org-clock-out t]
  16590. ["Clock cancel" org-clock-cancel t]
  16591. "--"
  16592. ["Mark as default task" org-clock-mark-default-task t]
  16593. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16594. ["Goto running clock" org-clock-goto t]
  16595. "--"
  16596. ["Display times" org-clock-display t]
  16597. ["Create clock table" org-clock-report t]
  16598. "--"
  16599. ["Record DONE time"
  16600. (progn (setq org-log-done (not org-log-done))
  16601. (message "Switching to %s will %s record a timestamp"
  16602. (car org-done-keywords)
  16603. (if org-log-done "automatically" "not")))
  16604. :style toggle :selected org-log-done])
  16605. "--"
  16606. ["Agenda Command..." org-agenda t]
  16607. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16608. ("File List for Agenda")
  16609. ("Special views current file"
  16610. ["TODO Tree" org-show-todo-tree t]
  16611. ["Check Deadlines" org-check-deadlines t]
  16612. ["Tags/Property tree" org-match-sparse-tree t])
  16613. "--"
  16614. ["Export/Publish..." org-export-dispatch t]
  16615. ("LaTeX"
  16616. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16617. :style toggle :selected org-cdlatex-mode]
  16618. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16619. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16620. ["Modify math symbol" org-cdlatex-math-modify
  16621. (org-inside-LaTeX-fragment-p)]
  16622. ["Insert citation" org-reftex-citation t])
  16623. "--"
  16624. ("Documentation"
  16625. ["Show Version" org-version t]
  16626. ["Info Documentation" org-info t]
  16627. ["Browse Org News" org-browse-news t])
  16628. ("Customize"
  16629. ["Browse Org Group" org-customize t]
  16630. "--"
  16631. ["Expand This Menu" org-create-customize-menu t])
  16632. ["Send bug report" org-submit-bug-report t]
  16633. "--"
  16634. ("Refresh/Reload"
  16635. ["Refresh setup current buffer" org-mode-restart t]
  16636. ["Reload Org (after update)" org-reload t]
  16637. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16638. (easy-menu-define org-tbl-menu org-mode-map "Org Table menu"
  16639. '("Table"
  16640. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16641. ["Next Field" org-cycle (org-at-table-p)]
  16642. ["Previous Field" org-shifttab (org-at-table-p)]
  16643. ["Next Row" org-return (org-at-table-p)]
  16644. "--"
  16645. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16646. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16647. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16648. "--"
  16649. ("Column"
  16650. ["Move Column Left" org-metaleft (org-at-table-p)]
  16651. ["Move Column Right" org-metaright (org-at-table-p)]
  16652. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16653. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16654. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16655. ("Row"
  16656. ["Move Row Up" org-metaup (org-at-table-p)]
  16657. ["Move Row Down" org-metadown (org-at-table-p)]
  16658. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16659. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16660. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16661. "--"
  16662. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16663. ("Rectangle"
  16664. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16665. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16666. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16667. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16668. "--"
  16669. ("Calculate"
  16670. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16671. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16672. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16673. "--"
  16674. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16675. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16676. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16677. "--"
  16678. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16679. "--"
  16680. ["Sum Column/Rectangle" org-table-sum
  16681. (or (org-at-table-p) (org-region-active-p))]
  16682. ["Which Column?" org-table-current-column (org-at-table-p)])
  16683. ["Debug Formulas"
  16684. org-table-toggle-formula-debugger
  16685. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16686. ["Show Col/Row Numbers"
  16687. org-table-toggle-coordinate-overlays
  16688. :style toggle
  16689. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16690. "--"
  16691. ["Create" org-table-create (not (org-at-table-p))]
  16692. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16693. ["Import from File" org-table-import (not (org-at-table-p))]
  16694. ["Export to File" org-table-export (org-at-table-p)]
  16695. "--"
  16696. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16697. "--"
  16698. ("Plot"
  16699. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16700. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16701. (defun org-info (&optional node)
  16702. "Read documentation for Org in the info system.
  16703. With optional NODE, go directly to that node."
  16704. (interactive)
  16705. (info (format "(org)%s" (or node ""))))
  16706. (defun org-browse-news ()
  16707. "Browse the news for the latest major release."
  16708. (interactive)
  16709. (browse-url "https://orgmode.org/Changes.html"))
  16710. ;;;###autoload
  16711. (defun org-submit-bug-report ()
  16712. "Submit a bug report on Org via mail.
  16713. Don't hesitate to report any problems or inaccurate documentation.
  16714. If you don't have setup sending mail from (X)Emacs, please copy the
  16715. output buffer into your mail program, as it gives us important
  16716. information about your Org version and configuration."
  16717. (interactive)
  16718. (require 'reporter)
  16719. (defvar reporter-prompt-for-summary-p)
  16720. (org-load-modules-maybe)
  16721. (org-require-autoloaded-modules)
  16722. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  16723. (reporter-submit-bug-report
  16724. "emacs-orgmode@gnu.org"
  16725. (org-version nil 'full)
  16726. (let (list)
  16727. (save-window-excursion
  16728. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  16729. (delete-other-windows)
  16730. (erase-buffer)
  16731. (insert "You are about to submit a bug report to the Org mailing list.
  16732. If your report is about Org installation, please read this section:
  16733. https://orgmode.org/org.html#Installation
  16734. Please read https://orgmode.org/org.html#Feedback on how to make
  16735. a good report, it will help Org contributors fixing your problem.
  16736. Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  16737. if the issue you are about to raise has already been dealt with.
  16738. We also would like to add your full Org and Outline configuration
  16739. to the bug report. It will help us debugging the issue.
  16740. *HOWEVER*, some variables you have customized may contain private
  16741. information. The names of customers, colleagues, or friends, might
  16742. appear in the form of file names, tags, todo states or search strings.
  16743. If you answer \"yes\" to the prompt, you might want to check and remove
  16744. such private information before sending the email.")
  16745. (add-text-properties (point-min) (point-max) '(face org-warning))
  16746. (when (yes-or-no-p "Include your Org configuration ")
  16747. (mapatoms
  16748. (lambda (v)
  16749. (and (boundp v)
  16750. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  16751. (or (and (symbol-value v)
  16752. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  16753. (and
  16754. (get v 'custom-type) (get v 'standard-value)
  16755. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  16756. (push v list)))))
  16757. (kill-buffer (get-buffer "*Warn about privacy*"))
  16758. list))
  16759. nil nil
  16760. "Remember to cover the basics, that is, what you expected to happen and
  16761. what in fact did happen. You don't know how to make a good report? See
  16762. https://orgmode.org/manual/Feedback.html#Feedback
  16763. Your bug report will be posted to the Org mailing list.
  16764. ------------------------------------------------------------------------")
  16765. (save-excursion
  16766. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  16767. (replace-match "\\1Bug: \\3 [\\2]")))))
  16768. (defun org-install-agenda-files-menu ()
  16769. "Install agenda file menu."
  16770. (let ((bl (buffer-list)))
  16771. (save-excursion
  16772. (while bl
  16773. (set-buffer (pop bl))
  16774. (when (derived-mode-p 'org-mode) (setq bl nil)))
  16775. (when (derived-mode-p 'org-mode)
  16776. (easy-menu-change
  16777. '("Org") "File List for Agenda"
  16778. (append
  16779. (list
  16780. ["Edit File List" (org-edit-agenda-file-list) t]
  16781. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  16782. ["Remove Current File from List" org-remove-file t]
  16783. ["Cycle through agenda files" org-cycle-agenda-files t]
  16784. ["Occur in all agenda files" org-occur-in-agenda-files t]
  16785. "--")
  16786. (mapcar 'org-file-menu-entry
  16787. ;; Prevent initialization from failing.
  16788. (ignore-errors (org-agenda-files t)))))))))
  16789. ;;;; Documentation
  16790. (defun org-require-autoloaded-modules ()
  16791. (interactive)
  16792. (mapc #'require
  16793. '(org-agenda org-archive org-attach org-clock org-colview org-id
  16794. org-table org-timer)))
  16795. ;;;###autoload
  16796. (defun org-reload (&optional uncompiled)
  16797. "Reload all Org Lisp files.
  16798. With prefix arg UNCOMPILED, load the uncompiled versions."
  16799. (interactive "P")
  16800. (require 'loadhist)
  16801. (let* ((org-dir (org-find-library-dir "org"))
  16802. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  16803. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  16804. (remove-re (format "\\`%s\\'"
  16805. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  16806. (feats (delete-dups
  16807. (mapcar 'file-name-sans-extension
  16808. (mapcar 'file-name-nondirectory
  16809. (delq nil
  16810. (mapcar 'feature-file
  16811. features))))))
  16812. (lfeat (append
  16813. (sort
  16814. (setq feats
  16815. (delq nil (mapcar
  16816. (lambda (f)
  16817. (if (and (string-match feature-re f)
  16818. (not (string-match remove-re f)))
  16819. f nil))
  16820. feats)))
  16821. 'string-lessp)
  16822. (list "org-version" "org")))
  16823. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  16824. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  16825. load-uncore load-misses)
  16826. (setq load-misses
  16827. (delq 't
  16828. (mapcar (lambda (f)
  16829. (or (org-load-noerror-mustsuffix (concat org-dir f))
  16830. (and (string= org-dir contrib-dir)
  16831. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  16832. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  16833. (push f load-uncore)
  16834. 't)
  16835. f))
  16836. lfeat)))
  16837. (when load-uncore
  16838. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  16839. (if (> (length load-uncore) 1) "s were" " was")
  16840. (reverse load-uncore)))
  16841. (if load-misses
  16842. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  16843. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  16844. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  16845. ;;;###autoload
  16846. (defun org-customize ()
  16847. "Call the customize function with org as argument."
  16848. (interactive)
  16849. (org-load-modules-maybe)
  16850. (org-require-autoloaded-modules)
  16851. (customize-browse 'org))
  16852. (defun org-create-customize-menu ()
  16853. "Create a full customization menu for Org mode, insert it into the menu."
  16854. (interactive)
  16855. (org-load-modules-maybe)
  16856. (org-require-autoloaded-modules)
  16857. (easy-menu-change
  16858. '("Org") "Customize"
  16859. `(["Browse Org group" org-customize t]
  16860. "--"
  16861. ,(customize-menu-create 'org)
  16862. ["Set" Custom-set t]
  16863. ["Save" Custom-save t]
  16864. ["Reset to Current" Custom-reset-current t]
  16865. ["Reset to Saved" Custom-reset-saved t]
  16866. ["Reset to Standard Settings" Custom-reset-standard t]))
  16867. (message "\"Org\"-menu now contains full customization menu"))
  16868. ;;;; Miscellaneous stuff
  16869. ;;; Generally useful functions
  16870. (defun org-in-clocktable-p ()
  16871. "Check if the cursor is in a clocktable."
  16872. (let ((pos (point)) start)
  16873. (save-excursion
  16874. (end-of-line 1)
  16875. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  16876. (setq start (match-beginning 0))
  16877. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  16878. (>= (match-end 0) pos)
  16879. start))))
  16880. (defun org-in-verbatim-emphasis ()
  16881. (save-match-data
  16882. (and (org-in-regexp org-verbatim-re 2)
  16883. (>= (point) (match-beginning 3))
  16884. (<= (point) (match-end 4)))))
  16885. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  16886. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  16887. (if (and marker (marker-buffer marker)
  16888. (buffer-live-p (marker-buffer marker)))
  16889. (progn
  16890. (pop-to-buffer-same-window (marker-buffer marker))
  16891. (when (or (> marker (point-max)) (< marker (point-min)))
  16892. (widen))
  16893. (goto-char marker)
  16894. (org-show-context 'org-goto))
  16895. (if bookmark
  16896. (bookmark-jump bookmark)
  16897. (error "Cannot find location"))))
  16898. (defun org-quote-csv-field (s)
  16899. "Quote field for inclusion in CSV material."
  16900. (if (string-match "[\",]" s)
  16901. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  16902. s))
  16903. (defun org-force-self-insert (N)
  16904. "Needed to enforce self-insert under remapping."
  16905. (interactive "p")
  16906. (self-insert-command N))
  16907. (defun org-quote-vert (s)
  16908. "Replace \"|\" with \"\\vert\"."
  16909. (while (string-match "|" s)
  16910. (setq s (replace-match "\\vert" t t s)))
  16911. s)
  16912. (defun org-uuidgen-p (s)
  16913. "Is S an ID created by UUIDGEN?"
  16914. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  16915. (defun org-in-src-block-p (&optional inside)
  16916. "Whether point is in a code source block.
  16917. When INSIDE is non-nil, don't consider we are within a source
  16918. block when point is at #+BEGIN_SRC or #+END_SRC."
  16919. (let ((case-fold-search t))
  16920. (or (and (eq (get-char-property (point) 'src-block) t))
  16921. (and (not inside)
  16922. (save-match-data
  16923. (save-excursion
  16924. (beginning-of-line)
  16925. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  16926. (defun org-context ()
  16927. "Return a list of contexts of the current cursor position.
  16928. If several contexts apply, all are returned.
  16929. Each context entry is a list with a symbol naming the context, and
  16930. two positions indicating start and end of the context. Possible
  16931. contexts are:
  16932. :headline anywhere in a headline
  16933. :headline-stars on the leading stars in a headline
  16934. :todo-keyword on a TODO keyword (including DONE) in a headline
  16935. :tags on the TAGS in a headline
  16936. :priority on the priority cookie in a headline
  16937. :item on the first line of a plain list item
  16938. :item-bullet on the bullet/number of a plain list item
  16939. :checkbox on the checkbox in a plain list item
  16940. :table in an Org table
  16941. :table-special on a special filed in a table
  16942. :table-table in a table.el table
  16943. :clocktable in a clocktable
  16944. :src-block in a source block
  16945. :link on a hyperlink
  16946. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  16947. :latex-fragment on a LaTeX fragment
  16948. :latex-preview on a LaTeX fragment with overlaid preview image
  16949. This function expects the position to be visible because it uses font-lock
  16950. faces as a help to recognize the following contexts: :table-special, :link,
  16951. and :keyword."
  16952. (let* ((f (get-text-property (point) 'face))
  16953. (faces (if (listp f) f (list f)))
  16954. (case-fold-search t)
  16955. (p (point)) clist o)
  16956. ;; First the large context
  16957. (cond
  16958. ((org-at-heading-p t)
  16959. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  16960. (when (progn
  16961. (beginning-of-line 1)
  16962. (looking-at org-todo-line-tags-regexp))
  16963. (push (org-point-in-group p 1 :headline-stars) clist)
  16964. (push (org-point-in-group p 2 :todo-keyword) clist)
  16965. (push (org-point-in-group p 4 :tags) clist))
  16966. (goto-char p)
  16967. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  16968. (when (looking-at "\\[#[A-Z0-9]\\]")
  16969. (push (org-point-in-group p 0 :priority) clist)))
  16970. ((org-at-item-p)
  16971. (push (org-point-in-group p 2 :item-bullet) clist)
  16972. (push (list :item (point-at-bol)
  16973. (save-excursion (org-end-of-item) (point)))
  16974. clist)
  16975. (and (org-at-item-checkbox-p)
  16976. (push (org-point-in-group p 0 :checkbox) clist)))
  16977. ((org-at-table-p)
  16978. (push (list :table (org-table-begin) (org-table-end)) clist)
  16979. (when (memq 'org-formula faces)
  16980. (push (list :table-special
  16981. (previous-single-property-change p 'face)
  16982. (next-single-property-change p 'face))
  16983. clist)))
  16984. ((org-at-table-p 'any)
  16985. (push (list :table-table) clist)))
  16986. (goto-char p)
  16987. (let ((case-fold-search t))
  16988. ;; New the "medium" contexts: clocktables, source blocks
  16989. (cond ((org-in-clocktable-p)
  16990. (push (list :clocktable
  16991. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  16992. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  16993. (match-beginning 1))
  16994. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  16995. (match-end 0)))
  16996. clist))
  16997. ((org-in-src-block-p)
  16998. (push (list :src-block
  16999. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  17000. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  17001. (match-beginning 1))
  17002. (and (search-forward "#+END_SRC" nil t)
  17003. (match-beginning 0)))
  17004. clist))))
  17005. (goto-char p)
  17006. ;; Now the small context
  17007. (cond
  17008. ((org-at-timestamp-p)
  17009. (push (org-point-in-group p 0 :timestamp) clist))
  17010. ((memq 'org-link faces)
  17011. (push (list :link
  17012. (previous-single-property-change p 'face)
  17013. (next-single-property-change p 'face))
  17014. clist))
  17015. ((memq 'org-special-keyword faces)
  17016. (push (list :keyword
  17017. (previous-single-property-change p 'face)
  17018. (next-single-property-change p 'face))
  17019. clist))
  17020. ((setq o (cl-some
  17021. (lambda (o)
  17022. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  17023. o))
  17024. (overlays-at (point))))
  17025. (push (list :latex-fragment
  17026. (overlay-start o) (overlay-end o))
  17027. clist)
  17028. (push (list :latex-preview
  17029. (overlay-start o) (overlay-end o))
  17030. clist))
  17031. ((org-inside-LaTeX-fragment-p)
  17032. ;; FIXME: positions wrong.
  17033. (push (list :latex-fragment (point) (point)) clist)))
  17034. (setq clist (nreverse (delq nil clist)))
  17035. clist))
  17036. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  17037. "Non-nil when point is between matches of START-RE and END-RE.
  17038. Also return a non-nil value when point is on one of the matches.
  17039. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  17040. buffer positions. Default values are the positions of headlines
  17041. surrounding the point.
  17042. The functions returns a cons cell whose car (resp. cdr) is the
  17043. position before START-RE (resp. after END-RE)."
  17044. (save-match-data
  17045. (let ((pos (point))
  17046. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  17047. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  17048. beg end)
  17049. (save-excursion
  17050. ;; Point is on a block when on START-RE or if START-RE can be
  17051. ;; found before it...
  17052. (and (or (org-in-regexp start-re)
  17053. (re-search-backward start-re limit-up t))
  17054. (setq beg (match-beginning 0))
  17055. ;; ... and END-RE after it...
  17056. (goto-char (match-end 0))
  17057. (re-search-forward end-re limit-down t)
  17058. (> (setq end (match-end 0)) pos)
  17059. ;; ... without another START-RE in-between.
  17060. (goto-char (match-beginning 0))
  17061. (not (re-search-backward start-re (1+ beg) t))
  17062. ;; Return value.
  17063. (cons beg end))))))
  17064. (defun org-in-block-p (names)
  17065. "Non-nil when point belongs to a block whose name belongs to NAMES.
  17066. NAMES is a list of strings containing names of blocks.
  17067. Return first block name matched, or nil. Beware that in case of
  17068. nested blocks, the returned name may not belong to the closest
  17069. block from point."
  17070. (save-match-data
  17071. (catch 'exit
  17072. (let ((case-fold-search t)
  17073. (lim-up (save-excursion (outline-previous-heading)))
  17074. (lim-down (save-excursion (outline-next-heading))))
  17075. (dolist (name names)
  17076. (let ((n (regexp-quote name)))
  17077. (when (org-between-regexps-p
  17078. (concat "^[ \t]*#\\+begin_" n)
  17079. (concat "^[ \t]*#\\+end_" n)
  17080. lim-up lim-down)
  17081. (throw 'exit n)))))
  17082. nil)))
  17083. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  17084. "Call `multi-occur' with buffers for all agenda files."
  17085. (interactive "sOrg-files matching: ")
  17086. (let* ((files (org-agenda-files))
  17087. (tnames (mapcar #'file-truename files))
  17088. (extra org-agenda-text-search-extra-files))
  17089. (when (eq (car extra) 'agenda-archives)
  17090. (setq extra (cdr extra))
  17091. (setq files (org-add-archive-files files)))
  17092. (dolist (f extra)
  17093. (unless (member (file-truename f) tnames)
  17094. (unless (member f files) (setq files (append files (list f))))
  17095. (setq tnames (append tnames (list (file-truename f))))))
  17096. (multi-occur
  17097. (mapcar (lambda (x)
  17098. (with-current-buffer
  17099. ;; FIXME: Why not just (find-file-noselect x)?
  17100. ;; Is it to avoid the "revert buffer" prompt?
  17101. (or (get-file-buffer x) (find-file-noselect x))
  17102. (widen)
  17103. (current-buffer)))
  17104. files)
  17105. regexp)))
  17106. (add-hook 'occur-mode-find-occurrence-hook
  17107. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  17108. (defun org-occur-link-in-agenda-files ()
  17109. "Create a link and search for it in the agendas.
  17110. The link is not stored in `org-stored-links', it is just created
  17111. for the search purpose."
  17112. (interactive)
  17113. (let ((link (condition-case nil
  17114. (org-store-link nil)
  17115. (error "Unable to create a link to here"))))
  17116. (org-occur-in-agenda-files (regexp-quote link))))
  17117. (defun org-back-over-empty-lines ()
  17118. "Move backwards over whitespace, to the beginning of the first empty line.
  17119. Returns the number of empty lines passed."
  17120. (let ((pos (point)))
  17121. (if (cdr (assq 'heading org-blank-before-new-entry))
  17122. (skip-chars-backward " \t\n\r")
  17123. (unless (eobp)
  17124. (forward-line -1)))
  17125. (beginning-of-line 2)
  17126. (goto-char (min (point) pos))
  17127. (count-lines (point) pos)))
  17128. ;;; TODO: Only called once, from ox-odt which should probably use
  17129. ;;; org-export-inline-image-p or something.
  17130. (defun org-file-image-p (file)
  17131. "Return non-nil if FILE is an image."
  17132. (save-match-data
  17133. (string-match (image-file-name-regexp) file)))
  17134. (defun org-get-cursor-date (&optional with-time)
  17135. "Return the date at cursor in as a time.
  17136. This works in the calendar and in the agenda, anywhere else it just
  17137. returns the current time.
  17138. If WITH-TIME is non-nil, returns the time of the event at point (in
  17139. the agenda) or the current time of the day; otherwise returns the
  17140. earliest time on the cursor date that Org treats as that date
  17141. (bearing in mind `org-extend-today-until')."
  17142. (let (date day defd tp hod mod)
  17143. (when with-time
  17144. (setq tp (get-text-property (point) 'time))
  17145. (when (and tp (string-match "\\([0-2]?[0-9]\\):\\([0-5][0-9]\\)" tp))
  17146. (setq hod (string-to-number (match-string 1 tp))
  17147. mod (string-to-number (match-string 2 tp))))
  17148. (or tp (let ((now (decode-time)))
  17149. (setq hod (nth 2 now)
  17150. mod (nth 1 now)))))
  17151. (cond
  17152. ((eq major-mode 'calendar-mode)
  17153. (setq date (calendar-cursor-to-date)
  17154. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17155. (nth 1 date) (nth 0 date) (nth 2 date))))
  17156. ((eq major-mode 'org-agenda-mode)
  17157. (setq day (get-text-property (point) 'day))
  17158. (when day
  17159. (setq date (calendar-gregorian-from-absolute day)
  17160. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17161. (nth 1 date) (nth 0 date) (nth 2 date))))))
  17162. (or defd (current-time))))
  17163. (defun org-mark-subtree (&optional up)
  17164. "Mark the current subtree.
  17165. This puts point at the start of the current subtree, and mark at
  17166. the end. If a numeric prefix UP is given, move up into the
  17167. hierarchy of headlines by UP levels before marking the subtree."
  17168. (interactive "P")
  17169. (org-with-limited-levels
  17170. (cond ((org-at-heading-p) (beginning-of-line))
  17171. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  17172. (t (outline-previous-visible-heading 1))))
  17173. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  17174. (if (called-interactively-p 'any)
  17175. (call-interactively 'org-mark-element)
  17176. (org-mark-element)))
  17177. ;;; Indentation
  17178. (defvar org-element-greater-elements)
  17179. (defun org--get-expected-indentation (element contentsp)
  17180. "Expected indentation column for current line, according to ELEMENT.
  17181. ELEMENT is an element containing point. CONTENTSP is non-nil
  17182. when indentation is to be computed according to contents of
  17183. ELEMENT."
  17184. (let ((type (org-element-type element))
  17185. (start (org-element-property :begin element))
  17186. (post-affiliated (org-element-property :post-affiliated element)))
  17187. (org-with-wide-buffer
  17188. (cond
  17189. (contentsp
  17190. (cl-case type
  17191. ((diary-sexp footnote-definition) 0)
  17192. ((headline inlinetask nil)
  17193. (if (not org-adapt-indentation) 0
  17194. (let ((level (org-current-level)))
  17195. (if level (1+ level) 0))))
  17196. ((item plain-list) (org-list-item-body-column post-affiliated))
  17197. (t
  17198. (goto-char start)
  17199. (current-indentation))))
  17200. ((and
  17201. (eq org-adapt-indentation 'headline-data)
  17202. (memq type '(planning clock node-property property-drawer drawer)))
  17203. (org--get-expected-indentation
  17204. (org-element-property :parent element) t))
  17205. ((memq type '(headline inlinetask nil))
  17206. (if (org-match-line "[ \t]*$")
  17207. (org--get-expected-indentation element t)
  17208. 0))
  17209. ((memq type '(diary-sexp footnote-definition)) 0)
  17210. ;; First paragraph of a footnote definition or an item.
  17211. ;; Indent like parent.
  17212. ((< (line-beginning-position) start)
  17213. (org--get-expected-indentation
  17214. (org-element-property :parent element) t))
  17215. ;; At first line: indent according to previous sibling, if any,
  17216. ;; ignoring footnote definitions and inline tasks, or parent's
  17217. ;; contents.
  17218. ((and ( = (line-beginning-position) start)
  17219. (eq org-adapt-indentation t))
  17220. (catch 'exit
  17221. (while t
  17222. (if (= (point-min) start) (throw 'exit 0)
  17223. (goto-char (1- start))
  17224. (let* ((previous (org-element-at-point))
  17225. (parent previous))
  17226. (while (and parent (<= (org-element-property :end parent) start))
  17227. (setq previous parent
  17228. parent (org-element-property :parent parent)))
  17229. (cond
  17230. ((not previous) (throw 'exit 0))
  17231. ((> (org-element-property :end previous) start)
  17232. (throw 'exit (org--get-expected-indentation previous t)))
  17233. ((memq (org-element-type previous)
  17234. '(footnote-definition inlinetask))
  17235. (setq start (org-element-property :begin previous)))
  17236. (t (goto-char (org-element-property :begin previous))
  17237. (throw 'exit
  17238. (if (bolp) (current-indentation)
  17239. ;; At first paragraph in an item or
  17240. ;; a footnote definition.
  17241. (org--get-expected-indentation
  17242. (org-element-property :parent previous) t))))))))))
  17243. ;; Otherwise, move to the first non-blank line above.
  17244. ((not (eq org-adapt-indentation 'headline-data))
  17245. (beginning-of-line)
  17246. (let ((pos (point)))
  17247. (skip-chars-backward " \r\t\n")
  17248. (cond
  17249. ;; Two blank lines end a footnote definition or a plain
  17250. ;; list. When we indent an empty line after them, the
  17251. ;; containing list or footnote definition is over, so it
  17252. ;; qualifies as a previous sibling. Therefore, we indent
  17253. ;; like its first line.
  17254. ((and (memq type '(footnote-definition plain-list))
  17255. (> (count-lines (point) pos) 2))
  17256. (goto-char start)
  17257. (current-indentation))
  17258. ;; Line above is the first one of a paragraph at the
  17259. ;; beginning of an item or a footnote definition. Indent
  17260. ;; like parent.
  17261. ((< (line-beginning-position) start)
  17262. (org--get-expected-indentation
  17263. (org-element-property :parent element) t))
  17264. ;; Line above is the beginning of an element, i.e., point
  17265. ;; was originally on the blank lines between element's start
  17266. ;; and contents.
  17267. ((= (line-beginning-position) post-affiliated)
  17268. (org--get-expected-indentation element t))
  17269. ;; POS is after contents in a greater element. Indent like
  17270. ;; the beginning of the element.
  17271. ((and (memq type org-element-greater-elements)
  17272. (let ((cend (org-element-property :contents-end element)))
  17273. (and cend (<= cend pos))))
  17274. ;; As a special case, if point is at the end of a footnote
  17275. ;; definition or an item, indent like the very last element
  17276. ;; within. If that last element is an item, indent like
  17277. ;; its contents.
  17278. (if (memq type '(footnote-definition item plain-list))
  17279. (let ((last (org-element-at-point)))
  17280. (goto-char pos)
  17281. (org--get-expected-indentation
  17282. last (eq (org-element-type last) 'item)))
  17283. (goto-char start)
  17284. (current-indentation)))
  17285. ;; In any other case, indent like the current line.
  17286. (t (current-indentation)))))
  17287. ;; Finally, no indentation is needed, fall back to 0.
  17288. (t (current-indentation))))))
  17289. (defun org--align-node-property ()
  17290. "Align node property at point.
  17291. Alignment is done according to `org-property-format', which see."
  17292. (when (save-excursion
  17293. (beginning-of-line)
  17294. (looking-at org-property-re))
  17295. (replace-match
  17296. (concat (match-string 4)
  17297. (org-trim
  17298. (format org-property-format (match-string 1) (match-string 3))))
  17299. t t)))
  17300. (defun org-indent-line ()
  17301. "Indent line depending on context.
  17302. Indentation is done according to the following rules:
  17303. - Footnote definitions, diary sexps, headlines and inline tasks
  17304. have to start at column 0.
  17305. - On the very first line of an element, consider, in order, the
  17306. next rules until one matches:
  17307. 1. If there's a sibling element before, ignoring footnote
  17308. definitions and inline tasks, indent like its first line.
  17309. 2. If element has a parent, indent like its contents. More
  17310. precisely, if parent is an item, indent after the bullet.
  17311. Else, indent like parent's first line.
  17312. 3. Otherwise, indent relatively to current level, if
  17313. `org-adapt-indentation' is non-nil, or to left margin.
  17314. - On a blank line at the end of an element, indent according to
  17315. the type of the element. More precisely
  17316. 1. If element is a plain list, an item, or a footnote
  17317. definition, indent like the very last element within.
  17318. 2. If element is a paragraph, indent like its last non blank
  17319. line.
  17320. 3. Otherwise, indent like its very first line.
  17321. - In the code part of a source block, use language major mode
  17322. to indent current line if `org-src-tab-acts-natively' is
  17323. non-nil. If it is nil, do nothing.
  17324. - Otherwise, indent like the first non-blank line above.
  17325. The function doesn't indent an item as it could break the whole
  17326. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17327. `\\[org-shiftmetaright]'.
  17328. Also align node properties according to `org-property-format'."
  17329. (interactive)
  17330. (unless (org-at-heading-p)
  17331. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  17332. (type (org-element-type element)))
  17333. (cond ((and (memq type '(plain-list item))
  17334. (= (line-beginning-position)
  17335. (org-element-property :post-affiliated element)))
  17336. nil)
  17337. ((and (eq type 'latex-environment)
  17338. (>= (point) (org-element-property :post-affiliated element))
  17339. (< (point)
  17340. (org-with-point-at (org-element-property :end element)
  17341. (skip-chars-backward " \t\n")
  17342. (line-beginning-position 2))))
  17343. nil)
  17344. ((and (eq type 'src-block)
  17345. org-src-tab-acts-natively
  17346. (> (line-beginning-position)
  17347. (org-element-property :post-affiliated element))
  17348. (< (line-beginning-position)
  17349. (org-with-point-at (org-element-property :end element)
  17350. (skip-chars-backward " \t\n")
  17351. (line-beginning-position))))
  17352. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17353. (t
  17354. (let ((column (org--get-expected-indentation element nil)))
  17355. ;; Preserve current column.
  17356. (if (<= (current-column) (current-indentation))
  17357. (indent-line-to column)
  17358. (save-excursion (indent-line-to column))))
  17359. ;; Align node property. Also preserve current column.
  17360. (when (eq type 'node-property)
  17361. (let ((column (current-column)))
  17362. (org--align-node-property)
  17363. (org-move-to-column column))))))))
  17364. (defun org-indent-region (start end)
  17365. "Indent each non-blank line in the region.
  17366. Called from a program, START and END specify the region to
  17367. indent. The function will not indent contents of example blocks,
  17368. verse blocks and export blocks as leading white spaces are
  17369. assumed to be significant there."
  17370. (interactive "r")
  17371. (save-excursion
  17372. (goto-char start)
  17373. (skip-chars-forward " \r\t\n")
  17374. (unless (eobp) (beginning-of-line))
  17375. (let ((indent-to
  17376. (lambda (ind pos)
  17377. ;; Set IND as indentation for all lines between point and
  17378. ;; POS. Blank lines are ignored. Leave point after POS
  17379. ;; once done.
  17380. (let ((limit (copy-marker pos)))
  17381. (while (< (point) limit)
  17382. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17383. (forward-line))
  17384. (set-marker limit nil))))
  17385. (end (copy-marker end)))
  17386. (while (< (point) end)
  17387. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17388. (let* ((element (org-element-at-point))
  17389. (type (org-element-type element))
  17390. (element-end (copy-marker (org-element-property :end element)))
  17391. (ind (org--get-expected-indentation element nil)))
  17392. (cond
  17393. ;; Element indented as a single block. Example blocks
  17394. ;; preserving indentation are a special case since the
  17395. ;; "contents" must not be indented whereas the block
  17396. ;; boundaries can.
  17397. ((or (memq type '(export-block latex-environment))
  17398. (and (eq type 'example-block)
  17399. (not
  17400. (or org-src-preserve-indentation
  17401. (org-element-property :preserve-indent element)))))
  17402. (let ((offset (- ind (current-indentation))))
  17403. (unless (zerop offset)
  17404. (indent-rigidly (org-element-property :begin element)
  17405. (org-element-property :end element)
  17406. offset)))
  17407. (goto-char element-end))
  17408. ;; Elements indented line wise. Be sure to exclude
  17409. ;; example blocks (preserving indentation) and source
  17410. ;; blocks from this category as they are treated
  17411. ;; specially later.
  17412. ((or (memq type '(paragraph table table-row))
  17413. (not (or (org-element-property :contents-begin element)
  17414. (memq type '(example-block src-block)))))
  17415. (when (eq type 'node-property)
  17416. (org--align-node-property)
  17417. (beginning-of-line))
  17418. (funcall indent-to ind (min element-end end)))
  17419. ;; Elements consisting of three parts: before the
  17420. ;; contents, the contents, and after the contents. The
  17421. ;; contents are treated specially, according to the
  17422. ;; element type, or not indented at all. Other parts are
  17423. ;; indented as a single block.
  17424. (t
  17425. (let* ((post (copy-marker
  17426. (org-element-property :post-affiliated element)))
  17427. (cbeg
  17428. (copy-marker
  17429. (cond
  17430. ((not (org-element-property :contents-begin element))
  17431. ;; Fake contents for source blocks.
  17432. (org-with-wide-buffer
  17433. (goto-char post)
  17434. (line-beginning-position 2)))
  17435. ((memq type '(footnote-definition item plain-list))
  17436. ;; Contents in these elements could start on
  17437. ;; the same line as the beginning of the
  17438. ;; element. Make sure we start indenting
  17439. ;; from the second line.
  17440. (org-with-wide-buffer
  17441. (goto-char post)
  17442. (end-of-line)
  17443. (skip-chars-forward " \r\t\n")
  17444. (if (eobp) (point) (line-beginning-position))))
  17445. (t (org-element-property :contents-begin element)))))
  17446. (cend (copy-marker
  17447. (or (org-element-property :contents-end element)
  17448. ;; Fake contents for source blocks.
  17449. (org-with-wide-buffer
  17450. (goto-char element-end)
  17451. (skip-chars-backward " \r\t\n")
  17452. (line-beginning-position)))
  17453. t)))
  17454. ;; Do not change items indentation individually as it
  17455. ;; might break the list as a whole. On the other
  17456. ;; hand, when at a plain list, indent it as a whole.
  17457. (cond ((eq type 'plain-list)
  17458. (let ((offset (- ind (current-indentation))))
  17459. (unless (zerop offset)
  17460. (indent-rigidly (org-element-property :begin element)
  17461. (org-element-property :end element)
  17462. offset))
  17463. (goto-char cbeg)))
  17464. ((eq type 'item) (goto-char cbeg))
  17465. (t (funcall indent-to ind (min cbeg end))))
  17466. (when (< (point) end)
  17467. (cl-case type
  17468. ((example-block verse-block))
  17469. (src-block
  17470. ;; In a source block, indent source code
  17471. ;; according to language major mode, but only if
  17472. ;; `org-src-tab-acts-natively' is non-nil.
  17473. (when (and (< (point) end) org-src-tab-acts-natively)
  17474. (ignore-errors
  17475. (org-babel-do-in-edit-buffer
  17476. (indent-region (point-min) (point-max))))))
  17477. (t (org-indent-region (point) (min cend end))))
  17478. (goto-char (min cend end))
  17479. (when (< (point) end)
  17480. (funcall indent-to ind (min element-end end))))
  17481. (set-marker post nil)
  17482. (set-marker cbeg nil)
  17483. (set-marker cend nil))))
  17484. (set-marker element-end nil))))
  17485. (set-marker end nil))))
  17486. (defun org-indent-drawer ()
  17487. "Indent the drawer at point."
  17488. (interactive)
  17489. (unless (save-excursion
  17490. (beginning-of-line)
  17491. (looking-at-p org-drawer-regexp))
  17492. (user-error "Not at a drawer"))
  17493. (let ((element (org-element-at-point)))
  17494. (unless (memq (org-element-type element) '(drawer property-drawer))
  17495. (user-error "Not at a drawer"))
  17496. (org-with-wide-buffer
  17497. (org-indent-region (org-element-property :begin element)
  17498. (org-element-property :end element))))
  17499. (message "Drawer at point indented"))
  17500. (defun org-indent-block ()
  17501. "Indent the block at point."
  17502. (interactive)
  17503. (unless (save-excursion
  17504. (beginning-of-line)
  17505. (let ((case-fold-search t))
  17506. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17507. (user-error "Not at a block"))
  17508. (let ((element (org-element-at-point)))
  17509. (unless (memq (org-element-type element)
  17510. '(comment-block center-block dynamic-block example-block
  17511. export-block quote-block special-block
  17512. src-block verse-block))
  17513. (user-error "Not at a block"))
  17514. (org-with-wide-buffer
  17515. (org-indent-region (org-element-property :begin element)
  17516. (org-element-property :end element))))
  17517. (message "Block at point indented"))
  17518. ;;; Filling
  17519. ;; We use our own fill-paragraph and auto-fill functions.
  17520. ;; `org-fill-paragraph' relies on adaptive filling and context
  17521. ;; checking. Appropriate `fill-prefix' is computed with
  17522. ;; `org-adaptive-fill-function'.
  17523. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17524. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17525. ;; `org-adaptive-fill-function' value. Internally,
  17526. ;; `org-comment-line-break-function' breaks the line.
  17527. ;; `org-setup-filling' installs filling and auto-filling related
  17528. ;; variables during `org-mode' initialization.
  17529. (defun org-setup-filling ()
  17530. (require 'org-element)
  17531. ;; Prevent auto-fill from inserting unwanted new items.
  17532. (when (boundp 'fill-nobreak-predicate)
  17533. (setq-local
  17534. fill-nobreak-predicate
  17535. (org-uniquify
  17536. (append fill-nobreak-predicate
  17537. '(org-fill-line-break-nobreak-p
  17538. org-fill-n-macro-as-item-nobreak-p
  17539. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17540. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17541. (setq-local paragraph-start paragraph-ending)
  17542. (setq-local paragraph-separate paragraph-ending))
  17543. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17544. (setq-local auto-fill-inhibit-regexp nil)
  17545. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17546. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17547. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17548. (defun org-fill-line-break-nobreak-p ()
  17549. "Non-nil when a new line at point would create an Org line break."
  17550. (save-excursion
  17551. (skip-chars-backward " \t")
  17552. (skip-chars-backward "\\\\")
  17553. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17554. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17555. "Non-nil when a new line at point would split a timestamp."
  17556. (and (org-at-timestamp-p 'lax)
  17557. (not (looking-at org-ts-regexp-both))))
  17558. (defun org-fill-n-macro-as-item-nobreak-p ()
  17559. "Non-nil when a new line at point would create a new list."
  17560. ;; During export, a "n" macro followed by a dot or a closing
  17561. ;; parenthesis can end up being parsed as a new list item.
  17562. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17563. (defun org-adaptive-fill-function ()
  17564. "Compute a fill prefix for the current line.
  17565. Return fill prefix, as a string, or nil if current line isn't
  17566. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17567. matches in paragraphs or comments, use it."
  17568. (org-with-wide-buffer
  17569. (unless (org-at-heading-p)
  17570. (let* ((p (line-beginning-position))
  17571. (element (save-excursion
  17572. (beginning-of-line)
  17573. (org-element-at-point)))
  17574. (type (org-element-type element))
  17575. (post-affiliated (org-element-property :post-affiliated element)))
  17576. (unless (< p post-affiliated)
  17577. (cl-case type
  17578. (comment
  17579. (save-excursion
  17580. (beginning-of-line)
  17581. (looking-at "[ \t]*")
  17582. (concat (match-string 0) "# ")))
  17583. (footnote-definition "")
  17584. ((item plain-list)
  17585. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17586. (paragraph
  17587. ;; Fill prefix is usually the same as the current line,
  17588. ;; unless the paragraph is at the beginning of an item.
  17589. (let ((parent (org-element-property :parent element)))
  17590. (save-excursion
  17591. (beginning-of-line)
  17592. (cond ((eq (org-element-type parent) 'item)
  17593. (make-string (org-list-item-body-column
  17594. (org-element-property :begin parent))
  17595. ?\s))
  17596. ((and adaptive-fill-regexp
  17597. ;; Locally disable
  17598. ;; `adaptive-fill-function' to let
  17599. ;; `fill-context-prefix' handle
  17600. ;; `adaptive-fill-regexp' variable.
  17601. (let (adaptive-fill-function)
  17602. (fill-context-prefix
  17603. post-affiliated
  17604. (org-element-property :end element)))))
  17605. ((looking-at "[ \t]+") (match-string 0))
  17606. (t "")))))
  17607. (comment-block
  17608. ;; Only fill contents if P is within block boundaries.
  17609. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17610. (forward-line)
  17611. (point)))
  17612. (cend (save-excursion
  17613. (goto-char (org-element-property :end element))
  17614. (skip-chars-backward " \r\t\n")
  17615. (line-beginning-position))))
  17616. (when (and (>= p cbeg) (< p cend))
  17617. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17618. (match-string 0)
  17619. ""))))))))))
  17620. (defun org-fill-element (&optional justify)
  17621. "Fill element at point, when applicable.
  17622. This function only applies to comment blocks, comments, example
  17623. blocks and paragraphs. Also, as a special case, re-align table
  17624. when point is at one.
  17625. If JUSTIFY is non-nil (interactively, with prefix argument),
  17626. justify as well. If `sentence-end-double-space' is non-nil, then
  17627. period followed by one space does not end a sentence, so don't
  17628. break a line there. The variable `fill-column' controls the
  17629. width for filling.
  17630. For convenience, when point is at a plain list, an item or
  17631. a footnote definition, try to fill the first paragraph within."
  17632. (with-syntax-table org-mode-transpose-word-syntax-table
  17633. ;; Move to end of line in order to get the first paragraph within
  17634. ;; a plain list or a footnote definition.
  17635. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17636. ;; First check if point is in a blank line at the beginning of
  17637. ;; the buffer. In that case, ignore filling.
  17638. (cl-case (org-element-type element)
  17639. ;; Use major mode filling function is source blocks.
  17640. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  17641. ;; Align Org tables, leave table.el tables as-is.
  17642. (table-row (org-table-align) t)
  17643. (table
  17644. (when (eq (org-element-property :type element) 'org)
  17645. (save-excursion
  17646. (goto-char (org-element-property :post-affiliated element))
  17647. (org-table-align)))
  17648. t)
  17649. (paragraph
  17650. ;; Paragraphs may contain `line-break' type objects.
  17651. (let ((beg (max (point-min)
  17652. (org-element-property :contents-begin element)))
  17653. (end (min (point-max)
  17654. (org-element-property :contents-end element))))
  17655. ;; Do nothing if point is at an affiliated keyword.
  17656. (if (< (line-end-position) beg) t
  17657. ;; Fill paragraph, taking line breaks into account.
  17658. (save-excursion
  17659. (goto-char beg)
  17660. (let ((cuts (list beg)))
  17661. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17662. (when (eq 'line-break
  17663. (org-element-type
  17664. (save-excursion (backward-char)
  17665. (org-element-context))))
  17666. (push (point) cuts)))
  17667. (dolist (c (delq end cuts))
  17668. (fill-region-as-paragraph c end justify)
  17669. (setq end c))))
  17670. t)))
  17671. ;; Contents of `comment-block' type elements should be
  17672. ;; filled as plain text, but only if point is within block
  17673. ;; markers.
  17674. (comment-block
  17675. (let* ((case-fold-search t)
  17676. (beg (save-excursion
  17677. (goto-char (org-element-property :begin element))
  17678. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17679. (forward-line)
  17680. (point)))
  17681. (end (save-excursion
  17682. (goto-char (org-element-property :end element))
  17683. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17684. (line-beginning-position))))
  17685. (if (or (< (point) beg) (> (point) end)) t
  17686. (fill-region-as-paragraph
  17687. (save-excursion (end-of-line)
  17688. (re-search-backward "^[ \t]*$" beg 'move)
  17689. (line-beginning-position))
  17690. (save-excursion (beginning-of-line)
  17691. (re-search-forward "^[ \t]*$" end 'move)
  17692. (line-beginning-position))
  17693. justify))))
  17694. ;; Fill comments.
  17695. (comment
  17696. (let ((begin (org-element-property :post-affiliated element))
  17697. (end (org-element-property :end element)))
  17698. (when (and (>= (point) begin) (<= (point) end))
  17699. (let ((begin (save-excursion
  17700. (end-of-line)
  17701. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17702. (progn (forward-line) (point))
  17703. begin)))
  17704. (end (save-excursion
  17705. (end-of-line)
  17706. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17707. (1- (line-beginning-position))
  17708. (skip-chars-backward " \r\t\n")
  17709. (line-end-position)))))
  17710. ;; Do not fill comments when at a blank line.
  17711. (when (> end begin)
  17712. (let ((fill-prefix
  17713. (save-excursion
  17714. (beginning-of-line)
  17715. (looking-at "[ \t]*#")
  17716. (let ((comment-prefix (match-string 0)))
  17717. (goto-char (match-end 0))
  17718. (if (looking-at adaptive-fill-regexp)
  17719. (concat comment-prefix (match-string 0))
  17720. (concat comment-prefix " "))))))
  17721. (save-excursion
  17722. (fill-region-as-paragraph begin end justify))))))
  17723. t))
  17724. ;; Ignore every other element.
  17725. (otherwise t)))))
  17726. (defun org-fill-paragraph (&optional justify region)
  17727. "Fill element at point, when applicable.
  17728. This function only applies to comment blocks, comments, example
  17729. blocks and paragraphs. Also, as a special case, re-align table
  17730. when point is at one.
  17731. For convenience, when point is at a plain list, an item or
  17732. a footnote definition, try to fill the first paragraph within.
  17733. If JUSTIFY is non-nil (interactively, with prefix argument),
  17734. justify as well. If `sentence-end-double-space' is non-nil, then
  17735. period followed by one space does not end a sentence, so don't
  17736. break a line there. The variable `fill-column' controls the
  17737. width for filling.
  17738. The REGION argument is non-nil if called interactively; in that
  17739. case, if Transient Mark mode is enabled and the mark is active,
  17740. fill each of the elements in the active region, instead of just
  17741. filling the current element."
  17742. (interactive (progn
  17743. (barf-if-buffer-read-only)
  17744. (list (when current-prefix-arg 'full) t)))
  17745. (let ((hash (and (not (buffer-modified-p))
  17746. (org-buffer-hash))))
  17747. (cond
  17748. ((and region transient-mark-mode mark-active
  17749. (not (eq (region-beginning) (region-end))))
  17750. (let ((origin (point-marker))
  17751. (start (region-beginning)))
  17752. (unwind-protect
  17753. (progn
  17754. (goto-char (region-end))
  17755. (skip-chars-backward " \t\n")
  17756. (while (> (point) start)
  17757. (org-fill-element justify)
  17758. (org-backward-paragraph)))
  17759. (goto-char origin)
  17760. (set-marker origin nil))))
  17761. (t
  17762. (save-excursion
  17763. (when (org-match-line "[ \t]*$")
  17764. (skip-chars-forward " \t\n"))
  17765. (org-fill-element justify))))
  17766. ;; If we didn't change anything in the buffer (and the buffer was
  17767. ;; previously unmodified), then flip the modification status back
  17768. ;; to "unchanged".
  17769. (when (and hash (equal hash (org-buffer-hash)))
  17770. (set-buffer-modified-p nil))))
  17771. (defun org-auto-fill-function ()
  17772. "Auto-fill function."
  17773. ;; Check if auto-filling is meaningful.
  17774. (let ((fc (current-fill-column)))
  17775. (when (and fc (> (current-column) fc))
  17776. (let* ((fill-prefix (org-adaptive-fill-function))
  17777. ;; Enforce empty fill prefix, if required. Otherwise, it
  17778. ;; will be computed again.
  17779. (adaptive-fill-mode (not (equal fill-prefix ""))))
  17780. (when fill-prefix (do-auto-fill))))))
  17781. (defun org-comment-line-break-function (&optional soft)
  17782. "Break line at point and indent, continuing comment if within one.
  17783. The inserted newline is marked hard if variable
  17784. `use-hard-newlines' is true, unless optional argument SOFT is
  17785. non-nil."
  17786. (if soft (insert-and-inherit ?\n) (newline 1))
  17787. (save-excursion (forward-char -1) (delete-horizontal-space))
  17788. (delete-horizontal-space)
  17789. (indent-to-left-margin)
  17790. (insert-before-markers-and-inherit fill-prefix))
  17791. ;;; Fixed Width Areas
  17792. (defun org-toggle-fixed-width ()
  17793. "Toggle fixed-width markup.
  17794. Add or remove fixed-width markup on current line, whenever it
  17795. makes sense. Return an error otherwise.
  17796. If a region is active and if it contains only fixed-width areas
  17797. or blank lines, remove all fixed-width markup in it. If the
  17798. region contains anything else, convert all non-fixed-width lines
  17799. to fixed-width ones.
  17800. Blank lines at the end of the region are ignored unless the
  17801. region only contains such lines."
  17802. (interactive)
  17803. (if (not (org-region-active-p))
  17804. ;; No region:
  17805. ;;
  17806. ;; Remove fixed width marker only in a fixed-with element.
  17807. ;;
  17808. ;; Add fixed width maker in paragraphs, in blank lines after
  17809. ;; elements or at the beginning of a headline or an inlinetask,
  17810. ;; and before any one-line elements (e.g., a clock).
  17811. (progn
  17812. (beginning-of-line)
  17813. (let* ((element (org-element-at-point))
  17814. (type (org-element-type element)))
  17815. (cond
  17816. ((and (eq type 'fixed-width)
  17817. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  17818. (replace-match
  17819. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  17820. ((and (memq type '(babel-call clock comment diary-sexp headline
  17821. horizontal-rule keyword paragraph
  17822. planning))
  17823. (<= (org-element-property :post-affiliated element) (point)))
  17824. (skip-chars-forward " \t")
  17825. (insert ": "))
  17826. ((and (looking-at-p "[ \t]*$")
  17827. (or (eq type 'inlinetask)
  17828. (save-excursion
  17829. (skip-chars-forward " \r\t\n")
  17830. (<= (org-element-property :end element) (point)))))
  17831. (delete-region (point) (line-end-position))
  17832. (org-indent-line)
  17833. (insert ": "))
  17834. (t (user-error "Cannot insert a fixed-width line here")))))
  17835. ;; Region active.
  17836. (let* ((begin (save-excursion
  17837. (goto-char (region-beginning))
  17838. (line-beginning-position)))
  17839. (end (copy-marker
  17840. (save-excursion
  17841. (goto-char (region-end))
  17842. (unless (eolp) (beginning-of-line))
  17843. (if (save-excursion (re-search-backward "\\S-" begin t))
  17844. (progn (skip-chars-backward " \r\t\n") (point))
  17845. (point)))))
  17846. (all-fixed-width-p
  17847. (catch 'not-all-p
  17848. (save-excursion
  17849. (goto-char begin)
  17850. (skip-chars-forward " \r\t\n")
  17851. (when (eobp) (throw 'not-all-p nil))
  17852. (while (< (point) end)
  17853. (let ((element (org-element-at-point)))
  17854. (if (eq (org-element-type element) 'fixed-width)
  17855. (goto-char (org-element-property :end element))
  17856. (throw 'not-all-p nil))))
  17857. t))))
  17858. (if all-fixed-width-p
  17859. (save-excursion
  17860. (goto-char begin)
  17861. (while (< (point) end)
  17862. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  17863. (replace-match
  17864. "" nil nil nil
  17865. (if (= (line-end-position) (match-end 0)) 0 1)))
  17866. (forward-line)))
  17867. (let ((min-ind (point-max)))
  17868. ;; Find minimum indentation across all lines.
  17869. (save-excursion
  17870. (goto-char begin)
  17871. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  17872. (setq min-ind 0)
  17873. (catch 'zerop
  17874. (while (< (point) end)
  17875. (unless (looking-at-p "[ \t]*$")
  17876. (let ((ind (current-indentation)))
  17877. (setq min-ind (min min-ind ind))
  17878. (when (zerop ind) (throw 'zerop t))))
  17879. (forward-line)))))
  17880. ;; Loop over all lines and add fixed-width markup everywhere
  17881. ;; but in fixed-width lines.
  17882. (save-excursion
  17883. (goto-char begin)
  17884. (while (< (point) end)
  17885. (cond
  17886. ((org-at-heading-p)
  17887. (insert ": ")
  17888. (forward-line)
  17889. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  17890. (insert ":")
  17891. (forward-line)))
  17892. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  17893. (let* ((element (org-element-at-point))
  17894. (element-end (org-element-property :end element)))
  17895. (if (eq (org-element-type element) 'fixed-width)
  17896. (progn (goto-char element-end)
  17897. (skip-chars-backward " \r\t\n")
  17898. (forward-line))
  17899. (let ((limit (min end element-end)))
  17900. (while (< (point) limit)
  17901. (org-move-to-column min-ind t)
  17902. (insert ": ")
  17903. (forward-line))))))
  17904. (t
  17905. (org-move-to-column min-ind t)
  17906. (insert ": ")
  17907. (forward-line)))))))
  17908. (set-marker end nil))))
  17909. ;;; Blocks
  17910. (defun org-block-map (function &optional start end)
  17911. "Call FUNCTION at the head of all source blocks in the current buffer.
  17912. Optional arguments START and END can be used to limit the range."
  17913. (let ((start (or start (point-min)))
  17914. (end (or end (point-max))))
  17915. (save-excursion
  17916. (goto-char start)
  17917. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  17918. (save-excursion
  17919. (save-match-data
  17920. (goto-char (match-beginning 0))
  17921. (funcall function)))))))
  17922. (defun org-next-block (arg &optional backward block-regexp)
  17923. "Jump to the next block.
  17924. With a prefix argument ARG, jump forward ARG many blocks.
  17925. When BACKWARD is non-nil, jump to the previous block.
  17926. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  17927. Match data is set according to this regexp when the function
  17928. returns.
  17929. Return point at beginning of the opening line of found block.
  17930. Throw an error if no block is found."
  17931. (interactive "p")
  17932. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  17933. (case-fold-search t)
  17934. (search-fn (if backward #'re-search-backward #'re-search-forward))
  17935. (count (or arg 1))
  17936. (origin (point))
  17937. last-element)
  17938. (if backward (beginning-of-line) (end-of-line))
  17939. (while (and (> count 0) (funcall search-fn re nil t))
  17940. (let ((element (save-excursion
  17941. (goto-char (match-beginning 0))
  17942. (save-match-data (org-element-at-point)))))
  17943. (when (and (memq (org-element-type element)
  17944. '(center-block comment-block dynamic-block
  17945. example-block export-block quote-block
  17946. special-block src-block verse-block))
  17947. (<= (match-beginning 0)
  17948. (org-element-property :post-affiliated element)))
  17949. (setq last-element element)
  17950. (cl-decf count))))
  17951. (if (= count 0)
  17952. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  17953. (save-match-data (org-show-context)))
  17954. (goto-char origin)
  17955. (user-error "No %s code blocks" (if backward "previous" "further")))))
  17956. (defun org-previous-block (arg &optional block-regexp)
  17957. "Jump to the previous block.
  17958. With a prefix argument ARG, jump backward ARG many source blocks.
  17959. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  17960. (interactive "p")
  17961. (org-next-block arg t block-regexp))
  17962. ;;; Comments
  17963. ;; Org comments syntax is quite complex. It requires the entire line
  17964. ;; to be just a comment. Also, even with the right syntax at the
  17965. ;; beginning of line, some elements (e.g., verse-block or
  17966. ;; example-block) don't accept comments. Usual Emacs comment commands
  17967. ;; cannot cope with those requirements. Therefore, Org replaces them.
  17968. ;; Org still relies on `comment-dwim', but cannot trust
  17969. ;; `comment-only-p'. So, `comment-region-function' and
  17970. ;; `uncomment-region-function' both point
  17971. ;; to`org-comment-or-uncomment-region'. Eventually,
  17972. ;; `org-insert-comment' takes care of insertion of comments at the
  17973. ;; beginning of line.
  17974. ;; `org-setup-comments-handling' install comments related variables
  17975. ;; during `org-mode' initialization.
  17976. (defun org-setup-comments-handling ()
  17977. (interactive)
  17978. (setq-local comment-use-syntax nil)
  17979. (setq-local comment-start "# ")
  17980. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  17981. (setq-local comment-insert-comment-function 'org-insert-comment)
  17982. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  17983. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  17984. (defun org-insert-comment ()
  17985. "Insert an empty comment above current line.
  17986. If the line is empty, insert comment at its beginning. When
  17987. point is within a source block, comment according to the related
  17988. major mode."
  17989. (if (let ((element (org-element-at-point)))
  17990. (and (eq (org-element-type element) 'src-block)
  17991. (< (save-excursion
  17992. (goto-char (org-element-property :post-affiliated element))
  17993. (line-end-position))
  17994. (point))
  17995. (> (save-excursion
  17996. (goto-char (org-element-property :end element))
  17997. (skip-chars-backward " \r\t\n")
  17998. (line-beginning-position))
  17999. (point))))
  18000. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  18001. (beginning-of-line)
  18002. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  18003. (open-line 1))
  18004. (org-indent-line)
  18005. (insert "# ")))
  18006. (defvar comment-empty-lines) ; From newcomment.el.
  18007. (defun org-comment-or-uncomment-region (beg end &rest _)
  18008. "Comment or uncomment each non-blank line in the region.
  18009. Uncomment each non-blank line between BEG and END if it only
  18010. contains commented lines. Otherwise, comment them. If region is
  18011. strictly within a source block, use appropriate comment syntax."
  18012. (if (let ((element (org-element-at-point)))
  18013. (and (eq (org-element-type element) 'src-block)
  18014. (< (save-excursion
  18015. (goto-char (org-element-property :post-affiliated element))
  18016. (line-end-position))
  18017. beg)
  18018. (>= (save-excursion
  18019. (goto-char (org-element-property :end element))
  18020. (skip-chars-backward " \r\t\n")
  18021. (line-beginning-position))
  18022. end)))
  18023. ;; Translate region boundaries for the Org buffer to the source
  18024. ;; buffer.
  18025. (let ((offset (- end beg)))
  18026. (save-excursion
  18027. (goto-char beg)
  18028. (org-babel-do-in-edit-buffer
  18029. (comment-or-uncomment-region (point) (+ offset (point))))))
  18030. (save-restriction
  18031. ;; Restrict region
  18032. (narrow-to-region (save-excursion (goto-char beg)
  18033. (skip-chars-forward " \r\t\n" end)
  18034. (line-beginning-position))
  18035. (save-excursion (goto-char end)
  18036. (skip-chars-backward " \r\t\n" beg)
  18037. (line-end-position)))
  18038. (let ((uncommentp
  18039. ;; UNCOMMENTP is non-nil when every non blank line between
  18040. ;; BEG and END is a comment.
  18041. (save-excursion
  18042. (goto-char (point-min))
  18043. (while (and (not (eobp))
  18044. (let ((element (org-element-at-point)))
  18045. (and (eq (org-element-type element) 'comment)
  18046. (goto-char (min (point-max)
  18047. (org-element-property
  18048. :end element)))))))
  18049. (eobp))))
  18050. (if uncommentp
  18051. ;; Only blank lines and comments in region: uncomment it.
  18052. (save-excursion
  18053. (goto-char (point-min))
  18054. (while (not (eobp))
  18055. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  18056. (replace-match "" nil nil nil 1))
  18057. (forward-line)))
  18058. ;; Comment each line in region.
  18059. (let ((min-indent (point-max)))
  18060. ;; First find the minimum indentation across all lines.
  18061. (save-excursion
  18062. (goto-char (point-min))
  18063. (while (and (not (eobp)) (not (zerop min-indent)))
  18064. (unless (looking-at "[ \t]*$")
  18065. (setq min-indent (min min-indent (current-indentation))))
  18066. (forward-line)))
  18067. ;; Then loop over all lines.
  18068. (save-excursion
  18069. (goto-char (point-min))
  18070. (while (not (eobp))
  18071. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  18072. ;; Don't get fooled by invisible text (e.g. link path)
  18073. ;; when moving to column MIN-INDENT.
  18074. (let ((buffer-invisibility-spec nil))
  18075. (org-move-to-column min-indent t))
  18076. (insert comment-start))
  18077. (forward-line)))))))))
  18078. (defun org-comment-dwim (_arg)
  18079. "Call the comment command you mean.
  18080. Call `org-toggle-comment' if on a heading, otherwise call
  18081. `comment-dwim', within a source edit buffer if needed."
  18082. (interactive "*P")
  18083. (cond ((org-at-heading-p)
  18084. (call-interactively #'org-toggle-comment))
  18085. ((org-in-src-block-p)
  18086. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  18087. (t (call-interactively #'comment-dwim))))
  18088. ;;; Timestamps API
  18089. ;; This section contains tools to operate on, or create, timestamp
  18090. ;; objects, as returned by, e.g. `org-element-context'.
  18091. (defun org-timestamp-from-string (s)
  18092. "Convert Org timestamp S, as a string, into a timestamp object.
  18093. Return nil if S is not a valid timestamp string."
  18094. (when (org-string-nw-p s)
  18095. (with-temp-buffer
  18096. (save-excursion (insert s))
  18097. (org-element-timestamp-parser))))
  18098. (defun org-timestamp-from-time (time &optional with-time inactive)
  18099. "Convert a time value into a timestamp object.
  18100. TIME is an Emacs internal time representation, as returned, e.g.,
  18101. by `current-time'.
  18102. When optional argument WITH-TIME is non-nil, return a timestamp
  18103. object with a time part, i.e., with hours and minutes.
  18104. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  18105. return an active timestamp."
  18106. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  18107. (org-element-create 'timestamp
  18108. (list :type (if inactive 'inactive 'active)
  18109. :year-start year
  18110. :month-start month
  18111. :day-start day
  18112. :hour-start (and with-time hour)
  18113. :minute-start (and with-time minute)))))
  18114. (defun org-timestamp-to-time (timestamp &optional end)
  18115. "Convert TIMESTAMP object into an Emacs internal time value.
  18116. Use end of date range or time range when END is non-nil.
  18117. Otherwise, use its start."
  18118. (apply #'encode-time 0
  18119. (mapcar
  18120. (lambda (prop) (or (org-element-property prop timestamp) 0))
  18121. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  18122. '(:minute-start :hour-start :day-start :month-start
  18123. :year-start)))))
  18124. (defun org-timestamp-has-time-p (timestamp)
  18125. "Non-nil when TIMESTAMP has a time specified."
  18126. (org-element-property :hour-start timestamp))
  18127. (defun org-timestamp-format (timestamp format &optional end utc)
  18128. "Format a TIMESTAMP object into a string.
  18129. FORMAT is a format specifier to be passed to
  18130. `format-time-string'.
  18131. When optional argument END is non-nil, use end of date-range or
  18132. time-range, if possible.
  18133. When optional argument UTC is non-nil, time is be expressed as
  18134. Universal Time."
  18135. (format-time-string format (org-timestamp-to-time timestamp end)
  18136. (and utc t)))
  18137. (defun org-timestamp-split-range (timestamp &optional end)
  18138. "Extract a TIMESTAMP object from a date or time range.
  18139. END, when non-nil, means extract the end of the range.
  18140. Otherwise, extract its start.
  18141. Return a new timestamp object."
  18142. (let ((type (org-element-property :type timestamp)))
  18143. (if (memq type '(active inactive diary)) timestamp
  18144. (let ((split-ts (org-element-copy timestamp)))
  18145. ;; Set new type.
  18146. (org-element-put-property
  18147. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  18148. ;; Copy start properties over end properties if END is
  18149. ;; non-nil. Otherwise, copy end properties over `start' ones.
  18150. (let ((p-alist '((:minute-start . :minute-end)
  18151. (:hour-start . :hour-end)
  18152. (:day-start . :day-end)
  18153. (:month-start . :month-end)
  18154. (:year-start . :year-end))))
  18155. (dolist (p-cell p-alist)
  18156. (org-element-put-property
  18157. split-ts
  18158. (funcall (if end #'car #'cdr) p-cell)
  18159. (org-element-property
  18160. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  18161. ;; Eventually refresh `:raw-value'.
  18162. (org-element-put-property split-ts :raw-value nil)
  18163. (org-element-put-property
  18164. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  18165. (defun org-timestamp-translate (timestamp &optional boundary)
  18166. "Translate TIMESTAMP object to custom format.
  18167. Format string is defined in `org-time-stamp-custom-formats',
  18168. which see.
  18169. When optional argument BOUNDARY is non-nil, it is either the
  18170. symbol `start' or `end'. In this case, only translate the
  18171. starting or ending part of TIMESTAMP if it is a date or time
  18172. range. Otherwise, translate both parts.
  18173. Return timestamp as-is if `org-display-custom-times' is nil or if
  18174. it has a `diary' type."
  18175. (let ((type (org-element-property :type timestamp)))
  18176. (if (or (not org-display-custom-times) (eq type 'diary))
  18177. (org-element-interpret-data timestamp)
  18178. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  18179. org-time-stamp-custom-formats)))
  18180. (if (and (not boundary) (memq type '(active-range inactive-range)))
  18181. (concat (org-timestamp-format timestamp fmt)
  18182. "--"
  18183. (org-timestamp-format timestamp fmt t))
  18184. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  18185. ;;; Other stuff
  18186. (defvar reftex-docstruct-symbol)
  18187. (defvar org--rds)
  18188. (defun org-reftex-citation ()
  18189. "Use reftex-citation to insert a citation into the buffer.
  18190. This looks for a line like
  18191. #+BIBLIOGRAPHY: foo plain option:-d
  18192. and derives from it that foo.bib is the bibliography file relevant
  18193. for this document. It then installs the necessary environment for RefTeX
  18194. to work in this buffer and calls `reftex-citation' to insert a citation
  18195. into the buffer.
  18196. Export of such citations to both LaTeX and HTML is handled by the contributed
  18197. package ox-bibtex by Taru Karttunen."
  18198. (interactive)
  18199. (let ((reftex-docstruct-symbol 'org--rds)
  18200. org--rds bib)
  18201. (org-with-wide-buffer
  18202. (let ((case-fold-search t)
  18203. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  18204. (if (not (save-excursion
  18205. (or (re-search-forward re nil t)
  18206. (re-search-backward re nil t))))
  18207. (user-error "No bibliography defined in file")
  18208. (setq bib (concat (match-string 1) ".bib")
  18209. org--rds (list (list 'bib bib))))))
  18210. (call-interactively 'reftex-citation)))
  18211. ;;;; Functions extending outline functionality
  18212. (defun org-beginning-of-line (&optional n)
  18213. "Go to the beginning of the current visible line.
  18214. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18215. symbol `reversed', on the first attempt move to where the
  18216. headline text starts, and only move to beginning of line when the
  18217. cursor is already before the start of the text of the headline.
  18218. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  18219. start of the text on the second attempt.
  18220. With argument N not nil or 1, move forward N - 1 lines first."
  18221. (interactive "^p")
  18222. (let ((origin (point))
  18223. (special (pcase org-special-ctrl-a/e
  18224. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  18225. deactivate-mark)
  18226. ;; First move to a visible line.
  18227. (if (bound-and-true-p visual-line-mode)
  18228. (beginning-of-visual-line n)
  18229. (move-beginning-of-line n)
  18230. ;; `move-beginning-of-line' may leave point after invisible
  18231. ;; characters if line starts with such of these (e.g., with
  18232. ;; a link at column 0). Really move to the beginning of the
  18233. ;; current visible line.
  18234. (beginning-of-line))
  18235. (cond
  18236. ;; No special behavior. Point is already at the beginning of
  18237. ;; a line, logical or visual.
  18238. ((not special))
  18239. ;; `beginning-of-visual-line' left point before logical beginning
  18240. ;; of line: point is at the beginning of a visual line. Bail
  18241. ;; out.
  18242. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  18243. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  18244. ;; At a headline, special position is before the title, but
  18245. ;; after any TODO keyword or priority cookie.
  18246. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  18247. (line-end-position)))
  18248. (bol (point)))
  18249. (if (eq special 'reversed)
  18250. (when (and (= origin bol) (eq last-command this-command))
  18251. (goto-char refpos))
  18252. (when (or (> origin refpos) (= origin bol))
  18253. (goto-char refpos)))))
  18254. ((and (looking-at org-list-full-item-re)
  18255. (memq (org-element-type (save-match-data (org-element-at-point)))
  18256. '(item plain-list)))
  18257. ;; Set special position at first white space character after
  18258. ;; bullet, and check-box, if any.
  18259. (let ((after-bullet
  18260. (let ((box (match-end 3)))
  18261. (cond ((not box) (match-end 1))
  18262. ((eq (char-after box) ?\s) (1+ box))
  18263. (t box)))))
  18264. (if (eq special 'reversed)
  18265. (when (and (= (point) origin) (eq last-command this-command))
  18266. (goto-char after-bullet))
  18267. (when (or (> origin after-bullet) (= (point) origin))
  18268. (goto-char after-bullet)))))
  18269. ;; No special context. Point is already at beginning of line.
  18270. (t nil))))
  18271. (defun org-end-of-line (&optional n)
  18272. "Go to the end of the line, but before ellipsis, if any.
  18273. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18274. symbol `reversed', ignore tags on the first attempt, and only
  18275. move to after the tags when the cursor is already beyond the end
  18276. of the headline.
  18277. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  18278. on the second attempt.
  18279. With argument N not nil or 1, move forward N - 1 lines first."
  18280. (interactive "^p")
  18281. (let ((origin (point))
  18282. (special (pcase org-special-ctrl-a/e
  18283. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  18284. deactivate-mark)
  18285. ;; First move to a visible line.
  18286. (if (bound-and-true-p visual-line-mode)
  18287. (beginning-of-visual-line n)
  18288. (move-beginning-of-line n))
  18289. (cond
  18290. ;; At a headline, with tags.
  18291. ((and special
  18292. (save-excursion
  18293. (beginning-of-line)
  18294. (let ((case-fold-search nil))
  18295. (looking-at org-complex-heading-regexp)))
  18296. (match-end 5))
  18297. (let ((tags (save-excursion
  18298. (goto-char (match-beginning 5))
  18299. (skip-chars-backward " \t")
  18300. (point)))
  18301. (visual-end (and (bound-and-true-p visual-line-mode)
  18302. (save-excursion
  18303. (end-of-visual-line)
  18304. (point)))))
  18305. ;; If `end-of-visual-line' brings us before end of line or
  18306. ;; even tags, i.e., the headline spans over multiple visual
  18307. ;; lines, move there.
  18308. (cond ((and visual-end
  18309. (< visual-end tags)
  18310. (<= origin visual-end))
  18311. (goto-char visual-end))
  18312. ((eq special 'reversed)
  18313. (if (and (= origin (line-end-position))
  18314. (eq this-command last-command))
  18315. (goto-char tags)
  18316. (end-of-line)))
  18317. (t
  18318. (if (or (< origin tags) (= origin (line-end-position)))
  18319. (goto-char tags)
  18320. (end-of-line))))))
  18321. ((bound-and-true-p visual-line-mode)
  18322. (let ((bol (line-beginning-position)))
  18323. (end-of-visual-line)
  18324. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18325. ;; end of a line, backtrack and use `end-of-line' instead.
  18326. (when (/= bol (line-beginning-position))
  18327. (goto-char bol)
  18328. (end-of-line))))
  18329. (t (end-of-line)))))
  18330. (defun org-backward-sentence (&optional _arg)
  18331. "Go to beginning of sentence, or beginning of table field.
  18332. This will call `backward-sentence' or `org-table-beginning-of-field',
  18333. depending on context."
  18334. (interactive)
  18335. (let* ((element (org-element-at-point))
  18336. (contents-begin (org-element-property :contents-begin element))
  18337. (table (org-element-lineage element '(table) t)))
  18338. (if (and table
  18339. (> (point) contents-begin)
  18340. (<= (point) (org-element-property :contents-end table)))
  18341. (call-interactively #'org-table-beginning-of-field)
  18342. (save-restriction
  18343. (when (and contents-begin
  18344. (< (point-min) contents-begin)
  18345. (> (point) contents-begin))
  18346. (narrow-to-region contents-begin
  18347. (org-element-property :contents-end element)))
  18348. (call-interactively #'backward-sentence)))))
  18349. (defun org-forward-sentence (&optional _arg)
  18350. "Go to end of sentence, or end of table field.
  18351. This will call `forward-sentence' or `org-table-end-of-field',
  18352. depending on context."
  18353. (interactive)
  18354. (if (and (org-at-heading-p)
  18355. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18356. (save-restriction
  18357. (narrow-to-region (line-beginning-position) (line-end-position))
  18358. (call-interactively #'forward-sentence))
  18359. (let* ((element (org-element-at-point))
  18360. (contents-end (org-element-property :contents-end element))
  18361. (table (org-element-lineage element '(table) t)))
  18362. (if (and table
  18363. (>= (point) (org-element-property :contents-begin table))
  18364. (< (point) contents-end))
  18365. (call-interactively #'org-table-end-of-field)
  18366. (save-restriction
  18367. (when (and contents-end
  18368. (> (point-max) contents-end)
  18369. ;; Skip blank lines between elements.
  18370. (< (org-element-property :end element)
  18371. (save-excursion (goto-char contents-end)
  18372. (skip-chars-forward " \r\t\n"))))
  18373. (narrow-to-region (org-element-property :contents-begin element)
  18374. contents-end))
  18375. ;; End of heading is considered as the end of a sentence.
  18376. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18377. (call-interactively #'forward-sentence)))))))
  18378. (defun org-kill-line (&optional _arg)
  18379. "Kill line, to tags or end of line."
  18380. (interactive)
  18381. (cond
  18382. ((or (not org-special-ctrl-k)
  18383. (bolp)
  18384. (not (org-at-heading-p)))
  18385. (when (and (get-char-property (line-end-position) 'invisible)
  18386. org-ctrl-k-protect-subtree
  18387. (or (eq org-ctrl-k-protect-subtree 'error)
  18388. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18389. (user-error
  18390. (substitute-command-keys
  18391. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18392. (call-interactively
  18393. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18394. ((org-match-line org-tag-line-re)
  18395. (let ((end (save-excursion
  18396. (goto-char (match-beginning 1))
  18397. (skip-chars-backward " \t")
  18398. (point))))
  18399. (if (<= end (point)) ;on tags part
  18400. (kill-region (point) (line-end-position))
  18401. (kill-region (point) end)))
  18402. ;; Only align tags when we are still on a heading:
  18403. (if (org-at-heading-p) (org-align-tags)))
  18404. (t (kill-region (point) (line-end-position)))))
  18405. (defun org-yank (&optional arg)
  18406. "Yank. If the kill is a subtree, treat it specially.
  18407. This command will look at the current kill and check if is a single
  18408. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18409. cursor is at the beginning of a line or after the stars of a currently
  18410. empty headline, then the yank is handled specially. How exactly depends
  18411. on the value of the following variables.
  18412. `org-yank-folded-subtrees'
  18413. By default, this variable is non-nil, which results in
  18414. subtree(s) being folded after insertion, except if doing so
  18415. would swallow text after the yanked text.
  18416. `org-yank-adjusted-subtrees'
  18417. When non-nil (the default value is nil), the subtree will be
  18418. promoted or demoted in order to fit into the local outline tree
  18419. structure, which means that the level will be adjusted so that it
  18420. becomes the smaller one of the two *visible* surrounding headings.
  18421. Any prefix to this command will cause `yank' to be called directly with
  18422. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18423. will just
  18424. plainly yank the text as it is.
  18425. \[1] The test checks if the first non-white line is a heading
  18426. and if there are no other headings with fewer stars."
  18427. (interactive "P")
  18428. (org-yank-generic 'yank arg))
  18429. (defun org-yank-generic (command arg)
  18430. "Perform some yank-like command.
  18431. This function implements the behavior described in the `org-yank'
  18432. documentation. However, it has been generalized to work for any
  18433. interactive command with similar behavior."
  18434. ;; pretend to be command COMMAND
  18435. (setq this-command command)
  18436. (if arg
  18437. (call-interactively command)
  18438. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18439. (and (org-kill-is-subtree-p)
  18440. (or (bolp)
  18441. (and (looking-at "[ \t]*$")
  18442. (string-match
  18443. "\\`\\*+\\'"
  18444. (buffer-substring (point-at-bol) (point)))))))
  18445. swallowp)
  18446. (cond
  18447. ((and subtreep org-yank-folded-subtrees)
  18448. (let ((beg (point))
  18449. end)
  18450. (if (and subtreep org-yank-adjusted-subtrees)
  18451. (org-paste-subtree nil nil 'for-yank)
  18452. (call-interactively command))
  18453. (setq end (point))
  18454. (goto-char beg)
  18455. (when (and (bolp) subtreep
  18456. (not (setq swallowp
  18457. (org-yank-folding-would-swallow-text beg end))))
  18458. (org-with-limited-levels
  18459. (or (looking-at org-outline-regexp)
  18460. (re-search-forward org-outline-regexp-bol end t))
  18461. (while (and (< (point) end) (looking-at org-outline-regexp))
  18462. (org-flag-subtree t)
  18463. (org-cycle-show-empty-lines 'folded)
  18464. (condition-case nil
  18465. (outline-forward-same-level 1)
  18466. (error (goto-char end))))))
  18467. (when swallowp
  18468. (message
  18469. "Inserted text not folded because that would swallow text"))
  18470. (goto-char end)
  18471. (skip-chars-forward " \t\n\r")
  18472. (beginning-of-line 1)
  18473. (push-mark beg 'nomsg)))
  18474. ((and subtreep org-yank-adjusted-subtrees)
  18475. (let ((beg (point-at-bol)))
  18476. (org-paste-subtree nil nil 'for-yank)
  18477. (push-mark beg 'nomsg)))
  18478. (t
  18479. (call-interactively command))))))
  18480. (defun org-yank-folding-would-swallow-text (beg end)
  18481. "Would hide-subtree at BEG swallow any text after END?"
  18482. (let (level)
  18483. (org-with-limited-levels
  18484. (save-excursion
  18485. (goto-char beg)
  18486. (when (or (looking-at org-outline-regexp)
  18487. (re-search-forward org-outline-regexp-bol end t))
  18488. (setq level (org-outline-level)))
  18489. (goto-char end)
  18490. (skip-chars-forward " \t\r\n\v\f")
  18491. (not (or (eobp)
  18492. (and (bolp) (looking-at-p org-outline-regexp)
  18493. (<= (org-outline-level) level))))))))
  18494. (defun org-back-to-heading (&optional invisible-ok)
  18495. "Call `outline-back-to-heading', but provide a better error message."
  18496. (condition-case nil
  18497. (outline-back-to-heading invisible-ok)
  18498. (error
  18499. (user-error "Before first headline at position %d in buffer %s"
  18500. (point) (current-buffer)))))
  18501. (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  18502. "Go back to heading or first point in buffer.
  18503. If point is before first heading go to first point in buffer
  18504. instead of back to heading."
  18505. (condition-case nil
  18506. (outline-back-to-heading invisible-ok)
  18507. (error
  18508. (goto-char (point-min)))))
  18509. (defun org-before-first-heading-p ()
  18510. "Before first heading?"
  18511. (org-with-limited-levels
  18512. (save-excursion
  18513. (end-of-line)
  18514. (null (re-search-backward org-outline-regexp-bol nil t)))))
  18515. (defun org-at-heading-p (&optional _)
  18516. "Non-nil when on a headline."
  18517. (outline-on-heading-p t))
  18518. (defun org-in-commented-heading-p (&optional no-inheritance)
  18519. "Non-nil if point is under a commented heading.
  18520. This function also checks ancestors of the current headline,
  18521. unless optional argument NO-INHERITANCE is non-nil."
  18522. (cond
  18523. ((org-before-first-heading-p) nil)
  18524. ((let ((headline (nth 4 (org-heading-components))))
  18525. (and headline
  18526. (let ((case-fold-search nil))
  18527. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  18528. headline)))))
  18529. (no-inheritance nil)
  18530. (t
  18531. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  18532. (defun org-in-archived-heading-p (&optional no-inheritance)
  18533. "Non-nil if point is under an archived heading.
  18534. This function also checks ancestors of the current headline,
  18535. unless optional argument NO-INHERITANCE is non-nil."
  18536. (cond
  18537. ((org-before-first-heading-p) nil)
  18538. ((let ((tags (nth 5 (org-heading-components))))
  18539. (and tags
  18540. (let ((case-fold-search nil))
  18541. (string-match-p org-archive-tag tags)))))
  18542. (no-inheritance nil)
  18543. (t
  18544. (save-excursion (and (org-up-heading-safe) (org-in-archived-heading-p))))))
  18545. (defun org-at-comment-p nil
  18546. "Return t if cursor is in a commented line."
  18547. (save-excursion
  18548. (save-match-data
  18549. (beginning-of-line)
  18550. (looking-at org-comment-regexp))))
  18551. (defun org-at-keyword-p nil
  18552. "Return t if cursor is at a keyword-line."
  18553. (save-excursion
  18554. (move-beginning-of-line 1)
  18555. (looking-at org-keyword-regexp)))
  18556. (defun org-at-drawer-p nil
  18557. "Return t if cursor is at a drawer keyword."
  18558. (save-excursion
  18559. (move-beginning-of-line 1)
  18560. (looking-at org-drawer-regexp)))
  18561. (defun org-at-block-p nil
  18562. "Return t if cursor is at a block keyword."
  18563. (save-excursion
  18564. (move-beginning-of-line 1)
  18565. (looking-at org-block-regexp)))
  18566. (defun org-point-at-end-of-empty-headline ()
  18567. "If point is at the end of an empty headline, return t, else nil.
  18568. If the heading only contains a TODO keyword, it is still still considered
  18569. empty."
  18570. (let ((case-fold-search nil))
  18571. (and (looking-at "[ \t]*$")
  18572. org-todo-line-regexp
  18573. (save-excursion
  18574. (beginning-of-line)
  18575. (looking-at org-todo-line-regexp)
  18576. (string= (match-string 3) "")))))
  18577. (defun org-at-heading-or-item-p ()
  18578. (or (org-at-heading-p) (org-at-item-p)))
  18579. (defun org-up-heading-all (arg)
  18580. "Move to the heading line of which the present line is a subheading.
  18581. This function considers both visible and invisible heading lines.
  18582. With argument, move up ARG levels."
  18583. (outline-up-heading arg t))
  18584. (defun org-up-heading-safe ()
  18585. "Move to the heading line of which the present line is a subheading.
  18586. This version will not throw an error. It will return the level of the
  18587. headline found, or nil if no higher level is found.
  18588. Also, this function will be a lot faster than `outline-up-heading',
  18589. because it relies on stars being the outline starters. This can really
  18590. make a significant difference in outlines with very many siblings."
  18591. (when (ignore-errors (org-back-to-heading t))
  18592. (let ((level-up (1- (funcall outline-level))))
  18593. (and (> level-up 0)
  18594. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  18595. (funcall outline-level)))))
  18596. (defun org-up-heading-or-point-min ()
  18597. "Move to the heading line of which the present is a subheading, or point-min.
  18598. This version is needed to make point-min behave like a virtual
  18599. heading of level 0 for property-inheritance. It will return the
  18600. level of the headline found (down to 0) or nil if already at a
  18601. point before the first headline or at point-min."
  18602. (when (ignore-errors (org-back-to-heading t))
  18603. (if (< 1 (funcall outline-level))
  18604. (org-up-heading-safe)
  18605. (unless (= (point) (point-min)) (goto-char (point-min))))))
  18606. (defun org-first-sibling-p ()
  18607. "Is this heading the first child of its parents?"
  18608. (interactive)
  18609. (let ((re org-outline-regexp-bol)
  18610. level l)
  18611. (unless (org-at-heading-p t)
  18612. (user-error "Not at a heading"))
  18613. (setq level (funcall outline-level))
  18614. (save-excursion
  18615. (if (not (re-search-backward re nil t))
  18616. t
  18617. (setq l (funcall outline-level))
  18618. (< l level)))))
  18619. (defun org-goto-sibling (&optional previous)
  18620. "Goto the next sibling, even if it is invisible.
  18621. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18622. when a sibling was found. When none is found, return nil and don't
  18623. move point."
  18624. (let ((fun (if previous 're-search-backward 're-search-forward))
  18625. (pos (point))
  18626. (re org-outline-regexp-bol)
  18627. level l)
  18628. (when (ignore-errors (org-back-to-heading t))
  18629. (setq level (funcall outline-level))
  18630. (catch 'exit
  18631. (or previous (forward-char 1))
  18632. (while (funcall fun re nil t)
  18633. (setq l (funcall outline-level))
  18634. (when (< l level) (goto-char pos) (throw 'exit nil))
  18635. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18636. (goto-char pos)
  18637. nil))))
  18638. (defun org-show-siblings ()
  18639. "Show all siblings of the current headline."
  18640. (save-excursion
  18641. (while (org-goto-sibling) (org-flag-heading nil)))
  18642. (save-excursion
  18643. (while (org-goto-sibling 'previous)
  18644. (org-flag-heading nil))))
  18645. (defun org-goto-first-child ()
  18646. "Goto the first child, even if it is invisible.
  18647. Return t when a child was found. Otherwise don't move point and
  18648. return nil."
  18649. (let (level (pos (point)) (re org-outline-regexp-bol))
  18650. (when (ignore-errors (org-back-to-heading t))
  18651. (setq level (outline-level))
  18652. (forward-char 1)
  18653. (if (and (re-search-forward re nil t) (> (outline-level) level))
  18654. (progn (goto-char (match-beginning 0)) t)
  18655. (goto-char pos) nil))))
  18656. (defun org-show-hidden-entry ()
  18657. "Show an entry where even the heading is hidden."
  18658. (save-excursion
  18659. (org-show-entry)))
  18660. (defun org-flag-heading (flag &optional entry)
  18661. "Flag the current heading. FLAG non-nil means make invisible.
  18662. When ENTRY is non-nil, show the entire entry."
  18663. (save-excursion
  18664. (org-back-to-heading t)
  18665. ;; Check if we should show the entire entry
  18666. (if (not entry)
  18667. (org-flag-region
  18668. (line-end-position 0) (line-end-position) flag 'outline)
  18669. (org-show-entry)
  18670. (save-excursion
  18671. (and (outline-next-heading)
  18672. (org-flag-heading nil))))))
  18673. (defun org-get-next-sibling ()
  18674. "Move to next heading of the same level, and return point.
  18675. If there is no such heading, return nil.
  18676. This is like outline-next-sibling, but invisible headings are ok."
  18677. (let ((level (funcall outline-level)))
  18678. (outline-next-heading)
  18679. (while (and (not (eobp)) (> (funcall outline-level) level))
  18680. (outline-next-heading))
  18681. (unless (or (eobp) (< (funcall outline-level) level))
  18682. (point))))
  18683. (defun org-get-last-sibling ()
  18684. "Move to previous heading of the same level, and return point.
  18685. If there is no such heading, return nil."
  18686. (let ((opoint (point))
  18687. (level (funcall outline-level)))
  18688. (outline-previous-heading)
  18689. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18690. (while (and (> (funcall outline-level) level)
  18691. (not (bobp)))
  18692. (outline-previous-heading))
  18693. (unless (< (funcall outline-level) level)
  18694. (point)))))
  18695. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  18696. "Goto to the end of a subtree."
  18697. ;; This contains an exact copy of the original function, but it uses
  18698. ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  18699. ;; trees and before first headline. And is uses an invisible-ok argument.
  18700. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18701. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18702. ;; with many children and grandchildren etc, this can be much faster
  18703. ;; than the outline version.
  18704. (org-back-to-heading-or-point-min invisible-ok)
  18705. (let ((first t)
  18706. (level (funcall outline-level)))
  18707. (cond ((= level 0)
  18708. (goto-char (point-max)))
  18709. ((and (derived-mode-p 'org-mode) (< level 1000))
  18710. ;; A true heading (not a plain list item), in Org
  18711. ;; This means we can easily find the end by looking
  18712. ;; only for the right number of stars. Using a regexp to do
  18713. ;; this is so much faster than using a Lisp loop.
  18714. (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  18715. (forward-char 1)
  18716. (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  18717. (t
  18718. ;; something else, do it the slow way
  18719. (while (and (not (eobp))
  18720. (or first (> (funcall outline-level) level)))
  18721. (setq first nil)
  18722. (outline-next-heading))))
  18723. (unless to-heading
  18724. (when (memq (preceding-char) '(?\n ?\^M))
  18725. ;; Go to end of line before heading
  18726. (forward-char -1)
  18727. (when (memq (preceding-char) '(?\n ?\^M))
  18728. ;; leave blank line before heading
  18729. (forward-char -1)))))
  18730. (point))
  18731. (defun org-end-of-meta-data (&optional full)
  18732. "Skip planning line and properties drawer in current entry.
  18733. When optional argument FULL is t, also skip planning information,
  18734. clocking lines and any kind of drawer.
  18735. When FULL is non-nil but not t, skip planning information,
  18736. clocking lines and only non-regular drawers, i.e. properties and
  18737. logbook drawers."
  18738. (org-back-to-heading t)
  18739. (forward-line)
  18740. ;; Skip planning information.
  18741. (when (looking-at-p org-planning-line-re) (forward-line))
  18742. ;; Skip property drawer.
  18743. (when (looking-at org-property-drawer-re)
  18744. (goto-char (match-end 0))
  18745. (forward-line))
  18746. ;; When FULL is not nil, skip more.
  18747. (when (and full (not (org-at-heading-p)))
  18748. (catch 'exit
  18749. (let ((end (save-excursion (outline-next-heading) (point)))
  18750. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  18751. (while (not (eobp))
  18752. (cond ;; Skip clock lines.
  18753. ((looking-at-p re) (forward-line))
  18754. ;; Skip logbook drawer.
  18755. ((looking-at-p org-logbook-drawer-re)
  18756. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18757. (forward-line)
  18758. (throw 'exit t)))
  18759. ;; When FULL is t, skip regular drawer too.
  18760. ((and (eq full t) (looking-at-p org-drawer-regexp))
  18761. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18762. (forward-line)
  18763. (throw 'exit t)))
  18764. (t (throw 'exit t))))))))
  18765. (defun org--line-fully-invisible-p ()
  18766. "Return non-nil if the current line is fully invisible."
  18767. (let ((line-beg (line-beginning-position))
  18768. (line-pos (1- (line-end-position)))
  18769. (is-invisible t))
  18770. (while (and (< line-beg line-pos) is-invisible)
  18771. (setq is-invisible (org-invisible-p line-pos))
  18772. (setq line-pos (1- line-pos)))
  18773. is-invisible))
  18774. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  18775. "Move forward to the ARG'th subheading at same level as this one.
  18776. Stop at the first and last subheadings of a superior heading.
  18777. Normally this only looks at visible headings, but when INVISIBLE-OK is
  18778. non-nil it will also look at invisible ones."
  18779. (interactive "p")
  18780. (let ((backward? (and arg (< arg 0))))
  18781. (if (org-before-first-heading-p)
  18782. (if backward? (goto-char (point-min)) (outline-next-heading))
  18783. (org-back-to-heading invisible-ok)
  18784. (unless backward? (end-of-line)) ;do not match current headline
  18785. (let ((level (- (match-end 0) (match-beginning 0) 1))
  18786. (f (if backward? #'re-search-backward #'re-search-forward))
  18787. (count (if arg (abs arg) 1))
  18788. (result (point)))
  18789. (while (and (> count 0)
  18790. (funcall f org-outline-regexp-bol nil 'move))
  18791. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  18792. (cond ((< l level) (setq count 0))
  18793. ((and (= l level)
  18794. (or invisible-ok
  18795. ;; FIXME: See commit a700fadd72 and the
  18796. ;; related discussion on why using
  18797. ;; `org--line-fully-invisible-p' is needed
  18798. ;; here, which is to serve the needs of an
  18799. ;; external package. If the change is
  18800. ;; wrong regarding Org itself, it should
  18801. ;; be removed.
  18802. (not (org--line-fully-invisible-p))))
  18803. (cl-decf count)
  18804. (when (= l level) (setq result (point)))))))
  18805. (goto-char result))
  18806. (beginning-of-line))))
  18807. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  18808. "Move backward to the ARG'th subheading at same level as this one.
  18809. Stop at the first and last subheadings of a superior heading."
  18810. (interactive "p")
  18811. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  18812. (defun org-next-visible-heading (arg)
  18813. "Move to the next visible heading line.
  18814. With ARG, repeats or can move backward if negative."
  18815. (interactive "p")
  18816. (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  18817. (if (< arg 0)
  18818. (beginning-of-line)
  18819. (end-of-line))
  18820. (while (and (< arg 0) (re-search-backward regexp nil :move))
  18821. (unless (bobp)
  18822. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  18823. (`(outline . ,o)
  18824. (goto-char (overlay-start o))
  18825. (re-search-backward regexp nil :move))
  18826. (_ nil))))
  18827. (cl-incf arg))
  18828. (while (and (> arg 0) (re-search-forward regexp nil t))
  18829. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  18830. (`(outline . ,o)
  18831. (goto-char (overlay-end o))
  18832. (re-search-forward regexp nil :move))
  18833. (_
  18834. (end-of-line)
  18835. nil))) ;leave the loop
  18836. (cl-decf arg))
  18837. (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
  18838. (defun org-previous-visible-heading (arg)
  18839. "Move to the previous visible heading.
  18840. With ARG, repeats or can move forward if negative."
  18841. (interactive "p")
  18842. (org-next-visible-heading (- arg)))
  18843. (defun org-forward-paragraph (&optional arg)
  18844. "Move forward by a paragraph, or equivalent, unit.
  18845. With argument ARG, do it ARG times;
  18846. a negative argument ARG = -N means move backward N paragraphs.
  18847. The function moves point between two structural
  18848. elements (paragraphs, tables, lists, etc.).
  18849. It also provides the following special moves for convenience:
  18850. - on a table or a property drawer, move to its beginning;
  18851. - on comment, example, export, source and verse blocks, stop
  18852. at blank lines;
  18853. - skip consecutive clocks, diary S-exps, and keywords."
  18854. (interactive "^p")
  18855. (unless arg (setq arg 1))
  18856. (if (< arg 0) (org-backward-paragraph (- arg))
  18857. (while (and (> arg 0) (not (eobp)))
  18858. (org--forward-paragraph-once)
  18859. (cl-decf arg))
  18860. ;; Return moves left.
  18861. arg))
  18862. (defun org-backward-paragraph (&optional arg)
  18863. "Move backward by a paragraph, or equivalent, unit.
  18864. With argument ARG, do it ARG times;
  18865. a negative argument ARG = -N means move forward N paragraphs.
  18866. The function moves point between two structural
  18867. elements (paragraphs, tables, lists, etc.).
  18868. It also provides the following special moves for convenience:
  18869. - on a table or a property drawer, move to its beginning;
  18870. - on comment, example, export, source and verse blocks, stop
  18871. at blank lines;
  18872. - skip consecutive clocks, diary S-exps, and keywords."
  18873. (interactive "^p")
  18874. (unless arg (setq arg 1))
  18875. (if (< arg 0) (org-forward-paragraph (- arg))
  18876. (while (and (> arg 0) (not (bobp)))
  18877. (org--backward-paragraph-once)
  18878. (cl-decf arg))
  18879. ;; Return moves left.
  18880. arg))
  18881. (defun org--paragraph-at-point ()
  18882. "Return paragraph, or equivalent, element at point.
  18883. Paragraph element at point is the element at point, with the
  18884. following special cases:
  18885. - treat table rows (resp. node properties) as the table
  18886. \(resp. property drawer) containing them.
  18887. - treat plain lists with an item every line as a whole.
  18888. - treat consecutive keywords, clocks, and diary-sexps as a single
  18889. block.
  18890. Function may return a real element, or a pseudo-element with type
  18891. `pseudo-paragraph'."
  18892. (let* ((e (org-element-at-point))
  18893. (type (org-element-type e))
  18894. ;; If we need to fake a new pseudo-element, triplet is
  18895. ;;
  18896. ;; (BEG END PARENT)
  18897. ;;
  18898. ;; where BEG and END are element boundaries, and PARENT the
  18899. ;; element containing it, or nil.
  18900. (triplet
  18901. (cond
  18902. ((memq type '(table property-drawer))
  18903. (list (org-element-property :begin e)
  18904. (org-element-property :end e)
  18905. (org-element-property :parent e)))
  18906. ((memq type '(node-property table-row))
  18907. (let ((e (org-element-property :parent e)))
  18908. (list (org-element-property :begin e)
  18909. (org-element-property :end e)
  18910. (org-element-property :parent e))))
  18911. ((memq type '(clock diary-sexp keyword))
  18912. (let* ((regexp (pcase type
  18913. (`clock org-clock-line-re)
  18914. (`diary-sexp "%%(")
  18915. (_ org-keyword-regexp)))
  18916. (end (if (< 0 (org-element-property :post-blank e))
  18917. (org-element-property :end e)
  18918. (org-with-wide-buffer
  18919. (forward-line)
  18920. (while (looking-at regexp) (forward-line))
  18921. (skip-chars-forward " \t\n")
  18922. (line-beginning-position))))
  18923. (begin (org-with-point-at (org-element-property :begin e)
  18924. (while (and (not (bobp)) (looking-at regexp))
  18925. (forward-line -1))
  18926. ;; We may have gotten one line too far.
  18927. (if (looking-at regexp)
  18928. (point)
  18929. (line-beginning-position 2)))))
  18930. (list begin end (org-element-property :parent e))))
  18931. ;; Find the full plain list containing point, the check it
  18932. ;; contains exactly one line per item.
  18933. ((let ((l (org-element-lineage e '(plain-list) t)))
  18934. (while (memq (org-element-type (org-element-property :parent l))
  18935. '(item plain-list))
  18936. (setq l (org-element-property :parent l)))
  18937. (and l
  18938. (org-with-point-at (org-element-property :post-affiliated l)
  18939. (forward-line (length (org-element-property :structure l)))
  18940. (= (point) (org-element-property :contents-end l)))
  18941. ;; Return value.
  18942. (list (org-element-property :begin l)
  18943. (org-element-property :end l)
  18944. (org-element-property :parent l)))))
  18945. (t nil)))) ;no triplet: return element
  18946. (pcase triplet
  18947. (`(,b ,e ,p)
  18948. (org-element-create
  18949. 'pseudo-paragraph
  18950. (list :begin b :end e :parent p :post-blank 0 :post-affiliated b)))
  18951. (_ e))))
  18952. (defun org--forward-paragraph-once ()
  18953. "Move forward to end of paragraph or equivalent, once.
  18954. See `org-forward-paragraph'."
  18955. (interactive)
  18956. (save-restriction
  18957. (widen)
  18958. (skip-chars-forward " \t\n")
  18959. (cond
  18960. ((eobp) nil)
  18961. ;; When inside a folded part, move out of it.
  18962. ((pcase (get-char-property-and-overlay (point) 'invisible)
  18963. (`(,(or `outline `org-hide-block) . ,o)
  18964. (goto-char (overlay-end o))
  18965. (forward-line)
  18966. t)
  18967. (_ nil)))
  18968. (t
  18969. (let* ((element (org--paragraph-at-point))
  18970. (type (org-element-type element))
  18971. (contents-begin (org-element-property :contents-begin element))
  18972. (end (org-element-property :end element))
  18973. (post-affiliated (org-element-property :post-affiliated element)))
  18974. (cond
  18975. ((eq type 'plain-list)
  18976. (forward-char)
  18977. (org--forward-paragraph-once))
  18978. ;; If the element is folded, skip it altogether.
  18979. ((pcase (org-with-point-at post-affiliated
  18980. (get-char-property-and-overlay (line-end-position)
  18981. 'invisible))
  18982. (`(,(or `outline `org-hide-block) . ,o)
  18983. (goto-char (overlay-end o))
  18984. (forward-line)
  18985. t)
  18986. (_ nil)))
  18987. ;; At a greater element, move inside.
  18988. ((and contents-begin
  18989. (> contents-begin (point))
  18990. (not (eq type 'paragraph)))
  18991. (goto-char contents-begin)
  18992. ;; Items and footnote definitions contents may not start at
  18993. ;; the beginning of the line. In this case, skip until the
  18994. ;; next paragraph.
  18995. (cond
  18996. ((not (bolp)) (org--forward-paragraph-once))
  18997. ((org-previous-line-empty-p) (forward-line -1))
  18998. (t nil)))
  18999. ;; Move between empty lines in some blocks.
  19000. ((memq type '(comment-block example-block export-block src-block
  19001. verse-block))
  19002. (let ((contents-start
  19003. (org-with-point-at post-affiliated
  19004. (line-beginning-position 2))))
  19005. (if (< (point) contents-start)
  19006. (goto-char contents-start)
  19007. (let ((contents-end
  19008. (org-with-point-at end
  19009. (skip-chars-backward " \t\n")
  19010. (line-beginning-position))))
  19011. (cond
  19012. ((>= (point) contents-end)
  19013. (goto-char end)
  19014. (skip-chars-backward " \t\n")
  19015. (forward-line))
  19016. ((re-search-forward "^[ \t]*\n" contents-end :move)
  19017. (forward-line -1))
  19018. (t nil))))))
  19019. (t
  19020. ;; Move to element's end.
  19021. (goto-char end)
  19022. (skip-chars-backward " \t\n")
  19023. (forward-line))))))))
  19024. (defun org--backward-paragraph-once ()
  19025. "Move backward to start of paragraph or equivalent, once.
  19026. See `org-backward-paragraph'."
  19027. (interactive)
  19028. (save-restriction
  19029. (widen)
  19030. (cond
  19031. ((bobp) nil)
  19032. ;; Blank lines at the beginning of the buffer.
  19033. ((and (org-match-line "^[ \t]*$")
  19034. (save-excursion (skip-chars-backward " \t\n") (bobp)))
  19035. (goto-char (point-min)))
  19036. ;; When inside a folded part, move out of it.
  19037. ((pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  19038. (`(,(or `outline `org-hide-block) . ,o)
  19039. (goto-char (1- (overlay-start o)))
  19040. (org--backward-paragraph-once)
  19041. t)
  19042. (_ nil)))
  19043. (t
  19044. (let* ((element (org--paragraph-at-point))
  19045. (type (org-element-type element))
  19046. (begin (org-element-property :begin element))
  19047. (post-affiliated (org-element-property :post-affiliated element))
  19048. (contents-end (org-element-property :contents-end element))
  19049. (end (org-element-property :end element))
  19050. (parent (org-element-property :parent element))
  19051. (reach
  19052. ;; Move to the visible empty line above position P, or
  19053. ;; to position P. Return t.
  19054. (lambda (p)
  19055. (goto-char p)
  19056. (when (and (org-previous-line-empty-p)
  19057. (let ((end (line-end-position 0)))
  19058. (or (= end (point-min))
  19059. (not (org-invisible-p (1- end))))))
  19060. (forward-line -1))
  19061. t)))
  19062. (cond
  19063. ;; Already at the beginning of an element.
  19064. ((= begin (point))
  19065. (cond
  19066. ;; There is a blank line above. Move there.
  19067. ((and (org-previous-line-empty-p)
  19068. (not (org-invisible-p (1- (line-end-position 0)))))
  19069. (forward-line -1))
  19070. ;; At the beginning of the first element within a greater
  19071. ;; element. Move to the beginning of the greater element.
  19072. ((and parent (= begin (org-element-property :contents-begin parent)))
  19073. (funcall reach (org-element-property :begin parent)))
  19074. ;; Since we have to move anyway, find the beginning
  19075. ;; position of the element above.
  19076. (t
  19077. (forward-char -1)
  19078. (org--backward-paragraph-once))))
  19079. ;; Skip paragraphs at the very beginning of footnote
  19080. ;; definitions or items.
  19081. ((and (eq type 'paragraph)
  19082. (org-with-point-at begin (not (bolp))))
  19083. (funcall reach (progn (goto-char begin) (line-beginning-position))))
  19084. ;; If the element is folded, skip it altogether.
  19085. ((org-with-point-at post-affiliated
  19086. (org-invisible-p (line-end-position) t))
  19087. (funcall reach begin))
  19088. ;; At the end of a greater element, move inside.
  19089. ((and contents-end
  19090. (<= contents-end (point))
  19091. (not (eq type 'paragraph)))
  19092. (cond
  19093. ((memq type '(footnote-definition plain-list))
  19094. (skip-chars-backward " \t\n")
  19095. (org--backward-paragraph-once))
  19096. ((= contents-end (point))
  19097. (forward-char -1)
  19098. (org--backward-paragraph-once))
  19099. (t
  19100. (goto-char contents-end))))
  19101. ;; Move between empty lines in some blocks.
  19102. ((and (memq type '(comment-block example-block export-block src-block
  19103. verse-block))
  19104. (let ((contents-start
  19105. (org-with-point-at post-affiliated
  19106. (line-beginning-position 2))))
  19107. (when (> (point) contents-start)
  19108. (let ((contents-end
  19109. (org-with-point-at end
  19110. (skip-chars-backward " \t\n")
  19111. (line-beginning-position))))
  19112. (if (> (point) contents-end)
  19113. (progn (goto-char contents-end) t)
  19114. (skip-chars-backward " \t\n" begin)
  19115. (re-search-backward "^[ \t]*\n" contents-start :move)
  19116. t))))))
  19117. ;; Move to element's start.
  19118. (t
  19119. (funcall reach begin))))))))
  19120. (defun org-forward-element ()
  19121. "Move forward by one element.
  19122. Move to the next element at the same level, when possible."
  19123. (interactive)
  19124. (cond ((eobp) (user-error "Cannot move further down"))
  19125. ((org-with-limited-levels (org-at-heading-p))
  19126. (let ((origin (point)))
  19127. (goto-char (org-end-of-subtree nil t))
  19128. (unless (org-with-limited-levels (org-at-heading-p))
  19129. (goto-char origin)
  19130. (user-error "Cannot move further down"))))
  19131. (t
  19132. (let* ((elem (org-element-at-point))
  19133. (end (org-element-property :end elem))
  19134. (parent (org-element-property :parent elem)))
  19135. (cond ((and parent (= (org-element-property :contents-end parent) end))
  19136. (goto-char (org-element-property :end parent)))
  19137. ((integer-or-marker-p end) (goto-char end))
  19138. (t (message "No element at point")))))))
  19139. (defun org-backward-element ()
  19140. "Move backward by one element.
  19141. Move to the previous element at the same level, when possible."
  19142. (interactive)
  19143. (cond ((bobp) (user-error "Cannot move further up"))
  19144. ((org-with-limited-levels (org-at-heading-p))
  19145. ;; At a headline, move to the previous one, if any, or stay
  19146. ;; here.
  19147. (let ((origin (point)))
  19148. (org-with-limited-levels (org-backward-heading-same-level 1))
  19149. ;; When current headline has no sibling above, move to its
  19150. ;; parent.
  19151. (when (= (point) origin)
  19152. (or (org-with-limited-levels (org-up-heading-safe))
  19153. (progn (goto-char origin)
  19154. (user-error "Cannot move further up"))))))
  19155. (t
  19156. (let* ((elem (org-element-at-point))
  19157. (beg (org-element-property :begin elem)))
  19158. (cond
  19159. ;; Move to beginning of current element if point isn't
  19160. ;; there already.
  19161. ((null beg) (message "No element at point"))
  19162. ((/= (point) beg) (goto-char beg))
  19163. (t (goto-char beg)
  19164. (skip-chars-backward " \r\t\n")
  19165. (unless (bobp)
  19166. (let ((prev (org-element-at-point)))
  19167. (goto-char (org-element-property :begin prev))
  19168. (while (and (setq prev (org-element-property :parent prev))
  19169. (<= (org-element-property :end prev) beg))
  19170. (goto-char (org-element-property :begin prev)))))))))))
  19171. (defun org-up-element ()
  19172. "Move to upper element."
  19173. (interactive)
  19174. (if (org-with-limited-levels (org-at-heading-p))
  19175. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19176. (let* ((elem (org-element-at-point))
  19177. (parent (org-element-property :parent elem)))
  19178. (if parent (goto-char (org-element-property :begin parent))
  19179. (if (org-with-limited-levels (org-before-first-heading-p))
  19180. (user-error "No surrounding element")
  19181. (org-with-limited-levels (org-back-to-heading)))))))
  19182. (defun org-down-element ()
  19183. "Move to inner element."
  19184. (interactive)
  19185. (let ((element (org-element-at-point)))
  19186. (cond
  19187. ((memq (org-element-type element) '(plain-list table))
  19188. (goto-char (org-element-property :contents-begin element))
  19189. (forward-char))
  19190. ((memq (org-element-type element) org-element-greater-elements)
  19191. ;; If contents are hidden, first disclose them.
  19192. (when (org-invisible-p (line-end-position)) (org-cycle))
  19193. (goto-char (or (org-element-property :contents-begin element)
  19194. (user-error "No content for this element"))))
  19195. (t (user-error "No inner element")))))
  19196. (defun org-drag-element-backward ()
  19197. "Move backward element at point."
  19198. (interactive)
  19199. (let ((elem (or (org-element-at-point)
  19200. (user-error "No element at point"))))
  19201. (if (eq (org-element-type elem) 'headline)
  19202. ;; Preserve point when moving a whole tree, even if point was
  19203. ;; on blank lines below the headline.
  19204. (let ((offset (skip-chars-backward " \t\n")))
  19205. (unwind-protect (org-move-subtree-up)
  19206. (forward-char (- offset))))
  19207. (let ((prev-elem
  19208. (save-excursion
  19209. (goto-char (org-element-property :begin elem))
  19210. (skip-chars-backward " \r\t\n")
  19211. (unless (bobp)
  19212. (let* ((beg (org-element-property :begin elem))
  19213. (prev (org-element-at-point))
  19214. (up prev))
  19215. (while (and (setq up (org-element-property :parent up))
  19216. (<= (org-element-property :end up) beg))
  19217. (setq prev up))
  19218. prev)))))
  19219. ;; Error out if no previous element or previous element is
  19220. ;; a parent of the current one.
  19221. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19222. (user-error "Cannot drag element backward")
  19223. (let ((pos (point)))
  19224. (org-element-swap-A-B prev-elem elem)
  19225. (goto-char (+ (org-element-property :begin prev-elem)
  19226. (- pos (org-element-property :begin elem))))))))))
  19227. (defun org-drag-element-forward ()
  19228. "Move forward element at point."
  19229. (interactive)
  19230. (let* ((pos (point))
  19231. (elem (or (org-element-at-point)
  19232. (user-error "No element at point"))))
  19233. (when (= (point-max) (org-element-property :end elem))
  19234. (user-error "Cannot drag element forward"))
  19235. (goto-char (org-element-property :end elem))
  19236. (let ((next-elem (org-element-at-point)))
  19237. (when (or (org-element-nested-p elem next-elem)
  19238. (and (eq (org-element-type next-elem) 'headline)
  19239. (not (eq (org-element-type elem) 'headline))))
  19240. (goto-char pos)
  19241. (user-error "Cannot drag element forward"))
  19242. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19243. ;; body's length (without final blanks) and by the length of
  19244. ;; blanks between ELEM and NEXT-ELEM.
  19245. (let ((size-next (- (save-excursion
  19246. (goto-char (org-element-property :end next-elem))
  19247. (skip-chars-backward " \r\t\n")
  19248. (forward-line)
  19249. ;; Small correction if buffer doesn't end
  19250. ;; with a newline character.
  19251. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19252. (org-element-property :begin next-elem)))
  19253. (size-blank (- (org-element-property :end elem)
  19254. (save-excursion
  19255. (goto-char (org-element-property :end elem))
  19256. (skip-chars-backward " \r\t\n")
  19257. (forward-line)
  19258. (point)))))
  19259. (org-element-swap-A-B elem next-elem)
  19260. (goto-char (+ pos size-next size-blank))))))
  19261. (defun org-drag-line-forward (arg)
  19262. "Drag the line at point ARG lines forward."
  19263. (interactive "p")
  19264. (dotimes (_ (abs arg))
  19265. (let ((c (current-column)))
  19266. (if (< 0 arg)
  19267. (progn
  19268. (beginning-of-line 2)
  19269. (transpose-lines 1)
  19270. (beginning-of-line 0))
  19271. (transpose-lines 1)
  19272. (beginning-of-line -1))
  19273. (org-move-to-column c))))
  19274. (defun org-drag-line-backward (arg)
  19275. "Drag the line at point ARG lines backward."
  19276. (interactive "p")
  19277. (org-drag-line-forward (- arg)))
  19278. (defun org-mark-element ()
  19279. "Put point at beginning of this element, mark at end.
  19280. Interactively, if this command is repeated or (in Transient Mark
  19281. mode) if the mark is active, it marks the next element after the
  19282. ones already marked."
  19283. (interactive)
  19284. (let (deactivate-mark)
  19285. (if (and (called-interactively-p 'any)
  19286. (or (and (eq last-command this-command) (mark t))
  19287. (and transient-mark-mode mark-active)))
  19288. (set-mark
  19289. (save-excursion
  19290. (goto-char (mark))
  19291. (goto-char (org-element-property :end (org-element-at-point)))
  19292. (point)))
  19293. (let ((element (org-element-at-point)))
  19294. (end-of-line)
  19295. (push-mark (min (point-max) (org-element-property :end element)) t t)
  19296. (goto-char (org-element-property :begin element))))))
  19297. (defun org-narrow-to-element ()
  19298. "Narrow buffer to current element."
  19299. (interactive)
  19300. (let ((elem (org-element-at-point)))
  19301. (cond
  19302. ((eq (car elem) 'headline)
  19303. (narrow-to-region
  19304. (org-element-property :begin elem)
  19305. (org-element-property :end elem)))
  19306. ((memq (car elem) org-element-greater-elements)
  19307. (narrow-to-region
  19308. (org-element-property :contents-begin elem)
  19309. (org-element-property :contents-end elem)))
  19310. (t
  19311. (narrow-to-region
  19312. (org-element-property :begin elem)
  19313. (org-element-property :end elem))))))
  19314. (defun org-transpose-element ()
  19315. "Transpose current and previous elements, keeping blank lines between.
  19316. Point is moved after both elements."
  19317. (interactive)
  19318. (org-skip-whitespace)
  19319. (let ((end (org-element-property :end (org-element-at-point))))
  19320. (org-drag-element-backward)
  19321. (goto-char end)))
  19322. (defun org-unindent-buffer ()
  19323. "Un-indent the visible part of the buffer.
  19324. Relative indentation (between items, inside blocks, etc.) isn't
  19325. modified."
  19326. (interactive)
  19327. (unless (eq major-mode 'org-mode)
  19328. (user-error "Cannot un-indent a buffer not in Org mode"))
  19329. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19330. (unindent-tree
  19331. (lambda (contents)
  19332. (dolist (element (reverse contents))
  19333. (if (memq (org-element-type element) '(headline section))
  19334. (funcall unindent-tree (org-element-contents element))
  19335. (save-excursion
  19336. (save-restriction
  19337. (narrow-to-region
  19338. (org-element-property :begin element)
  19339. (org-element-property :end element))
  19340. (org-do-remove-indentation))))))))
  19341. (funcall unindent-tree (org-element-contents parse-tree))))
  19342. (defun org-make-options-regexp (kwds &optional extra)
  19343. "Make a regular expression for keyword lines.
  19344. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19345. when non-nil, is a regexp matching keywords names."
  19346. (concat "^[ \t]*#\\+\\("
  19347. (regexp-opt kwds)
  19348. (and extra (concat (and kwds "\\|") extra))
  19349. "\\):[ \t]*\\(.*\\)"))
  19350. ;;; Conveniently switch to Info nodes
  19351. (defun org-info-find-node (&optional nodename)
  19352. "Find Info documentation NODENAME or Org documentation according context.
  19353. Started from `gnus-info-find-node'."
  19354. (interactive)
  19355. (Info-goto-node
  19356. (or nodename
  19357. (let ((default-org-info-node "(org) Top"))
  19358. (cond
  19359. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19360. ((eq 'org-mode major-mode)
  19361. (let* ((context (org-element-at-point))
  19362. (element-info-nodes ; compare to `org-element-all-elements'.
  19363. `((babel-call . "(org) Evaluating Code Blocks")
  19364. (center-block . "(org) Paragraphs")
  19365. (clock . ,default-org-info-node)
  19366. (comment . "(org) Comment Lines")
  19367. (comment-block . "(org) Comment Lines")
  19368. (diary-sexp . ,default-org-info-node)
  19369. (drawer . "(org) Drawers")
  19370. (dynamic-block . "(org) Dynamic Blocks")
  19371. (example-block . "(org) Literal Examples")
  19372. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19373. (fixed-width . ,default-org-info-node)
  19374. (footnote-definition . "(org) Creating Footnotes")
  19375. (headline . "(org) Document Structure")
  19376. (horizontal-rule . "(org) Built-in Table Editor")
  19377. (inlinetask . ,default-org-info-node)
  19378. (item . "(org) Plain Lists")
  19379. (keyword . "(org) Per-file keywords")
  19380. (latex-environment . "(org) LaTeX Export")
  19381. (node-property . "(org) Properties and Columns")
  19382. (paragraph . "(org) Paragraphs")
  19383. (plain-list . "(org) Plain Lists")
  19384. (planning . "(org) Deadlines and Scheduling")
  19385. (property-drawer . "(org) Properties and Columns")
  19386. (quote-block . "(org) Paragraphs")
  19387. (section . ,default-org-info-node)
  19388. (special-block . ,default-org-info-node)
  19389. (src-block . "(org) Working with Source Code")
  19390. (table . "(org) Tables")
  19391. (table-row . "(org) Tables")
  19392. (verse-block . "(org) Paragraphs"))))
  19393. (or (cdr (assoc (car context) element-info-nodes))
  19394. default-org-info-node)))
  19395. (t default-org-info-node))))))
  19396. ;;; Finish up
  19397. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  19398. (lambda () (add-hook 'change-major-mode-hook
  19399. 'org-show-all 'append 'local)))
  19400. (provide 'org)
  19401. (run-hooks 'org-load-hook)
  19402. ;; Local variables:
  19403. ;; generated-autoload-file: "org-loaddefs.el"
  19404. ;; End:
  19405. ;;; org.el ends here