org.el 815 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128
  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-2022 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
  6. ;; Maintainer: Bastien Guerry <bzg@gnu.org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; URL: https://orgmode.org
  9. ;; Package-Requires: ((emacs "25.1"))
  10. ;; Version: 9.6-dev
  11. ;; This file is part of GNU Emacs.
  12. ;;
  13. ;; GNU Emacs is free software: you can redistribute it and/or modify
  14. ;; it under the terms of the GNU General Public License as published by
  15. ;; the Free Software Foundation, either version 3 of the License, or
  16. ;; (at your option) any later version.
  17. ;; GNU Emacs is distributed in the hope that it will be useful,
  18. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. ;; GNU General Public License for more details.
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  23. ;;
  24. ;;; Commentary:
  25. ;;
  26. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  27. ;; project planning with a fast and effective plain-text system.
  28. ;;
  29. ;; Org mode develops organizational tasks around NOTES files that
  30. ;; contain information about projects as plain text. Org mode is
  31. ;; implemented on top of outline-mode, which makes it possible to keep
  32. ;; the content of large files well structured. Visibility cycling and
  33. ;; structure editing help to work with the tree. Tables are easily
  34. ;; created with a built-in table editor. Org mode supports ToDo
  35. ;; items, deadlines, time stamps, and scheduling. It dynamically
  36. ;; compiles entries into an agenda that utilizes and smoothly
  37. ;; integrates much of the Emacs calendar and diary. Plain text
  38. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  39. ;; entries, and any files related to the projects. For printing and
  40. ;; sharing of notes, an Org file can be exported as a structured ASCII
  41. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  42. ;; file. It can also serve as a publishing tool for a set of linked
  43. ;; webpages.
  44. ;;
  45. ;; Installation and Activation
  46. ;; ---------------------------
  47. ;; See the corresponding sections in the manual at
  48. ;;
  49. ;; https://orgmode.org/org.html#Installation
  50. ;;
  51. ;; Documentation
  52. ;; -------------
  53. ;; The documentation of Org mode can be found in the TeXInfo file. The
  54. ;; distribution also contains a PDF version of it. At the Org mode website,
  55. ;; you can read the same text online as HTML. There is also an excellent
  56. ;; reference card made by Philip Rooke. This card can be found in the
  57. ;; doc/ directory.
  58. ;;
  59. ;; A list of recent changes can be found at
  60. ;; https://orgmode.org/Changes.html
  61. ;;
  62. ;;; Code:
  63. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  64. (defvar org-inlinetask-min-level)
  65. ;;;; Require other packages
  66. (require 'org-compat)
  67. (org-assert-version)
  68. (require 'cl-lib)
  69. (eval-when-compile (require 'gnus-sum))
  70. (require 'calendar)
  71. (require 'find-func)
  72. (require 'format-spec)
  73. (or (eq this-command 'eval-buffer)
  74. (condition-case nil
  75. (load (concat (file-name-directory load-file-name)
  76. "org-loaddefs.el")
  77. nil t t t)
  78. (error
  79. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  80. (sit-for 3)
  81. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  82. (sit-for 3))))
  83. (eval-and-compile (require 'org-macs))
  84. (require 'org-compat)
  85. (require 'org-keys)
  86. (require 'ol)
  87. (require 'oc)
  88. (require 'org-table)
  89. (require 'org-fold)
  90. (require 'org-cycle)
  91. (defvaralias 'org-hide-block-startup 'org-cycle-hide-block-startup)
  92. (defvaralias 'org-pre-cycle-hook 'org-cycle-pre-hook)
  93. (defvaralias 'org-tab-first-hook 'org-cycle-tab-first-hook)
  94. (defalias 'org-global-cycle #'org-cycle-global)
  95. (defalias 'org-overview #'org-cycle-overview)
  96. (defalias 'org-content #'org-cycle-content)
  97. (defalias 'org-reveal #'org-fold-reveal)
  98. (defalias 'org-force-cycle-archived #'org-cycle-force-archived)
  99. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  100. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  101. (defvar org-outline-regexp "\\*+ "
  102. "Regexp to match Org headlines.")
  103. (defvar org-outline-regexp-bol "^\\*+ "
  104. "Regexp to match Org headlines.
  105. This is similar to `org-outline-regexp' but additionally makes
  106. sure that we are at the beginning of the line.")
  107. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  108. "Matches a headline, putting stars and text into groups.
  109. Stars are put in group 1 and the trimmed body in group 2.")
  110. (declare-function calendar-check-holidays "holidays" (date))
  111. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  112. (declare-function cdlatex-math-symbol "ext:cdlatex")
  113. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  114. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  115. (declare-function org-add-archive-files "org-archive" (files))
  116. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  117. (declare-function org-agenda-todo-yesterday "org-agenda" (&optional arg))
  118. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  119. (declare-function org-agenda-redo "org-agenda" (&optional all))
  120. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  121. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  122. (declare-function org-archive-subtree-default "org-archive" ())
  123. (declare-function org-archive-to-archive-sibling "org-archive" ())
  124. (declare-function org-attach "org-attach" ())
  125. (declare-function org-attach-dir "org-attach"
  126. (&optional create-if-not-exists-p no-fs-check))
  127. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  128. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  129. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  130. (declare-function org-clock-auto-clockout "org-clock" ())
  131. (declare-function org-clock-cancel "org-clock" ())
  132. (declare-function org-clock-display "org-clock" (&optional arg))
  133. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  134. (declare-function org-clock-goto "org-clock" (&optional select))
  135. (declare-function org-clock-in "org-clock" (&optional select start-time))
  136. (declare-function org-clock-in-last "org-clock" (&optional arg))
  137. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  138. (declare-function org-clock-out-if-current "org-clock" ())
  139. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  140. (declare-function org-clock-report "org-clock" (&optional arg))
  141. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  142. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  143. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  144. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  145. (declare-function org-clock-update-time-maybe "org-clock" ())
  146. (declare-function org-clocktable-shift "org-clock" (dir n))
  147. (declare-function org-columns-quit "org-colview" ())
  148. (declare-function org-columns-insert-dblock "org-colview" ())
  149. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  150. (declare-function org-duration-to-minutes "org-duration" (duration &optional canonical))
  151. (declare-function org-element-at-point "org-element" (&optional pom cached-only))
  152. (declare-function org-element-at-point-no-context "org-element" (&optional pom))
  153. (declare-function org-element-cache-refresh "org-element" (pos))
  154. (declare-function org-element-cache-reset "org-element" (&optional all))
  155. (declare-function org-element-cache-map "org-element" (func &rest keys))
  156. (declare-function org-element-contents "org-element" (element))
  157. (declare-function org-element-context "org-element" (&optional element))
  158. (declare-function org-element-copy "org-element" (datum))
  159. (declare-function org-element-create "org-element" (type &optional props &rest children))
  160. (declare-function org-element-extract-element "org-element" (element))
  161. (declare-function org-element-insert-before "org-element" (element location))
  162. (declare-function org-element-interpret-data "org-element" (data))
  163. (declare-function org-element-keyword-parser "org-element" (limit affiliated))
  164. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  165. (declare-function org-element-link-parser "org-element" ())
  166. (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion with-affiliated))
  167. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  168. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  169. (declare-function org-element-parse-secondary-string "org-element" (string restriction &optional parent))
  170. (declare-function org-element-property "org-element" (property element))
  171. (declare-function org-element-put-property "org-element" (element property value))
  172. (declare-function org-element-restriction "org-element" (element))
  173. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  174. (declare-function org-element-timestamp-parser "org-element" ())
  175. (declare-function org-element-type "org-element" (element))
  176. (declare-function org-element--cache-active-p "org-element" ())
  177. (declare-function org-export-dispatch "ox" (&optional arg))
  178. (declare-function org-export-get-backend "ox" (name))
  179. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  180. (declare-function org-feed-goto-inbox "org-feed" (feed))
  181. (declare-function org-feed-update-all "org-feed" ())
  182. (declare-function org-goto "org-goto" (&optional alternative-interface))
  183. (declare-function org-id-find-id-file "org-id" (id))
  184. (declare-function org-id-get-create "org-id" (&optional force))
  185. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  186. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  187. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  188. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  189. (declare-function org-num-mode "org-num" (&optional arg))
  190. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  191. (declare-function org-persist-load "org-persist" (container &optional associated hash-must-match))
  192. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  193. (declare-function org-timer "org-timer" (&optional restart no-insert))
  194. (declare-function org-timer-item "org-timer" (&optional arg))
  195. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  196. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  197. (declare-function org-timer-start "org-timer" (&optional offset))
  198. (declare-function org-timer-stop "org-timer" ())
  199. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  200. (declare-function org-update-radio-target-regexp "ol" ())
  201. (defvar org-agenda-buffer-name)
  202. (defvar org-element-paragraph-separate)
  203. (defvar org-element-cache-map-continue-from)
  204. (defvar org-element--timestamp-regexp)
  205. (defvar org-indent-indentation-per-level)
  206. (defvar org-radio-target-regexp)
  207. (defvar org-target-link-regexp)
  208. (defvar org-target-regexp)
  209. (defvar org-id-overriding-file-name)
  210. ;; load languages based on value of `org-babel-load-languages'
  211. (defvar org-babel-load-languages)
  212. (defvar crm-separator) ; dynamically scoped param
  213. ;;;###autoload
  214. (defun org-babel-do-load-languages (sym value)
  215. "Load the languages defined in `org-babel-load-languages'."
  216. (set-default-toplevel-value sym value)
  217. (dolist (pair org-babel-load-languages)
  218. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  219. (if active
  220. (require (intern (concat "ob-" lang)))
  221. (fmakunbound
  222. (intern (concat "org-babel-execute:" lang)))
  223. (fmakunbound
  224. (intern (concat "org-babel-expand-body:" lang)))))))
  225. ;;;###autoload
  226. (defun org-babel-load-file (file &optional compile)
  227. "Load Emacs Lisp source code blocks in the Org FILE.
  228. This function exports the source code using `org-babel-tangle'
  229. and then loads the resulting file using `load-file'. With
  230. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  231. byte-compiled before it is loaded."
  232. (interactive "fFile to load: \nP")
  233. (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
  234. ;; Tangle only if the Org file is newer than the Elisp file.
  235. (unless (org-file-newer-than-p
  236. tangled-file
  237. (file-attribute-modification-time
  238. (file-attributes (file-truename file))))
  239. ;; Make sure that tangled file modification time is
  240. ;; updated even when `org-babel-tangle-file' does not make changes.
  241. ;; This avoids re-tangling changed FILE where the changes did
  242. ;; not affect the tangled code.
  243. (when (file-exists-p tangled-file)
  244. (set-file-times tangled-file))
  245. (org-babel-tangle-file file
  246. tangled-file
  247. (rx string-start
  248. (or "emacs-lisp" "elisp")
  249. string-end)))
  250. (if compile
  251. (progn
  252. (byte-compile-file tangled-file)
  253. (load-file (byte-compile-dest-file tangled-file))
  254. (message "Compiled and loaded %s" tangled-file))
  255. (load-file tangled-file)
  256. (message "Loaded %s" tangled-file))))
  257. (defcustom org-babel-load-languages '((emacs-lisp . t))
  258. "Languages which can be evaluated in Org buffers.
  259. \\<org-mode-map>
  260. This list can be used to load support for any of the available
  261. languages with babel support (see info node `(org) Languages'). Each
  262. language will depend on a different set of system executables and/or
  263. Emacs modes.
  264. When a language is \"loaded\", code blocks in that language can
  265. be evaluated with `org-babel-execute-src-block', which is bound
  266. by default to \\[org-ctrl-c-ctrl-c].
  267. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  268. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  269. default, only Emacs Lisp is loaded, since it has no specific
  270. requirement."
  271. :group 'org-babel
  272. :set 'org-babel-do-load-languages
  273. :version "24.1"
  274. :type '(alist :tag "Babel Languages"
  275. :key-type
  276. (choice
  277. (const :tag "Awk" awk)
  278. (const :tag "C" C)
  279. (const :tag "R" R)
  280. (const :tag "Calc" calc)
  281. (const :tag "Clojure" clojure)
  282. (const :tag "CSS" css)
  283. (const :tag "Ditaa" ditaa)
  284. (const :tag "Dot" dot)
  285. (const :tag "Emacs Lisp" emacs-lisp)
  286. (const :tag "Forth" forth)
  287. (const :tag "Fortran" fortran)
  288. (const :tag "Gnuplot" gnuplot)
  289. (const :tag "Haskell" haskell)
  290. (const :tag "Java" java)
  291. (const :tag "Javascript" js)
  292. (const :tag "LaTeX" latex)
  293. (const :tag "Lilypond" lilypond)
  294. (const :tag "Lisp" lisp)
  295. (const :tag "Makefile" makefile)
  296. (const :tag "Maxima" maxima)
  297. (const :tag "Matlab" matlab)
  298. (const :tag "Ocaml" ocaml)
  299. (const :tag "Octave" octave)
  300. (const :tag "Org" org)
  301. (const :tag "Perl" perl)
  302. (const :tag "Pico Lisp" picolisp)
  303. (const :tag "PlantUML" plantuml)
  304. (const :tag "Python" python)
  305. (const :tag "Ruby" ruby)
  306. (const :tag "Sass" sass)
  307. (const :tag "Scala" scala)
  308. (const :tag "Scheme" scheme)
  309. (const :tag "Screen" screen)
  310. (const :tag "Shell Script" shell)
  311. (const :tag "Sql" sql)
  312. (const :tag "Sqlite" sqlite)
  313. (const :tag "Stan" stan))
  314. :value-type (boolean :tag "Activate" :value t)))
  315. ;;;; Customization variables
  316. (defcustom org-clone-delete-id nil
  317. "Remove ID property of clones of a subtree.
  318. When non-nil, clones of a subtree don't inherit the ID property.
  319. Otherwise they inherit the ID property with a new unique
  320. identifier."
  321. :type 'boolean
  322. :version "24.1"
  323. :group 'org-id)
  324. ;;; Version
  325. (org-check-version)
  326. ;;;###autoload
  327. (defun org-version (&optional here full message)
  328. "Show the Org version.
  329. Interactively, or when MESSAGE is non-nil, show it in echo area.
  330. With prefix argument, or when HERE is non-nil, insert it at point.
  331. In non-interactive uses, a reduced version string is output unless
  332. FULL is given."
  333. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  334. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  335. (save-load-suffixes load-suffixes)
  336. (load-suffixes (list ".el"))
  337. (org-install-dir
  338. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  339. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  340. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  341. (let* ((load-suffixes save-load-suffixes)
  342. (release (org-release))
  343. (git-version (org-git-version))
  344. (version (format "Org mode version %s (%s @ %s)"
  345. release
  346. git-version
  347. (if org-install-dir
  348. (if (string= org-dir org-install-dir)
  349. org-install-dir
  350. (concat "mixed installation! "
  351. org-install-dir
  352. " and "
  353. org-dir))
  354. "org-loaddefs.el can not be found!")))
  355. (version1 (if full version release)))
  356. (when here (insert version1))
  357. (when message (message "%s" version1))
  358. version1)))
  359. (defconst org-version (org-version))
  360. ;;; Syntax Constants
  361. ;;;; Comments
  362. (defconst org-comment-regexp
  363. (rx (seq bol (zero-or-more (any "\t ")) "#" (or " " eol)))
  364. "Regular expression for comment lines.")
  365. ;;;; Keyword
  366. (defconst org-keyword-regexp "^[ \t]*#\\+\\(\\S-+?\\):[ \t]*\\(.*\\)$"
  367. "Regular expression for keyword-lines.")
  368. ;;;; Block
  369. (defconst org-block-regexp
  370. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  371. "Regular expression for hiding blocks.")
  372. (defconst org-dblock-start-re
  373. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  374. "Matches the start line of a dynamic block, with parameters.")
  375. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  376. "Matches the end of a dynamic block.")
  377. ;;;; Timestamp
  378. (defconst org-ts--internal-regexp
  379. (rx (seq
  380. (= 4 digit) "-" (= 2 digit) "-" (= 2 digit)
  381. (optional " " (*? nonl))))
  382. "Regular expression matching the innards of a time stamp.")
  383. (defconst org-ts-regexp (format "<\\(%s\\)>" org-ts--internal-regexp)
  384. "Regular expression for fast time stamp matching.")
  385. (defconst org-ts-regexp-inactive
  386. (format "\\[\\(%s\\)\\]" org-ts--internal-regexp)
  387. "Regular expression for fast inactive time stamp matching.")
  388. (defconst org-ts-regexp-both (format "[[<]\\(%s\\)[]>]" org-ts--internal-regexp)
  389. "Regular expression for fast time stamp matching.")
  390. (defconst org-ts-regexp0
  391. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  392. "Regular expression matching time strings for analysis.
  393. This one does not require the space after the date, so it can be used
  394. on a string that terminates immediately after the date.")
  395. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  396. "Regular expression matching time strings for analysis.")
  397. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  398. "Regular expression matching time stamps, with groups.")
  399. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  400. "Regular expression matching time stamps (also [..]), with groups.")
  401. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  402. "Regular expression matching a time stamp range.")
  403. (defconst org-tr-regexp-both
  404. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  405. "Regular expression matching a time stamp range.")
  406. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  407. org-ts-regexp "\\)?")
  408. "Regular expression matching a time stamp or time stamp range.")
  409. (defconst org-tsr-regexp-both
  410. (concat org-ts-regexp-both "\\(--?-?"
  411. org-ts-regexp-both "\\)?")
  412. "Regular expression matching a time stamp or time stamp range.
  413. The time stamps may be either active or inactive.")
  414. (defconst org-repeat-re
  415. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  416. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  417. "Regular expression for specifying repeated events.
  418. After a match, group 1 contains the repeat expression.")
  419. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  420. "Formats for `format-time-string' which are used for time stamps.")
  421. ;;;; Clock and Planning
  422. (defconst org-clock-string "CLOCK:"
  423. "String used as prefix for timestamps clocking work hours on an item.")
  424. (defvar org-closed-string "CLOSED:"
  425. "String used as the prefix for timestamps logging closing a TODO entry.")
  426. (defvar org-deadline-string "DEADLINE:"
  427. "String to mark deadline entries.
  428. \\<org-mode-map>
  429. A deadline is this string, followed by a time stamp. It must be
  430. a word, terminated by a colon. You can insert a schedule keyword
  431. and a timestamp with `\\[org-deadline]'.")
  432. (defvar org-scheduled-string "SCHEDULED:"
  433. "String to mark scheduled TODO entries.
  434. \\<org-mode-map>
  435. A schedule is this string, followed by a time stamp. It must be
  436. a word, terminated by a colon. You can insert a schedule keyword
  437. and a timestamp with `\\[org-schedule]'.")
  438. (defconst org-ds-keyword-length
  439. (+ 2
  440. (apply #'max
  441. (mapcar #'length
  442. (list org-deadline-string org-scheduled-string
  443. org-clock-string org-closed-string))))
  444. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  445. (defconst org-planning-line-re
  446. (concat "^[ \t]*"
  447. (regexp-opt
  448. (list org-closed-string org-deadline-string org-scheduled-string)
  449. t))
  450. "Matches a line with planning info.
  451. Matched keyword is in group 1.")
  452. (defconst org-clock-line-re
  453. (concat "^[ \t]*" org-clock-string)
  454. "Matches a line with clock info.")
  455. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  456. "Matches the DEADLINE keyword.")
  457. (defconst org-deadline-time-regexp
  458. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  459. "Matches the DEADLINE keyword together with a time stamp.")
  460. (defconst org-deadline-time-hour-regexp
  461. (concat "\\<" org-deadline-string
  462. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  463. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  464. (defconst org-deadline-line-regexp
  465. (concat "\\<\\(" org-deadline-string "\\).*")
  466. "Matches the DEADLINE keyword and the rest of the line.")
  467. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  468. "Matches the SCHEDULED keyword.")
  469. (defconst org-scheduled-time-regexp
  470. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  471. "Matches the SCHEDULED keyword together with a time stamp.")
  472. (defconst org-scheduled-time-hour-regexp
  473. (concat "\\<" org-scheduled-string
  474. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  475. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  476. (defconst org-closed-time-regexp
  477. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  478. "Matches the CLOSED keyword together with a time stamp.")
  479. (defconst org-keyword-time-regexp
  480. (concat "\\<"
  481. (regexp-opt
  482. (list org-scheduled-string org-deadline-string org-closed-string
  483. org-clock-string)
  484. t)
  485. " *[[<]\\([^]>]+\\)[]>]")
  486. "Matches any of the 4 keywords, together with the time stamp.")
  487. (defconst org-keyword-time-not-clock-regexp
  488. (concat
  489. "\\<"
  490. (regexp-opt
  491. (list org-scheduled-string org-deadline-string org-closed-string) t)
  492. " *[[<]\\([^]>]+\\)[]>]")
  493. "Matches any of the 3 keywords, together with the time stamp.")
  494. (defconst org-all-time-keywords
  495. (mapcar (lambda (w) (substring w 0 -1))
  496. (list org-scheduled-string org-deadline-string
  497. org-clock-string org-closed-string))
  498. "List of time keywords.")
  499. ;;;; Drawer
  500. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  501. "Matches first or last line of a hidden block.
  502. Group 1 contains drawer's name or \"END\".")
  503. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  504. "Regular expression matching the first line of a property drawer.")
  505. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  506. "Regular expression matching the last line of a property drawer.")
  507. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  508. "Regular expression matching the first line of a clock drawer.")
  509. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  510. "Regular expression matching the last line of a clock drawer.")
  511. (defconst org-logbook-drawer-re
  512. (rx (seq bol (0+ (any "\t ")) ":LOGBOOK:" (0+ (any "\t ")) "\n"
  513. (*? (0+ nonl) "\n")
  514. (0+ (any "\t ")) ":END:" (0+ (any "\t ")) eol))
  515. "Matches an entire LOGBOOK drawer.")
  516. (defconst org-property-drawer-re
  517. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  518. "\\(?:[ \t]*:\\S-+:\\(?:[ \t].*\\)?[ \t]*\n\\)*?"
  519. "[ \t]*:END:[ \t]*$")
  520. "Matches an entire property drawer.")
  521. (defconst org-clock-drawer-re
  522. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  523. org-clock-drawer-end-re "\\)\n?")
  524. "Matches an entire clock drawer.")
  525. ;;;; Headline
  526. (defconst org-heading-keyword-regexp-format
  527. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  528. "Printf format for a regexp matching a headline with some keyword.
  529. This regexp will match the headline of any node which has the
  530. exact keyword that is put into the format. The keyword isn't in
  531. any group by default, but the stars and the body are.")
  532. (defconst org-heading-keyword-maybe-regexp-format
  533. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  534. "Printf format for a regexp matching a headline, possibly with some keyword.
  535. This regexp can match any headline with the specified keyword, or
  536. without a keyword. The keyword isn't in any group by default,
  537. but the stars and the body are.")
  538. (defconst org-archive-tag "ARCHIVE"
  539. "The tag that marks a subtree as archived.
  540. An archived subtree does not open during visibility cycling, and does
  541. not contribute to the agenda listings.")
  542. (defconst org-tag-re "[[:alnum:]_@#%]+"
  543. "Regexp matching a single tag.")
  544. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  545. "Regexp matching the tag group at the end of a line, with leading spaces.
  546. Tags are stored in match group 1. Match group 2 stores the tags
  547. without the enclosing colons.")
  548. (defconst org-tag-line-re
  549. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  550. "Regexp matching tags in a headline.
  551. Tags are stored in match group 1. Match group 2 stores the tags
  552. without the enclosing colons.")
  553. (eval-and-compile
  554. (defconst org-comment-string "COMMENT"
  555. "Entries starting with this keyword will never be exported.
  556. \\<org-mode-map>
  557. An entry can be toggled between COMMENT and normal with
  558. `\\[org-toggle-comment]'."))
  559. ;;;; LaTeX Environments and Fragments
  560. (defconst org-latex-regexps
  561. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  562. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  563. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  564. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  565. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  566. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  567. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  568. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  569. "Regular expressions for matching embedded LaTeX.")
  570. ;;;; Node Property
  571. (defconst org-effort-property "Effort"
  572. "The property that is being used to keep track of effort estimates.
  573. Effort estimates given in this property need to be in the format
  574. defined in org-duration.el.")
  575. ;;; The custom variables
  576. (defgroup org nil
  577. "Outline-based notes management and organizer."
  578. :tag "Org"
  579. :group 'outlines
  580. :group 'calendar)
  581. (defcustom org-mode-hook nil
  582. "Mode hook for Org mode, run after the mode was turned on."
  583. :group 'org
  584. :type 'hook)
  585. (defcustom org-load-hook nil
  586. "Hook that is run after org.el has been loaded."
  587. :group 'org
  588. :type 'hook)
  589. (make-obsolete-variable
  590. 'org-load-hook
  591. "use `with-eval-after-load' instead." "9.5")
  592. (defcustom org-log-buffer-setup-hook nil
  593. "Hook that is run after an Org log buffer is created."
  594. :group 'org
  595. :version "24.1"
  596. :type 'hook)
  597. (defvar org-modules) ; defined below
  598. (defvar org-modules-loaded nil
  599. "Have the modules been loaded already?")
  600. ;;;###autoload
  601. (defun org-load-modules-maybe (&optional force)
  602. "Load all extensions listed in `org-modules'."
  603. (when (or force (not org-modules-loaded))
  604. (dolist (ext org-modules)
  605. (condition-case nil (require ext)
  606. (error (message "Problems while trying to load feature `%s'" ext))))
  607. (setq org-modules-loaded t)))
  608. (defun org-set-modules (var value)
  609. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  610. (set-default-toplevel-value var value)
  611. (when (featurep 'org)
  612. (org-load-modules-maybe 'force)
  613. (org-element-cache-reset 'all)))
  614. (defcustom org-modules '(ol-doi ol-w3m ol-bbdb ol-bibtex ol-docview ol-gnus ol-info ol-irc ol-mhe ol-rmail ol-eww)
  615. "Modules that should always be loaded together with org.el.
  616. If a description starts with <C>, the file is not part of Emacs and Org mode,
  617. so loading it will require that you have properly installed org-contrib
  618. package from NonGNU Emacs Lisp Package Archive
  619. https://elpa.nongnu.org/nongnu/org-contrib.html
  620. You can also use this system to load external packages (i.e. neither Org
  621. core modules, nor org-contrib modules). Just add symbols
  622. to the end of the list. If the package is called org-xyz.el, then you need
  623. to add the symbol `xyz', and the package must have a call to:
  624. (provide \\='org-xyz)
  625. For export specific modules, see also `org-export-backends'."
  626. :group 'org
  627. :set 'org-set-modules
  628. :package-version '(Org . "9.5")
  629. :type
  630. '(set :greedy t
  631. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  632. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  633. (const :tag " crypt: Encryption of subtrees" org-crypt)
  634. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  635. (const :tag " docview: Links to Docview buffers" ol-docview)
  636. (const :tag " doi: Links to DOI references" ol-doi)
  637. (const :tag " eww: Store link to URL of Eww" ol-eww)
  638. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  639. (const :tag " habit: Track your consistency with habits" org-habit)
  640. (const :tag " id: Global IDs for identifying entries" org-id)
  641. (const :tag " info: Links to Info nodes" ol-info)
  642. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  643. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  644. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  645. (const :tag " mouse: Additional mouse support" org-mouse)
  646. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  647. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  648. (const :tag " tempo: Fast completion for structures" org-tempo)
  649. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  650. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  651. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  652. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  653. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  654. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  655. (const :tag "C collector: Collect properties into tables" org-collector)
  656. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  657. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  658. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  659. (const :tag "C eval: Include command output as text" org-eval)
  660. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  661. (const :tag "C git-link: Links to specific file version" ol-git-link)
  662. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  663. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  664. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  665. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  666. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  667. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  668. (const :tag "C man: Links to man pages in Org mode" ol-man)
  669. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  670. (const :tag "C notify: Notifications for Org mode" org-notify)
  671. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  672. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  673. (const :tag "C registry: A registry for Org links" org-registry)
  674. (const :tag "C screen: Visit screen sessions through links" org-screen)
  675. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  676. (const :tag "C secretary: Team management with Org" org-secretary)
  677. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  678. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  679. (const :tag "C track: Keep up with Org mode development" org-track)
  680. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  681. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  682. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  683. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  684. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  685. (defvar org-export-registered-backends) ; From ox.el.
  686. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  687. (declare-function org-export-backend-name "ox" (backend) t)
  688. (defcustom org-export-backends '(ascii html icalendar latex odt)
  689. "List of export back-ends that should be always available.
  690. If a description starts with <C>, the file is not part of Emacs and Org mode,
  691. so loading it will require that you have properly installed org-contrib
  692. package from NonGNU Emacs Lisp Package Archive
  693. https://elpa.nongnu.org/nongnu/org-contrib.html
  694. Unlike to `org-modules', libraries in this list will not be
  695. loaded along with Org, but only once the export framework is
  696. needed.
  697. This variable needs to be set before org.el is loaded. If you
  698. need to make a change while Emacs is running, use the customize
  699. interface or run the following code, where VAL stands for the new
  700. value of the variable, after updating it:
  701. (progn
  702. (setq org-export-registered-backends
  703. (cl-remove-if-not
  704. (lambda (backend)
  705. (let ((name (org-export-backend-name backend)))
  706. (or (memq name val)
  707. (catch \\='parentp
  708. (dolist (b val)
  709. (and (org-export-derived-backend-p b name)
  710. (throw \\='parentp t)))))))
  711. org-export-registered-backends))
  712. (let ((new-list (mapcar #\\='org-export-backend-name
  713. org-export-registered-backends)))
  714. (dolist (backend val)
  715. (cond
  716. ((not (load (format \"ox-%s\" backend) t t))
  717. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  718. backend))
  719. ((not (memq backend new-list)) (push backend new-list))))
  720. (set-default \\='org-export-backends new-list)))
  721. Adding a back-end to this list will also pull the back-end it
  722. depends on, if any."
  723. :group 'org
  724. :group 'org-export
  725. :version "26.1"
  726. :package-version '(Org . "9.0")
  727. :initialize 'custom-initialize-set
  728. :set (lambda (var val)
  729. (if (not (featurep 'ox)) (set-default-toplevel-value var val)
  730. ;; Any back-end not required anymore (not present in VAL and not
  731. ;; a parent of any back-end in the new value) is removed from the
  732. ;; list of registered back-ends.
  733. (setq org-export-registered-backends
  734. (cl-remove-if-not
  735. (lambda (backend)
  736. (let ((name (org-export-backend-name backend)))
  737. (or (memq name val)
  738. (catch 'parentp
  739. (dolist (b val)
  740. (and (org-export-derived-backend-p b name)
  741. (throw 'parentp t)))))))
  742. org-export-registered-backends))
  743. ;; Now build NEW-LIST of both new back-ends and required
  744. ;; parents.
  745. (let ((new-list (mapcar #'org-export-backend-name
  746. org-export-registered-backends)))
  747. (dolist (backend val)
  748. (cond
  749. ((not (load (format "ox-%s" backend) t t))
  750. (message "Problems while trying to load export back-end `%s'"
  751. backend))
  752. ((not (memq backend new-list)) (push backend new-list))))
  753. ;; Set VAR to that list with fixed dependencies.
  754. (set-default-toplevel-value var new-list))))
  755. :type '(set :greedy t
  756. (const :tag " ascii Export buffer to ASCII format" ascii)
  757. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  758. (const :tag " html Export buffer to HTML format" html)
  759. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  760. (const :tag " latex Export buffer to LaTeX format" latex)
  761. (const :tag " man Export buffer to MAN format" man)
  762. (const :tag " md Export buffer to Markdown format" md)
  763. (const :tag " odt Export buffer to ODT format" odt)
  764. (const :tag " org Export buffer to Org format" org)
  765. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  766. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  767. (const :tag "C deck Export buffer to deck.js presentations" deck)
  768. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  769. (const :tag "C groff Export buffer to Groff format" groff)
  770. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  771. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  772. (const :tag "C s5 Export buffer to s5 presentations" s5)
  773. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  774. (eval-after-load 'ox
  775. '(dolist (backend org-export-backends)
  776. (condition-case nil (require (intern (format "ox-%s" backend)))
  777. (error (message "Problems while trying to load export back-end `%s'"
  778. backend)))))
  779. (defcustom org-support-shift-select nil
  780. "Non-nil means make shift-cursor commands select text when possible.
  781. \\<org-mode-map>
  782. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  783. start selecting a region, or enlarge regions started in this way.
  784. In Org mode, in special contexts, these same keys are used for
  785. other purposes, important enough to compete with shift selection.
  786. Org tries to balance these needs by supporting `shift-select-mode'
  787. outside these special contexts, under control of this variable.
  788. The default of this variable is nil, to avoid confusing behavior. Shifted
  789. cursor keys will then execute Org commands in the following contexts:
  790. - on a headline, changing TODO state (left/right) and priority (up/down)
  791. - on a time stamp, changing the time
  792. - in a plain list item, changing the bullet type
  793. - in a property definition line, switching between allowed values
  794. - in the BEGIN line of a clock table (changing the time block).
  795. - in a table, moving the cell in the specified direction.
  796. Outside these contexts, the commands will throw an error.
  797. When this variable is t and the cursor is not in a special
  798. context, Org mode will support shift-selection for making and
  799. enlarging regions. To make this more effective, the bullet
  800. cycling will no longer happen anywhere in an item line, but only
  801. if the cursor is exactly on the bullet.
  802. If you set this variable to the symbol `always', then the keys
  803. will not be special in headlines, property lines, item lines, and
  804. table cells, to make shift selection work there as well. If this is
  805. what you want, you can use the following alternative commands:
  806. `\\[org-todo]' and `\\[org-priority]' \
  807. to change TODO state and priority,
  808. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  809. can be used to switch TODO sets,
  810. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  811. and properties can be edited by hand or in column view.
  812. However, when the cursor is on a timestamp, shift-cursor commands
  813. will still edit the time stamp - this is just too good to give up."
  814. :group 'org
  815. :type '(choice
  816. (const :tag "Never" nil)
  817. (const :tag "When outside special context" t)
  818. (const :tag "Everywhere except timestamps" always)))
  819. (defcustom org-loop-over-headlines-in-active-region t
  820. "Shall some commands act upon headlines in the active region?
  821. When set to t, some commands will be performed in all headlines
  822. within the active region.
  823. When set to `start-level', some commands will be performed in all
  824. headlines within the active region, provided that these headlines
  825. are of the same level than the first one.
  826. When set to a string, those commands will be performed on the
  827. matching headlines within the active region. Such string must be
  828. a tags/property/todo match as it is used in the agenda tags view.
  829. The list of commands is: `org-schedule', `org-deadline',
  830. `org-todo', `org-set-tags-command', `org-archive-subtree',
  831. `org-archive-set-tag', `org-toggle-archive-tag' and
  832. `org-archive-to-archive-sibling'. The archiving commands skip
  833. already archived entries.
  834. See `org-agenda-loop-over-headlines-in-active-region' for the
  835. equivalent option for agenda views."
  836. :type '(choice (const :tag "Don't loop" nil)
  837. (const :tag "All headlines in active region" t)
  838. (const :tag "In active region, headlines at the same level than the first one" start-level)
  839. (string :tag "Tags/Property/Todo matcher"))
  840. :package-version '(Org . "9.4")
  841. :group 'org-todo
  842. :group 'org-archive)
  843. (defcustom org-startup-folded 'showeverything
  844. "Non-nil means entering Org mode will switch to OVERVIEW.
  845. This can also be configured on a per-file basis by adding one of
  846. the following lines anywhere in the buffer:
  847. #+STARTUP: fold (or `overview', this is equivalent)
  848. #+STARTUP: nofold (or `showall', this is equivalent)
  849. #+STARTUP: content
  850. #+STARTUP: show<n>levels (<n> = 2..5)
  851. #+STARTUP: showeverything
  852. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  853. to ignore this option when Org opens agenda files for the first
  854. time."
  855. :group 'org-startup
  856. :package-version '(Org . "9.4")
  857. :type '(choice
  858. (const :tag "nofold: show all" nil)
  859. (const :tag "fold: overview" t)
  860. (const :tag "fold: show two levels" show2levels)
  861. (const :tag "fold: show three levels" show3levels)
  862. (const :tag "fold: show four levels" show4evels)
  863. (const :tag "fold: show five levels" show5levels)
  864. (const :tag "content: all headlines" content)
  865. (const :tag "show everything, even drawers" showeverything)))
  866. (defcustom org-startup-truncated t
  867. "Non-nil means entering Org mode will set `truncate-lines'.
  868. This is useful since some lines containing links can be very long and
  869. uninteresting. Also tables look terrible when wrapped.
  870. The variable `org-startup-truncated' allows to configure
  871. truncation for Org mode different to the other modes that use the
  872. variable `truncate-lines' and as a shortcut instead of putting
  873. the variable `truncate-lines' into the `org-mode-hook'. If one
  874. wants to configure truncation for Org mode not statically but
  875. dynamically e.g. in a hook like `ediff-prepare-buffer-hook' then
  876. the variable `truncate-lines' has to be used because in such a
  877. case it is too late to set the variable `org-startup-truncated'."
  878. :group 'org-startup
  879. :type 'boolean)
  880. (defcustom org-startup-indented nil
  881. "Non-nil means turn on `org-indent-mode' on startup.
  882. This can also be configured on a per-file basis by adding one of
  883. the following lines anywhere in the buffer:
  884. #+STARTUP: indent
  885. #+STARTUP: noindent"
  886. :group 'org-structure
  887. :type '(choice
  888. (const :tag "Not" nil)
  889. (const :tag "Globally (slow on startup in large files)" t)))
  890. (defcustom org-startup-numerated nil
  891. "Non-nil means turn on `org-num-mode' on startup.
  892. This can also be configured on a per-file basis by adding one of
  893. the following lines anywhere in the buffer:
  894. #+STARTUP: num
  895. #+STARTUP: nonum"
  896. :group 'org-structure
  897. :package-version '(Org . "9.4")
  898. :type '(choice
  899. (const :tag "Not" nil)
  900. (const :tag "Globally" t)))
  901. (defcustom org-use-sub-superscripts t
  902. "Non-nil means interpret \"_\" and \"^\" for display.
  903. If you want to control how Org exports those characters, see
  904. `org-export-with-sub-superscripts'.
  905. When this option is turned on, you can use TeX-like syntax for
  906. sub- and superscripts within the buffer. Several characters after
  907. \"_\" or \"^\" will be considered as a single item - so grouping
  908. with {} is normally not needed. For example, the following things
  909. will be parsed as single sub- or superscripts:
  910. 10^24 or 10^tau several digits will be considered 1 item.
  911. 10^-12 or 10^-tau a leading sign with digits or a word
  912. x^2-y^3 will be read as x^2 - y^3, because items are
  913. terminated by almost any nonword/nondigit char.
  914. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  915. Still, ambiguity is possible. So when in doubt, use {} to enclose
  916. the sub/superscript. If you set this variable to the symbol `{}',
  917. the braces are *required* in order to trigger interpretations as
  918. sub/superscript. This can be helpful in documents that need \"_\"
  919. frequently in plain text."
  920. :group 'org-startup
  921. :version "24.4"
  922. :package-version '(Org . "8.0")
  923. :type '(choice
  924. (const :tag "Always interpret" t)
  925. (const :tag "Only with braces" {})
  926. (const :tag "Never interpret" nil)))
  927. (defcustom org-startup-with-beamer-mode nil
  928. "Non-nil means turn on `org-beamer-mode' on startup.
  929. This can also be configured on a per-file basis by adding one of
  930. the following lines anywhere in the buffer:
  931. #+STARTUP: beamer"
  932. :group 'org-startup
  933. :version "24.1"
  934. :type 'boolean)
  935. (defcustom org-startup-align-all-tables nil
  936. "Non-nil means align all tables when visiting a file.
  937. This can also be configured on a per-file basis by adding one of
  938. the following lines anywhere in the buffer:
  939. #+STARTUP: align
  940. #+STARTUP: noalign"
  941. :group 'org-startup
  942. :type 'boolean)
  943. (defcustom org-startup-shrink-all-tables nil
  944. "Non-nil means shrink all table columns with a width cookie.
  945. This can also be configured on a per-file basis by adding one of
  946. the following lines anywhere in the buffer:
  947. #+STARTUP: shrink"
  948. :group 'org-startup
  949. :type 'boolean
  950. :version "27.1"
  951. :package-version '(Org . "9.2")
  952. :safe #'booleanp)
  953. (defcustom org-startup-with-inline-images nil
  954. "Non-nil means show inline images when loading a new Org file.
  955. This can also be configured on a per-file basis by adding one of
  956. the following lines anywhere in the buffer:
  957. #+STARTUP: inlineimages
  958. #+STARTUP: noinlineimages"
  959. :group 'org-startup
  960. :version "24.1"
  961. :type 'boolean)
  962. (defcustom org-startup-with-latex-preview nil
  963. "Non-nil means preview LaTeX fragments when loading a new Org file.
  964. This can also be configured on a per-file basis by adding one of
  965. the following lines anywhere in the buffer:
  966. #+STARTUP: latexpreview
  967. #+STARTUP: nolatexpreview"
  968. :group 'org-startup
  969. :version "24.4"
  970. :package-version '(Org . "8.0")
  971. :type 'boolean)
  972. (defcustom org-insert-mode-line-in-empty-file nil
  973. "Non-nil means insert the first line setting Org mode in empty files.
  974. When the function `org-mode' is called interactively in an empty file, this
  975. normally means that the file name does not automatically trigger Org mode.
  976. To ensure that the file will always be in Org mode in the future, a
  977. line enforcing Org mode will be inserted into the buffer, if this option
  978. has been set."
  979. :group 'org-startup
  980. :type 'boolean)
  981. (defcustom org-ellipsis nil
  982. "The ellipsis to use in the Org mode outline.
  983. When nil, just use the standard three dots. When a non-empty string,
  984. use that string instead.
  985. The change affects only Org mode (which will then use its own display table).
  986. Changing this requires executing `\\[org-mode]' in a buffer to become
  987. effective. It cannot be set as a local variable."
  988. :group 'org-startup
  989. :type '(choice (const :tag "Default" nil)
  990. (string :tag "String" :value "...#")))
  991. (defvar org-display-table nil
  992. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  993. (defcustom org-directory "~/org"
  994. "Directory with Org files.
  995. This is just a default location to look for Org files. There is no need
  996. at all to put your files into this directory. It is used in the
  997. following situations:
  998. 1. When a capture template specifies a target file that is not an
  999. absolute path. The path will then be interpreted relative to
  1000. `org-directory'
  1001. 2. When the value of variable `org-agenda-files' is a single file, any
  1002. relative paths in this file will be taken as relative to
  1003. `org-directory'."
  1004. :group 'org-refile
  1005. :group 'org-capture
  1006. :type 'directory)
  1007. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  1008. "Default target for storing notes.
  1009. Used as a fall back file for org-capture.el, for templates that
  1010. do not specify a target file."
  1011. :group 'org-refile
  1012. :group 'org-capture
  1013. :type 'file)
  1014. (defcustom org-reverse-note-order nil
  1015. "Non-nil means store new notes at the beginning of a file or entry.
  1016. When nil, new notes will be filed to the end of a file or entry.
  1017. This can also be a list with cons cells of regular expressions that
  1018. are matched against file names, and values."
  1019. :group 'org-capture
  1020. :group 'org-refile
  1021. :type '(choice
  1022. (const :tag "Reverse always" t)
  1023. (const :tag "Reverse never" nil)
  1024. (repeat :tag "By file name regexp"
  1025. (cons regexp boolean))))
  1026. (defgroup org-keywords nil
  1027. "Keywords in Org mode."
  1028. :tag "Org Keywords"
  1029. :group 'org)
  1030. (defcustom org-closed-keep-when-no-todo nil
  1031. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  1032. :group 'org-todo
  1033. :group 'org-keywords
  1034. :version "24.4"
  1035. :package-version '(Org . "8.0")
  1036. :type 'boolean)
  1037. (defgroup org-structure nil
  1038. "Options concerning the general structure of Org files."
  1039. :tag "Org Structure"
  1040. :group 'org)
  1041. (defcustom org-indirect-buffer-display 'other-window
  1042. "How should indirect tree buffers be displayed?
  1043. This applies to indirect buffers created with the commands
  1044. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1045. Valid values are:
  1046. current-window Display in the current window
  1047. other-window Just display in another window.
  1048. dedicated-frame Create one new frame, and re-use it each time.
  1049. new-frame Make a new frame each time. Note that in this case
  1050. previously-made indirect buffers are kept, and you need to
  1051. kill these buffers yourself."
  1052. :group 'org-structure
  1053. :group 'org-agenda-windows
  1054. :type '(choice
  1055. (const :tag "In current window" current-window)
  1056. (const :tag "In current frame, other window" other-window)
  1057. (const :tag "Each time a new frame" new-frame)
  1058. (const :tag "One dedicated frame" dedicated-frame)))
  1059. (defconst org-file-apps-gnu
  1060. '((remote . emacs)
  1061. (system . mailcap)
  1062. (t . mailcap))
  1063. "Default file applications on a UNIX or GNU/Linux system.
  1064. See `org-file-apps'.")
  1065. (defconst org-file-apps-macos
  1066. '((remote . emacs)
  1067. (system . "open %s")
  1068. ("ps.gz" . "gv %s")
  1069. ("eps.gz" . "gv %s")
  1070. ("dvi" . "xdvi %s")
  1071. ("fig" . "xfig %s")
  1072. (t . "open %s"))
  1073. "Default file applications on a macOS system.
  1074. The system \"open\" is known as a default, but we use X11 applications
  1075. for some files for which the OS does not have a good default.
  1076. See `org-file-apps'.")
  1077. (defconst org-file-apps-windowsnt
  1078. (list '(remote . emacs)
  1079. (cons 'system (lambda (file _path)
  1080. (with-no-warnings (w32-shell-execute "open" file))))
  1081. (cons t (lambda (file _path)
  1082. (with-no-warnings (w32-shell-execute "open" file)))))
  1083. "Default file applications on a Windows NT system.
  1084. The system \"open\" is used for most files.
  1085. See `org-file-apps'.")
  1086. (defcustom org-file-apps
  1087. '((auto-mode . emacs)
  1088. (directory . emacs)
  1089. ("\\.mm\\'" . default)
  1090. ("\\.x?html?\\'" . default)
  1091. ("\\.pdf\\'" . default))
  1092. "Applications for opening `file:path' items in a document.
  1093. \\<org-mode-map>
  1094. Org mode uses system defaults for different file types, but you
  1095. can use this variable to set the application for a given file
  1096. extension. The entries in this list are cons cells where the car
  1097. identifies files and the cdr the corresponding command.
  1098. Possible values for the file identifier are:
  1099. \"string\" A string as a file identifier can be interpreted in different
  1100. ways, depending on its contents:
  1101. - Alphanumeric characters only:
  1102. Match links with this file extension.
  1103. Example: (\"pdf\" . \"evince %s\")
  1104. to open PDFs with evince.
  1105. - Regular expression: Match links where the
  1106. filename matches the regexp. If you want to
  1107. use groups here, use shy groups.
  1108. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1109. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1110. to open *.html and *.xhtml with firefox.
  1111. - Regular expression which contains (non-shy) groups:
  1112. Match links where the whole link, including \"::\", and
  1113. anything after that, matches the regexp.
  1114. In a custom command string, %1, %2, etc. are replaced with
  1115. the parts of the link that were matched by the groups.
  1116. For backwards compatibility, if a command string is given
  1117. that does not use any of the group matches, this case is
  1118. handled identically to the second one (i.e. match against
  1119. file name only).
  1120. In a custom function, you can access the group matches with
  1121. (match-string n link).
  1122. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1123. \"evince -p %1 %s\")
  1124. to open [[file:document.pdf::5]] with evince at page 5.
  1125. Likely, you will need more entries: without page
  1126. number; with search pattern; with cross-reference
  1127. anchor; some combination of options. Consider simple
  1128. pattern here and a Lisp function to determine command
  1129. line arguments instead. Passing argument list to
  1130. `call-process' or `make-process' directly allows to
  1131. avoid treating some character in peculiar file names
  1132. as shell specialls causing executing part of file
  1133. name as a subcommand.
  1134. `directory' Matches a directory
  1135. `remote' Matches a remote file, accessible through tramp or efs.
  1136. Remote files most likely should be visited through Emacs
  1137. because external applications cannot handle such paths.
  1138. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1139. so all files Emacs knows how to handle. Using this with
  1140. command `emacs' will open most files in Emacs. Beware that this
  1141. will also open html files inside Emacs, unless you add
  1142. (\"html\" . default) to the list as well.
  1143. `system' The system command to open files, like `open' on Windows
  1144. and macOS, and mailcap under GNU/Linux. This is the command
  1145. that will be selected if you call `org-open-at-point' with a
  1146. double prefix argument (`\\[universal-argument] \
  1147. \\[universal-argument] \\[org-open-at-point]').
  1148. t Default for files not matched by any of the other options.
  1149. Possible values for the command are:
  1150. `emacs' The file will be visited by the current Emacs process.
  1151. `default' Use the default application for this file type, which is the
  1152. association for t in the list, most likely in the system-specific
  1153. part. This can be used to overrule an unwanted setting in the
  1154. system-specific variable.
  1155. `system' Use the system command for opening files, like \"open\".
  1156. This command is specified by the entry whose car is `system'.
  1157. Most likely, the system-specific version of this variable
  1158. does define this command, but you can overrule/replace it
  1159. here.
  1160. `mailcap' Use command specified in the mailcaps.
  1161. string A command to be executed by a shell; %s will be replaced
  1162. by the path to the file.
  1163. function A Lisp function, which will be called with two arguments:
  1164. the file path and the original link string, without the
  1165. \"file:\" prefix.
  1166. For more examples, see the system specific constants
  1167. `org-file-apps-macos'
  1168. `org-file-apps-windowsnt'
  1169. `org-file-apps-gnu'."
  1170. :group 'org
  1171. :package-version '(Org . "9.4")
  1172. :type '(repeat
  1173. (cons (choice :value ""
  1174. (string :tag "Extension")
  1175. (const :tag "System command to open files" system)
  1176. (const :tag "Default for unrecognized files" t)
  1177. (const :tag "Remote file" remote)
  1178. (const :tag "Links to a directory" directory)
  1179. (const :tag "Any files that have Emacs modes"
  1180. auto-mode))
  1181. (choice :value ""
  1182. (const :tag "Visit with Emacs" emacs)
  1183. (const :tag "Use default" default)
  1184. (const :tag "Use the system command" system)
  1185. (string :tag "Command")
  1186. (function :tag "Function")))))
  1187. (defcustom org-resource-download-policy 'prompt
  1188. "The policy applied to requests to obtain remote resources.
  1189. This affects keywords like #+setupfile and #+incude on export,
  1190. `org-persist-write:url',and `org-attach-url' in non-interactive
  1191. Emacs sessions.
  1192. This recognises four possible values:
  1193. - t, remote resources should always be downloaded.
  1194. - prompt, you will be prompted to download resources nt considered safe.
  1195. - safe, only resources considered safe will be downloaded.
  1196. - nil, never download remote resources.
  1197. A resource is considered safe if it matches one of the patterns
  1198. in `org-safe-remote-resources'."
  1199. :group 'org
  1200. :type '(choice (const :tag "Always download remote resources" t)
  1201. (const :tag "Prompt before downloading an unsafe resource" prompt)
  1202. (const :tag "Only download resources considered safe" safe)
  1203. (const :tag "Never download any resources" nil)))
  1204. (defcustom org-safe-remote-resources nil
  1205. "A list of regexp patterns matching safe URIs.
  1206. URI regexps are applied to both URLs and Org files requesting
  1207. remote resources."
  1208. :group 'org
  1209. :type '(list regexp))
  1210. (defcustom org-open-non-existing-files nil
  1211. "Non-nil means `org-open-file' opens non-existing files.
  1212. When nil, an error is thrown.
  1213. This variable applies only to external applications because they
  1214. might choke on non-existing files. If the link is to a file that
  1215. will be opened in Emacs, the variable is ignored."
  1216. :group 'org
  1217. :type 'boolean
  1218. :safe #'booleanp)
  1219. (defcustom org-open-directory-means-index-dot-org nil
  1220. "When non-nil a link to a directory really means to \"index.org\".
  1221. When nil, following a directory link runs Dired or opens
  1222. a finder/explorer window on that directory."
  1223. :group 'org
  1224. :type 'boolean
  1225. :safe #'booleanp)
  1226. (defcustom org-bookmark-names-plist
  1227. '(:last-capture "org-capture-last-stored"
  1228. :last-refile "org-refile-last-stored"
  1229. :last-capture-marker "org-capture-last-stored-marker")
  1230. "Names for bookmarks automatically set by some Org commands.
  1231. This can provide strings as names for a number of bookmarks Org sets
  1232. automatically. The following keys are currently implemented:
  1233. :last-capture
  1234. :last-capture-marker
  1235. :last-refile
  1236. When a key does not show up in the property list, the corresponding bookmark
  1237. is not set."
  1238. :group 'org-structure
  1239. :type 'plist)
  1240. (defgroup org-edit-structure nil
  1241. "Options concerning structure editing in Org mode."
  1242. :tag "Org Edit Structure"
  1243. :group 'org-structure)
  1244. (defcustom org-odd-levels-only nil
  1245. "Non-nil means skip even levels and only use odd levels for the outline.
  1246. This has the effect that two stars are being added/taken away in
  1247. promotion/demotion commands. It also influences how levels are
  1248. handled by the exporters.
  1249. Changing it requires restart of `font-lock-mode' to become effective
  1250. for fontification also in regions already fontified.
  1251. You may also set this on a per-file basis by adding one of the following
  1252. lines to the buffer:
  1253. #+STARTUP: odd
  1254. #+STARTUP: oddeven"
  1255. :group 'org-edit-structure
  1256. :group 'org-appearance
  1257. :type 'boolean)
  1258. (defcustom org-adapt-indentation nil
  1259. "Non-nil means adapt indentation to outline node level.
  1260. When set to t, Org assumes that you write outlines by indenting
  1261. text in each node to align with the headline, after the stars.
  1262. When this variable is set to `headline-data', Org only adapts the
  1263. indentation of the data lines right below the headline, such as
  1264. planning/clock lines and property/logbook drawers.
  1265. The following issues are influenced by this variable:
  1266. - The indentation is increased by one space in a demotion
  1267. command, and decreased by one in a promotion command. However,
  1268. in the latter case, if shifting some line in the entry body
  1269. would alter document structure (e.g., insert a new headline),
  1270. indentation is not changed at all.
  1271. - Property drawers and planning information is inserted indented
  1272. when this variable is set. When nil, they will not be indented.
  1273. - TAB indents a line relative to current level. The lines below
  1274. a headline will be indented when this variable is set to t.
  1275. Note that this is all about true indentation, by adding and
  1276. removing space characters. See also \"org-indent.el\" which does
  1277. level-dependent indentation in a virtual way, i.e. at display
  1278. time in Emacs."
  1279. :group 'org-edit-structure
  1280. :type '(choice
  1281. (const :tag "Adapt indentation for all lines" t)
  1282. (const :tag "Adapt indentation for headline data lines"
  1283. headline-data)
  1284. (const :tag "Do not adapt indentation at all" nil))
  1285. :safe (lambda (x) (memq x '(t nil headline-data))))
  1286. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1287. (defcustom org-special-ctrl-a/e nil
  1288. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1289. When t, `C-a' will bring back the cursor to the beginning of the
  1290. headline text, i.e. after the stars and after a possible TODO
  1291. keyword. In an item, this will be the position after bullet and
  1292. check-box, if any. When the cursor is already at that position,
  1293. another `C-a' will bring it to the beginning of the line.
  1294. `C-e' will jump to the end of the headline, ignoring the presence
  1295. of tags in the headline. A second `C-e' will then jump to the
  1296. true end of the line, after any tags. This also means that, when
  1297. this variable is non-nil, `C-e' also will never jump beyond the
  1298. end of the heading of a folded section, i.e. not after the
  1299. ellipses.
  1300. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1301. normally, going to the true line boundary first. Only a directly
  1302. following, identical keypress will bring the cursor to the
  1303. special positions.
  1304. This may also be a cons cell where the behavior for `C-a' and
  1305. `C-e' is set separately."
  1306. :group 'org-edit-structure
  1307. :type '(choice
  1308. (const :tag "off" nil)
  1309. (const :tag "on: after stars/bullet and before tags first" t)
  1310. (const :tag "reversed: true line boundary first" reversed)
  1311. (cons :tag "Set C-a and C-e separately"
  1312. (choice :tag "Special C-a"
  1313. (const :tag "off" nil)
  1314. (const :tag "on: after stars/bullet first" t)
  1315. (const :tag "reversed: before stars/bullet first" reversed))
  1316. (choice :tag "Special C-e"
  1317. (const :tag "off" nil)
  1318. (const :tag "on: before tags first" t)
  1319. (const :tag "reversed: after tags first" reversed)))))
  1320. (defcustom org-special-ctrl-k nil
  1321. "Non-nil means `C-k' will behave specially in headlines.
  1322. When nil, `C-k' will call the default `kill-line' command.
  1323. When t, the following will happen while the cursor is in the headline:
  1324. - When at the beginning of a headline, kill the entire subtree.
  1325. - When in the middle of the headline text, kill the text up to the tags.
  1326. - When after the headline text and before the tags, kill all the tags."
  1327. :group 'org-edit-structure
  1328. :type 'boolean)
  1329. (defcustom org-ctrl-k-protect-subtree nil
  1330. "Non-nil means, do not delete a hidden subtree with `C-k'.
  1331. When set to the symbol `error', simply throw an error when `C-k' is
  1332. used to kill (part-of) a headline that has hidden text behind it.
  1333. Any other non-nil value will result in a query to the user, if it is
  1334. OK to kill that hidden subtree. When nil, kill without remorse."
  1335. :group 'org-edit-structure
  1336. :version "24.1"
  1337. :type '(choice
  1338. (const :tag "Do not protect hidden subtrees" nil)
  1339. (const :tag "Protect hidden subtrees with a security query" t)
  1340. (const :tag "Never kill a hidden subtree with C-k" error)))
  1341. (defcustom org-special-ctrl-o t
  1342. "Non-nil means, make `open-line' (\\[open-line]) insert a row in tables."
  1343. :group 'org-edit-structure
  1344. :type 'boolean)
  1345. (defcustom org-yank-folded-subtrees t
  1346. "Non-nil means when yanking subtrees, fold them.
  1347. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1348. it starts with a heading and all other headings in it are either children
  1349. or siblings, then fold all the subtrees. However, do this only if no
  1350. text after the yank would be swallowed into a folded tree by this action."
  1351. :group 'org-edit-structure
  1352. :type 'boolean)
  1353. (defcustom org-yank-adjusted-subtrees nil
  1354. "Non-nil means when yanking subtrees, adjust the level.
  1355. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1356. this function for details."
  1357. :group 'org-edit-structure
  1358. :type 'boolean)
  1359. (defcustom org-M-RET-may-split-line '((default . t))
  1360. "Non-nil means M-RET will split the line at the cursor position.
  1361. When nil, it will go to the end of the line before making a
  1362. new line.
  1363. You may also set this option in a different way for different
  1364. contexts. Valid contexts are:
  1365. headline when creating a new headline
  1366. item when creating a new item
  1367. table in a table field
  1368. default the value to be used for all contexts not explicitly
  1369. customized"
  1370. :group 'org-structure
  1371. :group 'org-table
  1372. :type '(choice
  1373. (const :tag "Always" t)
  1374. (const :tag "Never" nil)
  1375. (repeat :greedy t :tag "Individual contexts"
  1376. (cons
  1377. (choice :tag "Context"
  1378. (const headline)
  1379. (const item)
  1380. (const table)
  1381. (const default))
  1382. (boolean)))))
  1383. (defcustom org-insert-heading-respect-content nil
  1384. "Non-nil means insert new headings after the current subtree.
  1385. \\<org-mode-map>
  1386. When nil, the new heading is created directly after the current line.
  1387. The commands `\\[org-insert-heading-respect-content]' and \
  1388. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1389. for the duration of the command."
  1390. :group 'org-structure
  1391. :type 'boolean)
  1392. (defcustom org-blank-before-new-entry '((heading . auto)
  1393. (plain-list-item . auto))
  1394. "Should `org-insert-heading' leave a blank line before new heading/item?
  1395. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1396. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1397. which case Org will look at the surrounding headings/items and try to
  1398. make an intelligent decision whether to insert a blank line or not."
  1399. :group 'org-edit-structure
  1400. :type '(list
  1401. (cons (const heading)
  1402. (choice (const :tag "Never" nil)
  1403. (const :tag "Always" t)
  1404. (const :tag "Auto" auto)))
  1405. (cons (const plain-list-item)
  1406. (choice (const :tag "Never" nil)
  1407. (const :tag "Always" t)
  1408. (const :tag "Auto" auto)))))
  1409. (defcustom org-insert-heading-hook nil
  1410. "Hook being run after inserting a new heading."
  1411. :group 'org-edit-structure
  1412. :type 'hook)
  1413. (defgroup org-sparse-trees nil
  1414. "Options concerning sparse trees in Org mode."
  1415. :tag "Org Sparse Trees"
  1416. :group 'org-structure)
  1417. (defcustom org-highlight-sparse-tree-matches t
  1418. "Non-nil means highlight all matches that define a sparse tree.
  1419. The highlights will automatically disappear the next time the buffer is
  1420. changed by an edit command."
  1421. :group 'org-sparse-trees
  1422. :type 'boolean)
  1423. (defcustom org-remove-highlights-with-change t
  1424. "Non-nil means any change to the buffer will remove temporary highlights.
  1425. \\<org-mode-map>\
  1426. Such highlights are created by `org-occur' and `org-clock-display'.
  1427. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1428. to get rid of the highlights.
  1429. The highlights created by `org-latex-preview' always need
  1430. `\\[org-latex-preview]' to be removed."
  1431. :group 'org-sparse-trees
  1432. :group 'org-time
  1433. :type 'boolean)
  1434. (defcustom org-occur-case-fold-search t
  1435. "Non-nil means `org-occur' should be case-insensitive.
  1436. If set to `smart' the search will be case-insensitive only if it
  1437. doesn't specify any upper case character."
  1438. :group 'org-sparse-trees
  1439. :version "26.1"
  1440. :type '(choice
  1441. (const :tag "Case-sensitive" nil)
  1442. (const :tag "Case-insensitive" t)
  1443. (const :tag "Case-insensitive for lower case searches only" smart)))
  1444. (defcustom org-occur-hook '(org-first-headline-recenter)
  1445. "Hook that is run after `org-occur' has constructed a sparse tree.
  1446. This can be used to recenter the window to show as much of the structure
  1447. as possible."
  1448. :group 'org-sparse-trees
  1449. :type 'hook)
  1450. (defcustom org-self-insert-cluster-for-undo nil
  1451. "Non-nil means cluster self-insert commands for undo when possible.
  1452. If this is set, then, like in the Emacs command loop, 20 consecutive
  1453. characters will be undone together.
  1454. This is configurable, because there is some impact on typing performance."
  1455. :group 'org-table
  1456. :type 'boolean)
  1457. (defvaralias 'org-activate-links 'org-highlight-links)
  1458. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1459. "Types of links that should be highlighted in Org files.
  1460. This is a list of symbols, each one of them leading to the
  1461. highlighting of a certain link type.
  1462. You can still open links that are not highlighted.
  1463. In principle, it does not hurt to turn on highlighting for all
  1464. link types. There may be a small gain when turning off unused
  1465. link types. The types are:
  1466. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1467. angle Links in angular brackets that may contain whitespace like
  1468. <bbdb:Carsten Dominik>.
  1469. plain Plain links in normal text, no whitespace, like https://gnu.org.
  1470. radio Text that is matched by a radio target, see manual for details.
  1471. tag Tag settings in a headline (link to tag search).
  1472. date Time stamps (link to calendar).
  1473. footnote Footnote labels.
  1474. If you set this variable during an Emacs session, use `org-mode-restart'
  1475. in the Org buffer so that the change takes effect."
  1476. :group 'org-appearance
  1477. :type '(set :greedy t
  1478. (const :tag "Double bracket links" bracket)
  1479. (const :tag "Angular bracket links" angle)
  1480. (const :tag "Plain text links" plain)
  1481. (const :tag "Radio target matches" radio)
  1482. (const :tag "Tags" tag)
  1483. (const :tag "Timestamps" date)
  1484. (const :tag "Footnotes" footnote)))
  1485. (defcustom org-mark-ring-length 4
  1486. "Number of different positions to be recorded in the ring.
  1487. Changing this requires a restart of Emacs to work correctly."
  1488. :group 'org-link-follow
  1489. :type 'integer)
  1490. (defgroup org-todo nil
  1491. "Options concerning TODO items in Org mode."
  1492. :tag "Org TODO"
  1493. :group 'org)
  1494. (defgroup org-progress nil
  1495. "Options concerning Progress logging in Org mode."
  1496. :tag "Org Progress"
  1497. :group 'org-time)
  1498. (defvar org-todo-interpretation-widgets
  1499. '((:tag "Sequence (cycling hits every state)" sequence)
  1500. (:tag "Type (cycling directly to DONE)" type))
  1501. "The available interpretation symbols for customizing `org-todo-keywords'.
  1502. Interested libraries should add to this list.")
  1503. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1504. "List of TODO entry keyword sequences and their interpretation.
  1505. \\<org-mode-map>This is a list of sequences.
  1506. Each sequence starts with a symbol, either `sequence' or `type',
  1507. indicating if the keywords should be interpreted as a sequence of
  1508. action steps, or as different types of TODO items. The first
  1509. keywords are states requiring action - these states will select a headline
  1510. for inclusion into the global TODO list Org produces. If one of the
  1511. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1512. signify that no further action is necessary. If \"|\" is not found,
  1513. the last keyword is treated as the only DONE state of the sequence.
  1514. The command `\\[org-todo]' cycles an entry through these states, and one
  1515. additional state where no keyword is present. For details about this
  1516. cycling, see the manual.
  1517. TODO keywords and interpretation can also be set on a per-file basis with
  1518. the special #+SEQ_TODO and #+TYP_TODO lines.
  1519. Each keyword can optionally specify a character for fast state selection
  1520. \(in combination with the variable `org-use-fast-todo-selection')
  1521. and specifiers for state change logging, using the same syntax that
  1522. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1523. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1524. indicates to record a time stamp each time this state is selected.
  1525. Each keyword may also specify if a timestamp or a note should be
  1526. recorded when entering or leaving the state, by adding additional
  1527. characters in the parenthesis after the keyword. This looks like this:
  1528. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1529. record only the time of the state change. With X and Y being either
  1530. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1531. Y when leaving the state if and only if the *target* state does not
  1532. define X. You may omit any of the fast-selection key or X or /Y,
  1533. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1534. For backward compatibility, this variable may also be just a list
  1535. of keywords. In this case the interpretation (sequence or type) will be
  1536. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1537. :group 'org-todo
  1538. :group 'org-keywords
  1539. :type '(choice
  1540. (repeat :tag "Old syntax, just keywords"
  1541. (string :tag "Keyword"))
  1542. (repeat :tag "New syntax"
  1543. (cons
  1544. (choice
  1545. :tag "Interpretation"
  1546. ;;Quick and dirty way to see
  1547. ;;`org-todo-interpretation'. This takes the
  1548. ;;place of item arguments
  1549. :convert-widget
  1550. (lambda (widget)
  1551. (widget-put widget
  1552. :args (mapcar
  1553. (lambda (x)
  1554. (widget-convert
  1555. (cons 'const x)))
  1556. org-todo-interpretation-widgets))
  1557. widget))
  1558. (repeat
  1559. (string :tag "Keyword"))))))
  1560. (defvar-local org-todo-keywords-1 nil
  1561. "All TODO and DONE keywords active in a buffer.")
  1562. (defvar org-todo-keywords-for-agenda nil)
  1563. (defvar org-done-keywords-for-agenda nil)
  1564. (defvar org-todo-keyword-alist-for-agenda nil)
  1565. (defvar org-tag-alist-for-agenda nil
  1566. "Alist of all tags from all agenda files.")
  1567. (defvar org-tag-groups-alist-for-agenda nil
  1568. "Alist of all groups tags from all current agenda files.")
  1569. (defvar-local org-tag-groups-alist nil)
  1570. (defvar org-agenda-contributing-files nil)
  1571. (defvar-local org-current-tag-alist nil
  1572. "Alist of all tag groups in current buffer.
  1573. This variable takes into consideration `org-tag-alist',
  1574. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1575. (defvar-local org-not-done-keywords nil)
  1576. (defvar-local org-done-keywords nil)
  1577. (defvar-local org-todo-heads nil)
  1578. (defvar-local org-todo-sets nil)
  1579. (defvar-local org-todo-log-states nil)
  1580. (defvar-local org-todo-kwd-alist nil)
  1581. (defvar-local org-todo-key-alist nil)
  1582. (defvar-local org-todo-key-trigger nil)
  1583. (defcustom org-todo-interpretation 'sequence
  1584. "Controls how TODO keywords are interpreted.
  1585. This variable is in principle obsolete and is only used for
  1586. backward compatibility, if the interpretation of todo keywords is
  1587. not given already in `org-todo-keywords'. See that variable for
  1588. more information."
  1589. :group 'org-todo
  1590. :group 'org-keywords
  1591. :type '(choice (const sequence)
  1592. (const type)))
  1593. (defcustom org-use-fast-todo-selection 'auto
  1594. "\\<org-mode-map>\
  1595. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1596. This variable describes if and under what circumstances the cycling
  1597. mechanism for TODO keywords will be replaced by a single-key, direct
  1598. selection scheme, where the choices are displayed in a little window.
  1599. When nil, fast selection is never used. This means that the command
  1600. will always switch to the next state.
  1601. When it is the symbol `auto', fast selection is whenever selection
  1602. keys have been defined.
  1603. `expert' is like `auto', but no special window with the keyword
  1604. will be shown, choices will only be listed in the prompt.
  1605. In all cases, the special interface is only used if access keys have
  1606. actually been assigned by the user, i.e. if keywords in the configuration
  1607. are followed by a letter in parenthesis, like TODO(t)."
  1608. :group 'org-todo
  1609. :set (lambda (var val)
  1610. (cond
  1611. ((eq var t) (set-default-toplevel-value var 'auto))
  1612. ((eq var 'prefix) (set-default-toplevel-value var nil))
  1613. (t (set-default-toplevel-value var val))))
  1614. :type '(choice
  1615. (const :tag "Never" nil)
  1616. (const :tag "Automatically, when key letter have been defined" auto)
  1617. (const :tag "Automatically, but don't show the selection window" expert)))
  1618. (defcustom org-provide-todo-statistics t
  1619. "Non-nil means update todo statistics after insert and toggle.
  1620. ALL-HEADLINES means update todo statistics by including headlines
  1621. with no TODO keyword as well, counting them as not done.
  1622. A list of TODO keywords means the same, but skip keywords that are
  1623. not in this list.
  1624. When set to a list of two lists, the first list contains keywords
  1625. to consider as TODO keywords, the second list contains keywords
  1626. to consider as DONE keywords.
  1627. When this is set, todo statistics is updated in the parent of the
  1628. current entry each time a todo state is changed."
  1629. :group 'org-todo
  1630. :type '(choice
  1631. (const :tag "Yes, only for TODO entries" t)
  1632. (const :tag "Yes, including all entries" all-headlines)
  1633. (repeat :tag "Yes, for TODOs in this list"
  1634. (string :tag "TODO keyword"))
  1635. (list :tag "Yes, for TODOs and DONEs in these lists"
  1636. (repeat (string :tag "TODO keyword"))
  1637. (repeat (string :tag "DONE keyword")))
  1638. (other :tag "No TODO statistics" nil)))
  1639. (defcustom org-hierarchical-todo-statistics t
  1640. "Non-nil means TODO statistics covers just direct children.
  1641. When nil, all entries in the subtree are considered.
  1642. This has only an effect if `org-provide-todo-statistics' is set.
  1643. To set this to nil for only a single subtree, use a COOKIE_DATA
  1644. property and include the word \"recursive\" into the value."
  1645. :group 'org-todo
  1646. :type 'boolean)
  1647. (defcustom org-after-todo-state-change-hook nil
  1648. "Hook which is run after the state of a TODO item was changed.
  1649. The new state (a string with a TODO keyword, or nil) is available in the
  1650. Lisp variable `org-state'."
  1651. :group 'org-todo
  1652. :type 'hook)
  1653. (defvar org-blocker-hook nil
  1654. "Hook for functions that are allowed to block a state change.
  1655. Functions in this hook should not modify the buffer.
  1656. Each function gets as its single argument a property list,
  1657. see `org-trigger-hook' for more information about this list.
  1658. If any of the functions in this hook returns nil, the state change
  1659. is blocked.")
  1660. (defvar org-trigger-hook nil
  1661. "Hook for functions that are triggered by a state change.
  1662. Each function gets as its single argument a property list with at
  1663. least the following elements:
  1664. (:type type-of-change :position pos-at-entry-start
  1665. :from old-state :to new-state)
  1666. Depending on the type, more properties may be present.
  1667. This mechanism is currently implemented for:
  1668. TODO state changes
  1669. ------------------
  1670. :type todo-state-change
  1671. :from previous state (keyword as a string), or nil, or a symbol
  1672. `todo' or `done', to indicate the general type of state.
  1673. :to new state, like in :from")
  1674. (defcustom org-enforce-todo-dependencies nil
  1675. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1676. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1677. be blocked if any prior sibling is not yet done.
  1678. Finally, if the parent is blocked because of ordered siblings of its own,
  1679. the child will also be blocked."
  1680. :set (lambda (var val)
  1681. (set-default-toplevel-value var val)
  1682. (if val
  1683. (add-hook 'org-blocker-hook
  1684. 'org-block-todo-from-children-or-siblings-or-parent)
  1685. (remove-hook 'org-blocker-hook
  1686. 'org-block-todo-from-children-or-siblings-or-parent)))
  1687. :group 'org-todo
  1688. :type 'boolean)
  1689. (defcustom org-enforce-todo-checkbox-dependencies nil
  1690. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1691. When this is nil, checkboxes have no influence on switching TODO states.
  1692. When non-nil, you first need to check off all check boxes before the TODO
  1693. entry can be switched to DONE.
  1694. This variable needs to be set before org.el is loaded, and you need to
  1695. restart Emacs after a change to make the change effective. The only way
  1696. to change it while Emacs is running is through the customize interface."
  1697. :set (lambda (var val)
  1698. (set-default-toplevel-value var val)
  1699. (if val
  1700. (add-hook 'org-blocker-hook
  1701. 'org-block-todo-from-checkboxes)
  1702. (remove-hook 'org-blocker-hook
  1703. 'org-block-todo-from-checkboxes)))
  1704. :group 'org-todo
  1705. :type 'boolean)
  1706. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1707. "Non-nil means inserting a TODO heading is treated as state change.
  1708. So when the command `\\[org-insert-todo-heading]' is used, state change
  1709. logging will apply if appropriate. When nil, the new TODO item will
  1710. be inserted directly, and no logging will take place."
  1711. :group 'org-todo
  1712. :type 'boolean)
  1713. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1714. "Non-nil means switching TODO states with S-cursor counts as state change.
  1715. This is the default behavior. However, setting this to nil allows a
  1716. convenient way to select a TODO state and bypass any logging associated
  1717. with that."
  1718. :group 'org-todo
  1719. :type 'boolean)
  1720. (defcustom org-todo-state-tags-triggers nil
  1721. "Tag changes that should be triggered by TODO state changes.
  1722. This is a list. Each entry is
  1723. (state-change (tag . flag) .......)
  1724. State-change can be a string with a state, and empty string to indicate the
  1725. state that has no TODO keyword, or it can be one of the symbols `todo'
  1726. or `done', meaning any not-done or done state, respectively."
  1727. :group 'org-todo
  1728. :group 'org-tags
  1729. :type '(repeat
  1730. (cons (choice :tag "When changing to"
  1731. (const :tag "Not-done state" todo)
  1732. (const :tag "Done state" done)
  1733. (string :tag "State"))
  1734. (repeat
  1735. (cons :tag "Tag action"
  1736. (string :tag "Tag")
  1737. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1738. (defcustom org-log-done nil
  1739. "Information to record when a task moves to the DONE state.
  1740. Possible values are:
  1741. nil Don't add anything, just change the keyword
  1742. time Add a time stamp to the task
  1743. note Prompt for a note and add it with template `org-log-note-headings'
  1744. This option can also be set with on a per-file-basis with
  1745. #+STARTUP: nologdone
  1746. #+STARTUP: logdone
  1747. #+STARTUP: lognotedone
  1748. You can have local logging settings for a subtree by setting the LOGGING
  1749. property to one or more of these keywords."
  1750. :group 'org-todo
  1751. :group 'org-progress
  1752. :type '(choice
  1753. (const :tag "No logging" nil)
  1754. (const :tag "Record CLOSED timestamp" time)
  1755. (const :tag "Record CLOSED timestamp with note." note)))
  1756. ;; Normalize old uses of org-log-done.
  1757. (cond
  1758. ((eq org-log-done t) (setq org-log-done 'time))
  1759. ((and (listp org-log-done) (memq 'done org-log-done))
  1760. (setq org-log-done 'note)))
  1761. (defcustom org-log-reschedule nil
  1762. "Information to record when the scheduling date of a task is modified.
  1763. Possible values are:
  1764. nil Don't add anything, just change the date
  1765. time Add a time stamp to the task
  1766. note Prompt for a note and add it with template `org-log-note-headings'
  1767. This option can also be set with on a per-file-basis with
  1768. #+STARTUP: nologreschedule
  1769. #+STARTUP: logreschedule
  1770. #+STARTUP: lognotereschedule
  1771. You can have local logging settings for a subtree by setting the LOGGING
  1772. property to one or more of these keywords.
  1773. This variable has an effect when calling `org-schedule' or
  1774. `org-agenda-schedule' only."
  1775. :group 'org-todo
  1776. :group 'org-progress
  1777. :type '(choice
  1778. (const :tag "No logging" nil)
  1779. (const :tag "Record timestamp" time)
  1780. (const :tag "Record timestamp with note" note)))
  1781. (defcustom org-log-redeadline nil
  1782. "Information to record when the deadline date of a task is modified.
  1783. Possible values are:
  1784. nil Don't add anything, just change the date
  1785. time Add a time stamp to the task
  1786. note Prompt for a note and add it with template `org-log-note-headings'
  1787. This option can also be set with on a per-file-basis with
  1788. #+STARTUP: nologredeadline
  1789. #+STARTUP: logredeadline
  1790. #+STARTUP: lognoteredeadline
  1791. You can have local logging settings for a subtree by setting the LOGGING
  1792. property to one or more of these keywords.
  1793. This variable has an effect when calling `org-deadline' or
  1794. `org-agenda-deadline' only."
  1795. :group 'org-todo
  1796. :group 'org-progress
  1797. :type '(choice
  1798. (const :tag "No logging" nil)
  1799. (const :tag "Record timestamp" time)
  1800. (const :tag "Record timestamp with note." note)))
  1801. (defcustom org-log-note-clock-out nil
  1802. "Non-nil means record a note when clocking out of an item.
  1803. This can also be configured on a per-file basis by adding one of
  1804. the following lines anywhere in the buffer:
  1805. #+STARTUP: lognoteclock-out
  1806. #+STARTUP: nolognoteclock-out"
  1807. :group 'org-todo
  1808. :group 'org-progress
  1809. :type 'boolean)
  1810. (defcustom org-log-done-with-time t
  1811. "Non-nil means the CLOSED time stamp will contain date and time.
  1812. When nil, only the date will be recorded."
  1813. :group 'org-progress
  1814. :type 'boolean)
  1815. (defcustom org-log-note-headings
  1816. '((done . "CLOSING NOTE %t")
  1817. (state . "State %-12s from %-12S %t")
  1818. (note . "Note taken on %t")
  1819. (reschedule . "Rescheduled from %S on %t")
  1820. (delschedule . "Not scheduled, was %S on %t")
  1821. (redeadline . "New deadline from %S on %t")
  1822. (deldeadline . "Removed deadline, was %S on %t")
  1823. (refile . "Refiled on %t")
  1824. (clock-out . ""))
  1825. "Headings for notes added to entries.
  1826. The value is an alist, with the car being a symbol indicating the
  1827. note context, and the cdr is the heading to be used. The heading
  1828. may also be the empty string. The following placeholders can be
  1829. used:
  1830. %t a time stamp.
  1831. %T an active time stamp instead the default inactive one
  1832. %d a short-format time stamp.
  1833. %D an active short-format time stamp.
  1834. %s the new TODO state or time stamp (inactive), in double quotes.
  1835. %S the old TODO state or time stamp (inactive), in double quotes.
  1836. %u the user name.
  1837. %U full user name.
  1838. In fact, it is not a good idea to change the `state' entry,
  1839. because Agenda Log mode depends on the format of these entries."
  1840. :group 'org-todo
  1841. :group 'org-progress
  1842. :type '(list :greedy t
  1843. (cons (const :tag "Heading when closing an item" done) string)
  1844. (cons (const :tag
  1845. "Heading when changing todo state (todo sequence only)"
  1846. state) string)
  1847. (cons (const :tag "Heading when just taking a note" note) string)
  1848. (cons (const :tag "Heading when rescheduling" reschedule) string)
  1849. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  1850. (cons (const :tag "Heading when changing deadline" redeadline) string)
  1851. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  1852. (cons (const :tag "Heading when refiling" refile) string)
  1853. (cons (const :tag "Heading when clocking out" clock-out) string)))
  1854. (unless (assq 'note org-log-note-headings)
  1855. (push '(note . "%t") org-log-note-headings))
  1856. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  1857. (defcustom org-log-into-drawer nil
  1858. "Non-nil means insert state change notes and time stamps into a drawer.
  1859. When nil, state changes notes will be inserted after the headline and
  1860. any scheduling and clock lines, but not inside a drawer.
  1861. The value of this variable should be the name of the drawer to use.
  1862. LOGBOOK is proposed as the default drawer for this purpose, you can
  1863. also set this to a string to define the drawer of your choice.
  1864. A value of t is also allowed, representing \"LOGBOOK\".
  1865. A value of t or nil can also be set with on a per-file-basis with
  1866. #+STARTUP: logdrawer
  1867. #+STARTUP: nologdrawer
  1868. If this variable is set, `org-log-state-notes-insert-after-drawers'
  1869. will be ignored.
  1870. You can set the property LOG_INTO_DRAWER to overrule this setting for
  1871. a subtree.
  1872. Do not check directly this variable in a Lisp program. Call
  1873. function `org-log-into-drawer' instead."
  1874. :group 'org-todo
  1875. :group 'org-progress
  1876. :type '(choice
  1877. (const :tag "Not into a drawer" nil)
  1878. (const :tag "LOGBOOK" t)
  1879. (string :tag "Other")))
  1880. (defun org-log-into-drawer ()
  1881. "Name of the log drawer, as a string, or nil.
  1882. This is the value of `org-log-into-drawer'. However, if the
  1883. current entry has or inherits a LOG_INTO_DRAWER property, it will
  1884. be used instead of the default value."
  1885. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  1886. (cond ((equal p "nil") nil)
  1887. ((equal p "t") "LOGBOOK")
  1888. ((stringp p) p)
  1889. (p "LOGBOOK")
  1890. ((stringp org-log-into-drawer) org-log-into-drawer)
  1891. (org-log-into-drawer "LOGBOOK"))))
  1892. (defcustom org-log-state-notes-insert-after-drawers nil
  1893. "Non-nil means insert state change notes after any drawers in entry.
  1894. Only the drawers that *immediately* follow the headline and the
  1895. deadline/scheduled line are skipped.
  1896. When nil, insert notes right after the heading and perhaps the line
  1897. with deadline/scheduling if present.
  1898. This variable will have no effect if `org-log-into-drawer' is
  1899. set."
  1900. :group 'org-todo
  1901. :group 'org-progress
  1902. :type 'boolean)
  1903. (defcustom org-log-states-order-reversed t
  1904. "Non-nil means the latest state note will be directly after heading.
  1905. When nil, the state change notes will be ordered according to time.
  1906. This option can also be set with on a per-file-basis with
  1907. #+STARTUP: logstatesreversed
  1908. #+STARTUP: nologstatesreversed"
  1909. :group 'org-todo
  1910. :group 'org-progress
  1911. :type 'boolean)
  1912. (defcustom org-todo-repeat-to-state nil
  1913. "The TODO state to which a repeater should return the repeating task.
  1914. By default this is the first task of a TODO sequence or the
  1915. previous state of a TYPE_TODO set. But you can specify to use
  1916. the previous state in a TODO sequence or a string.
  1917. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  1918. entry, which has precedence over this option."
  1919. :group 'org-todo
  1920. :version "24.1"
  1921. :type '(choice (const :tag "Use the previous TODO state" t)
  1922. (const :tag "Use the head of the TODO sequence" nil)
  1923. (string :tag "Use a specific TODO state")))
  1924. (defcustom org-log-repeat 'time
  1925. "Non-nil means record moving through the DONE state when triggering repeat.
  1926. An auto-repeating task is immediately switched back to TODO when
  1927. marked DONE. If you are not logging state changes (by adding \"@\"
  1928. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  1929. record a closing note, there will be no record of the task moving
  1930. through DONE. This variable forces taking a note anyway.
  1931. nil Don't force a record
  1932. time Record a time stamp
  1933. note Prompt for a note and add it with template `org-log-note-headings'
  1934. This option can also be set with on a per-file-basis with
  1935. #+STARTUP: nologrepeat
  1936. #+STARTUP: logrepeat
  1937. #+STARTUP: lognoterepeat
  1938. You can have local logging settings for a subtree by setting the LOGGING
  1939. property to one or more of these keywords."
  1940. :group 'org-todo
  1941. :group 'org-progress
  1942. :type '(choice
  1943. (const :tag "Don't force a record" nil)
  1944. (const :tag "Force recording the DONE state" time)
  1945. (const :tag "Force recording a note with the DONE state" note)))
  1946. (defcustom org-todo-repeat-hook nil
  1947. "Hook that is run after a task has been repeated."
  1948. :package-version '(Org . "9.2")
  1949. :group 'org-todo
  1950. :type 'hook)
  1951. (defgroup org-priorities nil
  1952. "Priorities in Org mode."
  1953. :tag "Org Priorities"
  1954. :group 'org-todo)
  1955. (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
  1956. (defcustom org-priority-enable-commands t
  1957. "Non-nil means priority commands are active.
  1958. When nil, these commands will be disabled, so that you never accidentally
  1959. set a priority."
  1960. :group 'org-priorities
  1961. :type 'boolean)
  1962. (defvaralias 'org-highest-priority 'org-priority-highest)
  1963. (defcustom org-priority-highest ?A
  1964. "The highest priority of TODO items.
  1965. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  1966. The default is the character ?A, which is 65 as a numeric value.
  1967. If you set `org-priority-highest' to a numeric value inferior to
  1968. 65, Org assumes you want to use digits for the priority cookie.
  1969. If you set it to >=65, Org assumes you want to use alphabetical
  1970. characters.
  1971. In both cases, the value of `org-priority-highest' must be
  1972. smaller than `org-priority-lowest': for example, if \"A\" is the
  1973. highest priority, it is smaller than the lowest \"C\" priority:
  1974. 65 < 67."
  1975. :group 'org-priorities
  1976. :type '(choice
  1977. (character :tag "Character")
  1978. (integer :tag "Integer (< 65)")))
  1979. (defvaralias 'org-lowest-priority 'org-priority-lowest)
  1980. (defcustom org-priority-lowest ?C
  1981. "The lowest priority of TODO items.
  1982. A character like ?C, ?B, etc., or a numeric value like 9, 8, etc.
  1983. The default is the character ?C, which is 67 as a numeric value.
  1984. If you set `org-priority-lowest' to a numeric value inferior to
  1985. 65, Org assumes you want to use digits for the priority cookie.
  1986. If you set it to >=65, Org assumes you want to use alphabetical
  1987. characters.
  1988. In both cases, the value of `org-priority-lowest' must be greater
  1989. than `org-priority-highest': for example, if \"C\" is the lowest
  1990. priority, it is greater than the highest \"A\" priority: 67 >
  1991. 65."
  1992. :group 'org-priorities
  1993. :type '(choice
  1994. (character :tag "Character")
  1995. (integer :tag "Integer (< 65)")))
  1996. (defvaralias 'org-default-priority 'org-priority-default)
  1997. (defcustom org-priority-default ?B
  1998. "The default priority of TODO items.
  1999. This is the priority an item gets if no explicit priority is given.
  2000. When starting to cycle on an empty priority the first step in the cycle
  2001. depends on `org-priority-start-cycle-with-default'. The resulting first
  2002. step priority must not exceed the range from `org-priority-highest' to
  2003. `org-priority-lowest' which means that `org-priority-default' has to be
  2004. in this range exclusive or inclusive to the range boundaries. Else the
  2005. first step refuses to set the default and the second will fall back on
  2006. \(depending on the command used) the highest or lowest priority."
  2007. :group 'org-priorities
  2008. :type '(choice
  2009. (character :tag "Character")
  2010. (integer :tag "Integer (< 65)")))
  2011. (defcustom org-priority-start-cycle-with-default t
  2012. "Non-nil means start with default priority when starting to cycle.
  2013. When this is nil, the first step in the cycle will be (depending on the
  2014. command used) one higher or lower than the default priority.
  2015. See also `org-priority-default'."
  2016. :group 'org-priorities
  2017. :type 'boolean)
  2018. (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
  2019. (defcustom org-priority-get-priority-function nil
  2020. "Function to extract the priority from a string.
  2021. The string is normally the headline. If this is nil, Org
  2022. computes the priority from the priority cookie like [#A] in the
  2023. headline. It returns an integer, increasing by 1000 for each
  2024. priority level.
  2025. The user can set a different function here, which should take a
  2026. string as an argument and return the numeric priority."
  2027. :group 'org-priorities
  2028. :version "24.1"
  2029. :type '(choice
  2030. (const nil)
  2031. (function)))
  2032. (defgroup org-time nil
  2033. "Options concerning time stamps and deadlines in Org mode."
  2034. :tag "Org Time"
  2035. :group 'org)
  2036. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2037. "Number of minutes to round time stamps to.
  2038. \\<org-mode-map>\
  2039. These are two values, the first applies when first creating a time stamp.
  2040. The second applies when changing it with the commands `S-up' and `S-down'.
  2041. When changing the time stamp, this means that it will change in steps
  2042. of N minutes, as given by the second value.
  2043. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2044. numbers should be factors of 60, so for example 5, 10, 15.
  2045. When this is larger than 1, you can still force an exact time stamp by using
  2046. a double prefix argument to a time stamp command like \
  2047. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2048. and by using a prefix arg to `S-up/down' to specify the exact number
  2049. of minutes to shift."
  2050. :group 'org-time
  2051. :get (lambda (var) ; Make sure both elements are there
  2052. (if (integerp (default-value var))
  2053. (list (default-value var) 5)
  2054. (default-value var)))
  2055. :type '(list
  2056. (integer :tag "when inserting times")
  2057. (integer :tag "when modifying times")))
  2058. ;; Normalize old customizations of this variable.
  2059. (when (integerp org-time-stamp-rounding-minutes)
  2060. (setq org-time-stamp-rounding-minutes
  2061. (list org-time-stamp-rounding-minutes
  2062. org-time-stamp-rounding-minutes)))
  2063. (defcustom org-display-custom-times nil
  2064. "Non-nil means overlay custom formats over all time stamps.
  2065. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2066. To turn this on on a per-file basis, insert anywhere in the file:
  2067. #+STARTUP: customtime"
  2068. :group 'org-time
  2069. :type 'sexp)
  2070. (make-variable-buffer-local 'org-display-custom-times)
  2071. (defcustom org-time-stamp-custom-formats
  2072. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2073. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2074. These are overlaid over the default ISO format if the variable
  2075. `org-display-custom-times' is set. Time like %H:%M should be at the
  2076. end of the second format. The custom formats are also honored by export
  2077. commands, if custom time display is turned on at the time of export."
  2078. :group 'org-time
  2079. :type 'sexp)
  2080. (defun org-time-stamp-format (&optional long inactive)
  2081. "Get the right format for a time string."
  2082. (let ((f (if long (cdr org-time-stamp-formats)
  2083. (car org-time-stamp-formats))))
  2084. (if inactive
  2085. (concat "[" (substring f 1 -1) "]")
  2086. f)))
  2087. (defcustom org-deadline-warning-days 14
  2088. "Number of days before expiration during which a deadline becomes active.
  2089. This variable governs the display in sparse trees and in the agenda.
  2090. When 0 or negative, it means use this number (the absolute value of it)
  2091. even if a deadline has a different individual lead time specified.
  2092. Custom commands can set this variable in the options section."
  2093. :group 'org-time
  2094. :group 'org-agenda-daily/weekly
  2095. :type 'integer)
  2096. (defcustom org-scheduled-delay-days 0
  2097. "Number of days before a scheduled item becomes active.
  2098. This variable governs the display in sparse trees and in the agenda.
  2099. The default value (i.e. 0) means: don't delay scheduled item.
  2100. When negative, it means use this number (the absolute value of it)
  2101. even if a scheduled item has a different individual delay time
  2102. specified.
  2103. Custom commands can set this variable in the options section."
  2104. :group 'org-time
  2105. :group 'org-agenda-daily/weekly
  2106. :version "24.4"
  2107. :package-version '(Org . "8.0")
  2108. :type 'integer)
  2109. (defcustom org-read-date-prefer-future t
  2110. "Non-nil means assume future for incomplete date input from user.
  2111. This affects the following situations:
  2112. 1. The user gives a month but not a year.
  2113. For example, if it is April and you enter \"feb 2\", this will be read
  2114. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2115. 2. The user gives a day, but no month.
  2116. For example, if today is the 15th, and you enter \"3\", Org will read
  2117. this as the third of *next* month. However, if you enter \"17\",
  2118. it will be considered as *this* month.
  2119. If you set this variable to the symbol `time', then also the following
  2120. will work:
  2121. 3. If the user gives a time.
  2122. If the time is before now, it will be interpreted as tomorrow.
  2123. Currently none of this works for ISO week specifications.
  2124. When this option is nil, the current day, month and year will always be
  2125. used as defaults.
  2126. See also `org-agenda-jump-prefer-future'."
  2127. :group 'org-time
  2128. :type '(choice
  2129. (const :tag "Never" nil)
  2130. (const :tag "Check month and day" t)
  2131. (const :tag "Check month, day, and time" time)))
  2132. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2133. "Should the agenda jump command prefer the future for incomplete dates?
  2134. The default is to do the same as configured in `org-read-date-prefer-future'.
  2135. But you can also set a deviating value here.
  2136. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2137. :group 'org-agenda
  2138. :group 'org-time
  2139. :version "24.1"
  2140. :type '(choice
  2141. (const :tag "Use org-read-date-prefer-future"
  2142. org-read-date-prefer-future)
  2143. (const :tag "Never" nil)
  2144. (const :tag "Always" t)))
  2145. (defcustom org-read-date-force-compatible-dates t
  2146. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2147. Depending on the system Emacs is running on, certain dates cannot
  2148. be represented with the type used internally to represent time.
  2149. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2150. correctly. Some systems allow for earlier dates, some for later,
  2151. some for both. One way to find out is to insert any date into an
  2152. Org buffer, putting the cursor on the year and hitting S-up and
  2153. S-down to test the range.
  2154. When this variable is set to t, the date/time prompt will not let
  2155. you specify dates outside the 1970-2037 range, so it is certain that
  2156. these dates will work in whatever version of Emacs you are
  2157. running, and also that you can move a file from one Emacs implementation
  2158. to another. Whenever Org is forcing the year for you, it will display
  2159. a message and beep.
  2160. When this variable is nil, Org will check if the date is
  2161. representable in the specific Emacs implementation you are using.
  2162. If not, it will force a year, usually the current year, and beep
  2163. to remind you. Currently this setting is not recommended because
  2164. the likelihood that you will open your Org files in an Emacs that
  2165. has limited date range is not negligible.
  2166. A workaround for this problem is to use diary sexp dates for time
  2167. stamps outside of this range."
  2168. :group 'org-time
  2169. :version "24.1"
  2170. :type 'boolean)
  2171. (defcustom org-read-date-display-live t
  2172. "Non-nil means display current interpretation of date prompt live.
  2173. This display will be in an overlay, in the minibuffer. Note that
  2174. live display is only active when `org-read-date-popup-calendar'
  2175. is non-nil."
  2176. :group 'org-time
  2177. :type 'boolean)
  2178. (defvaralias 'org-popup-calendar-for-date-prompt
  2179. 'org-read-date-popup-calendar)
  2180. (defcustom org-read-date-popup-calendar t
  2181. "Non-nil means pop up a calendar when prompting for a date.
  2182. In the calendar, the date can be selected with mouse-1. However, the
  2183. minibuffer will also be active, and you can simply enter the date as well.
  2184. When nil, only the minibuffer will be available."
  2185. :group 'org-time
  2186. :type 'boolean)
  2187. (defcustom org-extend-today-until 0
  2188. "The hour when your day really ends. Must be an integer.
  2189. This has influence for the following applications:
  2190. - When switching the agenda to \"today\". If it is still earlier than
  2191. the time given here, the day recognized as TODAY is actually yesterday.
  2192. - When a date is read from the user and it is still before the time given
  2193. here, the current date and time will be assumed to be yesterday, 23:59.
  2194. Also, timestamps inserted in capture templates follow this rule.
  2195. IMPORTANT: This is a feature whose implementation is and likely will
  2196. remain incomplete. Really, it is only here because past midnight seems to
  2197. be the favorite working time of John Wiegley :-)"
  2198. :group 'org-time
  2199. :type 'integer)
  2200. (defcustom org-use-effective-time nil
  2201. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2202. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2203. \"effective time\" of any timestamps between midnight and 8am will be
  2204. 23:59 of the previous day."
  2205. :group 'org-time
  2206. :version "24.1"
  2207. :type 'boolean)
  2208. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2209. "When non-nil, use the last clock out time for `org-todo'.
  2210. Note that this option has precedence over the combined use of
  2211. `org-use-effective-time' and `org-extend-today-until'."
  2212. :group 'org-time
  2213. :version "24.4"
  2214. :package-version '(Org . "8.0")
  2215. :type 'boolean)
  2216. (defcustom org-edit-timestamp-down-means-later nil
  2217. "Non-nil means S-down will increase the time in a time stamp.
  2218. When nil, S-up will increase."
  2219. :group 'org-time
  2220. :type 'boolean)
  2221. (defcustom org-calendar-follow-timestamp-change t
  2222. "Non-nil means make the calendar window follow timestamp changes.
  2223. When a timestamp is modified and the calendar window is visible, it will be
  2224. moved to the new date."
  2225. :group 'org-time
  2226. :type 'boolean)
  2227. (defgroup org-tags nil
  2228. "Options concerning tags in Org mode."
  2229. :tag "Org Tags"
  2230. :group 'org)
  2231. (defcustom org-tag-alist nil
  2232. "Default tags available in Org files.
  2233. The value of this variable is an alist. Associations either:
  2234. (TAG)
  2235. (TAG . SELECT)
  2236. (SPECIAL)
  2237. where TAG is a tag as a string, SELECT is character, used to
  2238. select that tag through the fast tag selection interface, and
  2239. SPECIAL is one of the following keywords: `:startgroup',
  2240. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2241. `:newline'. These keywords are used to define a hierarchy of
  2242. tags. See manual for details.
  2243. When this variable is nil, Org mode bases tag input on what is
  2244. already in the buffer. The value can be overridden locally by
  2245. using a TAGS keyword, e.g.,
  2246. #+TAGS: tag1 tag2
  2247. See also `org-tag-persistent-alist' to sidestep this behavior."
  2248. :group 'org-tags
  2249. :type '(repeat
  2250. (choice
  2251. (cons :tag "Tag with key"
  2252. (string :tag "Tag name")
  2253. (character :tag "Access char"))
  2254. (list :tag "Tag" (string :tag "Tag name"))
  2255. (const :tag "Start radio group" (:startgroup))
  2256. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2257. (const :tag "Group tags delimiter" (:grouptags))
  2258. (const :tag "End radio group" (:endgroup))
  2259. (const :tag "End tag group, non distinct" (:endgrouptag))
  2260. (const :tag "New line" (:newline)))))
  2261. (defcustom org-tag-persistent-alist nil
  2262. "Tags always available in Org files.
  2263. The value of this variable is an alist. Associations either:
  2264. (TAG)
  2265. (TAG . SELECT)
  2266. (SPECIAL)
  2267. where TAG is a tag as a string, SELECT is a character, used to
  2268. select that tag through the fast tag selection interface, and
  2269. SPECIAL is one of the following keywords: `:startgroup',
  2270. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2271. `:newline'. These keywords are used to define a hierarchy of
  2272. tags. See manual for details.
  2273. Unlike to `org-tag-alist', tags defined in this variable do not
  2274. depend on a local TAGS keyword. Instead, to disable these tags
  2275. on a per-file basis, insert anywhere in the file:
  2276. #+STARTUP: noptag"
  2277. :group 'org-tags
  2278. :type '(repeat
  2279. (choice
  2280. (cons :tag "Tag with key"
  2281. (string :tag "Tag name")
  2282. (character :tag "Access char"))
  2283. (list :tag "Tag" (string :tag "Tag name"))
  2284. (const :tag "Start radio group" (:startgroup))
  2285. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2286. (const :tag "Group tags delimiter" (:grouptags))
  2287. (const :tag "End radio group" (:endgroup))
  2288. (const :tag "End tag group, non distinct" (:endgrouptag))
  2289. (const :tag "New line" (:newline)))))
  2290. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2291. "If non-nil, always offer completion for all tags of all agenda files.
  2292. Setting this variable locally allows for dynamic generation of tag
  2293. completions in capture buffers.
  2294. (add-hook \\='org-capture-mode-hook
  2295. (lambda ()
  2296. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2297. :group 'org-tags
  2298. :version "24.1"
  2299. :type 'boolean)
  2300. (defvar org-file-tags nil
  2301. "List of tags that can be inherited by all entries in the file.
  2302. The tags will be inherited if the variable `org-use-tag-inheritance'
  2303. says they should be.
  2304. This variable is populated from #+FILETAGS lines.")
  2305. (defcustom org-use-fast-tag-selection 'auto
  2306. "Non-nil means use fast tag selection scheme.
  2307. This is a special interface to select and deselect tags with single keys.
  2308. When nil, fast selection is never used.
  2309. When the symbol `auto', fast selection is used if and only if selection
  2310. characters for tags have been configured, either through the variable
  2311. `org-tag-alist' or through a #+TAGS line in the buffer.
  2312. When t, fast selection is always used and selection keys are assigned
  2313. automatically if necessary."
  2314. :group 'org-tags
  2315. :type '(choice
  2316. (const :tag "Always" t)
  2317. (const :tag "Never" nil)
  2318. (const :tag "When selection characters are configured" auto)))
  2319. (defcustom org-fast-tag-selection-single-key nil
  2320. "Non-nil means fast tag selection exits after first change.
  2321. When nil, you have to press RET to exit it.
  2322. During fast tag selection, you can toggle this flag with `C-c'.
  2323. This variable can also have the value `expert'. In this case, the window
  2324. displaying the tags menu is not even shown, until you press `C-c' again."
  2325. :group 'org-tags
  2326. :type '(choice
  2327. (const :tag "No" nil)
  2328. (const :tag "Yes" t)
  2329. (const :tag "Expert" expert)))
  2330. (defvar org-fast-tag-selection-include-todo nil
  2331. "Non-nil means fast tags selection interface will also offer TODO states.
  2332. This is an undocumented feature, you should not rely on it.")
  2333. (defcustom org-tags-column -77
  2334. "The column to which tags should be indented in a headline.
  2335. If this number is positive, it specifies the column. If it is negative,
  2336. it means that the tags should be flushright to that column. For example,
  2337. -80 works well for a normal 80 character screen.
  2338. When 0, place tags directly after headline text, with only one space in
  2339. between."
  2340. :group 'org-tags
  2341. :type 'integer)
  2342. (defcustom org-auto-align-tags t
  2343. "Non-nil keeps tags aligned when modifying headlines.
  2344. Some operations (i.e. demoting) change the length of a headline and
  2345. therefore shift the tags around. With this option turned on, after
  2346. each such operation the tags are again aligned to `org-tags-column'."
  2347. :group 'org-tags
  2348. :type 'boolean)
  2349. (defcustom org-use-tag-inheritance t
  2350. "Non-nil means tags in levels apply also for sublevels.
  2351. When nil, only the tags directly given in a specific line apply there.
  2352. This may also be a list of tags that should be inherited, or a regexp that
  2353. matches tags that should be inherited. Additional control is possible
  2354. with the variable `org-tags-exclude-from-inheritance' which gives an
  2355. explicit list of tags to be excluded from inheritance, even if the value of
  2356. `org-use-tag-inheritance' would select it for inheritance.
  2357. If this option is t, a match early-on in a tree can lead to a large
  2358. number of matches in the subtree when constructing the agenda or creating
  2359. a sparse tree. If you only want to see the first match in a tree during
  2360. a search, check out the variable `org-tags-match-list-sublevels'."
  2361. :group 'org-tags
  2362. :type '(choice
  2363. (const :tag "Not" nil)
  2364. (const :tag "Always" t)
  2365. (repeat :tag "Specific tags" (string :tag "Tag"))
  2366. (regexp :tag "Tags matched by regexp")))
  2367. (defcustom org-tags-exclude-from-inheritance nil
  2368. "List of tags that should never be inherited.
  2369. This is a way to exclude a few tags from inheritance. For way to do
  2370. the opposite, to actively allow inheritance for selected tags,
  2371. see the variable `org-use-tag-inheritance'."
  2372. :group 'org-tags
  2373. :type '(repeat (string :tag "Tag")))
  2374. (defun org-tag-inherit-p (tag)
  2375. "Check if TAG is one that should be inherited."
  2376. (cond
  2377. ((member tag org-tags-exclude-from-inheritance) nil)
  2378. ((eq org-use-tag-inheritance t) t)
  2379. ((not org-use-tag-inheritance) nil)
  2380. ((stringp org-use-tag-inheritance)
  2381. (string-match org-use-tag-inheritance tag))
  2382. ((listp org-use-tag-inheritance)
  2383. (member tag org-use-tag-inheritance))
  2384. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2385. (defcustom org-tags-match-list-sublevels t
  2386. "Non-nil means list also sublevels of headlines matching a search.
  2387. This variable applies to tags/property searches, and also to stuck
  2388. projects because this search is based on a tags match as well.
  2389. When set to the symbol `indented', sublevels are indented with
  2390. leading dots.
  2391. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2392. the sublevels of a headline matching a tag search often also match
  2393. the same search. Listing all of them can create very long lists.
  2394. Setting this variable to nil causes subtrees of a match to be skipped.
  2395. This variable is semi-obsolete and probably should always be true. It
  2396. is better to limit inheritance to certain tags using the variables
  2397. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2398. :group 'org-tags
  2399. :type '(choice
  2400. (const :tag "No, don't list them" nil)
  2401. (const :tag "Yes, do list them" t)
  2402. (const :tag "List them, indented with leading dots" indented)))
  2403. (defcustom org-tags-sort-function nil
  2404. "When set, tags are sorted using this function as a comparator."
  2405. :group 'org-tags
  2406. :type '(choice
  2407. (const :tag "No sorting" nil)
  2408. (const :tag "Alphabetical" string-collate-lessp)
  2409. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2410. (function :tag "Custom function" nil)))
  2411. (defvar org-tags-history nil
  2412. "History of minibuffer reads for tags.")
  2413. (defvar org-last-tags-completion-table nil
  2414. "The last used completion table for tags.")
  2415. (defvar org-after-tags-change-hook nil
  2416. "Hook that is run after the tags in a line have changed.")
  2417. (defgroup org-properties nil
  2418. "Options concerning properties in Org mode."
  2419. :tag "Org Properties"
  2420. :group 'org)
  2421. (defcustom org-property-format "%-10s %s"
  2422. "How property key/value pairs should be formatted by `indent-line'.
  2423. When `indent-line' hits a property definition, it will format the line
  2424. according to this format, mainly to make sure that the values are
  2425. lined-up with respect to each other."
  2426. :group 'org-properties
  2427. :type 'string)
  2428. (defcustom org-properties-postprocess-alist nil
  2429. "Alist of properties and functions to adjust inserted values.
  2430. Elements of this alist must be of the form
  2431. ([string] [function])
  2432. where [string] must be a property name and [function] must be a
  2433. lambda expression: this lambda expression must take one argument,
  2434. the value to adjust, and return the new value as a string.
  2435. For example, this element will allow the property \"Remaining\"
  2436. to be updated wrt the relation between the \"Effort\" property
  2437. and the clock summary:
  2438. ((\"Remaining\" (lambda(value)
  2439. (let ((clocksum (org-clock-sum-current-item))
  2440. (effort (org-duration-to-minutes
  2441. (org-entry-get (point) \"Effort\"))))
  2442. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2443. :group 'org-properties
  2444. :version "24.1"
  2445. :type '(alist :key-type (string :tag "Property")
  2446. :value-type (function :tag "Function")))
  2447. (defcustom org-use-property-inheritance nil
  2448. "Non-nil means properties apply also for sublevels.
  2449. This setting is chiefly used during property searches. Turning it on can
  2450. cause significant overhead when doing a search, which is why it is not
  2451. on by default.
  2452. When nil, only the properties directly given in the current entry count.
  2453. When t, every property is inherited. The value may also be a list of
  2454. properties that should have inheritance, or a regular expression matching
  2455. properties that should be inherited.
  2456. However, note that some special properties use inheritance under special
  2457. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2458. and the properties ending in \"_ALL\" when they are used as descriptor
  2459. for valid values of a property.
  2460. Note for programmers:
  2461. When querying an entry with `org-entry-get', you can control if inheritance
  2462. should be used. By default, `org-entry-get' looks only at the local
  2463. properties. You can request inheritance by setting the inherit argument
  2464. to t (to force inheritance) or to `selective' (to respect the setting
  2465. in this variable)."
  2466. :group 'org-properties
  2467. :type '(choice
  2468. (const :tag "Not" nil)
  2469. (const :tag "Always" t)
  2470. (repeat :tag "Specific properties" (string :tag "Property"))
  2471. (regexp :tag "Properties matched by regexp")))
  2472. (defun org-property-inherit-p (property)
  2473. "Return a non-nil value if PROPERTY should be inherited."
  2474. (cond
  2475. ((eq org-use-property-inheritance t) t)
  2476. ((not org-use-property-inheritance) nil)
  2477. ((stringp org-use-property-inheritance)
  2478. (string-match org-use-property-inheritance property))
  2479. ((listp org-use-property-inheritance)
  2480. (member-ignore-case property org-use-property-inheritance))
  2481. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2482. (defcustom org-property-separators nil
  2483. "An alist to control how properties are combined.
  2484. The car of each item should be either a list of property names or
  2485. a regular expression, while the cdr should be the separator to
  2486. use when combining that property.
  2487. If an alist item cannot be found that matches a given property, a
  2488. single space will be used as the separator."
  2489. :group 'org-properties
  2490. :type '(alist :key-type (choice (repeat :tag "Properties" string)
  2491. (string :tag "Regular Expression"))
  2492. :value-type (restricted-sexp :tag "Separator"
  2493. :match-alternatives (stringp)
  2494. :value " ")))
  2495. (defun org--property-get-separator (property)
  2496. "Get the separator to use for combining PROPERTY."
  2497. (or
  2498. (catch 'separator
  2499. (dolist (spec org-property-separators)
  2500. (if (listp (car spec))
  2501. (if (member property (car spec))
  2502. (throw 'separator (cdr spec)))
  2503. (if (string-match-p (car spec) property)
  2504. (throw 'separator (cdr spec))))))
  2505. " "))
  2506. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2507. "The default column format, if no other format has been defined.
  2508. This variable can be set on the per-file basis by inserting a line
  2509. #+COLUMNS: %25ITEM ....."
  2510. :group 'org-properties
  2511. :type 'string)
  2512. (defcustom org-columns-default-format-for-agenda nil
  2513. "The default column format in an agenda buffer.
  2514. This will be used for column view in the agenda unless a format has
  2515. been set by adding `org-overriding-columns-format' to the local
  2516. settings list of a custom agenda view. When nil, the columns format
  2517. for the first item in the agenda list will be used, or as a fall-back,
  2518. `org-columns-default-format'."
  2519. :group 'org-properties
  2520. :type '(choice
  2521. (const :tag "No default" nil)
  2522. (string :tag "Format string")))
  2523. (defcustom org-columns-ellipses ".."
  2524. "The ellipses to be used when a field in column view is truncated.
  2525. When this is the empty string, as many characters as possible are shown,
  2526. but then there will be no visual indication that the field has been truncated.
  2527. When this is a string of length N, the last N characters of a truncated
  2528. field are replaced by this string. If the column is narrower than the
  2529. ellipses string, only part of the ellipses string will be shown."
  2530. :group 'org-properties
  2531. :type 'string)
  2532. (defconst org-global-properties-fixed
  2533. '(("VISIBILITY_ALL" . "folded children content all")
  2534. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2535. "List of property/value pairs that can be inherited by any entry.
  2536. These are fixed values, for the preset properties. The user variable
  2537. that can be used to add to this list is `org-global-properties'.
  2538. The entries in this list are cons cells where the car is a property
  2539. name and cdr is a string with the value. If the value represents
  2540. multiple items like an \"_ALL\" property, separate the items by
  2541. spaces.")
  2542. (defcustom org-global-properties nil
  2543. "List of property/value pairs that can be inherited by any entry.
  2544. This list will be combined with the constant `org-global-properties-fixed'.
  2545. The entries in this list are cons cells where the car is a property
  2546. name and cdr is a string with the value.
  2547. Buffer local properties are added either by a document property drawer
  2548. :PROPERTIES:
  2549. :NAME: VALUE
  2550. :END:
  2551. or by adding lines like
  2552. #+PROPERTY: NAME VALUE"
  2553. :group 'org-properties
  2554. :type '(repeat
  2555. (cons (string :tag "Property")
  2556. (string :tag "Value"))))
  2557. (defvar-local org-keyword-properties nil
  2558. "List of property/value pairs inherited by any entry.
  2559. Valid for the current buffer. This variable is populated from
  2560. PROPERTY keywords.
  2561. Note that properties are defined also in property drawers.
  2562. Properties defined there take precedence over properties defined
  2563. as keywords.")
  2564. (defgroup org-agenda nil
  2565. "Options concerning agenda views in Org mode."
  2566. :tag "Org Agenda"
  2567. :group 'org)
  2568. (defvar-local org-category nil
  2569. "Variable used by Org files to set a category for agenda display.
  2570. There are multiple ways to set the category. One way is to set
  2571. it in the document property drawer. For example:
  2572. :PROPERTIES:
  2573. :CATEGORY: ELisp
  2574. :END:
  2575. Other ways to define it is as an Emacs file variable, for example
  2576. # -*- mode: org; org-category: \"ELisp\"
  2577. or for the file to contain a special line:
  2578. #+CATEGORY: ELisp
  2579. If the file does not specify a category, then file's base name
  2580. is used instead.")
  2581. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2582. (defcustom org-agenda-files nil
  2583. "The files to be used for agenda display.
  2584. If an entry is a directory, all files in that directory that are matched
  2585. by `org-agenda-file-regexp' will be part of the file list.
  2586. If the value of the variable is not a list but a single file name, then
  2587. the list of agenda files is actually stored and maintained in that file,
  2588. one agenda file per line. In this file paths can be given relative to
  2589. `org-directory'. Tilde expansion and environment variable substitution
  2590. are also made.
  2591. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2592. and removed with `\\[org-remove-file]'."
  2593. :group 'org-agenda
  2594. :type '(choice
  2595. (repeat :tag "List of files and directories" file)
  2596. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2597. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2598. "Regular expression to match files for `org-agenda-files'.
  2599. If any element in the list in that variable contains a directory instead
  2600. of a normal file, all files in that directory that are matched by this
  2601. regular expression will be included."
  2602. :group 'org-agenda
  2603. :type 'regexp)
  2604. (defvaralias 'org-agenda-multi-occur-extra-files
  2605. 'org-agenda-text-search-extra-files)
  2606. (defcustom org-agenda-text-search-extra-files nil
  2607. "List of extra files to be searched by text search commands.
  2608. These files will be searched in addition to the agenda files by the
  2609. commands `org-search-view' (`\\[org-agenda] s') \
  2610. and `org-occur-in-agenda-files'.
  2611. Note that these files will only be searched for text search commands,
  2612. not for the other agenda views like todo lists, tag searches or the weekly
  2613. agenda. This variable is intended to list notes and possibly archive files
  2614. that should also be searched by these two commands.
  2615. In fact, if the first element in the list is the symbol `agenda-archives',
  2616. then all archive files of all agenda files will be added to the search
  2617. scope."
  2618. :group 'org-agenda
  2619. :type '(set :greedy t
  2620. (const :tag "Agenda Archives" agenda-archives)
  2621. (repeat :inline t (file))))
  2622. (defcustom org-agenda-skip-unavailable-files nil
  2623. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2624. A nil value means to remove them, after a query, from the list."
  2625. :group 'org-agenda
  2626. :type 'boolean)
  2627. (defgroup org-latex nil
  2628. "Options for embedding LaTeX code into Org mode."
  2629. :tag "Org LaTeX"
  2630. :group 'org)
  2631. (defcustom org-format-latex-options
  2632. '(:foreground default :background default :scale 1.0
  2633. :html-foreground "Black" :html-background "Transparent"
  2634. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2635. "Options for creating images from LaTeX fragments.
  2636. This is a property list with the following properties:
  2637. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2638. `default' means use the foreground of the default face.
  2639. `auto' means use the foreground from the text face.
  2640. :background the background color, or \"Transparent\".
  2641. `default' means use the background of the default face.
  2642. `auto' means use the background from the text face.
  2643. :scale a scaling factor for the size of the images, to get more pixels
  2644. :html-foreground, :html-background, :html-scale
  2645. the same numbers for HTML export.
  2646. :matchers a list indicating which matchers should be used to
  2647. find LaTeX fragments. Valid members of this list are:
  2648. \"begin\" find environments
  2649. \"$1\" find single characters surrounded by $.$
  2650. \"$\" find math expressions surrounded by $...$
  2651. \"$$\" find math expressions surrounded by $$....$$
  2652. \"\\(\" find math expressions surrounded by \\(...\\)
  2653. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2654. :group 'org-latex
  2655. :type 'plist)
  2656. (defcustom org-format-latex-signal-error t
  2657. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2658. When nil, just push out a message."
  2659. :group 'org-latex
  2660. :version "24.1"
  2661. :type 'boolean)
  2662. (defcustom org-latex-to-mathml-jar-file nil
  2663. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2664. Use this to specify additional executable file say a jar file.
  2665. When using MathToWeb as the converter, specify the full-path to
  2666. your mathtoweb.jar file."
  2667. :group 'org-latex
  2668. :version "24.1"
  2669. :type '(choice
  2670. (const :tag "None" nil)
  2671. (file :tag "JAR file" :must-match t)))
  2672. (defcustom org-latex-to-mathml-convert-command nil
  2673. "Command to convert LaTeX fragments to MathML.
  2674. Replace format-specifiers in the command as noted below and use
  2675. `shell-command' to convert LaTeX to MathML.
  2676. %j: Executable file in fully expanded form as specified by
  2677. `org-latex-to-mathml-jar-file'.
  2678. %I: Input LaTeX file in fully expanded form.
  2679. %i: The latex fragment to be converted.
  2680. %o: Output MathML file.
  2681. This command is used by `org-create-math-formula'.
  2682. When using MathToWeb as the converter, set this option to
  2683. \"java -jar %j -unicode -force -df %o %I\".
  2684. When using LaTeXML set this option to
  2685. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2686. :group 'org-latex
  2687. :version "24.1"
  2688. :type '(choice
  2689. (const :tag "None" nil)
  2690. (string :tag "\nShell command")))
  2691. (defcustom org-latex-to-html-convert-command nil
  2692. "Command to convert LaTeX fragments to HTML.
  2693. This command is very open-ended: the output of the command will
  2694. directly replace the LaTeX fragment in the resulting HTML.
  2695. Replace format-specifiers in the command as noted below and use
  2696. `shell-command' to convert LaTeX to HTML.
  2697. %i: The LaTeX fragment to be converted.
  2698. For example, this could be used with LaTeXML as
  2699. \"latexmlc \\='literal:%i\\=' --profile=math --preload=siunitx.sty 2>/dev/null\"."
  2700. :group 'org-latex
  2701. :package-version '(Org . "9.4")
  2702. :type '(choice
  2703. (const :tag "None" nil)
  2704. (string :tag "Shell command")))
  2705. (defcustom org-preview-latex-default-process 'dvipng
  2706. "The default process to convert LaTeX fragments to image files.
  2707. All available processes and theirs documents can be found in
  2708. `org-preview-latex-process-alist', which see."
  2709. :group 'org-latex
  2710. :version "26.1"
  2711. :package-version '(Org . "9.0")
  2712. :type 'symbol)
  2713. (defcustom org-preview-latex-process-alist
  2714. '((dvipng
  2715. :programs ("latex" "dvipng")
  2716. :description "dvi > png"
  2717. :message "you need to install the programs: latex and dvipng."
  2718. :image-input-type "dvi"
  2719. :image-output-type "png"
  2720. :image-size-adjust (1.0 . 1.0)
  2721. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2722. :image-converter ("dvipng -D %D -T tight -o %O %f")
  2723. :transparent-image-converter
  2724. ("dvipng -D %D -T tight -bg Transparent -o %O %f"))
  2725. (dvisvgm
  2726. :programs ("latex" "dvisvgm")
  2727. :description "dvi > svg"
  2728. :message "you need to install the programs: latex and dvisvgm."
  2729. :image-input-type "dvi"
  2730. :image-output-type "svg"
  2731. :image-size-adjust (1.7 . 1.5)
  2732. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2733. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2734. (imagemagick
  2735. :programs ("latex" "convert")
  2736. :description "pdf > png"
  2737. :message "you need to install the programs: latex and imagemagick."
  2738. :image-input-type "pdf"
  2739. :image-output-type "png"
  2740. :image-size-adjust (1.0 . 1.0)
  2741. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2742. :image-converter
  2743. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2744. "Definitions of external processes for LaTeX previewing.
  2745. Org mode can use some external commands to generate TeX snippet's images for
  2746. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2747. `org-create-formula-image' how to call them.
  2748. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2749. PROPERTIES accepts the following attributes:
  2750. :programs list of strings, required programs.
  2751. :description string, describe the process.
  2752. :message string, message it when required programs cannot be found.
  2753. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2754. :image-output-type string, output file type of image converter (e.g., \"png\").
  2755. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2756. image size showed in buffer and the cdr element is for
  2757. HTML file. This option is only useful for process
  2758. developers, users should use variable
  2759. `org-format-latex-options' instead.
  2760. :post-clean list of strings, files matched are to be cleaned up once
  2761. the image is generated. When nil, the files with \".dvi\",
  2762. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2763. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2764. be cleaned up.
  2765. :latex-header list of strings, the LaTeX header of the snippet file.
  2766. When nil, the fallback value is used instead, which is
  2767. controlled by `org-format-latex-header',
  2768. `org-latex-default-packages-alist' and
  2769. `org-latex-packages-alist', which see.
  2770. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2771. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2772. replaced with values defined below.
  2773. :image-converter list of image converter commands strings. Each of them is
  2774. given to the shell and supports any of the following
  2775. place-holders defined below.
  2776. If set, :transparent-image-converter is used instead of :image-converter to
  2777. convert an image when the background color is nil or \"Transparent\".
  2778. Place-holders used by `:image-converter' and `:latex-compiler':
  2779. %f input file name
  2780. %b base name of input file
  2781. %o base directory of input file
  2782. %O absolute output file name
  2783. Place-holders only used by `:image-converter':
  2784. %D dpi, which is used to adjust image size by some processing commands.
  2785. %S the image size scale ratio, which is used to adjust image size by some
  2786. processing commands."
  2787. :group 'org-latex
  2788. :version "26.1"
  2789. :package-version '(Org . "9.0")
  2790. :type '(alist :tag "LaTeX to image backends"
  2791. :value-type (plist)))
  2792. (defcustom org-preview-latex-image-directory "ltximg/"
  2793. "Path to store latex preview images.
  2794. A relative path here creates many directories relative to the
  2795. processed Org files paths. An absolute path puts all preview
  2796. images at the same place."
  2797. :group 'org-latex
  2798. :version "26.1"
  2799. :package-version '(Org . "9.0")
  2800. :type 'string)
  2801. (defun org-format-latex-mathml-available-p ()
  2802. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2803. (save-match-data
  2804. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2805. org-latex-to-mathml-convert-command)
  2806. (let ((executable (car (split-string
  2807. org-latex-to-mathml-convert-command))))
  2808. (when (executable-find executable)
  2809. (if (string-match
  2810. "%j" org-latex-to-mathml-convert-command)
  2811. (file-readable-p org-latex-to-mathml-jar-file)
  2812. t))))))
  2813. (defcustom org-format-latex-header "\\documentclass{article}
  2814. \\usepackage[usenames]{color}
  2815. \[DEFAULT-PACKAGES]
  2816. \[PACKAGES]
  2817. \\pagestyle{empty} % do not remove
  2818. % The settings below are copied from fullpage.sty
  2819. \\setlength{\\textwidth}{\\paperwidth}
  2820. \\addtolength{\\textwidth}{-3cm}
  2821. \\setlength{\\oddsidemargin}{1.5cm}
  2822. \\addtolength{\\oddsidemargin}{-2.54cm}
  2823. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2824. \\setlength{\\textheight}{\\paperheight}
  2825. \\addtolength{\\textheight}{-\\headheight}
  2826. \\addtolength{\\textheight}{-\\headsep}
  2827. \\addtolength{\\textheight}{-\\footskip}
  2828. \\addtolength{\\textheight}{-3cm}
  2829. \\setlength{\\topmargin}{1.5cm}
  2830. \\addtolength{\\topmargin}{-2.54cm}"
  2831. "The document header used for processing LaTeX fragments.
  2832. It is imperative that this header make sure that no page number
  2833. appears on the page. The package defined in the variables
  2834. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2835. will either replace the placeholder \"[PACKAGES]\" in this
  2836. header, or they will be appended."
  2837. :group 'org-latex
  2838. :type 'string)
  2839. (defun org-set-packages-alist (var val)
  2840. "Set the packages alist and make sure it has 3 elements per entry."
  2841. (set-default-toplevel-value var (mapcar (lambda (x)
  2842. (if (and (consp x) (= (length x) 2))
  2843. (list (car x) (nth 1 x) t)
  2844. x))
  2845. val)))
  2846. (defun org-get-packages-alist (var)
  2847. "Get the packages alist and make sure it has 3 elements per entry."
  2848. (mapcar (lambda (x)
  2849. (if (and (consp x) (= (length x) 2))
  2850. (list (car x) (nth 1 x) t)
  2851. x))
  2852. (default-value var)))
  2853. (defcustom org-latex-default-packages-alist
  2854. '(("AUTO" "inputenc" t ("pdflatex"))
  2855. ("T1" "fontenc" t ("pdflatex"))
  2856. ("" "graphicx" t)
  2857. ("" "longtable" nil)
  2858. ("" "wrapfig" nil)
  2859. ("" "rotating" nil)
  2860. ("normalem" "ulem" t)
  2861. ("" "amsmath" t)
  2862. ("" "amssymb" t)
  2863. ("" "capt-of" nil)
  2864. ("" "hyperref" nil))
  2865. "Alist of default packages to be inserted in the header.
  2866. Change this only if one of the packages here causes an
  2867. incompatibility with another package you are using.
  2868. The packages in this list are needed by one part or another of
  2869. Org mode to function properly:
  2870. - inputenc, fontenc: for basic font and character selection
  2871. - graphicx: for including images
  2872. - longtable: For multipage tables
  2873. - wrapfig: for figure placement
  2874. - rotating: for sideways figures and tables
  2875. - ulem: for underline and strike-through
  2876. - amsmath: for subscript and superscript and math environments
  2877. - amssymb: for various symbols used for interpreting the entities
  2878. in `org-entities'. You can skip some of this package if you don't
  2879. use any of the symbols.
  2880. - capt-of: for captions outside of floats
  2881. - hyperref: for cross references
  2882. Therefore you should not modify this variable unless you know
  2883. what you are doing. The one reason to change it anyway is that
  2884. you might be loading some other package that conflicts with one
  2885. of the default packages. Each element is either a cell or
  2886. a string.
  2887. A cell is of the format
  2888. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2889. If SNIPPET-FLAG is non-nil, the package also needs to be included
  2890. when compiling LaTeX snippets into images for inclusion into
  2891. non-LaTeX output.
  2892. COMPILERS is a list of compilers that should include the package,
  2893. see `org-latex-compiler'. If the document compiler is not in the
  2894. list, and the list is non-nil, the package will not be inserted
  2895. in the final document.
  2896. A string will be inserted as-is in the header of the document."
  2897. :group 'org-latex
  2898. :group 'org-export-latex
  2899. :set 'org-set-packages-alist
  2900. :get 'org-get-packages-alist
  2901. :version "26.1"
  2902. :package-version '(Org . "8.3")
  2903. :type '(repeat
  2904. (choice
  2905. (list :tag "options/package pair"
  2906. (string :tag "options")
  2907. (string :tag "package")
  2908. (boolean :tag "Snippet")
  2909. (choice
  2910. (const :tag "For all compilers" nil)
  2911. (repeat :tag "Allowed compiler" string)))
  2912. (string :tag "A line of LaTeX"))))
  2913. (defcustom org-latex-packages-alist nil
  2914. "Alist of packages to be inserted in every LaTeX header.
  2915. These will be inserted after `org-latex-default-packages-alist'.
  2916. Each element is either a cell or a string.
  2917. A cell is of the format:
  2918. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2919. SNIPPET-FLAG, when non-nil, indicates that this package is also
  2920. needed when turning LaTeX snippets into images for inclusion into
  2921. non-LaTeX output.
  2922. COMPILERS is a list of compilers that should include the package,
  2923. see `org-latex-compiler'. If the document compiler is not in the
  2924. list, and the list is non-nil, the package will not be inserted
  2925. in the final document.
  2926. A string will be inserted as-is in the header of the document.
  2927. Make sure that you only list packages here which:
  2928. - you want in every file;
  2929. - do not conflict with the setup in `org-format-latex-header';
  2930. - do not conflict with the default packages in
  2931. `org-latex-default-packages-alist'."
  2932. :group 'org-latex
  2933. :group 'org-export-latex
  2934. :set 'org-set-packages-alist
  2935. :get 'org-get-packages-alist
  2936. :type '(repeat
  2937. (choice
  2938. (list :tag "options/package pair"
  2939. (string :tag "options")
  2940. (string :tag "package")
  2941. (boolean :tag "Snippet"))
  2942. (string :tag "A line of LaTeX"))))
  2943. (defgroup org-appearance nil
  2944. "Settings for Org mode appearance."
  2945. :tag "Org Appearance"
  2946. :group 'org)
  2947. (defcustom org-level-color-stars-only nil
  2948. "Non-nil means fontify only the stars in each headline.
  2949. When nil, the entire headline is fontified.
  2950. Changing it requires restart of `font-lock-mode' to become effective
  2951. also in regions already fontified."
  2952. :group 'org-appearance
  2953. :type 'boolean)
  2954. (defcustom org-hide-leading-stars nil
  2955. "Non-nil means hide the first N-1 stars in a headline.
  2956. This works by using the face `org-hide' for these stars. This
  2957. face is white for a light background, and black for a dark
  2958. background. You may have to customize the face `org-hide' to
  2959. make this work.
  2960. Changing it requires restart of `font-lock-mode' to become effective
  2961. also in regions already fontified.
  2962. You may also set this on a per-file basis by adding one of the following
  2963. lines to the buffer:
  2964. #+STARTUP: hidestars
  2965. #+STARTUP: showstars"
  2966. :group 'org-appearance
  2967. :type 'boolean)
  2968. (defcustom org-hidden-keywords nil
  2969. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  2970. For example, a value (title) for this list makes the document's title
  2971. appear in the buffer without the initial \"#+TITLE:\" part."
  2972. :group 'org-appearance
  2973. :package-version '(Org . "9.5")
  2974. :type '(set (const :tag "#+AUTHOR" author)
  2975. (const :tag "#+DATE" date)
  2976. (const :tag "#+EMAIL" email)
  2977. (const :tag "#+SUBTITLE" subtitle)
  2978. (const :tag "#+TITLE" title)))
  2979. (defcustom org-custom-properties nil
  2980. "List of properties (as strings) with a special meaning.
  2981. The default use of these custom properties is to let the user
  2982. hide them with `org-toggle-custom-properties-visibility'."
  2983. :group 'org-properties
  2984. :group 'org-appearance
  2985. :version "24.3"
  2986. :type '(repeat (string :tag "Property Name")))
  2987. (defcustom org-fontify-todo-headline nil
  2988. "Non-nil means change the face of a headline if it is marked as TODO.
  2989. Normally, only the TODO/DONE keyword indicates the state of a headline.
  2990. When this is non-nil, the headline after the keyword is set to the
  2991. `org-headline-todo' as an additional indication."
  2992. :group 'org-appearance
  2993. :package-version '(Org . "9.4")
  2994. :type 'boolean
  2995. :safe #'booleanp)
  2996. (defcustom org-fontify-done-headline t
  2997. "Non-nil means change the face of a headline if it is marked DONE.
  2998. Normally, only the TODO/DONE keyword indicates the state of a headline.
  2999. When this is non-nil, the headline after the keyword is set to the
  3000. `org-headline-done' as an additional indication."
  3001. :group 'org-appearance
  3002. :package-version '(Org . "9.4")
  3003. :type 'boolean)
  3004. (defcustom org-fontify-emphasized-text t
  3005. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3006. Changing this variable requires a restart of Emacs to take effect."
  3007. :group 'org-appearance
  3008. :type 'boolean)
  3009. (defcustom org-fontify-whole-heading-line nil
  3010. "Non-nil means fontify the whole line for headings.
  3011. This is useful when setting a background color for the
  3012. org-level-* faces."
  3013. :group 'org-appearance
  3014. :type 'boolean)
  3015. (defcustom org-fontify-whole-block-delimiter-line t
  3016. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3017. This is useful when setting a background color for the
  3018. org-block-begin-line and org-block-end-line faces."
  3019. :group 'org-appearance
  3020. :type 'boolean)
  3021. (defcustom org-highlight-latex-and-related nil
  3022. "Non-nil means highlight LaTeX related syntax in the buffer.
  3023. When non-nil, the value should be a list containing any of the
  3024. following symbols:
  3025. `native' Highlight LaTeX snippets and environments natively.
  3026. `latex' Highlight LaTeX snippets and environments.
  3027. `script' Highlight subscript and superscript.
  3028. `entities' Highlight entities."
  3029. :group 'org-appearance
  3030. :version "24.4"
  3031. :package-version '(Org . "8.0")
  3032. :type '(choice
  3033. (const :tag "No highlighting" nil)
  3034. (set :greedy t :tag "Highlight"
  3035. (const :tag "LaTeX snippets and environments (native)" native)
  3036. (const :tag "LaTeX snippets and environments" latex)
  3037. (const :tag "Subscript and superscript" script)
  3038. (const :tag "Entities" entities))))
  3039. (defcustom org-hide-emphasis-markers nil
  3040. "Non-nil mean font-lock should hide the emphasis marker characters."
  3041. :group 'org-appearance
  3042. :type 'boolean
  3043. :safe #'booleanp)
  3044. (defcustom org-hide-macro-markers nil
  3045. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3046. :group 'org-appearance
  3047. :type 'boolean)
  3048. (defcustom org-pretty-entities nil
  3049. "Non-nil means show entities as UTF8 characters.
  3050. When nil, the \\name form remains in the buffer."
  3051. :group 'org-appearance
  3052. :version "24.1"
  3053. :type 'boolean)
  3054. (defcustom org-pretty-entities-include-sub-superscripts t
  3055. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3056. :group 'org-appearance
  3057. :version "24.1"
  3058. :type 'boolean)
  3059. (defvar org-emph-re nil
  3060. "Regular expression for matching emphasis.
  3061. After a match, the match groups contain these elements:
  3062. 0 The match of the full regular expression, including the characters
  3063. before and after the proper match
  3064. 1 The character before the proper match, or empty at beginning of line
  3065. 2 The proper match, including the leading and trailing markers
  3066. 3 The leading marker like * or /, indicating the type of highlighting
  3067. 4 The text between the emphasis markers, not including the markers
  3068. 5 The character after the match, empty at the end of a line")
  3069. (defvar org-verbatim-re nil
  3070. "Regular expression for matching verbatim text.")
  3071. (defvar org-emphasis-regexp-components) ; defined just below
  3072. (defvar org-emphasis-alist) ; defined just below
  3073. (defun org-set-emph-re (var val)
  3074. "Set variable and compute the emphasis regular expression."
  3075. (set-default-toplevel-value var val)
  3076. (when (and (boundp 'org-emphasis-alist)
  3077. (boundp 'org-emphasis-regexp-components)
  3078. org-emphasis-alist org-emphasis-regexp-components)
  3079. (pcase-let*
  3080. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3081. (body (if (<= nl 0) body
  3082. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3083. (template
  3084. (format (concat "\\([%s]\\|^\\)" ;before markers
  3085. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3086. "\\([%s]\\|$\\)") ;after markers
  3087. pre border border body border post)))
  3088. (setq org-emph-re (format template "*/_+"))
  3089. (setq org-verbatim-re (format template "=~")))))
  3090. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3091. ;; set this option proved cumbersome. See this message/thread:
  3092. ;; https://orgmode.org/list/B72CDC2B-72F6-43A8-AC70-E6E6295766EC@gmail.com
  3093. (defvar org-emphasis-regexp-components
  3094. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3095. "Components used to build the regular expression for emphasis.
  3096. This is a list with five entries. Terminology: In an emphasis string
  3097. like \" *strong word* \", we call the initial space PREMATCH, the final
  3098. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3099. and \"trong wor\" is the body. The different components in this variable
  3100. specify what is allowed/forbidden in each part:
  3101. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3102. post Chars allowed as postmatch. End of line will be allowed too.
  3103. border The chars *forbidden* as border characters.
  3104. body-regexp A regexp like \".\" to match a body character. Don't use
  3105. non-shy groups here, and don't allow newline here.
  3106. newline The maximum number of newlines allowed in an emphasis exp.
  3107. You need to reload Org or to restart Emacs after setting this.")
  3108. (defcustom org-emphasis-alist
  3109. '(("*" bold)
  3110. ("/" italic)
  3111. ("_" underline)
  3112. ("=" org-verbatim verbatim)
  3113. ("~" org-code verbatim)
  3114. ("+" (:strike-through t)))
  3115. "Alist of characters and faces to emphasize text.
  3116. Text starting and ending with a special character will be emphasized,
  3117. for example *bold*, _underlined_ and /italic/. This variable sets the
  3118. marker characters and the face to be used by font-lock for highlighting
  3119. in Org buffers.
  3120. You need to reload Org or to restart Emacs after customizing this."
  3121. :group 'org-appearance
  3122. :set 'org-set-emph-re
  3123. :version "24.4"
  3124. :package-version '(Org . "8.0")
  3125. :type '(repeat
  3126. (list
  3127. (string :tag "Marker character")
  3128. (choice
  3129. (face :tag "Font-lock-face")
  3130. (plist :tag "Face property list"))
  3131. (option (const verbatim)))))
  3132. (defvar org-protecting-blocks '("src" "example" "export")
  3133. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3134. This is needed for font-lock setup.")
  3135. ;;; Functions and variables from their packages
  3136. ;; Declared here to avoid compiler warnings
  3137. (defvar mark-active)
  3138. ;; Various packages
  3139. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3140. (declare-function calendar-forward-day "cal-move" (arg))
  3141. (declare-function calendar-goto-date "cal-move" (date))
  3142. (declare-function calendar-goto-today "cal-move" ())
  3143. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3144. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3145. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3146. (declare-function cdlatex-tab "ext:cdlatex" ())
  3147. (declare-function dired-get-filename
  3148. "dired"
  3149. (&optional localp no-error-if-not-filep))
  3150. (declare-function iswitchb-read-buffer
  3151. "iswitchb"
  3152. (prompt &optional
  3153. default require-match _predicate start matches-set))
  3154. (declare-function org-agenda-change-all-lines
  3155. "org-agenda"
  3156. (newhead hdmarker &optional fixface just-this))
  3157. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3158. "org-agenda"
  3159. (&optional end))
  3160. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3161. (declare-function org-agenda-format-item
  3162. "org-agenda"
  3163. (extra txt &optional level category tags dotime
  3164. remove-re habitp))
  3165. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3166. (declare-function org-agenda-save-markers-for-cut-and-paste
  3167. "org-agenda"
  3168. (beg end))
  3169. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3170. (declare-function org-agenda-skip "org-agenda" (&optional element))
  3171. (declare-function org-attach-expand "org-attach" (file))
  3172. (declare-function org-attach-reveal "org-attach" ())
  3173. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3174. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3175. (declare-function org-indent-mode "org-indent" (&optional arg))
  3176. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3177. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3178. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3179. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3180. (declare-function parse-time-string "parse-time" (string))
  3181. (defvar align-mode-rules-list)
  3182. (defvar calc-embedded-close-formula)
  3183. (defvar calc-embedded-open-formula)
  3184. (defvar calc-embedded-open-mode)
  3185. (defvar font-lock-unfontify-region-function)
  3186. (defvar iswitchb-temp-buflist)
  3187. (defvar org-agenda-tags-todo-honor-ignore-options)
  3188. (defvar remember-data-file)
  3189. (defvar texmathp-why)
  3190. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3191. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3192. (declare-function org-resolve-clocks "org-clock"
  3193. (&optional also-non-dangling-p prompt last-valid))
  3194. (defvar org-clock-start-time)
  3195. (defvar org-clock-marker (make-marker)
  3196. "Marker recording the last clock-in.")
  3197. (defvar org-clock-hd-marker (make-marker)
  3198. "Marker recording the last clock-in, but the headline position.")
  3199. (defvar org-clock-heading ""
  3200. "The heading of the current clock entry.")
  3201. (defun org-clocking-buffer ()
  3202. "Return the buffer where the clock is currently running.
  3203. Return nil if no clock is running."
  3204. (marker-buffer org-clock-marker))
  3205. (defalias 'org-clock-is-active #'org-clocking-buffer)
  3206. (defun org-check-running-clock ()
  3207. "Check if the current buffer contains the running clock.
  3208. If yes, offer to stop it and to save the buffer with the changes."
  3209. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3210. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3211. (buffer-name))))
  3212. (org-clock-out)
  3213. (when (y-or-n-p "Save changed buffer?")
  3214. (save-buffer))))
  3215. (defun org-clocktable-try-shift (dir n)
  3216. "Check if this line starts a clock table, if yes, shift the time block."
  3217. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3218. (org-clocktable-shift dir n)))
  3219. ;;;###autoload
  3220. (defun org-clock-persistence-insinuate ()
  3221. "Set up hooks for clock persistence."
  3222. (require 'org-clock)
  3223. (add-hook 'org-mode-hook 'org-clock-load)
  3224. (add-hook 'kill-emacs-hook 'org-clock-save))
  3225. (defun org-clock-auto-clockout-insinuate ()
  3226. "Set up hook for auto clocking out when Emacs is idle.
  3227. See `org-clock-auto-clockout-timer'.
  3228. This function is meant to be added to the user configuration."
  3229. (require 'org-clock)
  3230. (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t))
  3231. (defgroup org-archive nil
  3232. "Options concerning archiving in Org mode."
  3233. :tag "Org Archive"
  3234. :group 'org-structure)
  3235. (defcustom org-archive-location "%s_archive::"
  3236. "The location where subtrees should be archived.
  3237. The value of this variable is a string, consisting of two parts,
  3238. separated by a double-colon. The first part is a filename and
  3239. the second part is a headline.
  3240. When the filename is omitted, archiving happens in the same file.
  3241. %s in the filename will be replaced by the current file
  3242. name (without the directory part). Archiving to a different file
  3243. is useful to keep archived entries from contributing to the
  3244. Org Agenda.
  3245. The archived entries will be filed as subtrees of the specified
  3246. headline. When the headline is omitted, the subtrees are simply
  3247. filed away at the end of the file, as top-level entries. Also in
  3248. the heading you can use %s to represent the file name, this can be
  3249. useful when using the same archive for a number of different files.
  3250. Here are a few examples:
  3251. \"%s_archive::\"
  3252. If the current file is Projects.org, archive in file
  3253. Projects.org_archive, as top-level trees. This is the default.
  3254. \"::* Archived Tasks\"
  3255. Archive in the current file, under the top-level headline
  3256. \"* Archived Tasks\".
  3257. \"~/org/archive.org::\"
  3258. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3259. \"~/org/archive.org::* From %s\"
  3260. Archive in file ~/org/archive.org (absolute path), under headlines
  3261. \"From FILENAME\" where file name is the current file name.
  3262. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3263. The \"datetree/\" string is special, signifying to archive
  3264. items to the datetree. Items are placed in either the CLOSED
  3265. date of the item, or the current date if there is no CLOSED date.
  3266. The heading will be a subentry to the current date. There doesn't
  3267. need to be a heading, but there always needs to be a slash after
  3268. datetree. For example, to store archived items directly in the
  3269. datetree, use \"~/org/datetree.org::datetree/\".
  3270. \"basement::** Finished Tasks\"
  3271. Archive in file ./basement (relative path), as level 3 trees
  3272. below the level 2 heading \"** Finished Tasks\".
  3273. You may define it locally by setting an ARCHIVE property. If
  3274. such a property is found in the file or in an entry, and anywhere
  3275. up the hierarchy, it will be used.
  3276. You can also set it for the whole file using the keyword-syntax:
  3277. #+ARCHIVE: basement::** Finished Tasks"
  3278. :group 'org-archive
  3279. :type 'string)
  3280. (defcustom org-agenda-skip-archived-trees t
  3281. "Non-nil means the agenda will skip any items located in archived trees.
  3282. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3283. variable is no longer recommended, you should leave it at the value t.
  3284. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3285. :group 'org-archive
  3286. :group 'org-agenda-skip
  3287. :type 'boolean)
  3288. (defcustom org-columns-skip-archived-trees t
  3289. "Non-nil means ignore archived trees when creating column view."
  3290. :group 'org-archive
  3291. :group 'org-properties
  3292. :type 'boolean)
  3293. (defcustom org-sparse-tree-open-archived-trees nil
  3294. "Non-nil means sparse tree construction shows matches in archived trees.
  3295. When nil, matches in these trees are highlighted, but the trees are kept in
  3296. collapsed state."
  3297. :group 'org-archive
  3298. :group 'org-sparse-trees
  3299. :type 'boolean)
  3300. (defcustom org-sparse-tree-default-date-type nil
  3301. "The default date type when building a sparse tree.
  3302. When this is nil, a date is a scheduled or a deadline timestamp.
  3303. Otherwise, these types are allowed:
  3304. all: all timestamps
  3305. active: only active timestamps (<...>)
  3306. inactive: only inactive timestamps ([...])
  3307. scheduled: only scheduled timestamps
  3308. deadline: only deadline timestamps"
  3309. :type '(choice (const :tag "Scheduled or deadline" nil)
  3310. (const :tag "All timestamps" all)
  3311. (const :tag "Only active timestamps" active)
  3312. (const :tag "Only inactive timestamps" inactive)
  3313. (const :tag "Only scheduled timestamps" scheduled)
  3314. (const :tag "Only deadline timestamps" deadline)
  3315. (const :tag "Only closed timestamps" closed))
  3316. :version "26.1"
  3317. :package-version '(Org . "8.3")
  3318. :group 'org-sparse-trees)
  3319. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3320. ;; Declare Column View Code
  3321. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3322. (declare-function org-columns-compute "org-colview" (property))
  3323. ;; Declare ID code
  3324. (declare-function org-id-store-link "org-id")
  3325. (declare-function org-id-locations-load "org-id")
  3326. (declare-function org-id-locations-save "org-id")
  3327. (defvar org-id-track-globally)
  3328. ;;; Variables for pre-computed regular expressions, all buffer local
  3329. (defvar-local org-todo-regexp nil
  3330. "Matches any of the TODO state keywords.
  3331. Since TODO keywords are case-sensitive, `case-fold-search' is
  3332. expected to be bound to nil when matching against this regexp.")
  3333. (defvar-local org-not-done-regexp nil
  3334. "Matches any of the TODO state keywords except the last one.
  3335. Since TODO keywords are case-sensitive, `case-fold-search' is
  3336. expected to be bound to nil when matching against this regexp.")
  3337. (defvar-local org-not-done-heading-regexp nil
  3338. "Matches a TODO headline that is not done.
  3339. Since TODO keywords are case-sensitive, `case-fold-search' is
  3340. expected to be bound to nil when matching against this regexp.")
  3341. (defvar-local org-todo-line-regexp nil
  3342. "Matches a headline and puts TODO state into group 2 if present.
  3343. Since TODO keywords are case-sensitive, `case-fold-search' is
  3344. expected to be bound to nil when matching against this regexp.")
  3345. (defvar-local org-complex-heading-regexp nil
  3346. "Matches a headline and puts everything into groups:
  3347. group 1: Stars
  3348. group 2: The TODO keyword, maybe
  3349. group 3: Priority cookie
  3350. group 4: True headline
  3351. group 5: Tags
  3352. Since TODO keywords are case-sensitive, `case-fold-search' is
  3353. expected to be bound to nil when matching against this regexp.")
  3354. (defvar-local org-complex-heading-regexp-format nil
  3355. "Printf format to make regexp to match an exact headline.
  3356. This regexp will match the headline of any node which has the
  3357. exact headline text that is put into the format, but may have any
  3358. TODO state, priority, tags, statistics cookies (at the beginning
  3359. or end of the headline title), or COMMENT keyword.")
  3360. (defvar-local org-todo-line-tags-regexp nil
  3361. "Matches a headline and puts TODO state into group 2 if present.
  3362. Also put tags into group 4 if tags are present.")
  3363. (defconst org-plain-time-of-day-regexp
  3364. (concat
  3365. "\\(\\<[012]?[0-9]"
  3366. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3367. "\\(--?"
  3368. "\\(\\<[012]?[0-9]"
  3369. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3370. "\\)?")
  3371. "Regular expression to match a plain time or time range.
  3372. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3373. groups carry important information:
  3374. 0 the full match
  3375. 1 the first time, range or not
  3376. 8 the second time, if it is a range.")
  3377. (defconst org-plain-time-extension-regexp
  3378. (concat
  3379. "\\(\\<[012]?[0-9]"
  3380. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3381. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3382. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3383. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3384. groups carry important information:
  3385. 0 the full match
  3386. 7 hours of duration
  3387. 9 minutes of duration")
  3388. (defconst org-stamp-time-of-day-regexp
  3389. (concat
  3390. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3391. "\\([012][0-9]:[0-5][0-9]\\)\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?>"
  3392. "\\(--?"
  3393. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3394. "Regular expression to match a timestamp time or time range.
  3395. After a match, the following groups carry important information:
  3396. 0 the full match
  3397. 1 date plus weekday, for back referencing to make sure
  3398. both times are on the same day
  3399. 2 the first time, range or not
  3400. 4 the second time, if it is a range.")
  3401. (defconst org-startup-options
  3402. '(("fold" org-startup-folded t)
  3403. ("overview" org-startup-folded t)
  3404. ("nofold" org-startup-folded nil)
  3405. ("showall" org-startup-folded nil)
  3406. ("show2levels" org-startup-folded show2levels)
  3407. ("show3levels" org-startup-folded show3levels)
  3408. ("show4levels" org-startup-folded show4levels)
  3409. ("show5levels" org-startup-folded show5levels)
  3410. ("showeverything" org-startup-folded showeverything)
  3411. ("content" org-startup-folded content)
  3412. ("indent" org-startup-indented t)
  3413. ("noindent" org-startup-indented nil)
  3414. ("num" org-startup-numerated t)
  3415. ("nonum" org-startup-numerated nil)
  3416. ("hidestars" org-hide-leading-stars t)
  3417. ("showstars" org-hide-leading-stars nil)
  3418. ("odd" org-odd-levels-only t)
  3419. ("oddeven" org-odd-levels-only nil)
  3420. ("align" org-startup-align-all-tables t)
  3421. ("noalign" org-startup-align-all-tables nil)
  3422. ("shrink" org-startup-shrink-all-tables t)
  3423. ("inlineimages" org-startup-with-inline-images t)
  3424. ("noinlineimages" org-startup-with-inline-images nil)
  3425. ("latexpreview" org-startup-with-latex-preview t)
  3426. ("nolatexpreview" org-startup-with-latex-preview nil)
  3427. ("customtime" org-display-custom-times t)
  3428. ("logdone" org-log-done time)
  3429. ("lognotedone" org-log-done note)
  3430. ("nologdone" org-log-done nil)
  3431. ("lognoteclock-out" org-log-note-clock-out t)
  3432. ("nolognoteclock-out" org-log-note-clock-out nil)
  3433. ("logrepeat" org-log-repeat state)
  3434. ("lognoterepeat" org-log-repeat note)
  3435. ("logdrawer" org-log-into-drawer t)
  3436. ("nologdrawer" org-log-into-drawer nil)
  3437. ("logstatesreversed" org-log-states-order-reversed t)
  3438. ("nologstatesreversed" org-log-states-order-reversed nil)
  3439. ("nologrepeat" org-log-repeat nil)
  3440. ("logreschedule" org-log-reschedule time)
  3441. ("lognotereschedule" org-log-reschedule note)
  3442. ("nologreschedule" org-log-reschedule nil)
  3443. ("logredeadline" org-log-redeadline time)
  3444. ("lognoteredeadline" org-log-redeadline note)
  3445. ("nologredeadline" org-log-redeadline nil)
  3446. ("logrefile" org-log-refile time)
  3447. ("lognoterefile" org-log-refile note)
  3448. ("nologrefile" org-log-refile nil)
  3449. ("fninline" org-footnote-define-inline t)
  3450. ("nofninline" org-footnote-define-inline nil)
  3451. ("fnlocal" org-footnote-section nil)
  3452. ("fnauto" org-footnote-auto-label t)
  3453. ("fnprompt" org-footnote-auto-label nil)
  3454. ("fnconfirm" org-footnote-auto-label confirm)
  3455. ("fnplain" org-footnote-auto-label plain)
  3456. ("fnadjust" org-footnote-auto-adjust t)
  3457. ("nofnadjust" org-footnote-auto-adjust nil)
  3458. ("constcgs" constants-unit-system cgs)
  3459. ("constSI" constants-unit-system SI)
  3460. ("noptag" org-tag-persistent-alist nil)
  3461. ("hideblocks" org-hide-block-startup t)
  3462. ("nohideblocks" org-hide-block-startup nil)
  3463. ("hidedrawers" org-hide-drawer-startup t)
  3464. ("nohidedrawers" org-hide-drawer-startup nil)
  3465. ("beamer" org-startup-with-beamer-mode t)
  3466. ("entitiespretty" org-pretty-entities t)
  3467. ("entitiesplain" org-pretty-entities nil))
  3468. "Variable associated with STARTUP options for Org.
  3469. Each element is a list of three items: the startup options (as written
  3470. in the #+STARTUP line), the corresponding variable, and the value to set
  3471. this variable to if the option is found. An optional fourth element PUSH
  3472. means to push this value onto the list in the variable.")
  3473. (defcustom org-group-tags t
  3474. "When non-nil (the default), use group tags.
  3475. This can be turned on/off through `org-toggle-tags-groups'."
  3476. :group 'org-tags
  3477. :group 'org-startup
  3478. :type 'boolean)
  3479. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3480. (defun org-toggle-tags-groups ()
  3481. "Toggle support for group tags.
  3482. Support for group tags is controlled by the option
  3483. `org-group-tags', which is non-nil by default."
  3484. (interactive)
  3485. (setq org-group-tags (not org-group-tags))
  3486. (cond ((and (derived-mode-p 'org-agenda-mode)
  3487. org-group-tags)
  3488. (org-agenda-redo))
  3489. ((derived-mode-p 'org-mode)
  3490. (let ((org-inhibit-startup t)) (org-mode))))
  3491. (message "Groups tags support has been turned %s"
  3492. (if org-group-tags "on" "off")))
  3493. (defun org--tag-add-to-alist (alist1 alist2)
  3494. "Merge tags from ALIST1 into ALIST2.
  3495. Duplicates tags outside a group are removed. Keywords and order
  3496. are preserved.
  3497. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3498. See `org-tag-alist' for their structure."
  3499. (cond
  3500. ((null alist2) alist1)
  3501. ((null alist1) alist2)
  3502. (t
  3503. (let ((to-add nil)
  3504. (group-flag nil))
  3505. (dolist (tag-pair alist1)
  3506. (pcase tag-pair
  3507. (`(,(or :startgrouptag :startgroup))
  3508. (setq group-flag t)
  3509. (push tag-pair to-add))
  3510. (`(,(or :endgrouptag :endgroup))
  3511. (setq group-flag nil)
  3512. (push tag-pair to-add))
  3513. (`(,(or :grouptags :newline))
  3514. (push tag-pair to-add))
  3515. (`(,tag . ,_)
  3516. ;; Remove duplicates from ALIST1, unless they are in
  3517. ;; a group. Indeed, it makes sense to have a tag appear in
  3518. ;; multiple groups.
  3519. (when (or group-flag (not (assoc tag alist2)))
  3520. (push tag-pair to-add)))
  3521. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3522. ;; Preserve order of ALIST1.
  3523. (append (nreverse to-add) alist2)))))
  3524. (defun org-priority-to-value (s)
  3525. "Convert priority string S to its numeric value."
  3526. (or (save-match-data
  3527. (and (string-match "\\([0-9]+\\)" s)
  3528. (string-to-number (match-string 1 s))))
  3529. (string-to-char s)))
  3530. (defun org-set-regexps-and-options (&optional tags-only)
  3531. "Precompute regular expressions used in the current buffer.
  3532. When optional argument TAGS-ONLY is non-nil, only compute tags
  3533. related expressions."
  3534. (when (derived-mode-p 'org-mode)
  3535. (let ((alist (org-collect-keywords
  3536. (append '("FILETAGS" "TAGS")
  3537. (and (not tags-only)
  3538. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3539. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3540. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))
  3541. '("ARCHIVE" "CATEGORY" "COLUMNS" "PRIORITIES"))))
  3542. ;; Startup options. Get this early since it does change
  3543. ;; behavior for other options (e.g., tags).
  3544. (let ((startup (cl-mapcan (lambda (value) (split-string value))
  3545. (cdr (assoc "STARTUP" alist)))))
  3546. (dolist (option startup)
  3547. (pcase (assoc-string option org-startup-options t)
  3548. (`(,_ ,variable ,value t)
  3549. (unless (listp (symbol-value variable))
  3550. (set (make-local-variable variable) nil))
  3551. (add-to-list variable value))
  3552. (`(,_ ,variable ,value . ,_)
  3553. (set (make-local-variable variable) value))
  3554. (_ nil))))
  3555. (setq-local org-file-tags
  3556. (mapcar #'org-add-prop-inherited
  3557. (cl-mapcan (lambda (value)
  3558. (cl-mapcan
  3559. (lambda (k) (org-split-string k ":"))
  3560. (split-string value)))
  3561. (cdr (assoc "FILETAGS" alist)))))
  3562. (setq org-current-tag-alist
  3563. (org--tag-add-to-alist
  3564. org-tag-persistent-alist
  3565. (let ((tags (cdr (assoc "TAGS" alist))))
  3566. (if tags
  3567. (org-tag-string-to-alist
  3568. (mapconcat #'identity tags "\n"))
  3569. org-tag-alist))))
  3570. (setq org-tag-groups-alist
  3571. (org-tag-alist-to-groups org-current-tag-alist))
  3572. (unless tags-only
  3573. ;; Properties.
  3574. (let ((properties nil))
  3575. (dolist (value (cdr (assoc "PROPERTY" alist)))
  3576. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3577. (setq properties (org--update-property-plist
  3578. (match-string-no-properties 1 value)
  3579. (match-string-no-properties 2 value)
  3580. properties))))
  3581. (setq-local org-keyword-properties properties))
  3582. ;; Archive location.
  3583. (let ((archive (cdr (assoc "ARCHIVE" alist))))
  3584. (when archive (setq-local org-archive-location archive)))
  3585. ;; Category.
  3586. (let ((category (cdr (assoc "CATEGORY" alist))))
  3587. (when category
  3588. (setq-local org-category (intern category))
  3589. (setq-local org-keyword-properties
  3590. (org--update-property-plist
  3591. "CATEGORY" category org-keyword-properties))))
  3592. ;; Columns.
  3593. (let ((column (cdr (assoc "COLUMNS" alist))))
  3594. (when column (setq-local org-columns-default-format column)))
  3595. ;; Constants.
  3596. (let ((store nil))
  3597. (dolist (pair (cl-mapcan #'split-string
  3598. (cdr (assoc "CONSTANTS" alist))))
  3599. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" pair)
  3600. (let* ((name (match-string 1 pair))
  3601. (value (match-string 2 pair))
  3602. (old (assoc name store)))
  3603. (if old (setcdr old value)
  3604. (push (cons name value) store)))))
  3605. (setq org-table-formula-constants-local store))
  3606. ;; Link abbreviations.
  3607. (let ((links
  3608. (delq nil
  3609. (mapcar
  3610. (lambda (value)
  3611. (and (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3612. (cons (match-string-no-properties 1 value)
  3613. (match-string-no-properties 2 value))))
  3614. (cdr (assoc "LINK" alist))))))
  3615. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3616. ;; Priorities.
  3617. (let ((value (cdr (assoc "PRIORITIES" alist))))
  3618. (pcase (and value (split-string value))
  3619. (`(,high ,low ,default . ,_)
  3620. (setq-local org-priority-highest (org-priority-to-value high))
  3621. (setq-local org-priority-lowest (org-priority-to-value low))
  3622. (setq-local org-priority-default (org-priority-to-value default)))))
  3623. ;; Scripts.
  3624. (let ((value (cdr (assoc "OPTIONS" alist))))
  3625. (dolist (option value)
  3626. (when (string-match "\\^:\\(t\\|nil\\|{}\\)" option)
  3627. (setq-local org-use-sub-superscripts
  3628. (read (match-string 1 option))))))
  3629. ;; TODO keywords.
  3630. (setq-local org-todo-kwd-alist nil)
  3631. (setq-local org-todo-key-alist nil)
  3632. (setq-local org-todo-key-trigger nil)
  3633. (setq-local org-todo-keywords-1 nil)
  3634. (setq-local org-done-keywords nil)
  3635. (setq-local org-todo-heads nil)
  3636. (setq-local org-todo-sets nil)
  3637. (setq-local org-todo-log-states nil)
  3638. (let ((todo-sequences
  3639. (or (append (mapcar (lambda (value)
  3640. (cons 'type (split-string value)))
  3641. (cdr (assoc "TYP_TODO" alist)))
  3642. (mapcar (lambda (value)
  3643. (cons 'sequence (split-string value)))
  3644. (append (cdr (assoc "TODO" alist))
  3645. (cdr (assoc "SEQ_TODO" alist)))))
  3646. (let ((d (default-value 'org-todo-keywords)))
  3647. (if (not (stringp (car d))) d
  3648. ;; XXX: Backward compatibility code.
  3649. (list (cons org-todo-interpretation d)))))))
  3650. (dolist (sequence todo-sequences)
  3651. (let* ((sequence (or (run-hook-with-args-until-success
  3652. 'org-todo-setup-filter-hook sequence)
  3653. sequence))
  3654. (sequence-type (car sequence))
  3655. (keywords (cdr sequence))
  3656. (sep (member "|" keywords))
  3657. names alist)
  3658. (dolist (k (remove "|" keywords))
  3659. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3660. k)
  3661. (error "Invalid TODO keyword %s" k))
  3662. (let ((name (match-string 1 k))
  3663. (key (match-string 2 k))
  3664. (log (org-extract-log-state-settings k)))
  3665. (push name names)
  3666. (push (cons name (and key (string-to-char key))) alist)
  3667. (when log (push log org-todo-log-states))))
  3668. (let* ((names (nreverse names))
  3669. (done (if sep (org-remove-keyword-keys (cdr sep))
  3670. (last names)))
  3671. (head (car names))
  3672. (tail (list sequence-type head (car done) (org-last done))))
  3673. (add-to-list 'org-todo-heads head 'append)
  3674. (push names org-todo-sets)
  3675. (setq org-done-keywords (append org-done-keywords done nil))
  3676. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3677. (setq org-todo-key-alist
  3678. (append org-todo-key-alist
  3679. (and alist
  3680. (append '((:startgroup))
  3681. (nreverse alist)
  3682. '((:endgroup))))))
  3683. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3684. (setq org-todo-sets (nreverse org-todo-sets)
  3685. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3686. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3687. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3688. ;; Compute the regular expressions and other local variables.
  3689. ;; Using `org-outline-regexp-bol' would complicate them much,
  3690. ;; because of the fixed white space at the end of that string.
  3691. (unless org-done-keywords
  3692. (setq org-done-keywords
  3693. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3694. (setq org-not-done-keywords
  3695. (org-delete-all org-done-keywords
  3696. (copy-sequence org-todo-keywords-1))
  3697. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3698. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3699. org-not-done-heading-regexp
  3700. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3701. org-todo-line-regexp
  3702. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3703. org-complex-heading-regexp
  3704. (concat "^\\(\\*+\\)"
  3705. "\\(?: +" org-todo-regexp "\\)?"
  3706. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3707. "\\(?: +\\(.*?\\)\\)??"
  3708. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3709. "[ \t]*$")
  3710. org-complex-heading-regexp-format
  3711. (concat "^\\(\\*+\\)"
  3712. "\\(?: +" org-todo-regexp "\\)?"
  3713. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3714. "\\(?: +"
  3715. ;; Headline might be commented
  3716. "\\(?:" org-comment-string " +\\)?"
  3717. ;; Stats cookies can be stuck to body.
  3718. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3719. "\\(%s\\)"
  3720. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3721. "\\)"
  3722. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3723. "[ \t]*$")
  3724. org-todo-line-tags-regexp
  3725. (concat "^\\(\\*+\\)"
  3726. "\\(?: +" org-todo-regexp "\\)?"
  3727. "\\(?: +\\(.*?\\)\\)??"
  3728. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3729. "[ \t]*$"))
  3730. (org-compute-latex-and-related-regexp)))))
  3731. (defun org-collect-keywords (keywords &optional unique directory)
  3732. "Return values for KEYWORDS in current buffer, as an alist.
  3733. KEYWORDS is a list of strings. Return value is a list of
  3734. elements with the pattern:
  3735. (NAME . LIST-OF-VALUES)
  3736. where NAME is the upcase name of the keyword, and LIST-OF-VALUES
  3737. is a list of non-empty values, as strings, in order of appearance
  3738. in the buffer.
  3739. When KEYWORD appears in UNIQUE list, LIST-OF-VALUE is its first
  3740. value, empty or not, appearing in the buffer, as a string.
  3741. When KEYWORD appears in DIRECTORIES, each value is a cons cell:
  3742. (VALUE . DIRECTORY)
  3743. where VALUE is the regular value, and DIRECTORY is the variable
  3744. `default-directory' for the buffer containing the keyword. This
  3745. is important for values containing relative file names, since the
  3746. function follows SETUPFILE keywords, and may change its working
  3747. directory."
  3748. (let* ((keywords (cons "SETUPFILE" (mapcar #'upcase keywords)))
  3749. (unique (mapcar #'upcase unique))
  3750. (alist (org--collect-keywords-1
  3751. keywords unique directory
  3752. (and buffer-file-name (list buffer-file-name))
  3753. nil)))
  3754. ;; Re-order results.
  3755. (dolist (entry alist)
  3756. (pcase entry
  3757. (`(,_ . ,(and value (pred consp)))
  3758. (setcdr entry (nreverse value)))))
  3759. (nreverse alist)))
  3760. (defun org--collect-keywords-1 (keywords unique directory files alist)
  3761. (org-with-point-at 1
  3762. (let ((case-fold-search t)
  3763. (regexp (org-make-options-regexp keywords)))
  3764. (while (and keywords (re-search-forward regexp nil t))
  3765. (let ((element (org-element-at-point)))
  3766. (when (eq 'keyword (org-element-type element))
  3767. (let ((value (org-element-property :value element)))
  3768. (pcase (org-element-property :key element)
  3769. ("SETUPFILE"
  3770. (when (and (org-string-nw-p value)
  3771. (not buffer-read-only)) ;FIXME: bug in Gnus?
  3772. (let* ((uri (org-strip-quotes value))
  3773. (uri-is-url (org-url-p uri))
  3774. (uri (if uri-is-url
  3775. uri
  3776. (expand-file-name uri))))
  3777. (unless (member uri files)
  3778. (with-temp-buffer
  3779. (unless uri-is-url
  3780. (setq default-directory (file-name-directory uri)))
  3781. (let ((contents (org-file-contents uri :noerror)))
  3782. (when contents
  3783. (insert contents)
  3784. ;; Fake Org mode: `org-element-at-point'
  3785. ;; doesn't need full set-up.
  3786. (let ((major-mode 'org-mode))
  3787. (setq alist
  3788. (org--collect-keywords-1
  3789. keywords unique directory
  3790. (cons uri files)
  3791. alist))))))))))
  3792. (keyword
  3793. (let ((entry (assoc keyword alist))
  3794. (final
  3795. (cond ((not (member keyword directory)) value)
  3796. (buffer-file-name
  3797. (cons value
  3798. (file-name-directory buffer-file-name)))
  3799. (t (cons value default-directory)))))
  3800. (cond ((member keyword unique)
  3801. (push (cons keyword final) alist)
  3802. (setq keywords (remove keyword keywords))
  3803. (setq regexp (org-make-options-regexp keywords)))
  3804. ((null entry) (push (list keyword final) alist))
  3805. (t (push final (cdr entry)))))))))))
  3806. alist)))
  3807. (defun org-tag-string-to-alist (s)
  3808. "Return tag alist associated to string S.
  3809. S is a value for TAGS keyword or produced with
  3810. `org-tag-alist-to-string'. Return value is an alist suitable for
  3811. `org-tag-alist' or `org-tag-persistent-alist'."
  3812. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3813. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3814. "\\(?:(\\(.\\))\\)?\\'"))
  3815. alist group-flag)
  3816. (dolist (tokens lines (cdr (nreverse alist)))
  3817. (push '(:newline) alist)
  3818. (while tokens
  3819. (let ((token (pop tokens)))
  3820. (pcase token
  3821. ("{"
  3822. (push '(:startgroup) alist)
  3823. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3824. ("}"
  3825. (push '(:endgroup) alist)
  3826. (setq group-flag nil))
  3827. ("["
  3828. (push '(:startgrouptag) alist)
  3829. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3830. ("]"
  3831. (push '(:endgrouptag) alist)
  3832. (setq group-flag nil))
  3833. (":"
  3834. (push '(:grouptags) alist))
  3835. ((guard (string-match tag-re token))
  3836. (let ((tag (match-string 1 token))
  3837. (key (and (match-beginning 2)
  3838. (string-to-char (match-string 2 token)))))
  3839. ;; Push all tags in groups, no matter if they already
  3840. ;; appear somewhere else in the list.
  3841. (when (or group-flag (not (assoc tag alist)))
  3842. (push (cons tag key) alist))))))))))
  3843. (defun org-tag-alist-to-string (alist &optional skip-key)
  3844. "Return tag string associated to ALIST.
  3845. ALIST is an alist, as defined in `org-tag-alist' or
  3846. `org-tag-persistent-alist', or produced with
  3847. `org-tag-string-to-alist'.
  3848. Return value is a string suitable as a value for \"TAGS\"
  3849. keyword.
  3850. When optional argument SKIP-KEY is non-nil, skip selection keys
  3851. next to tags."
  3852. (mapconcat (lambda (token)
  3853. (pcase token
  3854. (`(:startgroup) "{")
  3855. (`(:endgroup) "}")
  3856. (`(:startgrouptag) "[")
  3857. (`(:endgrouptag) "]")
  3858. (`(:grouptags) ":")
  3859. (`(:newline) "\\n")
  3860. ((and
  3861. (guard (not skip-key))
  3862. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  3863. (format "%s(%c)" tag key))
  3864. (`(,(and tag (pred stringp)) . ,_) tag)
  3865. (_ (user-error "Invalid tag token: %S" token))))
  3866. alist
  3867. " "))
  3868. (defun org-tag-alist-to-groups (alist)
  3869. "Return group alist from tag ALIST.
  3870. ALIST is an alist, as defined in `org-tag-alist' or
  3871. `org-tag-persistent-alist', or produced with
  3872. `org-tag-string-to-alist'. Return value is an alist following
  3873. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  3874. a string, summarizing TAGS, as a list of strings."
  3875. (let (groups group-status current-group)
  3876. (dolist (token alist (nreverse groups))
  3877. (pcase token
  3878. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  3879. (`(,(or :endgroup :endgrouptag))
  3880. (when (eq group-status 'append)
  3881. (push (nreverse current-group) groups))
  3882. (setq group-status nil current-group nil))
  3883. (`(:grouptags) (setq group-status 'append))
  3884. ((and `(,tag . ,_) (guard group-status))
  3885. (if (eq group-status 'append) (push tag current-group)
  3886. (setq current-group (list tag))))
  3887. (_ nil)))))
  3888. (defvar org--file-cache (make-hash-table :test #'equal)
  3889. "Hash table to store contents of files referenced via a URL.
  3890. This is the cache of file URLs read using `org-file-contents'.")
  3891. (defun org-reset-file-cache ()
  3892. "Reset the cache of files downloaded by `org-file-contents'."
  3893. (clrhash org--file-cache))
  3894. (defun org-file-contents (file &optional noerror nocache)
  3895. "Return the contents of FILE, as a string.
  3896. FILE can be a file name or URL.
  3897. If FILE is a URL, download the contents. If the URL contents are
  3898. already cached in the `org--file-cache' hash table, the download step
  3899. is skipped.
  3900. If NOERROR is non-nil, ignore the error when unable to read the FILE
  3901. from file or URL, and return nil.
  3902. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  3903. is available. This option applies only if FILE is a URL."
  3904. (let* ((is-url (org-url-p file))
  3905. (cache (and is-url
  3906. (not nocache)
  3907. (gethash file org--file-cache))))
  3908. (cond
  3909. (cache)
  3910. (is-url
  3911. (if (org--should-fetch-remote-resource-p file)
  3912. (with-current-buffer (url-retrieve-synchronously file)
  3913. (goto-char (point-min))
  3914. ;; Move point to after the url-retrieve header.
  3915. (search-forward "\n\n" nil :move)
  3916. ;; Search for the success code only in the url-retrieve header.
  3917. (if (save-excursion
  3918. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  3919. ;; Update the cache `org--file-cache' and return contents.
  3920. (puthash file
  3921. (buffer-substring-no-properties (point) (point-max))
  3922. org--file-cache)
  3923. (funcall (if noerror #'message #'user-error)
  3924. "Unable to fetch file from %S"
  3925. file)
  3926. nil))
  3927. (funcall (if noerror #'message #'user-error)
  3928. "The remote resource %S is considered unsafe, and will not be downloaded."
  3929. file)))
  3930. (t
  3931. (with-temp-buffer
  3932. (condition-case nil
  3933. (progn
  3934. (insert-file-contents file)
  3935. (buffer-string))
  3936. (file-error
  3937. (funcall (if noerror #'message #'user-error)
  3938. "Unable to read file %S"
  3939. file)
  3940. nil)))))))
  3941. (defun org--should-fetch-remote-resource-p (uri)
  3942. "Return non-nil if the URI should be fetched."
  3943. (or (eq org-resource-download-policy t)
  3944. (org--safe-remote-resource-p uri)
  3945. (and (eq org-resource-download-policy 'prompt)
  3946. (org--confirm-resource-safe uri))))
  3947. (defun org--safe-remote-resource-p (uri)
  3948. "Return non-nil if URI is considered safe.
  3949. This checks every pattern in `org-safe-remote-resources', and
  3950. returns non-nil if any of them match."
  3951. (let ((uri-patterns org-safe-remote-resources)
  3952. (file-uri (and buffer-file-name
  3953. (concat "file://" (file-truename buffer-file-name))))
  3954. match-p)
  3955. (while (and (not match-p) uri-patterns)
  3956. (setq match-p (or (string-match-p (car uri-patterns) uri)
  3957. (and file-uri (string-match-p (car uri-patterns) file-uri)))
  3958. uri-patterns (cdr uri-patterns)))
  3959. match-p))
  3960. (defun org--confirm-resource-safe (uri)
  3961. "Ask the user if URI should be considered safe, returning non-nil if so."
  3962. (unless noninteractive
  3963. (let ((current-file (and buffer-file-name (file-truename buffer-file-name)))
  3964. (domain (and (string-match
  3965. (rx (seq "http" (? "s") "://")
  3966. (optional (+ (not (any "@/\n"))) "@")
  3967. (optional "www.")
  3968. (one-or-more (not (any ":/?\n"))))
  3969. uri)
  3970. (match-string 0 uri)))
  3971. (buf (get-buffer-create "*Org Remote Resource*")))
  3972. ;; Set up the contents of the *Org Remote Resource* buffer.
  3973. (with-current-buffer buf
  3974. (erase-buffer)
  3975. (insert "An org-mode document would like to download "
  3976. (propertize uri 'face '(:inherit org-link :weight normal))
  3977. ", which is not considered safe.\n\n"
  3978. "Do you want to download this? You can type\n "
  3979. (propertize "!" 'face 'success)
  3980. " to download this resource, and permanantly mark it as safe.\n "
  3981. (if domain
  3982. (concat
  3983. (propertize "d" 'face 'success)
  3984. " to download this resource, and mark the domain ("
  3985. (propertize domain 'face '(:inherit org-link :weight normal))
  3986. ") as safe.\n ")
  3987. "")
  3988. (propertize "f" 'face 'success)
  3989. (if current-file
  3990. (concat
  3991. " to download this resource, and permanantly mark all resources in "
  3992. (propertize current-file 'face 'underline)
  3993. " as safe.\n ")
  3994. "")
  3995. (propertize "y" 'face 'warning)
  3996. " to download this resource, just this once.\n "
  3997. (propertize "n" 'face 'error)
  3998. " to skip this resource.\n")
  3999. (setq-local cursor-type nil)
  4000. (set-buffer-modified-p nil)
  4001. (goto-char (point-min)))
  4002. ;; Display the buffer and read a choice.
  4003. (save-window-excursion
  4004. (pop-to-buffer buf)
  4005. (let* ((exit-chars (append '(?y ?n ?! ?d ?\s) (and current-file '(?f))))
  4006. (prompt (format "Please type y, n%s, d, or !%s: "
  4007. (if current-file ", f" "")
  4008. (if (< (line-number-at-pos (point-max))
  4009. (window-body-height))
  4010. ""
  4011. ", or C-v/M-v to scroll")))
  4012. char)
  4013. (setq char (read-char-choice prompt exit-chars))
  4014. (when (memq char '(?! ?f ?d))
  4015. (customize-push-and-save
  4016. 'org-safe-remote-resources
  4017. (list (if (eq char ?d)
  4018. (concat "\\`" (regexp-quote domain) "\\(?:/\\|\\'\\)")
  4019. (concat "\\`"
  4020. (regexp-quote
  4021. (if (and (= char ?f) current-file)
  4022. (concat "file://" current-file) uri))
  4023. "\\'")))))
  4024. (prog1 (memq char '(?y ?n ?! ?d ?\s ?f))
  4025. (quit-window t)))))))
  4026. (defun org-extract-log-state-settings (x)
  4027. "Extract the log state setting from a TODO keyword string.
  4028. This will extract info from a string like \"WAIT(w@/!)\"."
  4029. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4030. (let ((kw (match-string 1 x))
  4031. (log1 (and (match-end 3) (match-string 3 x)))
  4032. (log2 (and (match-end 4) (match-string 4 x))))
  4033. (and (or log1 log2)
  4034. (list kw
  4035. (and log1 (if (equal log1 "!") 'time 'note))
  4036. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4037. (defun org-remove-keyword-keys (list)
  4038. "Remove a pair of parenthesis at the end of each string in LIST."
  4039. (mapcar (lambda (x)
  4040. (if (string-match "(.*)$" x)
  4041. (substring x 0 (match-beginning 0))
  4042. x))
  4043. list))
  4044. (defun org-assign-fast-keys (alist)
  4045. "Assign fast keys to a keyword-key alist.
  4046. Respect keys that are already there."
  4047. (let (new e (alt ?0))
  4048. (while (setq e (pop alist))
  4049. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4050. (cdr e)) ;; Key already assigned.
  4051. (push e new)
  4052. (let ((clist (string-to-list (downcase (car e))))
  4053. (used (append new alist)))
  4054. (when (= (car clist) ?@)
  4055. (pop clist))
  4056. (while (and clist (rassoc (car clist) used))
  4057. (pop clist))
  4058. (unless clist
  4059. (while (rassoc alt used)
  4060. (cl-incf alt)))
  4061. (push (cons (car e) (or (car clist) alt)) new))))
  4062. (nreverse new)))
  4063. ;;; Some variables used in various places
  4064. (defvar org-window-configuration nil
  4065. "Used in various places to store a window configuration.")
  4066. (defvar org-selected-window nil
  4067. "Used in various places to store a window configuration.")
  4068. (defvar org-finish-function nil
  4069. "Function to be called when `C-c C-c' is used.
  4070. This is for getting out of special buffers like capture.")
  4071. (defvar org-last-state)
  4072. ;; Defined somewhere in this file, but used before definition.
  4073. (defvar org-entities) ;; defined in org-entities.el
  4074. (defvar org-struct-menu)
  4075. (defvar org-org-menu)
  4076. (defvar org-tbl-menu)
  4077. ;;;; Define the Org mode
  4078. (defun org-before-change-function (_beg _end)
  4079. "Every change indicates that a table might need an update."
  4080. (setq org-table-may-need-update t))
  4081. (defvar org-mode-map)
  4082. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4083. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4084. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4085. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4086. (defvar bidi-paragraph-direction)
  4087. (defvar buffer-face-mode-face)
  4088. (require 'outline)
  4089. ;; Other stuff we need.
  4090. (require 'time-date)
  4091. (when (< emacs-major-version 28) ; preloaded in Emacs 28
  4092. (require 'easymenu))
  4093. (require 'org-entities)
  4094. (require 'org-faces)
  4095. (require 'org-list)
  4096. (require 'org-pcomplete)
  4097. (require 'org-src)
  4098. (require 'org-footnote)
  4099. (require 'org-macro)
  4100. ;; babel
  4101. (require 'ob)
  4102. (defvar org-element-cache-persistent); Defined in org-element.el
  4103. (defvar org-element-use-cache); Defined in org-element.el
  4104. (defvar org-mode-loading nil
  4105. "Non-nil during Org mode initialisation.")
  4106. ;;;###autoload
  4107. (define-derived-mode org-mode outline-mode "Org"
  4108. "Outline-based notes management and organizer, alias
  4109. \"Carsten's outline-mode for keeping track of everything.\"
  4110. Org mode develops organizational tasks around a NOTES file which
  4111. contains information about projects as plain text. Org mode is
  4112. implemented on top of Outline mode, which is ideal to keep the content
  4113. of large files well structured. It supports ToDo items, deadlines and
  4114. time stamps, which magically appear in the diary listing of the Emacs
  4115. calendar. Tables are easily created with a built-in table editor.
  4116. Plain text URL-like links connect to websites, emails (VM), Usenet
  4117. messages (Gnus), BBDB entries, and any files related to the project.
  4118. For printing and sharing of notes, an Org file (or a part of it)
  4119. can be exported as a structured ASCII or HTML file.
  4120. The following commands are available:
  4121. \\{org-mode-map}"
  4122. (setq-local org-mode-loading t)
  4123. (org-load-modules-maybe)
  4124. (when org-agenda-file-menu-enabled
  4125. (org-install-agenda-files-menu))
  4126. (when (and org-link-descriptive
  4127. (eq org-fold-core-style 'overlays))
  4128. (add-to-invisibility-spec '(org-link)))
  4129. (org-fold-initialize (or (and (stringp org-ellipsis) (not (equal "" org-ellipsis)) org-ellipsis)
  4130. "..."))
  4131. (make-local-variable 'org-link-descriptive)
  4132. (when (eq org-fold-core-style 'overlays) (add-to-invisibility-spec '(org-hide-block . t)))
  4133. (if org-link-descriptive
  4134. (org-fold-core-set-folding-spec-property (car org-link--link-folding-spec) :visible nil)
  4135. (org-fold-core-set-folding-spec-property (car org-link--link-folding-spec) :visible t))
  4136. (setq-local outline-regexp org-outline-regexp)
  4137. (setq-local outline-level 'org-outline-level)
  4138. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4139. (unless org-display-table
  4140. (setq org-display-table (make-display-table)))
  4141. (set-display-table-slot
  4142. org-display-table 4
  4143. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4144. org-ellipsis)))
  4145. (setq buffer-display-table org-display-table))
  4146. (org-set-regexps-and-options)
  4147. (org-set-font-lock-defaults)
  4148. (when (and org-tag-faces (not org-tags-special-faces-re))
  4149. ;; tag faces set outside customize.... force initialization.
  4150. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4151. ;; Calc embedded
  4152. (setq-local calc-embedded-open-mode "# ")
  4153. ;; Modify a few syntax entries
  4154. (modify-syntax-entry ?\" "\"")
  4155. (modify-syntax-entry ?\\ "_")
  4156. (modify-syntax-entry ?~ "_")
  4157. (modify-syntax-entry ?< "(>")
  4158. (modify-syntax-entry ?> ")<")
  4159. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4160. ;; Activate before-change-function
  4161. (setq-local org-table-may-need-update t)
  4162. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4163. ;; Check for running clock before killing a buffer
  4164. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4165. ;; Initialize cache.
  4166. (org-element-cache-reset)
  4167. (when (and org-element-cache-persistent
  4168. org-element-use-cache)
  4169. (org-persist-load 'org-element--cache (current-buffer) t))
  4170. ;; Initialize macros templates.
  4171. (org-macro-initialize-templates)
  4172. ;; Initialize radio targets.
  4173. (org-update-radio-target-regexp)
  4174. ;; Indentation.
  4175. (setq-local indent-line-function 'org-indent-line)
  4176. (setq-local indent-region-function 'org-indent-region)
  4177. ;; Filling and auto-filling.
  4178. (org-setup-filling)
  4179. ;; Comments.
  4180. (org-setup-comments-handling)
  4181. ;; Beginning/end of defun
  4182. (setq-local beginning-of-defun-function 'org-backward-element)
  4183. (setq-local end-of-defun-function
  4184. (lambda ()
  4185. (if (not (org-at-heading-p))
  4186. (org-forward-element)
  4187. (org-forward-element)
  4188. (forward-char -1))))
  4189. ;; Next error for sparse trees
  4190. (setq-local next-error-function 'org-occur-next-match)
  4191. ;; Make commit log messages from Org documents easier.
  4192. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4193. ;; Make sure dependence stuff works reliably, even for users who set it
  4194. ;; too late :-(
  4195. (if org-enforce-todo-dependencies
  4196. (add-hook 'org-blocker-hook
  4197. 'org-block-todo-from-children-or-siblings-or-parent)
  4198. (remove-hook 'org-blocker-hook
  4199. 'org-block-todo-from-children-or-siblings-or-parent))
  4200. (if org-enforce-todo-checkbox-dependencies
  4201. (add-hook 'org-blocker-hook
  4202. 'org-block-todo-from-checkboxes)
  4203. (remove-hook 'org-blocker-hook
  4204. 'org-block-todo-from-checkboxes))
  4205. ;; Align options lines
  4206. (setq-local
  4207. align-mode-rules-list
  4208. '((org-in-buffer-settings
  4209. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4210. (modes . '(org-mode)))))
  4211. ;; Setup the pcomplete hooks
  4212. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4213. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4214. (setq-local pcomplete-default-completion-function #'ignore)
  4215. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4216. (setq-local pcomplete-termination-string "")
  4217. (add-hook 'completion-at-point-functions
  4218. #'pcomplete-completions-at-point nil t)
  4219. (setq-local buffer-face-mode-face 'org-default)
  4220. ;; If empty file that did not turn on Org mode automatically, make
  4221. ;; it to.
  4222. (when (and org-insert-mode-line-in-empty-file
  4223. (called-interactively-p 'any)
  4224. (= (point-min) (point-max)))
  4225. (insert "# -*- mode: org -*-\n\n"))
  4226. (unless org-inhibit-startup
  4227. (org-unmodified
  4228. (when org-startup-with-beamer-mode (org-beamer-mode))
  4229. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4230. (org-table-map-tables
  4231. (cond ((and org-startup-align-all-tables
  4232. org-startup-shrink-all-tables)
  4233. (lambda () (org-table-align) (org-table-shrink)))
  4234. (org-startup-align-all-tables #'org-table-align)
  4235. (t #'org-table-shrink))
  4236. t))
  4237. (when org-startup-with-inline-images (org-display-inline-images))
  4238. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4239. (unless org-inhibit-startup-visibility-stuff (org-cycle-set-startup-visibility))
  4240. (when org-startup-truncated (setq truncate-lines t))
  4241. (when org-startup-numerated (require 'org-num) (org-num-mode 1))
  4242. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4243. ;; Add a custom keymap for `visual-line-mode' so that activating
  4244. ;; this minor mode does not override Org's keybindings.
  4245. ;; FIXME: Probably `visual-line-mode' should take care of this.
  4246. (let ((oldmap (cdr (assoc 'visual-line-mode minor-mode-map-alist)))
  4247. (newmap (make-sparse-keymap)))
  4248. (set-keymap-parent newmap oldmap)
  4249. (define-key newmap [remap move-beginning-of-line] nil)
  4250. (define-key newmap [remap move-end-of-line] nil)
  4251. (define-key newmap [remap kill-line] nil)
  4252. (make-local-variable 'minor-mode-overriding-map-alist)
  4253. (push `(visual-line-mode . ,newmap) minor-mode-overriding-map-alist))
  4254. ;; Activate `org-table-header-line-mode'
  4255. (when org-table-header-line-p
  4256. (org-table-header-line-mode 1))
  4257. ;; Try to set `org-hide' face correctly.
  4258. (let ((foreground (org-find-invisible-foreground)))
  4259. (when foreground
  4260. (set-face-foreground 'org-hide foreground)))
  4261. ;; Set face extension as requested.
  4262. (org--set-faces-extend '(org-block-begin-line org-block-end-line)
  4263. org-fontify-whole-block-delimiter-line)
  4264. (org--set-faces-extend org-level-faces org-fontify-whole-heading-line)
  4265. (setq-local org-mode-loading nil))
  4266. ;; Update `customize-package-emacs-version-alist'
  4267. (add-to-list 'customize-package-emacs-version-alist
  4268. '(Org ("8.0" . "24.4")
  4269. ("8.1" . "24.4")
  4270. ("8.2" . "24.4")
  4271. ("8.2.7" . "24.4")
  4272. ("8.3" . "26.1")
  4273. ("9.0" . "26.1")
  4274. ("9.1" . "26.1")
  4275. ("9.2" . "27.1")
  4276. ("9.3" . "27.1")
  4277. ("9.4" . "27.2")
  4278. ("9.5" . "28.1")
  4279. ("9.6" . "29.1")))
  4280. (defvar org-mode-transpose-word-syntax-table
  4281. (let ((st (make-syntax-table text-mode-syntax-table)))
  4282. (dolist (c org-emphasis-alist st)
  4283. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4284. (when (fboundp 'abbrev-table-put)
  4285. (abbrev-table-put org-mode-abbrev-table
  4286. :parents (list text-mode-abbrev-table)))
  4287. (defun org-find-invisible-foreground ()
  4288. (let ((candidates (remove
  4289. "unspecified-bg"
  4290. (nconc
  4291. (list (face-background 'default)
  4292. (face-background 'org-default))
  4293. (mapcar
  4294. (lambda (alist)
  4295. (when (boundp alist)
  4296. (cdr (assq 'background-color (symbol-value alist)))))
  4297. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4298. (list (face-foreground 'org-hide))))))
  4299. (car (remove nil candidates))))
  4300. (defun org-current-time (&optional rounding-minutes past)
  4301. "Current time, possibly rounded to ROUNDING-MINUTES.
  4302. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4303. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4304. the rounding returns a past time."
  4305. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4306. (car org-time-stamp-rounding-minutes)))
  4307. (now (current-time)))
  4308. (if (< r 1)
  4309. now
  4310. (let* ((time (decode-time now))
  4311. (res (org-encode-time
  4312. (apply #'list
  4313. 0 (* r (round (nth 1 time) r))
  4314. (nthcdr 2 time)))))
  4315. (if (or (not past) (time-less-p res now))
  4316. res
  4317. (time-subtract res (* r 60)))))))
  4318. (defun org-today ()
  4319. "Return today date, considering `org-extend-today-until'."
  4320. (time-to-days
  4321. (time-since (* 3600 org-extend-today-until))))
  4322. ;;;; Font-Lock stuff, including the activators
  4323. (defconst org-match-sexp-depth 3
  4324. "Number of stacked braces for sub/superscript matching.")
  4325. (defun org-create-multibrace-regexp (left right n)
  4326. "Create a regular expression which will match a balanced sexp.
  4327. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4328. as single character strings.
  4329. The regexp returned will match the entire expression including the
  4330. delimiters. It will also define a single group which contains the
  4331. match except for the outermost delimiters. The maximum depth of
  4332. stacked delimiters is N. Escaping delimiters is not possible."
  4333. (let* ((nothing (concat "[^" left right "]*?"))
  4334. (or "\\|")
  4335. (re nothing)
  4336. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4337. (while (> n 1)
  4338. (setq n (1- n)
  4339. re (concat re or next)
  4340. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4341. (concat left "\\(" re "\\)" right)))
  4342. (defconst org-match-substring-regexp
  4343. (concat
  4344. "\\(\\S-\\)\\([_^]\\)\\("
  4345. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4346. "\\|"
  4347. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4348. "\\|"
  4349. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4350. "The regular expression matching a sub- or superscript.")
  4351. (defconst org-match-substring-with-braces-regexp
  4352. (concat
  4353. "\\(\\S-\\)\\([_^]\\)"
  4354. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4355. "The regular expression matching a sub- or superscript, forcing braces.")
  4356. (defvar org-emph-face nil)
  4357. (defun org-do-emphasis-faces (limit)
  4358. "Run through the buffer and emphasize strings."
  4359. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4360. (car org-emphasis-regexp-components))))
  4361. (catch :exit
  4362. (while (re-search-forward quick-re limit t)
  4363. (let* ((marker (match-string 2))
  4364. (verbatim? (member marker '("~" "="))))
  4365. (when (save-excursion
  4366. (goto-char (match-beginning 0))
  4367. (and
  4368. ;; Do not match table hlines.
  4369. (not (and (equal marker "+")
  4370. (org-match-line
  4371. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4372. ;; Do not match headline stars. Do not consider
  4373. ;; stars of a headline as closing marker for bold
  4374. ;; markup either.
  4375. (not (and (equal marker "*")
  4376. (save-excursion
  4377. (forward-char)
  4378. (skip-chars-backward "*")
  4379. (looking-at-p org-outline-regexp-bol))))
  4380. ;; Match full emphasis markup regexp.
  4381. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4382. ;; Do not span over paragraph boundaries.
  4383. (not (string-match-p org-element-paragraph-separate
  4384. (match-string 2)))
  4385. ;; Do not span over cells in table rows.
  4386. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4387. (string-match-p "|" (match-string 4))))))
  4388. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
  4389. (m (if org-hide-emphasis-markers 4 2)))
  4390. (font-lock-prepend-text-property
  4391. (match-beginning m) (match-end m) 'face face)
  4392. (when verbatim?
  4393. (org-remove-flyspell-overlays-in
  4394. (match-beginning 0) (match-end 0))
  4395. (when (and (org-fold-core-folding-spec-p 'org-link)
  4396. (org-fold-core-folding-spec-p 'org-link-description))
  4397. (org-fold-region (match-beginning 0) (match-end 0) nil 'org-link)
  4398. (org-fold-region (match-beginning 0) (match-end 0) nil 'org-link-description))
  4399. (remove-text-properties (match-beginning 2) (match-end 2)
  4400. '(display t invisible t intangible t)))
  4401. (add-text-properties (match-beginning 2) (match-end 2)
  4402. '(font-lock-multiline t org-emphasis t))
  4403. (when (and org-hide-emphasis-markers
  4404. (not (org-at-comment-p)))
  4405. (add-text-properties (match-end 4) (match-beginning 5)
  4406. '(invisible t))
  4407. (add-text-properties (match-beginning 3) (match-end 3)
  4408. '(invisible t)))
  4409. (throw :exit t))))))))
  4410. (defun org-emphasize (&optional char)
  4411. "Insert or change an emphasis, i.e. a font like bold or italic.
  4412. If there is an active region, change that region to a new emphasis.
  4413. If there is no region, just insert the marker characters and position
  4414. the cursor between them.
  4415. CHAR should be the marker character. If it is a space, it means to
  4416. remove the emphasis of the selected region.
  4417. If CHAR is not given (for example in an interactive call) it will be
  4418. prompted for."
  4419. (interactive)
  4420. (let ((erc org-emphasis-regexp-components)
  4421. (string "") beg end move s)
  4422. (if (org-region-active-p)
  4423. (setq beg (region-beginning)
  4424. end (region-end)
  4425. string (buffer-substring beg end))
  4426. (setq move t))
  4427. (unless char
  4428. (message "Emphasis marker or tag: [%s]"
  4429. (mapconcat #'car org-emphasis-alist ""))
  4430. (setq char (read-char-exclusive)))
  4431. (if (equal char ?\s)
  4432. (setq s ""
  4433. move nil)
  4434. (unless (assoc (char-to-string char) org-emphasis-alist)
  4435. (user-error "No such emphasis marker: \"%c\"" char))
  4436. (setq s (char-to-string char)))
  4437. (while (and (> (length string) 1)
  4438. (equal (substring string 0 1) (substring string -1))
  4439. (assoc (substring string 0 1) org-emphasis-alist))
  4440. (setq string (substring string 1 -1)))
  4441. (setq string (concat s string s))
  4442. (when beg (delete-region beg end))
  4443. (unless (or (bolp)
  4444. (string-match (concat "[" (nth 0 erc) "\n]")
  4445. (char-to-string (char-before (point)))))
  4446. (insert " "))
  4447. (unless (or (eobp)
  4448. (string-match (concat "[" (nth 1 erc) "\n]")
  4449. (char-to-string (char-after (point)))))
  4450. (insert " ") (backward-char 1))
  4451. (insert string)
  4452. (and move (backward-char 1))))
  4453. (defconst org-nonsticky-props
  4454. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4455. (defsubst org-rear-nonsticky-at (pos)
  4456. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4457. (defun org-activate-links--overlays (limit)
  4458. "Add link properties to links.
  4459. This includes angle, plain, and bracket links."
  4460. (catch :exit
  4461. (while (re-search-forward org-link-any-re limit t)
  4462. (let* ((start (match-beginning 0))
  4463. (end (match-end 0))
  4464. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4465. (visible-end (or (match-end 3) (match-end 2)))
  4466. (style (cond ((eq ?< (char-after start)) 'angle)
  4467. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4468. (t 'plain))))
  4469. (when (and (memq style org-highlight-links)
  4470. ;; Do not span over paragraph boundaries.
  4471. (not (string-match-p org-element-paragraph-separate
  4472. (match-string 0)))
  4473. ;; Do not confuse plain links with tags.
  4474. (not (and (eq style 'plain)
  4475. (let ((face (get-text-property
  4476. (max (1- start) (point-min)) 'face)))
  4477. (if (consp face) (memq 'org-tag face)
  4478. (eq 'org-tag face))))))
  4479. (let* ((link-object (save-excursion
  4480. (goto-char start)
  4481. (save-match-data (org-element-link-parser))))
  4482. (link (org-element-property :raw-link link-object))
  4483. (type (org-element-property :type link-object))
  4484. (path (org-element-property :path link-object))
  4485. (face-property (pcase (org-link-get-parameter type :face)
  4486. ((and (pred functionp) face) (funcall face path))
  4487. ((and (pred facep) face) face)
  4488. ((and (pred consp) face) face) ;anonymous
  4489. (_ 'org-link)))
  4490. (properties ;for link's visible part
  4491. (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4492. 'highlight)
  4493. 'keymap (or (org-link-get-parameter type :keymap)
  4494. org-mouse-map)
  4495. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4496. ((and (pred stringp) echo) echo)
  4497. ((and (pred functionp) echo) echo)
  4498. (_ (concat "LINK: " link)))
  4499. 'htmlize-link (pcase (org-link-get-parameter type
  4500. :htmlize-link)
  4501. ((and (pred functionp) f) (funcall f))
  4502. (_ `(:uri ,link)))
  4503. 'font-lock-multiline t)))
  4504. (org-remove-flyspell-overlays-in start end)
  4505. (org-rear-nonsticky-at end)
  4506. (if (not (eq 'bracket style))
  4507. (progn
  4508. (add-face-text-property start end face-property)
  4509. (add-text-properties start end properties))
  4510. ;; Handle invisible parts in bracket links.
  4511. (remove-text-properties start end '(invisible nil))
  4512. (let ((hidden
  4513. (append `(invisible
  4514. ,(or (org-link-get-parameter type :display)
  4515. 'org-link))
  4516. properties)))
  4517. (add-text-properties start visible-start hidden)
  4518. (add-face-text-property start end face-property)
  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-links--text-properties (limit)
  4529. "Add link properties to links.
  4530. This includes angle, plain, and bracket links."
  4531. (catch :exit
  4532. (while (re-search-forward org-link-any-re limit t)
  4533. (let* ((start (match-beginning 0))
  4534. (end (match-end 0))
  4535. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4536. (visible-end (or (match-end 3) (match-end 2)))
  4537. (style (cond ((eq ?< (char-after start)) 'angle)
  4538. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4539. (t 'plain))))
  4540. (when (and (memq style org-highlight-links)
  4541. ;; Do not span over paragraph boundaries.
  4542. (not (string-match-p org-element-paragraph-separate
  4543. (match-string 0)))
  4544. ;; Do not confuse plain links with tags.
  4545. (not (and (eq style 'plain)
  4546. (let ((face (get-text-property
  4547. (max (1- start) (point-min)) 'face)))
  4548. (if (consp face) (memq 'org-tag face)
  4549. (eq 'org-tag face))))))
  4550. (let* ((link-object (save-excursion
  4551. (goto-char start)
  4552. (save-match-data (org-element-link-parser))))
  4553. (link (org-element-property :raw-link link-object))
  4554. (type (org-element-property :type link-object))
  4555. (path (org-element-property :path link-object))
  4556. (face-property (pcase (org-link-get-parameter type :face)
  4557. ((and (pred functionp) face) (funcall face path))
  4558. ((and (pred facep) face) face)
  4559. ((and (pred consp) face) face) ;anonymous
  4560. (_ 'org-link)))
  4561. (properties ;for link's visible part
  4562. (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4563. 'highlight)
  4564. 'keymap (or (org-link-get-parameter type :keymap)
  4565. org-mouse-map)
  4566. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4567. ((and (pred stringp) echo) echo)
  4568. ((and (pred functionp) echo) echo)
  4569. (_ (concat "LINK: " link)))
  4570. 'htmlize-link (pcase (org-link-get-parameter type
  4571. :htmlize-link)
  4572. ((and (pred functionp) f) (funcall f))
  4573. (_ `(:uri ,link)))
  4574. 'font-lock-multiline t)))
  4575. (org-remove-flyspell-overlays-in start end)
  4576. (org-rear-nonsticky-at end)
  4577. (if (not (eq 'bracket style))
  4578. (progn
  4579. (add-face-text-property start end face-property)
  4580. (add-text-properties start end properties))
  4581. ;; Initialise folding when used outside org-mode.
  4582. (unless (or (derived-mode-p 'org-mode)
  4583. (and (org-fold-folding-spec-p 'org-link-description)
  4584. (org-fold-folding-spec-p 'org-link)))
  4585. (org-fold-initialize (or (and (stringp org-ellipsis) (not (equal "" org-ellipsis)) org-ellipsis)
  4586. "...")))
  4587. ;; Handle invisible parts in bracket links.
  4588. (let ((spec (or (org-link-get-parameter type :display)
  4589. 'org-link)))
  4590. (unless (org-fold-folding-spec-p spec)
  4591. (org-fold-add-folding-spec spec
  4592. (cdr org-link--link-folding-spec)
  4593. nil
  4594. 'append)
  4595. (org-fold-core-set-folding-spec-property spec :visible t))
  4596. (org-fold-region start end nil 'org-link)
  4597. (org-fold-region start end nil 'org-link-description)
  4598. ;; We are folding the whole emphasised text with SPEC
  4599. ;; first. It makes everything invisible (or whatever
  4600. ;; the user wants).
  4601. (org-fold-region start end t spec)
  4602. ;; The visible part of the text is folded using
  4603. ;; 'org-link-description, which is forcing this part of
  4604. ;; the text to be visible.
  4605. (org-fold-region visible-start visible-end t 'org-link-description)
  4606. (add-text-properties start end properties)
  4607. (add-face-text-property start end face-property)
  4608. (org-rear-nonsticky-at visible-start)
  4609. (org-rear-nonsticky-at visible-end)))
  4610. (let ((f (org-link-get-parameter type :activate-func)))
  4611. (when (functionp f)
  4612. (funcall f start end path (eq style 'bracket))))
  4613. (throw :exit t))))) ;signal success
  4614. nil))
  4615. (defsubst org-activate-links (limit)
  4616. "Add link properties to links.
  4617. This includes angle, plain, and bracket links."
  4618. (if (eq org-fold-core-style 'text-properties)
  4619. (org-activate-links--text-properties limit)
  4620. (org-activate-links--overlays limit)))
  4621. (defun org-activate-code (limit)
  4622. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4623. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4624. (remove-text-properties (match-beginning 0) (match-end 0)
  4625. '(display t invisible t intangible t))
  4626. t))
  4627. (defcustom org-src-fontify-natively t
  4628. "When non-nil, fontify code in code blocks.
  4629. See also the `org-block' face."
  4630. :type 'boolean
  4631. :version "26.1"
  4632. :package-version '(Org . "8.3")
  4633. :group 'org-appearance
  4634. :group 'org-babel)
  4635. (defcustom org-allow-promoting-top-level-subtree nil
  4636. "When non-nil, allow promoting a top level subtree.
  4637. The leading star of the top level headline will be replaced
  4638. by a #."
  4639. :type 'boolean
  4640. :version "24.1"
  4641. :group 'org-appearance)
  4642. (defun org-fontify-meta-lines-and-blocks (limit)
  4643. (condition-case nil
  4644. (org-fontify-meta-lines-and-blocks-1 limit)
  4645. (error (message "Org mode fontification error in %S at %d"
  4646. (current-buffer)
  4647. (line-number-at-pos)))))
  4648. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4649. "Fontify #+ lines and blocks."
  4650. (let ((case-fold-search t))
  4651. (when (re-search-forward
  4652. (rx bol (group (zero-or-more (any " \t")) "#"
  4653. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4654. (any " \t")
  4655. eol))
  4656. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4657. (zero-or-more (any " \t"))
  4658. (group (group (zero-or-more (not (any " \t\n"))))
  4659. (zero-or-more (any " \t"))
  4660. (group (zero-or-more any)))))
  4661. limit t)
  4662. (let ((beg (match-beginning 0))
  4663. (end-of-beginline (match-end 0))
  4664. ;; Including \n at end of #+begin line will include \n
  4665. ;; after the end of block content.
  4666. (block-start (match-end 0))
  4667. (block-end nil)
  4668. (lang (match-string 7)) ; The language, if it is a source block.
  4669. (bol-after-beginline (line-beginning-position 2))
  4670. (dc1 (downcase (match-string 2)))
  4671. (dc3 (downcase (match-string 3)))
  4672. (whole-blockline org-fontify-whole-block-delimiter-line)
  4673. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4674. (cond
  4675. ((and (match-end 4) (equal dc3 "+begin"))
  4676. ;; Truly a block
  4677. (setq block-type (downcase (match-string 5))
  4678. ;; Src, example, export, maybe more.
  4679. quoting (member block-type org-protecting-blocks))
  4680. (when (re-search-forward
  4681. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4682. (seq (zero-or-more (any " \t"))
  4683. "#+end"
  4684. ,(match-string 4)
  4685. word-end
  4686. (zero-or-more any)))))
  4687. ;; We look further than LIMIT on purpose.
  4688. nil t)
  4689. ;; We do have a matching #+end line.
  4690. (setq beg-of-endline (match-beginning 0)
  4691. end-of-endline (match-end 0)
  4692. nl-before-endline (1- (match-beginning 0)))
  4693. (setq block-end (match-beginning 0)) ; Include the final newline.
  4694. (when quoting
  4695. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4696. (remove-text-properties beg end-of-endline
  4697. '(display t invisible t intangible t)))
  4698. (add-text-properties
  4699. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4700. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4701. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4702. (cond
  4703. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4704. (save-match-data
  4705. (org-src-font-lock-fontify-block lang block-start block-end))
  4706. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4707. (quoting
  4708. (add-text-properties
  4709. bol-after-beginline beg-of-endline
  4710. (list 'face
  4711. (list :inherit
  4712. (let ((face-name
  4713. (intern (format "org-block-%s" lang))))
  4714. (append (and (facep face-name) (list face-name))
  4715. '(org-block)))))))
  4716. ((not org-fontify-quote-and-verse-blocks))
  4717. ((string= block-type "quote")
  4718. (add-face-text-property
  4719. bol-after-beginline beg-of-endline 'org-quote t))
  4720. ((string= block-type "verse")
  4721. (add-face-text-property
  4722. bol-after-beginline beg-of-endline 'org-verse t)))
  4723. ;; Fontify the #+begin and #+end lines of the blocks
  4724. (add-text-properties
  4725. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4726. '(face org-block-begin-line))
  4727. (unless (eq (char-after beg-of-endline) ?*)
  4728. (add-text-properties
  4729. beg-of-endline
  4730. (if whole-blockline
  4731. (let ((beg-of-next-line (1+ end-of-endline)))
  4732. (min (point-max) beg-of-next-line))
  4733. (min (point-max) end-of-endline))
  4734. '(face org-block-end-line)))
  4735. t))
  4736. ((member dc1 '("+title:" "+subtitle:" "+author:" "+email:" "+date:"))
  4737. (org-remove-flyspell-overlays-in
  4738. (match-beginning 0)
  4739. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4740. (add-text-properties
  4741. beg (match-end 3)
  4742. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4743. '(font-lock-fontified t invisible t)
  4744. '(font-lock-fontified t face org-document-info-keyword)))
  4745. (add-text-properties
  4746. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4747. (if (string-equal dc1 "+title:")
  4748. '(font-lock-fontified t face org-document-title)
  4749. '(font-lock-fontified t face org-document-info))))
  4750. ((string-prefix-p "+caption" dc1)
  4751. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4752. (remove-text-properties (match-beginning 0) (match-end 0)
  4753. '(display t invisible t intangible t))
  4754. ;; Handle short captions
  4755. (save-excursion
  4756. (beginning-of-line)
  4757. (looking-at (rx (group (zero-or-more (any " \t"))
  4758. "#+caption"
  4759. (optional "[" (zero-or-more any) "]")
  4760. ":")
  4761. (zero-or-more (any " \t")))))
  4762. (add-text-properties (line-beginning-position) (match-end 1)
  4763. '(font-lock-fontified t face org-meta-line))
  4764. (add-text-properties (match-end 0) (line-end-position)
  4765. '(font-lock-fontified t face org-block))
  4766. t)
  4767. ((member dc3 '(" " ""))
  4768. ;; Just a comment, the plus was not there
  4769. (org-remove-flyspell-overlays-in beg (match-end 0))
  4770. (add-text-properties
  4771. beg (match-end 0)
  4772. '(font-lock-fontified t face font-lock-comment-face)))
  4773. (t ;; Just any other in-buffer setting, but not indented
  4774. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4775. (remove-text-properties (match-beginning 0) (match-end 0)
  4776. '(display t invisible t intangible t))
  4777. (add-text-properties beg (match-end 0)
  4778. '(font-lock-fontified t face org-meta-line))
  4779. t))))))
  4780. (defun org-fontify-drawers (limit)
  4781. "Fontify drawers."
  4782. (when (re-search-forward org-drawer-regexp limit t)
  4783. (add-text-properties (1- (match-beginning 1)) (1+ (match-end 1))
  4784. '(font-lock-fontified t face org-drawer))
  4785. (org-remove-flyspell-overlays-in
  4786. (line-beginning-position) (line-beginning-position 2))
  4787. t))
  4788. (defun org-fontify-macros (limit)
  4789. "Fontify macros."
  4790. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4791. (let ((begin (match-beginning 0))
  4792. (opening-end (match-beginning 1)))
  4793. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4794. (match-string 1))
  4795. (let ((end (match-end 1))
  4796. (closing-start (match-beginning 1)))
  4797. (add-text-properties
  4798. begin end
  4799. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4800. (org-remove-flyspell-overlays-in begin end)
  4801. (when org-hide-macro-markers
  4802. (add-text-properties begin opening-end '(invisible t))
  4803. (add-text-properties closing-start end '(invisible t)))
  4804. t)))))
  4805. (defun org-fontify-extend-region (beg end _old-len)
  4806. (let ((end (if (progn (goto-char end) (looking-at-p "^[*#]"))
  4807. (1+ end) end))
  4808. (begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4809. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4810. (extend
  4811. (lambda (r1 r2 dir)
  4812. (let ((re (replace-regexp-in-string
  4813. "\\(begin\\|end\\)" r1
  4814. (replace-regexp-in-string
  4815. "[][]" r2
  4816. (match-string-no-properties 0)))))
  4817. (re-search-forward (regexp-quote re) nil t dir)))))
  4818. (goto-char beg)
  4819. (back-to-indentation)
  4820. (save-match-data
  4821. (cond ((looking-at end-re)
  4822. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4823. ((looking-at begin-re)
  4824. (cons beg (or (funcall extend "end" "]" 1) end)))
  4825. (t (cons beg end))))))
  4826. (defun org-activate-footnote-links (limit)
  4827. "Add text properties for footnotes."
  4828. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4829. (when fn
  4830. (let* ((beg (nth 1 fn))
  4831. (end (nth 2 fn))
  4832. (label (car fn))
  4833. (referencep (/= (line-beginning-position) beg)))
  4834. (when (and referencep (nth 3 fn))
  4835. (save-excursion
  4836. (goto-char beg)
  4837. (search-forward (or label "fn:"))
  4838. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4839. (add-text-properties beg end
  4840. (list 'mouse-face 'highlight
  4841. 'keymap org-mouse-map
  4842. 'help-echo
  4843. (if referencep "Footnote reference"
  4844. "Footnote definition")
  4845. 'font-lock-fontified t
  4846. 'font-lock-multiline t
  4847. 'face 'org-footnote))))))
  4848. (defun org-activate-dates (limit)
  4849. "Add text properties for dates."
  4850. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4851. (not (equal (char-before (match-beginning 0)) 91)))
  4852. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4853. (add-text-properties (match-beginning 0) (match-end 0)
  4854. (list 'mouse-face 'highlight
  4855. 'keymap org-mouse-map))
  4856. (org-rear-nonsticky-at (match-end 0))
  4857. (when org-display-custom-times
  4858. ;; If it's a date range, activate custom time for second date.
  4859. (when (match-end 3)
  4860. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4861. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4862. t))
  4863. (defun org-activate-target-links (limit)
  4864. "Add text properties for target matches."
  4865. (when org-target-link-regexp
  4866. (let ((case-fold-search t))
  4867. ;; `org-target-link-regexp' matches one character before the
  4868. ;; actual target.
  4869. (unless (bolp) (forward-char -1))
  4870. (when (re-search-forward org-target-link-regexp limit t)
  4871. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4872. (add-text-properties (match-beginning 1) (match-end 1)
  4873. (list 'mouse-face 'highlight
  4874. 'keymap org-mouse-map
  4875. 'help-echo "Radio target link"
  4876. 'org-linked-text t))
  4877. (org-rear-nonsticky-at (match-end 1))
  4878. t))))
  4879. (defvar org-latex-and-related-regexp nil
  4880. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4881. (defun org-compute-latex-and-related-regexp ()
  4882. "Compute regular expression for LaTeX, entities and sub/superscript.
  4883. Result depends on variable `org-highlight-latex-and-related'."
  4884. (let ((re-sub
  4885. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4886. ((eq org-use-sub-superscripts '{})
  4887. (list org-match-substring-with-braces-regexp))
  4888. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4889. (re-latex
  4890. (when (or (memq 'latex org-highlight-latex-and-related)
  4891. (memq 'native org-highlight-latex-and-related))
  4892. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4893. (delq nil
  4894. (mapcar (lambda (x)
  4895. (and (member (car x) matchers) (nth 1 x)))
  4896. org-latex-regexps)))))
  4897. (re-entities
  4898. (when (memq 'entities org-highlight-latex-and-related)
  4899. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4900. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4901. (setq-local org-latex-and-related-regexp
  4902. (mapconcat #'identity
  4903. (append re-latex re-entities re-sub)
  4904. "\\|"))))
  4905. (defun org-do-latex-and-related (limit)
  4906. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4907. Stop at first highlighted object, if any. Return t if some
  4908. highlighting was done, nil otherwise."
  4909. (when (org-string-nw-p org-latex-and-related-regexp)
  4910. (let ((latex-prefix-re (rx (or "$" "\\(" "\\[")))
  4911. (blank-line-re (rx (and "\n" (zero-or-more (or " " "\t")) "\n"))))
  4912. (catch 'found
  4913. (while (and (< (point) limit)
  4914. (re-search-forward org-latex-and-related-regexp nil t))
  4915. (cond
  4916. ((>= (match-beginning 0) limit)
  4917. (throw 'found nil))
  4918. ((cl-some (lambda (f)
  4919. (memq f '(org-code org-verbatim underline
  4920. org-special-keyword)))
  4921. (save-excursion
  4922. (goto-char (1+ (match-beginning 0)))
  4923. (face-at-point nil t))))
  4924. ;; Try to limit false positives. In this case, ignore
  4925. ;; $$...$$, \(...\), and \[...\] LaTeX constructs if they
  4926. ;; contain an empty line.
  4927. ((save-excursion
  4928. (goto-char (match-beginning 0))
  4929. (and (looking-at-p latex-prefix-re)
  4930. (save-match-data
  4931. (re-search-forward blank-line-re (1- (match-end 0)) t)))))
  4932. (t
  4933. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4934. '(?_ ?^))
  4935. 1
  4936. 0))
  4937. (start (+ offset (match-beginning 0)))
  4938. (end (match-end 0)))
  4939. (if (memq 'native org-highlight-latex-and-related)
  4940. (org-src-font-lock-fontify-block "latex" start end)
  4941. (font-lock-prepend-text-property start end
  4942. 'face 'org-latex-and-related))
  4943. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4944. '(font-lock-multiline t))
  4945. (throw 'found t)))))
  4946. nil))))
  4947. (defun org-restart-font-lock ()
  4948. "Restart `font-lock-mode', to force refontification."
  4949. (when font-lock-mode
  4950. (font-lock-mode -1)
  4951. (font-lock-mode 1)))
  4952. (defun org-activate-tags (limit)
  4953. (when (re-search-forward org-tag-line-re limit t)
  4954. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4955. (add-text-properties (match-beginning 1) (match-end 1)
  4956. (list 'mouse-face 'highlight
  4957. 'keymap org-mouse-map))
  4958. (org-rear-nonsticky-at (match-end 1))
  4959. t))
  4960. (defun org-outline-level ()
  4961. "Compute the outline level of the heading at point.
  4962. If this is called at a normal headline, the level is the number
  4963. of stars. Use `org-reduced-level' to remove the effect of
  4964. `org-odd-levels'. Unlike to `org-current-level', this function
  4965. takes into consideration inlinetasks."
  4966. (org-with-wide-buffer
  4967. (end-of-line)
  4968. (if (re-search-backward org-outline-regexp-bol nil t)
  4969. (1- (- (match-end 0) (match-beginning 0)))
  4970. 0)))
  4971. (defvar org-font-lock-keywords nil)
  4972. (defsubst org-re-property (property &optional literal allow-null value)
  4973. "Return a regexp matching a PROPERTY line.
  4974. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4975. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4976. non-nil, match properties even without a value.
  4977. Match group 3 is set to the value when it exists. If there is no
  4978. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4979. With optional argument VALUE, match only property lines with
  4980. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4981. unless LITERAL is non-nil."
  4982. (concat
  4983. "^\\(?4:[ \t]*\\)"
  4984. (format "\\(?1::\\(?2:%s\\):\\)"
  4985. (if literal property (regexp-quote property)))
  4986. (cond (value
  4987. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4988. (if literal value (regexp-quote value))))
  4989. (allow-null
  4990. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4991. (t
  4992. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4993. (defconst org-property-re
  4994. (org-re-property "\\S-+" 'literal t)
  4995. "Regular expression matching a property line.
  4996. There are four matching groups:
  4997. 1: :PROPKEY: including the leading and trailing colon,
  4998. 2: PROPKEY without the leading and trailing colon,
  4999. 3: PROPVAL without leading or trailing spaces,
  5000. 4: the indentation of the current line,
  5001. 5: trailing whitespace.")
  5002. (defvar org-font-lock-hook nil
  5003. "Functions to be called for special font lock stuff.")
  5004. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5005. (defvar org-font-lock-set-keywords-hook nil
  5006. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5007. This is called after `org-font-lock-extra-keywords' is defined, but before
  5008. it is installed to be used by font lock. This can be useful if something
  5009. needs to be inserted at a specific position in the font-lock sequence.")
  5010. (defun org-font-lock-hook (limit)
  5011. "Run `org-font-lock-hook' within LIMIT."
  5012. (run-hook-with-args 'org-font-lock-hook limit))
  5013. (defun org-set-font-lock-defaults ()
  5014. "Set font lock defaults for the current buffer."
  5015. (let ((org-font-lock-extra-keywords
  5016. (list
  5017. ;; Call the hook
  5018. '(org-font-lock-hook)
  5019. ;; Headlines
  5020. `(,(if org-fontify-whole-heading-line
  5021. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5022. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5023. (1 (org-get-level-face 1))
  5024. (2 (org-get-level-face 2))
  5025. (3 (org-get-level-face 3)))
  5026. ;; Table lines
  5027. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5028. (1 'org-table t))
  5029. ;; Table internals
  5030. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5031. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5032. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5033. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5034. ;; Properties
  5035. (list org-property-re
  5036. '(1 'org-special-keyword t)
  5037. '(3 'org-property-value t))
  5038. ;; Drawers
  5039. '(org-fontify-drawers)
  5040. ;; Link related fontification.
  5041. '(org-activate-links)
  5042. (when (memq 'tag org-highlight-links) '(org-activate-tags (1 'org-tag prepend)))
  5043. (when (memq 'radio org-highlight-links) '(org-activate-target-links (1 'org-link t)))
  5044. (when (memq 'date org-highlight-links) '(org-activate-dates (0 'org-date t)))
  5045. (when (memq 'footnote org-highlight-links) '(org-activate-footnote-links))
  5046. ;; Targets.
  5047. (list org-radio-target-regexp '(0 'org-target t))
  5048. (list org-target-regexp '(0 'org-target t))
  5049. ;; Diary sexps.
  5050. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5051. ;; Macro
  5052. '(org-fontify-macros)
  5053. ;; TODO keyword
  5054. (list (format org-heading-keyword-regexp-format
  5055. org-todo-regexp)
  5056. '(2 (org-get-todo-face 2) prepend))
  5057. ;; TODO
  5058. (when org-fontify-todo-headline
  5059. (list (format org-heading-keyword-regexp-format
  5060. (concat
  5061. "\\(?:"
  5062. (mapconcat 'regexp-quote org-not-done-keywords "\\|")
  5063. "\\)"))
  5064. '(2 'org-headline-todo prepend)))
  5065. ;; DONE
  5066. (when org-fontify-done-headline
  5067. (list (format org-heading-keyword-regexp-format
  5068. (concat
  5069. "\\(?:"
  5070. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5071. "\\)"))
  5072. '(2 'org-headline-done prepend)))
  5073. ;; Priorities
  5074. '(org-font-lock-add-priority-faces)
  5075. ;; Tags
  5076. '(org-font-lock-add-tag-faces)
  5077. ;; Tags groups
  5078. (when (and org-group-tags org-tag-groups-alist)
  5079. (list (concat org-outline-regexp-bol ".+\\(:"
  5080. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5081. ":\\).*$")
  5082. '(1 'org-tag-group prepend)))
  5083. ;; Special keywords
  5084. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5085. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5086. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5087. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5088. ;; Emphasis
  5089. (when org-fontify-emphasized-text '(org-do-emphasis-faces))
  5090. ;; Checkboxes
  5091. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5092. 1 'org-checkbox prepend)
  5093. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5094. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5095. (0 (org-get-checkbox-statistics-face) prepend)))
  5096. ;; Description list items
  5097. '("\\(?:^[ \t]*[-+]\\|^[ \t]+[*]\\)[ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5098. 1 'org-list-dt prepend)
  5099. ;; Inline export snippets
  5100. '("\\(@@\\)\\([a-z-]+:\\).*?\\(@@\\)"
  5101. (1 'font-lock-comment-face t)
  5102. (2 'org-tag t)
  5103. (3 'font-lock-comment-face t))
  5104. ;; ARCHIVEd headings
  5105. (list (concat
  5106. org-outline-regexp-bol
  5107. "\\(.*:" org-archive-tag ":.*\\)")
  5108. '(1 'org-archived prepend))
  5109. ;; Specials
  5110. '(org-do-latex-and-related)
  5111. '(org-fontify-entities)
  5112. '(org-raise-scripts)
  5113. ;; Code
  5114. '(org-activate-code (1 'org-code t))
  5115. ;; COMMENT
  5116. (list (format
  5117. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5118. org-todo-regexp
  5119. org-comment-string)
  5120. '(9 'org-special-keyword t))
  5121. ;; Blocks and meta lines
  5122. '(org-fontify-meta-lines-and-blocks)
  5123. '(org-fontify-inline-src-blocks)
  5124. ;; Citations. When an activate processor is specified, if
  5125. ;; specified, try loading it beforehand.
  5126. (progn
  5127. (unless (null org-cite-activate-processor)
  5128. (org-cite-try-load-processor org-cite-activate-processor))
  5129. '(org-cite-activate)))))
  5130. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5131. (run-hooks 'org-font-lock-set-keywords-hook)
  5132. ;; Now set the full font-lock-keywords
  5133. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5134. (setq-local font-lock-defaults
  5135. '(org-font-lock-keywords t nil nil backward-paragraph))
  5136. (setq-local font-lock-extend-after-change-region-function
  5137. #'org-fontify-extend-region)
  5138. (kill-local-variable 'font-lock-keywords)
  5139. nil))
  5140. (defun org-toggle-pretty-entities ()
  5141. "Toggle the composition display of entities as UTF8 characters."
  5142. (interactive)
  5143. (setq-local org-pretty-entities (not org-pretty-entities))
  5144. (org-restart-font-lock)
  5145. (if org-pretty-entities
  5146. (message "Entities are now displayed as UTF8 characters")
  5147. (save-restriction
  5148. (widen)
  5149. (decompose-region (point-min) (point-max))
  5150. (message "Entities are now displayed as plain text"))))
  5151. (defvar-local org-custom-properties-overlays nil
  5152. "List of overlays used for custom properties.")
  5153. (defun org-toggle-custom-properties-visibility ()
  5154. "Display or hide properties in `org-custom-properties'."
  5155. (interactive)
  5156. (if org-custom-properties-overlays
  5157. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5158. (setq org-custom-properties-overlays nil))
  5159. (when org-custom-properties
  5160. (org-with-wide-buffer
  5161. (goto-char (point-min))
  5162. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5163. (while (re-search-forward regexp nil t)
  5164. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5165. (when (and end (< (point) end))
  5166. ;; Hide first custom property in current drawer.
  5167. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5168. (overlay-put o 'invisible t)
  5169. (overlay-put o 'org-custom-property t)
  5170. (push o org-custom-properties-overlays))
  5171. ;; Hide additional custom properties in the same drawer.
  5172. (while (re-search-forward regexp end t)
  5173. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5174. (overlay-put o 'invisible t)
  5175. (overlay-put o 'org-custom-property t)
  5176. (push o org-custom-properties-overlays)))))
  5177. ;; Each entry is limited to a single property drawer.
  5178. (outline-next-heading)))))))
  5179. (defun org-fontify-entities (limit)
  5180. "Find an entity to fontify."
  5181. (let (ee)
  5182. (when org-pretty-entities
  5183. (catch 'match
  5184. ;; "\_ "-family is left out on purpose. Only the first one,
  5185. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5186. ;; confusing when adding a second white space character.
  5187. (while (re-search-forward
  5188. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5189. limit t)
  5190. (when (and (not (org-at-comment-p))
  5191. (setq ee (org-entity-get (match-string 1)))
  5192. (= (length (nth 6 ee)) 1))
  5193. (let* ((end (if (equal (match-string 2) "{}")
  5194. (match-end 2)
  5195. (match-end 1))))
  5196. (add-text-properties
  5197. (match-beginning 0) end
  5198. (list 'font-lock-fontified t))
  5199. (compose-region (match-beginning 0) end
  5200. (nth 6 ee) nil)
  5201. (backward-char 1)
  5202. (throw 'match t))))
  5203. nil))))
  5204. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5205. "Fontify string S like in Org mode."
  5206. (with-temp-buffer
  5207. (insert s)
  5208. (let ((org-odd-levels-only odd-levels))
  5209. (org-mode)
  5210. (font-lock-ensure)
  5211. (if org-link-descriptive
  5212. (org-link-display-format
  5213. (buffer-string))
  5214. (buffer-string)))))
  5215. (defun org-get-level-face (n)
  5216. "Get the right face for match N in font-lock matching of headlines."
  5217. (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
  5218. (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
  5219. (org-f (if org-cycle-level-faces
  5220. (nth (% (1- org-l) org-n-level-faces) org-level-faces)
  5221. (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
  5222. (cond
  5223. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5224. ((eq n 2) org-f)
  5225. (t (unless org-level-color-stars-only org-f)))))
  5226. (defun org-face-from-face-or-color (context inherit face-or-color)
  5227. "Create a face list that inherits INHERIT, but sets the foreground color.
  5228. When FACE-OR-COLOR is not a string, just return it."
  5229. (if (stringp face-or-color)
  5230. (list :inherit inherit
  5231. (cdr (assoc context org-faces-easy-properties))
  5232. face-or-color)
  5233. face-or-color))
  5234. (defun org-get-todo-face (kwd)
  5235. "Get the right face for a TODO keyword KWD.
  5236. If KWD is a number, get the corresponding match group."
  5237. (when (numberp kwd) (setq kwd (match-string kwd)))
  5238. (or (org-face-from-face-or-color
  5239. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5240. (and (member kwd org-done-keywords) 'org-done)
  5241. 'org-todo))
  5242. (defun org-get-priority-face (priority)
  5243. "Get the right face for PRIORITY.
  5244. PRIORITY is a character."
  5245. (or (org-face-from-face-or-color
  5246. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5247. 'org-priority))
  5248. (defun org-get-tag-face (tag)
  5249. "Get the right face for TAG.
  5250. If TAG is a number, get the corresponding match group."
  5251. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5252. (or (org-face-from-face-or-color
  5253. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5254. 'org-tag)))
  5255. (defvar org-priority-regexp) ; defined later in the file
  5256. (defun org-font-lock-add-priority-faces (limit)
  5257. "Add the special priority faces."
  5258. (while (re-search-forward (concat "^\\*+" org-priority-regexp) limit t)
  5259. (let ((beg (match-beginning 1))
  5260. (end (1+ (match-end 2))))
  5261. (add-face-text-property
  5262. beg end
  5263. (org-get-priority-face (string-to-char (match-string 2))))
  5264. (add-text-properties
  5265. beg end
  5266. (list 'font-lock-fontified t)))))
  5267. (defun org-font-lock-add-tag-faces (limit)
  5268. "Add the special tag faces."
  5269. (when (and org-tag-faces org-tags-special-faces-re)
  5270. (while (re-search-forward org-tags-special-faces-re limit t)
  5271. (add-face-text-property
  5272. (match-beginning 1)
  5273. (match-end 1)
  5274. (org-get-tag-face 1))
  5275. (add-text-properties (match-beginning 1) (match-end 1)
  5276. (list 'font-lock-fontified t))
  5277. (backward-char 1))))
  5278. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5279. "Remove fontification and activation overlays from links."
  5280. (font-lock-default-unfontify-region beg end)
  5281. (let* ((buffer-undo-list t)
  5282. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5283. (inhibit-modification-hooks t)
  5284. deactivate-mark buffer-file-name buffer-file-truename)
  5285. (decompose-region beg end)
  5286. (remove-text-properties beg end
  5287. '(mouse-face t keymap t org-linked-text t
  5288. invisible t intangible t
  5289. org-emphasis t))
  5290. (org-fold-region beg end nil 'org-link)
  5291. (org-fold-region beg end nil 'org-link-description)
  5292. (org-fold-core-update-optimisation beg end)
  5293. (org-remove-font-lock-display-properties beg end)))
  5294. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5295. ((raise 0.3) (height 0.7))
  5296. ((raise -0.5))
  5297. ((raise 0.5)))
  5298. "Display properties for showing superscripts and subscripts.")
  5299. (defun org-remove-font-lock-display-properties (beg end)
  5300. "Remove specific display properties that have been added by font lock.
  5301. The will remove the raise properties that are used to show superscripts
  5302. and subscripts."
  5303. (let (next prop)
  5304. (while (< beg end)
  5305. (setq next (next-single-property-change beg 'display nil end)
  5306. prop (get-text-property beg 'display))
  5307. (when (member prop org-script-display)
  5308. (put-text-property beg next 'display nil))
  5309. (setq beg next))))
  5310. (defun org-raise-scripts (limit)
  5311. "Add raise properties to sub/superscripts."
  5312. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5313. (re-search-forward
  5314. (if (eq org-use-sub-superscripts t)
  5315. org-match-substring-regexp
  5316. org-match-substring-with-braces-regexp)
  5317. limit t))
  5318. (let* ((pos (point)) table-p comment-p
  5319. (mpos (match-beginning 3))
  5320. (emph-p (get-text-property mpos 'org-emphasis))
  5321. (link-p (get-text-property mpos 'mouse-face))
  5322. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5323. (goto-char (line-beginning-position))
  5324. (setq table-p (looking-at-p org-table-dataline-regexp)
  5325. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5326. (goto-char pos)
  5327. ;; Handle a_b^c
  5328. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5329. (unless (or comment-p emph-p link-p keyw-p)
  5330. (put-text-property (match-beginning 3) (match-end 0)
  5331. 'display
  5332. (if (equal (char-after (match-beginning 2)) ?^)
  5333. (nth (if table-p 3 1) org-script-display)
  5334. (nth (if table-p 2 0) org-script-display)))
  5335. (put-text-property (match-beginning 2) (match-end 3)
  5336. 'org-emphasis t)
  5337. (add-text-properties (match-beginning 2) (match-end 2)
  5338. (list 'invisible t))
  5339. (when (and (eq (char-after (match-beginning 3)) ?{)
  5340. (eq (char-before (match-end 3)) ?}))
  5341. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5342. (list 'invisible t))
  5343. (add-text-properties (1- (match-end 3)) (match-end 3)
  5344. (list 'invisible t))))
  5345. t)))
  5346. (defun org-remove-empty-overlays-at (pos)
  5347. "Remove outline overlays that do not contain non-white stuff."
  5348. (dolist (o (overlays-at pos))
  5349. (and (eq 'outline (overlay-get o 'invisible))
  5350. (not (string-match-p
  5351. "\\S-" (buffer-substring (overlay-start o)
  5352. (overlay-end o))))
  5353. (delete-overlay o))))
  5354. ;; FIXME: This function is unused.
  5355. (defun org-show-empty-lines-in-parent ()
  5356. "Move to the parent and re-show empty lines before visible headlines."
  5357. (save-excursion
  5358. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5359. (org-cycle-show-empty-lines context))))
  5360. (defun org-files-list ()
  5361. "Return `org-agenda-files' list, plus all open Org files.
  5362. This is useful for operations that need to scan all of a user's
  5363. open and agenda-wise Org files."
  5364. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5365. (dolist (buf (buffer-list))
  5366. (with-current-buffer buf
  5367. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5368. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5369. :test #'equal))))
  5370. files))
  5371. (defsubst org-entry-beginning-position ()
  5372. "Return the beginning position of the current entry."
  5373. (save-excursion (org-back-to-heading t) (point)))
  5374. (defsubst org-entry-end-position ()
  5375. "Return the end position of the current entry."
  5376. (save-excursion (outline-next-heading) (point)))
  5377. (defun org-subtree-end-visible-p ()
  5378. "Is the end of the current subtree visible?"
  5379. (pos-visible-in-window-p
  5380. (save-excursion (org-end-of-subtree t) (point))))
  5381. (defun org-first-headline-recenter ()
  5382. "Move cursor to the first headline and recenter the headline."
  5383. (let ((window (get-buffer-window)))
  5384. (when window
  5385. (goto-char (point-min))
  5386. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5387. (set-window-start window (line-beginning-position))))))
  5388. ;; FIXME: It was in the middle of visibility section. Where should it go to?
  5389. (defvar org-called-with-limited-levels nil
  5390. "Non-nil when `org-with-limited-levels' is currently active.")
  5391. ;;; Indirect buffer display of subtrees
  5392. (defvar org-indirect-dedicated-frame nil
  5393. "This is the frame being used for indirect tree display.")
  5394. (defvar org-last-indirect-buffer nil)
  5395. (defun org-tree-to-indirect-buffer (&optional arg)
  5396. "Create indirect buffer and narrow it to current subtree.
  5397. With a numerical prefix ARG, go up to this level and then take that tree.
  5398. If ARG is negative, go up that many levels.
  5399. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  5400. indirect buffer previously made with this command, to avoid proliferation of
  5401. indirect buffers. However, when you call the command with a \
  5402. `\\[universal-argument]' prefix, or
  5403. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  5404. so that you can work with several indirect buffers at the same time. If
  5405. `org-indirect-buffer-display' is `dedicated-frame', the \
  5406. `\\[universal-argument]' prefix also
  5407. requests that a new frame be made for the new buffer, so that the dedicated
  5408. frame is not changed."
  5409. (interactive "P")
  5410. (let ((cbuf (current-buffer))
  5411. (cwin (selected-window))
  5412. (pos (point))
  5413. beg end level heading ibuf)
  5414. (save-excursion
  5415. (org-back-to-heading t)
  5416. (when (numberp arg)
  5417. (setq level (org-outline-level))
  5418. (when (< arg 0) (setq arg (+ level arg)))
  5419. (while (> (setq level (org-outline-level)) arg)
  5420. (org-up-heading-safe)))
  5421. (setq beg (point)
  5422. heading (org-get-heading 'no-tags))
  5423. (org-end-of-subtree t t)
  5424. (when (and (not (eobp)) (org-at-heading-p)) (backward-char 1))
  5425. (setq end (point)))
  5426. (when (and (buffer-live-p org-last-indirect-buffer)
  5427. (not (eq org-indirect-buffer-display 'new-frame))
  5428. (not arg))
  5429. (kill-buffer org-last-indirect-buffer))
  5430. (setq ibuf (org-get-indirect-buffer cbuf heading)
  5431. org-last-indirect-buffer ibuf)
  5432. (cond
  5433. ((or (eq org-indirect-buffer-display 'new-frame)
  5434. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  5435. (select-frame (make-frame))
  5436. (delete-other-windows)
  5437. (pop-to-buffer-same-window ibuf)
  5438. (org-set-frame-title heading))
  5439. ((eq org-indirect-buffer-display 'dedicated-frame)
  5440. (raise-frame
  5441. (select-frame (or (and org-indirect-dedicated-frame
  5442. (frame-live-p org-indirect-dedicated-frame)
  5443. org-indirect-dedicated-frame)
  5444. (setq org-indirect-dedicated-frame (make-frame)))))
  5445. (delete-other-windows)
  5446. (pop-to-buffer-same-window ibuf)
  5447. (org-set-frame-title (concat "Indirect: " heading)))
  5448. ((eq org-indirect-buffer-display 'current-window)
  5449. (pop-to-buffer-same-window ibuf))
  5450. ((eq org-indirect-buffer-display 'other-window)
  5451. (pop-to-buffer ibuf))
  5452. (t (error "Invalid value")))
  5453. (narrow-to-region beg end)
  5454. (org-fold-show-all '(headings drawers blocks))
  5455. (goto-char pos)
  5456. (run-hook-with-args 'org-cycle-hook 'all)
  5457. (and (window-live-p cwin) (select-window cwin))))
  5458. (defun org-get-indirect-buffer (&optional buffer heading)
  5459. (setq buffer (or buffer (current-buffer)))
  5460. (let ((n 1) (base (buffer-name buffer)) bname)
  5461. (while (buffer-live-p
  5462. (get-buffer
  5463. (setq bname
  5464. (concat base "-"
  5465. (if heading (concat heading "-" (number-to-string n))
  5466. (number-to-string n))))))
  5467. (setq n (1+ n)))
  5468. (condition-case nil
  5469. (let ((indirect-buffer (make-indirect-buffer buffer bname 'clone)))
  5470. ;; Decouple folding state. We need to do it manually since
  5471. ;; `make-indirect-buffer' does not run
  5472. ;; `clone-indirect-buffer-hook'.
  5473. (org-fold-core-decouple-indirect-buffer-folds)
  5474. ;; Return the buffer.
  5475. indirect-buffer)
  5476. (error (make-indirect-buffer buffer bname)))))
  5477. (defun org-set-frame-title (title)
  5478. "Set the title of the current frame to the string TITLE."
  5479. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  5480. ;;;; Structure editing
  5481. ;;; Inserting headlines
  5482. (defun org--blank-before-heading-p (&optional parent)
  5483. "Non-nil when an empty line should precede a new heading here.
  5484. When optional argument PARENT is non-nil, consider parent
  5485. headline instead of current one."
  5486. (pcase (assq 'heading org-blank-before-new-entry)
  5487. (`(heading . auto)
  5488. (save-excursion
  5489. (org-with-limited-levels
  5490. (unless (and (org-before-first-heading-p)
  5491. (not (outline-next-heading)))
  5492. (org-back-to-heading t)
  5493. (when parent (org-up-heading-safe))
  5494. (cond ((not (bobp))
  5495. (org-previous-line-empty-p))
  5496. ((outline-next-heading)
  5497. (org-previous-line-empty-p))
  5498. ;; Ignore trailing spaces on last buffer line.
  5499. ((progn (skip-chars-backward " \t") (bolp))
  5500. (org-previous-line-empty-p))
  5501. (t nil))))))
  5502. (`(heading . ,value) value)
  5503. (_ nil)))
  5504. (defun org-insert-heading (&optional arg invisible-ok top)
  5505. "Insert a new heading or an item with the same depth at point.
  5506. If point is at the beginning of a heading, insert a new heading
  5507. or a new headline above the current one. When at the beginning
  5508. of a regular line of text, turn it into a heading.
  5509. If point is in the middle of a line, split it and create a new
  5510. headline with the text in the current line after point (see
  5511. `org-M-RET-may-split-line' on how to modify this behavior). As
  5512. a special case, on a headline, splitting can only happen on the
  5513. title itself. E.g., this excludes breaking stars or tags.
  5514. With a `\\[universal-argument]' prefix, set \
  5515. `org-insert-heading-respect-content' to
  5516. a non-nil value for the duration of the command. This forces the
  5517. insertion of a heading after the current subtree, independently
  5518. on the location of point.
  5519. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  5520. insert the heading at the end of the tree
  5521. above the current heading. For example, if point is within a
  5522. 2nd-level heading, then it will insert a 2nd-level heading at
  5523. the end of the 1st-level parent subtree.
  5524. When INVISIBLE-OK is set, stop at invisible headlines when going
  5525. back. This is important for non-interactive uses of the
  5526. command.
  5527. When optional argument TOP is non-nil, insert a level 1 heading,
  5528. unconditionally."
  5529. (interactive "P")
  5530. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  5531. (level (org-current-level))
  5532. (stars (make-string (if (and level (not top)) level 1) ?*)))
  5533. (cond
  5534. ((or org-insert-heading-respect-content
  5535. (member arg '((4) (16)))
  5536. (and (not invisible-ok)
  5537. (invisible-p (max (1- (point)) (point-min)))))
  5538. ;; Position point at the location of insertion. Make sure we
  5539. ;; end up on a visible headline if INVISIBLE-OK is nil.
  5540. (org-with-limited-levels
  5541. (if (not level) (outline-next-heading) ;before first headline
  5542. (org-back-to-heading invisible-ok)
  5543. (when (equal arg '(16)) (org-up-heading-safe))
  5544. (org-end-of-subtree)))
  5545. (unless (bolp) (insert "\n"))
  5546. (when (and blank? (save-excursion
  5547. (backward-char)
  5548. (org-before-first-heading-p)))
  5549. (insert "\n")
  5550. (backward-char))
  5551. (when (and (not level) (not (eobp)) (not (bobp)))
  5552. (when (org-at-heading-p) (insert "\n"))
  5553. (backward-char))
  5554. (unless (and blank? (org-previous-line-empty-p))
  5555. (org-N-empty-lines-before-current (if blank? 1 0)))
  5556. (insert stars " ")
  5557. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  5558. ;; is visible.
  5559. (unless invisible-ok
  5560. (if (eq org-fold-core-style 'text-properties)
  5561. (cond
  5562. ((org-fold-folded-p
  5563. (max (point-min)
  5564. (1- (line-beginning-position)))
  5565. 'headline)
  5566. (org-fold-region (line-end-position 0) (line-end-position) nil 'headline))
  5567. (t nil))
  5568. (pcase (get-char-property-and-overlay (point) 'invisible)
  5569. (`(outline . ,o)
  5570. (move-overlay o (overlay-start o) (line-end-position 0)))
  5571. (_ nil)))))
  5572. ;; At a headline...
  5573. ((org-at-heading-p)
  5574. (cond ((bolp)
  5575. (when blank? (save-excursion (insert "\n")))
  5576. (save-excursion (insert stars " \n"))
  5577. (unless (and blank? (org-previous-line-empty-p))
  5578. (org-N-empty-lines-before-current (if blank? 1 0)))
  5579. (end-of-line))
  5580. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  5581. (org-match-line org-complex-heading-regexp)
  5582. (org-pos-in-match-range (point) 4))
  5583. ;; Grab the text that should moved to the new headline.
  5584. ;; Preserve tags.
  5585. (let ((split (delete-and-extract-region (point) (match-end 4))))
  5586. (if (looking-at "[ \t]*$") (replace-match "")
  5587. (org-align-tags))
  5588. (end-of-line)
  5589. (when blank? (insert "\n"))
  5590. (insert "\n" stars " ")
  5591. (when (org-string-nw-p split) (insert split))))
  5592. (t
  5593. (end-of-line)
  5594. (when blank? (insert "\n"))
  5595. (insert "\n" stars " "))))
  5596. ;; On regular text, turn line into a headline or split, if
  5597. ;; appropriate.
  5598. ((bolp)
  5599. (insert stars " ")
  5600. (unless (and blank? (org-previous-line-empty-p))
  5601. (org-N-empty-lines-before-current (if blank? 1 0))))
  5602. (t
  5603. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  5604. (end-of-line))
  5605. (insert "\n" stars " ")
  5606. (unless (and blank? (org-previous-line-empty-p))
  5607. (org-N-empty-lines-before-current (if blank? 1 0))))))
  5608. (run-hooks 'org-insert-heading-hook))
  5609. (defun org-N-empty-lines-before-current (n)
  5610. "Make the number of empty lines before current exactly N.
  5611. So this will delete or add empty lines."
  5612. (let ((column (current-column)))
  5613. (beginning-of-line)
  5614. (unless (bobp)
  5615. (let ((start (save-excursion
  5616. (skip-chars-backward " \r\t\n")
  5617. (line-end-position))))
  5618. (delete-region start (line-end-position 0))))
  5619. (insert (make-string n ?\n))
  5620. (move-to-column column)))
  5621. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  5622. "Return the heading of the current entry, without the stars.
  5623. When NO-TAGS is non-nil, don't include tags.
  5624. When NO-TODO is non-nil, don't include TODO keywords.
  5625. When NO-PRIORITY is non-nil, don't include priority cookie.
  5626. When NO-COMMENT is non-nil, don't include COMMENT string.
  5627. Return nil before first heading."
  5628. (unless (org-before-first-heading-p)
  5629. (save-excursion
  5630. (org-back-to-heading t)
  5631. (let ((case-fold-search nil))
  5632. (looking-at org-complex-heading-regexp)
  5633. ;; When using `org-fold-core--optimise-for-huge-buffers',
  5634. ;; returned text will be invisible. Clear it up.
  5635. (save-match-data
  5636. (org-fold-core-remove-optimisation (match-beginning 0) (match-end 0)))
  5637. (let ((todo (and (not no-todo) (match-string 2)))
  5638. (priority (and (not no-priority) (match-string 3)))
  5639. (headline (pcase (match-string 4)
  5640. (`nil "")
  5641. ((and (guard no-comment) h)
  5642. (replace-regexp-in-string
  5643. (eval-when-compile
  5644. (format "\\`%s[ \t]+" org-comment-string))
  5645. "" h))
  5646. (h h)))
  5647. (tags (and (not no-tags) (match-string 5))))
  5648. ;; Restore cleared optimisation.
  5649. (org-fold-core-update-optimisation (match-beginning 0) (match-end 0))
  5650. (mapconcat #'identity
  5651. (delq nil (list todo priority headline tags))
  5652. " "))))))
  5653. (defun org-heading-components ()
  5654. "Return the components of the current heading.
  5655. This is a list with the following elements:
  5656. - the level as an integer
  5657. - the reduced level, different if `org-odd-levels-only' is set.
  5658. - the TODO keyword, or nil
  5659. - the priority character, like ?A, or nil if no priority is given
  5660. - the headline text itself, or the tags string if no headline text
  5661. - the tags string, or nil."
  5662. (save-excursion
  5663. (org-back-to-heading t)
  5664. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  5665. (org-fold-core-remove-optimisation (match-beginning 0) (match-end 0))
  5666. (prog1
  5667. (list (length (match-string 1))
  5668. (org-reduced-level (length (match-string 1)))
  5669. (match-string-no-properties 2)
  5670. (and (match-end 3) (aref (match-string 3) 2))
  5671. (match-string-no-properties 4)
  5672. (match-string-no-properties 5))
  5673. (org-fold-core-update-optimisation (match-beginning 0) (match-end 0))))))
  5674. (defun org-get-entry ()
  5675. "Get the entry text, after heading, entire subtree."
  5676. (save-excursion
  5677. (org-back-to-heading t)
  5678. (filter-buffer-substring (line-beginning-position 2) (org-end-of-subtree t))))
  5679. (defun org-edit-headline (&optional heading)
  5680. "Edit the current headline.
  5681. Set it to HEADING when provided."
  5682. (interactive)
  5683. (org-with-wide-buffer
  5684. (org-back-to-heading t)
  5685. (let ((case-fold-search nil))
  5686. (when (looking-at org-complex-heading-regexp)
  5687. (let* ((old (match-string-no-properties 4))
  5688. (new (save-match-data
  5689. (org-trim (or heading (read-string "Edit: " old))))))
  5690. (unless (equal old new)
  5691. (if old (replace-match new t t nil 4)
  5692. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  5693. (insert " " new))
  5694. (org-align-tags)
  5695. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  5696. (defun org-insert-heading-after-current ()
  5697. "Insert a new heading with same level as current, after current subtree."
  5698. (interactive)
  5699. (org-back-to-heading)
  5700. (org-insert-heading)
  5701. (org-move-subtree-down)
  5702. (end-of-line 1))
  5703. (defun org-insert-heading-respect-content (&optional invisible-ok)
  5704. "Insert heading with `org-insert-heading-respect-content' set to t."
  5705. (interactive)
  5706. (org-insert-heading '(4) invisible-ok))
  5707. (defun org-insert-todo-heading-respect-content (&optional _)
  5708. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  5709. (interactive)
  5710. (let ((org-insert-heading-respect-content t))
  5711. (org-insert-todo-heading '(4) t)))
  5712. (defun org-insert-todo-heading (arg &optional force-heading)
  5713. "Insert a new heading with the same level and TODO state as current heading.
  5714. If the heading has no TODO state, or if the state is DONE, use
  5715. the first state (TODO by default). Also with one prefix arg,
  5716. force first state. With two prefix args, force inserting at the
  5717. end of the parent subtree.
  5718. When called at a plain list item, insert a new item with an
  5719. unchecked check box."
  5720. (interactive "P")
  5721. (when (or force-heading (not (org-insert-item 'checkbox)))
  5722. (org-insert-heading (or (and (equal arg '(16)) '(16))
  5723. force-heading))
  5724. (save-excursion
  5725. (org-forward-heading-same-level -1)
  5726. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  5727. (let* ((new-mark-x
  5728. (if (or (equal arg '(4))
  5729. (not (match-beginning 2))
  5730. (member (match-string 2) org-done-keywords))
  5731. (car org-todo-keywords-1)
  5732. (match-string 2)))
  5733. (new-mark
  5734. (or
  5735. (run-hook-with-args-until-success
  5736. 'org-todo-get-default-hook new-mark-x nil)
  5737. new-mark-x)))
  5738. (beginning-of-line 1)
  5739. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  5740. (if org-treat-insert-todo-heading-as-state-change
  5741. (org-todo new-mark)
  5742. (insert new-mark " "))))
  5743. (when org-provide-todo-statistics
  5744. (org-update-parent-todo-statistics))))
  5745. (defun org-insert-subheading (arg)
  5746. "Insert a new subheading and demote it.
  5747. Works for outline headings and for plain lists alike."
  5748. (interactive "P")
  5749. (org-insert-heading arg)
  5750. (cond
  5751. ((org-at-heading-p) (org-do-demote))
  5752. ((org-at-item-p) (org-indent-item))))
  5753. (defun org-insert-todo-subheading (arg)
  5754. "Insert a new subheading with TODO keyword or checkbox and demote it.
  5755. Works for outline headings and for plain lists alike."
  5756. (interactive "P")
  5757. (org-insert-todo-heading arg)
  5758. (cond
  5759. ((org-at-heading-p) (org-do-demote))
  5760. ((org-at-item-p) (org-indent-item))))
  5761. ;;; Promotion and Demotion
  5762. (defvar org-after-demote-entry-hook nil
  5763. "Hook run after an entry has been demoted.
  5764. The cursor will be at the beginning of the entry.
  5765. When a subtree is being demoted, the hook will be called for each node.")
  5766. (defvar org-after-promote-entry-hook nil
  5767. "Hook run after an entry has been promoted.
  5768. The cursor will be at the beginning of the entry.
  5769. When a subtree is being promoted, the hook will be called for each node.")
  5770. (defun org-promote-subtree ()
  5771. "Promote the entire subtree.
  5772. See also `org-promote'."
  5773. (interactive)
  5774. (save-excursion
  5775. (org-back-to-heading t)
  5776. (combine-change-calls (point) (save-excursion (org-end-of-subtree t))
  5777. (org-with-limited-levels (org-map-tree 'org-promote))))
  5778. (org-fix-position-after-promote))
  5779. (defun org-demote-subtree ()
  5780. "Demote the entire subtree.
  5781. See `org-demote' and `org-promote'."
  5782. (interactive)
  5783. (save-excursion
  5784. (org-back-to-heading t)
  5785. (combine-change-calls (point) (save-excursion (org-end-of-subtree t))
  5786. (org-with-limited-levels (org-map-tree 'org-demote))))
  5787. (org-fix-position-after-promote))
  5788. (defun org-do-promote ()
  5789. "Promote the current heading higher up the tree.
  5790. If the region is active in `transient-mark-mode', promote all
  5791. headings in the region."
  5792. (interactive)
  5793. (save-excursion
  5794. (if (org-region-active-p)
  5795. (org-map-region 'org-promote (region-beginning) (region-end))
  5796. (org-promote)))
  5797. (org-fix-position-after-promote))
  5798. (defun org-do-demote ()
  5799. "Demote the current heading lower down the tree.
  5800. If the region is active in `transient-mark-mode', demote all
  5801. headings in the region."
  5802. (interactive)
  5803. (save-excursion
  5804. (if (org-region-active-p)
  5805. (org-map-region 'org-demote (region-beginning) (region-end))
  5806. (org-demote)))
  5807. (org-fix-position-after-promote))
  5808. (defun org-fix-position-after-promote ()
  5809. "Fix cursor position and indentation after demoting/promoting."
  5810. (let ((pos (point)))
  5811. (when (save-excursion
  5812. (beginning-of-line)
  5813. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  5814. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  5815. (cond ((eobp) (insert " "))
  5816. ((eolp) (insert " "))
  5817. ((equal (char-after) ?\s) (forward-char 1))))))
  5818. (defun org-current-level ()
  5819. "Return the level of the current entry, or nil if before the first headline.
  5820. The level is the number of stars at the beginning of the
  5821. headline. Use `org-reduced-level' to remove the effect of
  5822. `org-odd-levels'. Unlike to `org-outline-level', this function
  5823. ignores inlinetasks."
  5824. (let ((level (org-with-limited-levels (org-outline-level))))
  5825. (and (> level 0) level)))
  5826. (defun org-get-previous-line-level ()
  5827. "Return the outline depth of the last headline before the current line.
  5828. Returns 0 for the first headline in the buffer, and nil if before the
  5829. first headline."
  5830. (and (org-current-level)
  5831. (or (and (/= (line-beginning-position) (point-min))
  5832. (save-excursion (beginning-of-line 0) (org-current-level)))
  5833. 0)))
  5834. (defun org-reduced-level (l)
  5835. "Compute the effective level of a heading.
  5836. This takes into account the setting of `org-odd-levels-only'."
  5837. (cond
  5838. ((zerop l) 0)
  5839. (org-odd-levels-only (1+ (floor (/ l 2))))
  5840. (t l)))
  5841. (defun org-level-increment ()
  5842. "Return the number of stars that will be added or removed at a
  5843. time to headlines when structure editing, based on the value of
  5844. `org-odd-levels-only'."
  5845. (if org-odd-levels-only 2 1))
  5846. (defun org-get-valid-level (level &optional change)
  5847. "Rectify a level change under the influence of `org-odd-levels-only'.
  5848. LEVEL is a current level, CHANGE is by how much the level should
  5849. be modified. Even if CHANGE is nil, LEVEL may be returned
  5850. modified because even level numbers will become the next higher
  5851. odd number. Returns values greater than 0."
  5852. (if org-odd-levels-only
  5853. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  5854. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  5855. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  5856. (max 1 (+ level (or change 0)))))
  5857. (defun org-promote ()
  5858. "Promote the current heading higher up the tree."
  5859. (org-with-wide-buffer
  5860. (org-back-to-heading t)
  5861. (let* ((after-change-functions (remq 'flyspell-after-change-function
  5862. after-change-functions))
  5863. (level (save-match-data (funcall outline-level)))
  5864. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  5865. (diff (abs (- level (length up-head) -1))))
  5866. (cond
  5867. ((and (= level 1) org-allow-promoting-top-level-subtree)
  5868. (replace-match "# " nil t))
  5869. ((= level 1)
  5870. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  5871. (t (replace-match (apply #'propertize up-head (text-properties-at (match-beginning 0))) t)))
  5872. (unless (= level 1)
  5873. (when org-auto-align-tags (org-align-tags))
  5874. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  5875. (run-hooks 'org-after-promote-entry-hook))))
  5876. (defun org-demote ()
  5877. "Demote the current heading lower down the tree."
  5878. (org-with-wide-buffer
  5879. (org-back-to-heading t)
  5880. (let* ((after-change-functions (remq 'flyspell-after-change-function
  5881. after-change-functions))
  5882. (level (save-match-data (funcall outline-level)))
  5883. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  5884. (diff (abs (- level (length down-head) -1))))
  5885. (org-fold-core-ignore-fragility-checks
  5886. (replace-match (apply #'propertize down-head (text-properties-at (match-beginning 0))) t)
  5887. (when org-auto-align-tags (org-align-tags))
  5888. (when org-adapt-indentation (org-fixup-indentation diff)))
  5889. (run-hooks 'org-after-demote-entry-hook))))
  5890. (defun org-cycle-level ()
  5891. "Cycle the level of an empty headline through possible states.
  5892. This goes first to child, then to parent, level, then up the hierarchy.
  5893. After top level, it switches back to sibling level."
  5894. (interactive)
  5895. (let ((org-adapt-indentation nil))
  5896. (when (org-point-at-end-of-empty-headline)
  5897. (setq this-command 'org-cycle-level) ; Only needed for caching
  5898. (let ((cur-level (org-current-level))
  5899. (prev-level (org-get-previous-line-level)))
  5900. (cond
  5901. ;; If first headline in file, promote to top-level.
  5902. ((= prev-level 0)
  5903. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  5904. do (org-do-promote)))
  5905. ;; If same level as prev, demote one.
  5906. ((= prev-level cur-level)
  5907. (org-do-demote))
  5908. ;; If parent is top-level, promote to top level if not already.
  5909. ((= prev-level 1)
  5910. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  5911. do (org-do-promote)))
  5912. ;; If top-level, return to prev-level.
  5913. ((= cur-level 1)
  5914. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  5915. do (org-do-demote)))
  5916. ;; If less than prev-level, promote one.
  5917. ((< cur-level prev-level)
  5918. (org-do-promote))
  5919. ;; If deeper than prev-level, promote until higher than
  5920. ;; prev-level.
  5921. ((> cur-level prev-level)
  5922. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  5923. do (org-do-promote))))
  5924. t))))
  5925. (defun org-map-tree (fun)
  5926. "Call FUN for every heading underneath the current one."
  5927. (org-back-to-heading t)
  5928. (let ((level (funcall outline-level)))
  5929. (save-excursion
  5930. (funcall fun)
  5931. (while (and (progn
  5932. (outline-next-heading)
  5933. (> (funcall outline-level) level))
  5934. (not (eobp)))
  5935. (funcall fun)))))
  5936. (defun org-map-region (fun beg end)
  5937. "Call FUN for every heading between BEG and END."
  5938. (let ((org-ignore-region t))
  5939. (save-excursion
  5940. (setq end (copy-marker end))
  5941. (goto-char beg)
  5942. (when (and (re-search-forward org-outline-regexp-bol nil t)
  5943. (< (point) end))
  5944. (funcall fun))
  5945. (while (and (progn
  5946. (outline-next-heading)
  5947. (< (point) end))
  5948. (not (eobp)))
  5949. (funcall fun)))))
  5950. (defun org-fixup-indentation (diff)
  5951. "Change the indentation in the current entry by DIFF.
  5952. DIFF is an integer. Indentation is done according to the
  5953. following rules:
  5954. - Planning information and property drawers are always indented
  5955. according to the new level of the headline;
  5956. - Footnote definitions and their contents are ignored;
  5957. - Inlinetasks' boundaries are not shifted;
  5958. - Empty lines are ignored;
  5959. - Other lines' indentation are shifted by DIFF columns, unless
  5960. it would introduce a structural change in the document, in
  5961. which case no shifting is done at all.
  5962. Assume point is at a heading or an inlinetask beginning."
  5963. (org-with-wide-buffer
  5964. (narrow-to-region (line-beginning-position)
  5965. (save-excursion
  5966. (if (org-with-limited-levels (org-at-heading-p))
  5967. (org-with-limited-levels (outline-next-heading))
  5968. (org-inlinetask-goto-end))
  5969. (point)))
  5970. (forward-line)
  5971. ;; Indent properly planning info and property drawer.
  5972. (when (looking-at-p org-planning-line-re)
  5973. (org-indent-line)
  5974. (forward-line))
  5975. (when (looking-at org-property-drawer-re)
  5976. (goto-char (match-end 0))
  5977. (forward-line)
  5978. (org-indent-region (match-beginning 0) (match-end 0)))
  5979. (when (looking-at org-logbook-drawer-re)
  5980. (let ((end-marker (move-marker (make-marker) (match-end 0)))
  5981. (col (+ (current-indentation) diff)))
  5982. (when (wholenump col)
  5983. (while (< (point) end-marker)
  5984. (if (natnump diff)
  5985. (insert (make-string diff 32))
  5986. (delete-char (abs diff)))
  5987. (forward-line)))))
  5988. (catch 'no-shift
  5989. (when (or (zerop diff) (not (eq org-adapt-indentation t)))
  5990. (throw 'no-shift nil))
  5991. ;; If DIFF is negative, first check if a shift is possible at all
  5992. ;; (e.g., it doesn't break structure). This can only happen if
  5993. ;; some contents are not properly indented.
  5994. (let ((case-fold-search t))
  5995. (when (< diff 0)
  5996. (let ((diff (- diff))
  5997. (forbidden-re (concat org-outline-regexp
  5998. "\\|"
  5999. (substring org-footnote-definition-re 1))))
  6000. (save-excursion
  6001. (while (not (eobp))
  6002. (cond
  6003. ((looking-at-p "[ \t]*$") (forward-line))
  6004. ((and (looking-at-p org-footnote-definition-re)
  6005. (let ((e (org-element-at-point)))
  6006. (and (eq (org-element-type e) 'footnote-definition)
  6007. (goto-char (org-element-property :end e))))))
  6008. ((looking-at-p org-outline-regexp) (forward-line))
  6009. ;; Give up if shifting would move before column 0 or
  6010. ;; if it would introduce a headline or a footnote
  6011. ;; definition.
  6012. (t
  6013. (skip-chars-forward " \t")
  6014. (let ((ind (current-column)))
  6015. (when (or (< ind diff)
  6016. (and (= ind diff) (looking-at-p forbidden-re)))
  6017. (throw 'no-shift nil)))
  6018. ;; Ignore contents of example blocks and source
  6019. ;; blocks if their indentation is meant to be
  6020. ;; preserved. Jump to block's closing line.
  6021. (beginning-of-line)
  6022. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6023. (let ((e (org-element-at-point)))
  6024. (and (memq (org-element-type e)
  6025. '(example-block src-block))
  6026. (or org-src-preserve-indentation
  6027. (org-element-property :preserve-indent e))
  6028. (goto-char (org-element-property :end e))
  6029. (progn (skip-chars-backward " \r\t\n")
  6030. (beginning-of-line)
  6031. t))))
  6032. (forward-line))))))))
  6033. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6034. ;; by DIFF. Also skip contents of source or example blocks
  6035. ;; when indentation is meant to be preserved.
  6036. (while (not (eobp))
  6037. (cond
  6038. ((and (looking-at-p org-footnote-definition-re)
  6039. (let ((e (org-element-at-point)))
  6040. (and (eq (org-element-type e) 'footnote-definition)
  6041. (goto-char (org-element-property :end e))))))
  6042. ((looking-at-p org-outline-regexp) (forward-line))
  6043. ((looking-at-p "[ \t]*$") (forward-line))
  6044. (t
  6045. (indent-line-to (+ (current-indentation) diff))
  6046. (beginning-of-line)
  6047. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6048. (let ((e (org-element-at-point)))
  6049. (and (memq (org-element-type e)
  6050. '(example-block src-block))
  6051. (or org-src-preserve-indentation
  6052. (org-element-property :preserve-indent e))
  6053. (goto-char (org-element-property :end e))
  6054. (progn (skip-chars-backward " \r\t\n")
  6055. (beginning-of-line)
  6056. t))))
  6057. (forward-line)))))))))
  6058. (defun org-convert-to-odd-levels ()
  6059. "Convert an Org file with all levels allowed to one with odd levels.
  6060. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6061. level 5 etc."
  6062. (interactive)
  6063. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6064. (let ((outline-level 'org-outline-level)
  6065. (org-odd-levels-only nil) n)
  6066. (save-excursion
  6067. (goto-char (point-min))
  6068. (while (re-search-forward "^\\*\\*+ " nil t)
  6069. (setq n (- (length (match-string 0)) 2))
  6070. (while (>= (setq n (1- n)) 0)
  6071. (org-demote))
  6072. (end-of-line 1))))))
  6073. (defun org-convert-to-oddeven-levels ()
  6074. "Convert an Org file with only odd levels to one with odd/even levels.
  6075. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6076. file contains a section with an even level, conversion would
  6077. destroy the structure of the file. An error is signaled in this
  6078. case."
  6079. (interactive)
  6080. (goto-char (point-min))
  6081. ;; First check if there are no even levels
  6082. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6083. (org-fold-show-set-visibility 'canonical)
  6084. (error "Not all levels are odd in this file. Conversion not possible"))
  6085. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6086. (let ((outline-regexp org-outline-regexp)
  6087. (outline-level 'org-outline-level)
  6088. (org-odd-levels-only nil) n)
  6089. (save-excursion
  6090. (goto-char (point-min))
  6091. (while (re-search-forward "^\\*\\*+ " nil t)
  6092. (setq n (/ (1- (length (match-string 0))) 2))
  6093. (while (>= (setq n (1- n)) 0)
  6094. (org-promote))
  6095. (end-of-line 1))))))
  6096. (defun org-tr-level (n)
  6097. "Make N odd if required."
  6098. (if org-odd-levels-only (1+ (/ n 2)) n))
  6099. ;;; Vertical tree motion, cutting and pasting of subtrees
  6100. (defun org-move-subtree-up (&optional arg)
  6101. "Move the current subtree up past ARG headlines of the same level."
  6102. (interactive "p")
  6103. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6104. (defun org-clean-visibility-after-subtree-move ()
  6105. "Fix visibility issues after moving a subtree."
  6106. ;; First, find a reasonable region to look at:
  6107. ;; Start two siblings above, end three below
  6108. (let* ((beg (save-excursion
  6109. (and (org-get-previous-sibling)
  6110. (org-get-previous-sibling))
  6111. (point)))
  6112. (end (save-excursion
  6113. (and (org-get-next-sibling)
  6114. (org-get-next-sibling)
  6115. (org-get-next-sibling))
  6116. (if (org-at-heading-p)
  6117. (line-end-position)
  6118. (point))))
  6119. (level (looking-at "\\*+"))
  6120. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6121. (save-excursion
  6122. (save-restriction
  6123. (narrow-to-region beg end)
  6124. (when re
  6125. ;; Properly fold already folded siblings
  6126. (goto-char (point-min))
  6127. (while (re-search-forward re nil t)
  6128. (when (and (not (org-invisible-p))
  6129. (org-invisible-p (line-end-position)))
  6130. (org-fold-heading nil))))
  6131. (org-cycle-hide-drawers 'all)
  6132. (org-cycle-show-empty-lines 'overview)))))
  6133. (defun org-move-subtree-down (&optional arg)
  6134. "Move the current subtree down past ARG headlines of the same level."
  6135. (interactive "p")
  6136. (setq arg (prefix-numeric-value arg))
  6137. (org-preserve-local-variables
  6138. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6139. 'org-get-previous-sibling))
  6140. (ins-point (make-marker))
  6141. (cnt (abs arg))
  6142. (col (current-column))
  6143. beg end txt folded)
  6144. ;; Select the tree
  6145. (org-back-to-heading)
  6146. (setq beg (point))
  6147. (save-match-data
  6148. (save-excursion (outline-end-of-heading)
  6149. (setq folded (org-invisible-p)))
  6150. (progn (org-end-of-subtree nil t)
  6151. (unless (eobp) (backward-char))))
  6152. (outline-next-heading)
  6153. (setq end (point))
  6154. (goto-char beg)
  6155. ;; Find insertion point, with error handling
  6156. (while (> cnt 0)
  6157. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6158. (goto-char beg)
  6159. (user-error "Cannot move past superior level or buffer limit"))
  6160. (setq cnt (1- cnt)))
  6161. (when (> arg 0)
  6162. ;; Moving forward - still need to move over subtree
  6163. (org-end-of-subtree t t)
  6164. (save-excursion
  6165. (org-back-over-empty-lines)
  6166. (or (bolp) (newline))))
  6167. (move-marker ins-point (point))
  6168. (setq txt (buffer-substring beg end))
  6169. (org-save-markers-in-region beg end)
  6170. (delete-region beg end)
  6171. (when (eq org-fold-core-style 'overlays) (org-remove-empty-overlays-at beg))
  6172. (unless (= beg (point-min)) (org-fold-region (1- beg) beg nil 'outline))
  6173. (unless (bobp) (org-fold-region (1- (point)) (point) nil 'outline))
  6174. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6175. (let ((bbb (point)))
  6176. (insert-before-markers txt)
  6177. (org-reinstall-markers-in-region bbb)
  6178. (move-marker ins-point bbb))
  6179. (or (bolp) (insert "\n"))
  6180. (goto-char ins-point)
  6181. (org-skip-whitespace)
  6182. (move-marker ins-point nil)
  6183. (if folded
  6184. (org-fold-subtree t)
  6185. (org-fold-show-entry 'hide-drawers)
  6186. (org-fold-show-children))
  6187. (org-clean-visibility-after-subtree-move)
  6188. ;; move back to the initial column we were at
  6189. (move-to-column col))))
  6190. (defvar org-subtree-clip ""
  6191. "Clipboard for cut and paste of subtrees.
  6192. This is actually only a copy of the kill, because we use the normal kill
  6193. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6194. (defvar org-subtree-clip-folded nil
  6195. "Was the last copied subtree folded?
  6196. This is used to fold the tree back after pasting.")
  6197. (defun org-cut-subtree (&optional n)
  6198. "Cut the current subtree into the clipboard.
  6199. With prefix arg N, cut this many sequential subtrees.
  6200. This is a short-hand for marking the subtree and then cutting it."
  6201. (interactive "p")
  6202. (org-copy-subtree n 'cut))
  6203. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6204. "Copy the current subtree into the clipboard.
  6205. With prefix arg N, copy this many sequential subtrees.
  6206. This is a short-hand for marking the subtree and then copying it.
  6207. If CUT is non-nil, actually cut the subtree.
  6208. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6209. of some markers in the region, even if CUT is non-nil. This is
  6210. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6211. (interactive "p")
  6212. (org-preserve-local-variables
  6213. (let (beg end folded (beg0 (point)))
  6214. (if (called-interactively-p 'any)
  6215. (org-back-to-heading nil) ; take what looks like a subtree
  6216. (org-back-to-heading t)) ; take what is really there
  6217. (setq beg (point))
  6218. (skip-chars-forward " \t\r\n")
  6219. (save-match-data
  6220. (if nosubtrees
  6221. (outline-next-heading)
  6222. (save-excursion (outline-end-of-heading)
  6223. (setq folded (org-invisible-p)))
  6224. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6225. (org-end-of-subtree t t)))
  6226. ;; Include the end of an inlinetask
  6227. (when (and (featurep 'org-inlinetask)
  6228. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6229. "END[ \t]*$")))
  6230. (end-of-line))
  6231. (setq end (point))
  6232. (goto-char beg0)
  6233. (when (> end beg)
  6234. (setq org-subtree-clip-folded folded)
  6235. (when (or cut force-store-markers)
  6236. (org-save-markers-in-region beg end))
  6237. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6238. (setq org-subtree-clip (current-kill 0))
  6239. (message "%s: Subtree(s) with %d characters"
  6240. (if cut "Cut" "Copied")
  6241. (length org-subtree-clip))))))
  6242. (defun org-paste-subtree (&optional level tree for-yank remove)
  6243. "Paste the clipboard as a subtree, with modification of headline level.
  6244. The entire subtree is promoted or demoted in order to match a new headline
  6245. level.
  6246. If the cursor is at the beginning of a headline, the same level as
  6247. that headline is used to paste the tree.
  6248. If not, the new level is derived from the *visible* headings
  6249. before and after the insertion point, and taken to be the inferior headline
  6250. level of the two. So if the previous visible heading is level 3 and the
  6251. next is level 4 (or vice versa), level 4 will be used for insertion.
  6252. This makes sure that the subtree remains an independent subtree and does
  6253. not swallow low level entries.
  6254. You can also force a different level, either by using a numeric prefix
  6255. argument, or by inserting the heading marker by hand. For example, if the
  6256. cursor is after \"*****\", then the tree will be shifted to level 5.
  6257. If optional TREE is given, use this text instead of the kill ring.
  6258. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6259. move back over whitespace before inserting, and move point to the end of
  6260. the inserted text when done.
  6261. When REMOVE is non-nil, remove the subtree from the clipboard."
  6262. (interactive "P")
  6263. (setq tree (or tree (and kill-ring (current-kill 0))))
  6264. (unless (org-kill-is-subtree-p tree)
  6265. (user-error
  6266. (substitute-command-keys
  6267. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6268. (org-with-limited-levels
  6269. (org-fold-core-ignore-fragility-checks
  6270. (let* ((visp (not (org-invisible-p)))
  6271. (txt tree)
  6272. (old-level (if (string-match org-outline-regexp-bol txt)
  6273. (- (match-end 0) (match-beginning 0) 1)
  6274. -1))
  6275. (force-level
  6276. (cond
  6277. (level (prefix-numeric-value level))
  6278. ;; When point is after the stars in an otherwise empty
  6279. ;; headline, use the number of stars as the forced level.
  6280. ((and (org-match-line "^\\*+[ \t]*$")
  6281. (not (eq ?* (char-after))))
  6282. (org-outline-level))
  6283. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6284. (previous-level
  6285. (save-excursion
  6286. (org-previous-visible-heading 1)
  6287. (if (org-at-heading-p) (org-outline-level) 1)))
  6288. (next-level
  6289. (save-excursion
  6290. (if (org-at-heading-p) (org-outline-level)
  6291. (org-next-visible-heading 1)
  6292. (if (org-at-heading-p) (org-outline-level) 1))))
  6293. (new-level (or force-level (max previous-level next-level)))
  6294. (shift (if (or (= old-level -1)
  6295. (= new-level -1)
  6296. (= old-level new-level))
  6297. 0
  6298. (- new-level old-level)))
  6299. (delta (if (> shift 0) -1 1))
  6300. (func (if (> shift 0) #'org-demote #'org-promote))
  6301. (org-odd-levels-only nil)
  6302. beg end newend)
  6303. ;; Remove the forced level indicator.
  6304. (when (and force-level (not level))
  6305. (delete-region (line-beginning-position) (point)))
  6306. ;; Paste before the next visible heading or at end of buffer,
  6307. ;; unless point is at the beginning of a headline.
  6308. (unless (and (bolp) (org-at-heading-p))
  6309. (org-next-visible-heading 1)
  6310. (unless (bolp) (insert "\n")))
  6311. (setq beg (point))
  6312. ;; Avoid re-parsing cache elements when i.e. level 1 heading
  6313. ;; is inserted and then promoted.
  6314. (combine-change-calls beg beg
  6315. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6316. (insert txt)
  6317. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6318. (setq newend (point))
  6319. (org-reinstall-markers-in-region beg)
  6320. (setq end (point))
  6321. (goto-char beg)
  6322. (skip-chars-forward " \t\n\r")
  6323. (setq beg (point))
  6324. (when (and (org-invisible-p) visp)
  6325. (save-excursion (org-fold-heading nil)))
  6326. ;; Shift if necessary.
  6327. (unless (= shift 0)
  6328. (save-restriction
  6329. (narrow-to-region beg end)
  6330. (while (not (= shift 0))
  6331. (org-map-region func (point-min) (point-max))
  6332. (setq shift (+ delta shift)))
  6333. (goto-char (point-min))
  6334. (setq newend (point-max)))))
  6335. (when (or for-yank (called-interactively-p 'interactive))
  6336. (message "Clipboard pasted as level %d subtree" new-level))
  6337. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6338. kill-ring
  6339. (equal org-subtree-clip (current-kill 0))
  6340. org-subtree-clip-folded)
  6341. ;; The tree was folded before it was killed/copied
  6342. (org-fold-subtree t))
  6343. (when for-yank (goto-char newend))
  6344. (when remove (pop kill-ring))))))
  6345. (defun org-kill-is-subtree-p (&optional txt)
  6346. "Check if the current kill is an outline subtree, or a set of trees.
  6347. Returns nil if kill does not start with a headline, or if the first
  6348. headline level is not the largest headline level in the tree.
  6349. So this will actually accept several entries of equal levels as well,
  6350. which is OK for `org-paste-subtree'.
  6351. If optional TXT is given, check this string instead of the current kill."
  6352. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6353. (re (org-get-limited-outline-regexp))
  6354. (^re (concat "^" re))
  6355. (start-level (and kill
  6356. (string-match
  6357. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6358. kill)
  6359. (- (match-end 2) (match-beginning 2) 1)))
  6360. (start (1+ (or (match-beginning 2) -1))))
  6361. (if (not start-level)
  6362. (progn
  6363. nil) ;; does not even start with a heading
  6364. (catch 'exit
  6365. (while (setq start (string-match ^re kill (1+ start)))
  6366. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6367. (throw 'exit nil)))
  6368. t))))
  6369. (defvar org-markers-to-move nil
  6370. "Markers that should be moved with a cut-and-paste operation.
  6371. Those markers are stored together with their positions relative to
  6372. the start of the region.")
  6373. (defun org-save-markers-in-region (beg end)
  6374. "Check markers in region.
  6375. If these markers are between BEG and END, record their position relative
  6376. to BEG, so that after moving the block of text, we can put the markers back
  6377. into place.
  6378. This function gets called just before an entry or tree gets cut from the
  6379. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  6380. called immediately, to move the markers with the entries."
  6381. (setq org-markers-to-move nil)
  6382. (when (featurep 'org-clock)
  6383. (org-clock-save-markers-for-cut-and-paste beg end))
  6384. (when (featurep 'org-agenda)
  6385. (org-agenda-save-markers-for-cut-and-paste beg end)))
  6386. (defun org-check-and-save-marker (marker beg end)
  6387. "Check if MARKER is between BEG and END.
  6388. If yes, remember the marker and the distance to BEG."
  6389. (when (and (marker-buffer marker)
  6390. (or (equal (marker-buffer marker) (current-buffer))
  6391. (equal (marker-buffer marker) (buffer-base-buffer (current-buffer))))
  6392. (>= marker beg) (< marker end))
  6393. (push (cons marker (- marker beg)) org-markers-to-move)))
  6394. (defun org-reinstall-markers-in-region (beg)
  6395. "Move all remembered markers to their position relative to BEG."
  6396. (dolist (x org-markers-to-move)
  6397. (move-marker (car x) (+ beg (cdr x))))
  6398. (setq org-markers-to-move nil))
  6399. (defun org-narrow-to-subtree (&optional element)
  6400. "Narrow buffer to the current subtree."
  6401. (interactive)
  6402. (if (org-element--cache-active-p)
  6403. (let* ((heading (org-element-lineage
  6404. (or element (org-element-at-point))
  6405. '(headline) t))
  6406. (end (org-element-property :end heading)))
  6407. (if (and heading end)
  6408. (narrow-to-region (org-element-property :begin heading)
  6409. (if (= end (point-max))
  6410. end (1- end)))
  6411. (signal 'outline-before-first-heading nil)))
  6412. (save-excursion
  6413. (save-match-data
  6414. (org-with-limited-levels
  6415. (narrow-to-region
  6416. (progn (org-back-to-heading t) (point))
  6417. (progn (org-end-of-subtree t t)
  6418. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  6419. (point))))))))
  6420. (defun org-toggle-narrow-to-subtree ()
  6421. "Narrow to the subtree at point or widen a narrowed buffer."
  6422. (interactive)
  6423. (if (buffer-narrowed-p)
  6424. (progn (widen) (message "Buffer widen"))
  6425. (org-narrow-to-subtree)
  6426. (message "Buffer narrowed to current subtree")))
  6427. (defun org-narrow-to-block ()
  6428. "Narrow buffer to the current block."
  6429. (interactive)
  6430. (let* ((case-fold-search t)
  6431. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  6432. "^[ \t]*#\\+end_.*")))
  6433. (if blockp
  6434. (narrow-to-region (car blockp) (cdr blockp))
  6435. (user-error "Not in a block"))))
  6436. (defun org-clone-subtree-with-time-shift (n &optional shift)
  6437. "Clone the task (subtree) at point N times.
  6438. The clones will be inserted as siblings.
  6439. In interactive use, the user will be prompted for the number of
  6440. clones to be produced. If the entry has a timestamp, the user
  6441. will also be prompted for a time shift, which may be a repeater
  6442. as used in time stamps, for example `+3d'. To disable this,
  6443. you can call the function with a universal prefix argument.
  6444. When a valid repeater is given and the entry contains any time
  6445. stamps, the clones will become a sequence in time, with time
  6446. stamps in the subtree shifted for each clone produced. If SHIFT
  6447. is nil or the empty string, time stamps will be left alone. The
  6448. ID property of the original subtree is removed.
  6449. In each clone, all the CLOCK entries will be removed. This
  6450. prevents Org from considering that the clocked times overlap.
  6451. If the original subtree did contain time stamps with a repeater,
  6452. the following will happen:
  6453. - the repeater will be removed in each clone
  6454. - an additional clone will be produced, with the current, unshifted
  6455. date(s) in the entry.
  6456. - the original entry will be placed *after* all the clones, with
  6457. repeater intact.
  6458. - the start days in the repeater in the original entry will be shifted
  6459. to past the last clone.
  6460. In this way you can spell out a number of instances of a repeating task,
  6461. and still retain the repeater to cover future instances of the task.
  6462. As described above, N+1 clones are produced when the original
  6463. subtree has a repeater. Setting N to 0, then, can be used to
  6464. remove the repeater from a subtree and create a shifted clone
  6465. with the original repeater."
  6466. (interactive "nNumber of clones to produce: ")
  6467. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  6468. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  6469. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  6470. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  6471. (shift
  6472. (or shift
  6473. (if (and (not (equal current-prefix-arg '(4)))
  6474. (save-excursion
  6475. (goto-char beg)
  6476. (re-search-forward org-ts-regexp-both end-of-tree t)))
  6477. (read-from-minibuffer
  6478. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  6479. ""))) ;No time shift
  6480. (doshift
  6481. (and (org-string-nw-p shift)
  6482. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
  6483. shift)
  6484. (user-error "Invalid shift specification %s" shift)))))
  6485. (goto-char end-of-tree)
  6486. (unless (bolp) (insert "\n"))
  6487. (let* ((end (point))
  6488. (template (buffer-substring beg end))
  6489. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  6490. (shift-what (pcase (and doshift (match-string 2 shift))
  6491. (`nil nil)
  6492. ("h" 'hour)
  6493. ("d" 'day)
  6494. ("w" (setq shift-n (* 7 shift-n)) 'day)
  6495. ("m" 'month)
  6496. ("y" 'year)
  6497. (_ (error "Unsupported time unit"))))
  6498. (nmin 1)
  6499. (nmax n)
  6500. (n-no-remove -1)
  6501. (org-id-overriding-file-name (buffer-file-name (buffer-base-buffer)))
  6502. (idprop (org-entry-get beg "ID")))
  6503. (when (and doshift
  6504. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  6505. template))
  6506. (delete-region beg end)
  6507. (setq end beg)
  6508. (setq nmin 0)
  6509. (setq nmax (1+ nmax))
  6510. (setq n-no-remove nmax))
  6511. (goto-char end)
  6512. (cl-loop for n from nmin to nmax do
  6513. (insert
  6514. ;; Prepare clone.
  6515. (with-temp-buffer
  6516. (insert template)
  6517. (org-mode)
  6518. (goto-char (point-min))
  6519. (org-fold-show-subtree)
  6520. (and idprop (if org-clone-delete-id
  6521. (org-entry-delete nil "ID")
  6522. (org-id-get-create t)))
  6523. (unless (= n 0)
  6524. (while (re-search-forward org-clock-line-re nil t)
  6525. (delete-region (line-beginning-position)
  6526. (line-beginning-position 2)))
  6527. (goto-char (point-min))
  6528. (while (re-search-forward org-drawer-regexp nil t)
  6529. (org-remove-empty-drawer-at (point))))
  6530. (goto-char (point-min))
  6531. (when doshift
  6532. (while (re-search-forward org-ts-regexp-both nil t)
  6533. (org-timestamp-change (* n shift-n) shift-what))
  6534. (unless (= n n-no-remove)
  6535. (goto-char (point-min))
  6536. (while (re-search-forward org-ts-regexp nil t)
  6537. (save-excursion
  6538. (goto-char (match-beginning 0))
  6539. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  6540. (delete-region (match-beginning 1) (match-end 1)))))))
  6541. (buffer-string)))))
  6542. (goto-char beg)))
  6543. ;;; Outline path
  6544. (defvar org-outline-path-cache nil
  6545. "Alist between buffer positions and outline paths.
  6546. It value is an alist (POSITION . PATH) where POSITION is the
  6547. buffer position at the beginning of an entry and PATH is a list
  6548. of strings describing the outline path for that entry, in reverse
  6549. order.")
  6550. (defun org--get-outline-path-1 (&optional use-cache)
  6551. "Return outline path to current headline.
  6552. Outline path is a list of strings, in reverse order. When
  6553. optional argument USE-CACHE is non-nil, make use of a cache. See
  6554. `org-get-outline-path' for details.
  6555. Assume buffer is widened and point is on a headline."
  6556. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  6557. (let ((p (point))
  6558. (heading (let ((case-fold-search nil))
  6559. (looking-at org-complex-heading-regexp)
  6560. (if (not (match-end 4)) ""
  6561. ;; Remove statistics cookies.
  6562. (org-trim
  6563. (org-link-display-format
  6564. (replace-regexp-in-string
  6565. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  6566. (match-string-no-properties 4))))))))
  6567. (if (org-up-heading-safe)
  6568. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  6569. (when use-cache
  6570. (push (cons p path) org-outline-path-cache))
  6571. path)
  6572. ;; This is a new root node. Since we assume we are moving
  6573. ;; forward, we can drop previous cache so as to limit number
  6574. ;; of associations there.
  6575. (let ((path (list heading)))
  6576. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  6577. path)))))
  6578. (defun org-get-outline-path (&optional with-self use-cache)
  6579. "Return the outline path to the current entry.
  6580. An outline path is a list of ancestors for current headline, as
  6581. a list of strings. Statistics cookies are removed and links are
  6582. replaced with their description, if any, or their path otherwise.
  6583. When optional argument WITH-SELF is non-nil, the path also
  6584. includes the current headline.
  6585. When optional argument USE-CACHE is non-nil, cache outline paths
  6586. between calls to this function so as to avoid backtracking. This
  6587. argument is useful when planning to find more than one outline
  6588. path in the same document. In that case, there are two
  6589. conditions to satisfy:
  6590. - `org-outline-path-cache' is set to nil before starting the
  6591. process;
  6592. - outline paths are computed by increasing buffer positions."
  6593. (org-with-wide-buffer
  6594. (and (or (and with-self (org-back-to-heading t))
  6595. (org-up-heading-safe))
  6596. (reverse (org--get-outline-path-1 use-cache)))))
  6597. (defun org-format-outline-path (path &optional width prefix separator)
  6598. "Format the outline path PATH for display.
  6599. WIDTH is the maximum number of characters that is available.
  6600. PREFIX is a prefix to be included in the returned string,
  6601. such as the file name.
  6602. SEPARATOR is inserted between the different parts of the path,
  6603. the default is \"/\"."
  6604. (setq width (or width 79))
  6605. (setq path (delq nil path))
  6606. (unless (> width 0)
  6607. (user-error "Argument `width' must be positive"))
  6608. (setq separator (or separator "/"))
  6609. (let* ((org-odd-levels-only nil)
  6610. (fpath (concat
  6611. prefix (and prefix path separator)
  6612. (mapconcat
  6613. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  6614. (cl-loop for head in path
  6615. for n from 0
  6616. collect (org-add-props
  6617. head nil 'face
  6618. (nth (% n org-n-level-faces) org-level-faces)))
  6619. separator))))
  6620. (when (> (length fpath) width)
  6621. (if (< width 7)
  6622. ;; It's unlikely that `width' will be this small, but don't
  6623. ;; waste characters by adding ".." if it is.
  6624. (setq fpath (substring fpath 0 width))
  6625. (setf (substring fpath (- width 2)) "..")))
  6626. fpath))
  6627. (defun org-display-outline-path (&optional file current separator just-return-string)
  6628. "Display the current outline path in the echo area.
  6629. If FILE is non-nil, prepend the output with the file name.
  6630. If CURRENT is non-nil, append the current heading to the output.
  6631. SEPARATOR is passed through to `org-format-outline-path'. It separates
  6632. the different parts of the path and defaults to \"/\".
  6633. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  6634. (interactive "P")
  6635. (let* (case-fold-search
  6636. (bfn (buffer-file-name (buffer-base-buffer)))
  6637. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  6638. res)
  6639. (when current (setq path (append path
  6640. (save-excursion
  6641. (org-back-to-heading t)
  6642. (when (looking-at org-complex-heading-regexp)
  6643. (list (match-string 4)))))))
  6644. (setq res
  6645. (org-format-outline-path
  6646. path
  6647. (1- (frame-width))
  6648. (and file bfn (concat (file-name-nondirectory bfn) separator))
  6649. separator))
  6650. (add-face-text-property 0 (length res)
  6651. `(:height ,(face-attribute 'default :height))
  6652. nil res)
  6653. (if just-return-string
  6654. res
  6655. (org-unlogged-message "%s" res))))
  6656. ;;; Outline Sorting
  6657. (defun org-sort (&optional with-case)
  6658. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  6659. Optional argument WITH-CASE means sort case-sensitively."
  6660. (interactive "P")
  6661. (org-call-with-arg
  6662. (cond ((org-at-table-p) #'org-table-sort-lines)
  6663. ((org-at-item-p) #'org-sort-list)
  6664. (t #'org-sort-entries))
  6665. with-case))
  6666. (defun org-sort-remove-invisible (s)
  6667. "Remove emphasis markers and any invisible property from string S.
  6668. Assume S may contain only objects."
  6669. ;; org-element-interpret-data clears any text property, including
  6670. ;; invisible part.
  6671. (org-element-interpret-data
  6672. (let ((tree (org-element-parse-secondary-string
  6673. s (org-element-restriction 'paragraph))))
  6674. (org-element-map tree '(bold code italic link strike-through underline verbatim)
  6675. (lambda (o)
  6676. (pcase (org-element-type o)
  6677. ;; Terminal object. Replace it with its value.
  6678. ((or `code `verbatim)
  6679. (let ((new (org-element-property :value o)))
  6680. (org-element-insert-before new o)
  6681. (org-element-put-property
  6682. new :post-blank (org-element-property :post-blank o))))
  6683. ;; Non-terminal objects. Splice contents.
  6684. (type
  6685. (let ((contents
  6686. (or (org-element-contents o)
  6687. (and (eq type 'link)
  6688. (list (org-element-property :raw-link o)))))
  6689. (c nil))
  6690. (while contents
  6691. (setq c (pop contents))
  6692. (org-element-insert-before c o))
  6693. (org-element-put-property
  6694. c :post-blank (org-element-property :post-blank o)))))
  6695. (org-element-extract-element o)))
  6696. ;; Return modified tree.
  6697. tree)))
  6698. (defvar org-after-sorting-entries-or-items-hook nil
  6699. "Hook that is run after a bunch of entries or items have been sorted.
  6700. When children are sorted, the cursor is in the parent line when this
  6701. hook gets called. When a region or a plain list is sorted, the cursor
  6702. will be in the first entry of the sorted region/list.")
  6703. (defun org-sort-entries
  6704. (&optional with-case sorting-type getkey-func compare-func property
  6705. interactive?)
  6706. "Sort entries on a certain level of an outline tree.
  6707. If there is an active region, the entries in the region are sorted.
  6708. Else, if the cursor is before the first entry, sort the top-level items.
  6709. Else, the children of the entry at point are sorted.
  6710. Sorting can be alphabetically, numerically, by date/time as given by
  6711. a time stamp, by a property, by priority order, or by a custom function.
  6712. The command prompts for the sorting type unless it has been given to the
  6713. function through the SORTING-TYPE argument, which needs to be a character,
  6714. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  6715. the precise meaning of each character:
  6716. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  6717. c By creation time, which is assumed to be the first inactive time stamp
  6718. at the beginning of a line.
  6719. d By deadline date/time.
  6720. k By clocking time.
  6721. n Numerically, by converting the beginning of the entry/item to a number.
  6722. o By order of TODO keywords.
  6723. p By priority according to the cookie.
  6724. r By the value of a property.
  6725. s By scheduled date/time.
  6726. t By date/time, either the first active time stamp in the entry, or, if
  6727. none exist, by the first inactive one.
  6728. Capital letters will reverse the sort order.
  6729. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  6730. called with point at the beginning of the record. It must return a
  6731. value that is compatible with COMPARE-FUNC, the function used to
  6732. compare entries.
  6733. Comparing entries ignores case by default. However, with an optional argument
  6734. WITH-CASE, the sorting considers case as well.
  6735. Sorting is done against the visible part of the headlines, it ignores hidden
  6736. links.
  6737. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  6738. A non-nil value for INTERACTIVE? is used to signal that this
  6739. function is being called interactively."
  6740. (interactive (list current-prefix-arg nil nil nil nil t))
  6741. (let ((case-func (if with-case 'identity 'downcase))
  6742. start beg end stars re re2
  6743. txt what tmp)
  6744. ;; Find beginning and end of region to sort
  6745. (cond
  6746. ((org-region-active-p)
  6747. ;; we will sort the region
  6748. (setq end (region-end)
  6749. what "region")
  6750. (goto-char (region-beginning))
  6751. (unless (org-at-heading-p) (outline-next-heading))
  6752. (setq start (point)))
  6753. ((or (org-at-heading-p)
  6754. (ignore-errors (progn (org-back-to-heading) t)))
  6755. ;; we will sort the children of the current headline
  6756. (org-back-to-heading)
  6757. (setq start (point)
  6758. end (progn (org-end-of-subtree t t)
  6759. (or (bolp) (insert "\n"))
  6760. (when (>= (org-back-over-empty-lines) 1)
  6761. (forward-line 1))
  6762. (point))
  6763. what "children")
  6764. (goto-char start)
  6765. (org-fold-show-subtree)
  6766. (outline-next-heading))
  6767. (t
  6768. ;; we will sort the top-level entries in this file
  6769. (goto-char (point-min))
  6770. (or (org-at-heading-p) (outline-next-heading))
  6771. (setq start (point))
  6772. (goto-char (point-max))
  6773. (beginning-of-line 1)
  6774. (when (looking-at ".*?\\S-")
  6775. ;; File ends in a non-white line
  6776. (end-of-line 1)
  6777. (insert "\n"))
  6778. (setq end (point-max))
  6779. (setq what "top-level")
  6780. (goto-char start)
  6781. (org-fold-show-all '(headings drawers blocks))))
  6782. (setq beg (point))
  6783. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  6784. (looking-at "\\(\\*+\\)")
  6785. (setq stars (match-string 1)
  6786. re (concat "^" (regexp-quote stars) " +")
  6787. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  6788. txt (buffer-substring beg end))
  6789. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  6790. (when (and (not (equal stars "*")) (string-match re2 txt))
  6791. (user-error "Region to sort contains a level above the first entry"))
  6792. (unless sorting-type
  6793. (message
  6794. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  6795. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  6796. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  6797. what)
  6798. (setq sorting-type (read-char-exclusive)))
  6799. (unless getkey-func
  6800. (and (= (downcase sorting-type) ?f)
  6801. (setq getkey-func
  6802. (or (and interactive?
  6803. (org-read-function
  6804. "Function for extracting keys: "))
  6805. (error "Missing key extractor")))))
  6806. (and (= (downcase sorting-type) ?r)
  6807. (not property)
  6808. (setq property
  6809. (completing-read "Property: "
  6810. (mapcar #'list (org-buffer-property-keys t))
  6811. nil t)))
  6812. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  6813. (message "Sorting entries...")
  6814. (save-restriction
  6815. (narrow-to-region start end)
  6816. (let ((restore-clock?
  6817. ;; The clock marker is lost when using `sort-subr'; mark
  6818. ;; the clock with temporary `:org-clock-marker-backup'
  6819. ;; text property.
  6820. (when (and (eq (org-clocking-buffer) (current-buffer))
  6821. (<= start (marker-position org-clock-marker))
  6822. (>= end (marker-position org-clock-marker)))
  6823. (with-silent-modifications
  6824. (put-text-property (1- org-clock-marker) org-clock-marker
  6825. :org-clock-marker-backup t))
  6826. t))
  6827. (dcst (downcase sorting-type))
  6828. (case-fold-search nil)
  6829. (now (current-time)))
  6830. (org-preserve-local-variables
  6831. (sort-subr
  6832. (/= dcst sorting-type)
  6833. ;; This function moves to the beginning character of the
  6834. ;; "record" to be sorted.
  6835. (lambda nil
  6836. (if (re-search-forward re nil t)
  6837. (goto-char (match-beginning 0))
  6838. (goto-char (point-max))))
  6839. ;; This function moves to the last character of the "record" being
  6840. ;; sorted.
  6841. (lambda nil
  6842. (save-match-data
  6843. (condition-case nil
  6844. (outline-forward-same-level 1)
  6845. (error
  6846. (goto-char (point-max))))))
  6847. ;; This function returns the value that gets sorted against.
  6848. (lambda ()
  6849. (cond
  6850. ((= dcst ?n)
  6851. (string-to-number
  6852. (org-sort-remove-invisible (org-get-heading t t t t))))
  6853. ((= dcst ?a)
  6854. (funcall case-func
  6855. (org-sort-remove-invisible (org-get-heading t t t t))))
  6856. ((= dcst ?k)
  6857. (or (get-text-property (point) :org-clock-minutes) 0))
  6858. ((= dcst ?t)
  6859. (let ((end (save-excursion (outline-next-heading) (point))))
  6860. (if (or (re-search-forward org-ts-regexp end t)
  6861. (re-search-forward org-ts-regexp-both end t))
  6862. (org-time-string-to-seconds (match-string 0))
  6863. (float-time now))))
  6864. ((= dcst ?c)
  6865. (let ((end (save-excursion (outline-next-heading) (point))))
  6866. (if (re-search-forward
  6867. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  6868. end t)
  6869. (org-time-string-to-seconds (match-string 0))
  6870. (float-time now))))
  6871. ((= dcst ?s)
  6872. (let ((end (save-excursion (outline-next-heading) (point))))
  6873. (if (re-search-forward org-scheduled-time-regexp end t)
  6874. (org-time-string-to-seconds (match-string 1))
  6875. (float-time now))))
  6876. ((= dcst ?d)
  6877. (let ((end (save-excursion (outline-next-heading) (point))))
  6878. (if (re-search-forward org-deadline-time-regexp end t)
  6879. (org-time-string-to-seconds (match-string 1))
  6880. (float-time now))))
  6881. ((= dcst ?p)
  6882. (if (re-search-forward org-priority-regexp (line-end-position) t)
  6883. (string-to-char (match-string 2))
  6884. org-priority-default))
  6885. ((= dcst ?r)
  6886. (or (org-entry-get nil property) ""))
  6887. ((= dcst ?o)
  6888. (when (looking-at org-complex-heading-regexp)
  6889. (let* ((m (match-string 2))
  6890. (s (if (member m org-done-keywords) '- '+)))
  6891. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  6892. ((= dcst ?f)
  6893. (if getkey-func
  6894. (progn
  6895. (setq tmp (funcall getkey-func))
  6896. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  6897. tmp)
  6898. (error "Invalid key function `%s'" getkey-func)))
  6899. (t (error "Invalid sorting type `%c'" sorting-type))))
  6900. nil
  6901. (cond
  6902. ((= dcst ?a) 'string-collate-lessp)
  6903. ((= dcst ?f)
  6904. (or compare-func
  6905. (and interactive?
  6906. (org-read-function
  6907. (concat "Function for comparing keys "
  6908. "(empty for default `sort-subr' predicate): ")
  6909. 'allow-empty))))
  6910. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  6911. (org-cycle-hide-drawers 'all)
  6912. (when restore-clock?
  6913. (move-marker org-clock-marker
  6914. (1+ (next-single-property-change
  6915. start :org-clock-marker-backup)))
  6916. (remove-text-properties (1- org-clock-marker) org-clock-marker
  6917. '(:org-clock-marker-backup t)))))
  6918. (run-hooks 'org-after-sorting-entries-or-items-hook)
  6919. (message "Sorting entries...done")))
  6920. (defun org-contextualize-keys (alist contexts)
  6921. "Return valid elements in ALIST depending on CONTEXTS.
  6922. `org-agenda-custom-commands' or `org-capture-templates' are the
  6923. values used for ALIST, and `org-agenda-custom-commands-contexts'
  6924. or `org-capture-templates-contexts' are the associated contexts
  6925. definitions."
  6926. (let ((contexts
  6927. ;; normalize contexts
  6928. (mapcar
  6929. (lambda(c) (cond ((listp (cadr c))
  6930. (list (car c) (car c) (nth 1 c)))
  6931. ((string= "" (cadr c))
  6932. (list (car c) (car c) (nth 2 c)))
  6933. (t c)))
  6934. contexts))
  6935. (a alist) r s)
  6936. ;; loop over all commands or templates
  6937. (dolist (c a)
  6938. (let (vrules repl)
  6939. (cond
  6940. ((not (assoc (car c) contexts))
  6941. (push c r))
  6942. ((and (assoc (car c) contexts)
  6943. (setq vrules (org-contextualize-validate-key
  6944. (car c) contexts)))
  6945. (mapc (lambda (vr)
  6946. (unless (equal (car vr) (cadr vr))
  6947. (setq repl vr)))
  6948. vrules)
  6949. (if (not repl) (push c r)
  6950. (push (cadr repl) s)
  6951. (push
  6952. (cons (car c)
  6953. (cdr (or (assoc (cadr repl) alist)
  6954. (error "Undefined key `%s' as contextual replacement for `%s'"
  6955. (cadr repl) (car c)))))
  6956. r))))))
  6957. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  6958. (delq
  6959. nil
  6960. (delete-dups
  6961. (mapcar (lambda (x)
  6962. (let ((tpl (car x)))
  6963. (unless (delq
  6964. nil
  6965. (mapcar (lambda (y)
  6966. (equal y tpl))
  6967. s))
  6968. x)))
  6969. (reverse r))))))
  6970. (defun org-contextualize-validate-key (key contexts)
  6971. "Check CONTEXTS for agenda or capture KEY."
  6972. (let (res)
  6973. (dolist (r contexts)
  6974. (dolist (rr (car (last r)))
  6975. (when
  6976. (and (equal key (car r))
  6977. (if (functionp rr) (funcall rr)
  6978. (or (and (eq (car rr) 'in-file)
  6979. (buffer-file-name)
  6980. (string-match (cdr rr) (buffer-file-name)))
  6981. (and (eq (car rr) 'in-mode)
  6982. (string-match (cdr rr) (symbol-name major-mode)))
  6983. (and (eq (car rr) 'in-buffer)
  6984. (string-match (cdr rr) (buffer-name)))
  6985. (when (and (eq (car rr) 'not-in-file)
  6986. (buffer-file-name))
  6987. (not (string-match (cdr rr) (buffer-file-name))))
  6988. (when (eq (car rr) 'not-in-mode)
  6989. (not (string-match (cdr rr) (symbol-name major-mode))))
  6990. (when (eq (car rr) 'not-in-buffer)
  6991. (not (string-match (cdr rr) (buffer-name)))))))
  6992. (push r res))))
  6993. (delete-dups (delq nil res))))
  6994. ;; Defined to provide a value for defcustom, since there is no
  6995. ;; string-collate-greaterp in Emacs.
  6996. (defun org-string-collate-greaterp (s1 s2)
  6997. "Return non-nil if S1 is greater than S2 in collation order."
  6998. (not (string-collate-lessp s1 s2)))
  6999. ;;;###autoload
  7000. (defun org-run-like-in-org-mode (cmd)
  7001. "Run a command, pretending that the current buffer is in Org mode.
  7002. This will temporarily bind local variables that are typically bound in
  7003. Org mode to the values they have in Org mode, and then interactively
  7004. call CMD."
  7005. (org-load-modules-maybe)
  7006. (let (vars vals)
  7007. (dolist (var (org-get-local-variables))
  7008. (when (or (not (boundp (car var)))
  7009. (eq (symbol-value (car var))
  7010. (default-value (car var))))
  7011. (push (car var) vars)
  7012. (push (cadr var) vals)))
  7013. (cl-progv vars vals
  7014. (call-interactively cmd))))
  7015. (defun org-get-category (&optional pos force-refresh)
  7016. "Get the category applying to position POS."
  7017. (save-match-data
  7018. (when force-refresh (org-refresh-category-properties))
  7019. (let ((pos (or pos (point))))
  7020. (if (org-element--cache-active-p)
  7021. ;; Sync cache.
  7022. (org-with-point-at (org-element-property :begin (org-element-at-point pos))
  7023. (or (org-entry-get-with-inheritance "CATEGORY")
  7024. "???"))
  7025. (or (get-text-property pos 'org-category)
  7026. (progn
  7027. (org-refresh-category-properties)
  7028. (get-text-property pos 'org-category)))))))
  7029. ;;; Refresh properties
  7030. (defun org-refresh-properties (dprop tprop)
  7031. "Refresh buffer text properties.
  7032. DPROP is the drawer property and TPROP is either the
  7033. corresponding text property to set, or an alist with each element
  7034. being a text property (as a symbol) and a function to apply to
  7035. the value of the drawer property."
  7036. (let* ((case-fold-search t)
  7037. (inhibit-read-only t)
  7038. (inherit? (org-property-inherit-p dprop))
  7039. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7040. (global-or-keyword (and inherit?
  7041. (org--property-global-or-keyword-value dprop nil))))
  7042. (with-silent-modifications
  7043. (org-with-point-at 1
  7044. ;; Set global and keyword based values to the whole buffer.
  7045. (when global-or-keyword
  7046. (put-text-property (point-min) (point-max) tprop global-or-keyword))
  7047. ;; Set values based on property-drawers throughout the document.
  7048. (while (re-search-forward property-re nil t)
  7049. (when (org-at-property-p)
  7050. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7051. (outline-next-heading))))))
  7052. (defun org-refresh-property (tprop p &optional inherit)
  7053. "Refresh the buffer text property TPROP from the drawer property P.
  7054. The refresh happens only for the current entry, or the whole
  7055. sub-tree if optional argument INHERIT is non-nil.
  7056. If point is before first headline, the function applies to the
  7057. part before the first headline. In that particular case, when
  7058. optional argument INHERIT is non-nil, it refreshes properties for
  7059. the whole buffer."
  7060. (save-excursion
  7061. (org-back-to-heading-or-point-min t)
  7062. (let ((start (point))
  7063. (end (save-excursion
  7064. (cond ((and inherit (org-before-first-heading-p))
  7065. (point-max))
  7066. (inherit
  7067. (org-end-of-subtree t t))
  7068. ((outline-next-heading))
  7069. ((point-max))))))
  7070. (with-silent-modifications
  7071. (if (symbolp tprop)
  7072. ;; TPROP is a text property symbol.
  7073. (put-text-property start end tprop p)
  7074. ;; TPROP is an alist with (property . function) elements.
  7075. (pcase-dolist (`(,prop . ,f) tprop)
  7076. (put-text-property start end prop (funcall f p))))))))
  7077. (defun org-refresh-category-properties ()
  7078. "Refresh category text properties in the buffer."
  7079. (unless (org-element--cache-active-p)
  7080. (let ((case-fold-search t)
  7081. (inhibit-read-only t)
  7082. (default-category
  7083. (cond ((null org-category)
  7084. (if buffer-file-name
  7085. (file-name-sans-extension
  7086. (file-name-nondirectory buffer-file-name))
  7087. "???"))
  7088. ((symbolp org-category) (symbol-name org-category))
  7089. (t org-category))))
  7090. (let ((category (catch 'buffer-category
  7091. (org-with-wide-buffer
  7092. (goto-char (point-max))
  7093. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7094. (let ((element (org-element-at-point-no-context)))
  7095. (when (eq (org-element-type element) 'keyword)
  7096. (throw 'buffer-category
  7097. (org-element-property :value element))))))
  7098. default-category)))
  7099. (with-silent-modifications
  7100. (org-with-wide-buffer
  7101. ;; Set buffer-wide property from keyword. Search last #+CATEGORY
  7102. ;; keyword. If none is found, fall-back to `org-category' or
  7103. ;; buffer file name, or set it by the document property drawer.
  7104. (put-text-property (point-min) (point-max)
  7105. 'org-category category)
  7106. ;; Set categories from the document property drawer or
  7107. ;; property drawers in the outline. If category is found in
  7108. ;; the property drawer for the whole buffer that value
  7109. ;; overrides the keyword-based value set above.
  7110. (goto-char (point-min))
  7111. (let ((regexp (org-re-property "CATEGORY")))
  7112. (while (re-search-forward regexp nil t)
  7113. (let ((value (match-string-no-properties 3)))
  7114. (when (org-at-property-p)
  7115. (put-text-property
  7116. (save-excursion (org-back-to-heading-or-point-min t))
  7117. (save-excursion (if (org-before-first-heading-p)
  7118. (point-max)
  7119. (org-end-of-subtree t t)))
  7120. 'org-category
  7121. value)))))))))))
  7122. (defun org-refresh-stats-properties ()
  7123. "Refresh stats text properties in the buffer."
  7124. (with-silent-modifications
  7125. (org-with-point-at 1
  7126. (let ((regexp (concat org-outline-regexp-bol
  7127. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7128. (while (re-search-forward regexp nil t)
  7129. (let* ((numerator (string-to-number (match-string 1)))
  7130. (denominator (and (match-end 2)
  7131. (string-to-number (match-string 2))))
  7132. (stats (cond ((not denominator) numerator) ;percent
  7133. ((= denominator 0) 0)
  7134. (t (/ (* numerator 100) denominator)))))
  7135. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7136. 'org-stats stats)))))))
  7137. (defun org-refresh-effort-properties ()
  7138. "Refresh effort properties."
  7139. (org-refresh-properties
  7140. org-effort-property
  7141. '((effort . identity)
  7142. (effort-minutes . org-duration-to-minutes))))
  7143. (defun org-find-file-at-mouse (ev)
  7144. "Open file link or URL at mouse."
  7145. (interactive "e")
  7146. (mouse-set-point ev)
  7147. (org-open-at-point 'in-emacs))
  7148. (defun org-open-at-mouse (ev)
  7149. "Open file link or URL at mouse.
  7150. See the docstring of `org-open-file' for details."
  7151. (interactive "e")
  7152. (mouse-set-point ev)
  7153. (when (eq major-mode 'org-agenda-mode)
  7154. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7155. (org-open-at-point))
  7156. (defvar org-window-config-before-follow-link nil
  7157. "The window configuration before following a link.
  7158. This is saved in case the need arises to restore it.")
  7159. (defun org--file-default-apps ()
  7160. "Return the default applications for this operating system."
  7161. (pcase system-type
  7162. (`darwin org-file-apps-macos)
  7163. (`windows-nt org-file-apps-windowsnt)
  7164. (_ org-file-apps-gnu)))
  7165. (defun org--file-apps-entry-locator-p (entry)
  7166. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7167. It assumes that is the case when the entry uses a regular
  7168. expression which has at least one grouping construct and the
  7169. action is either a Lisp form or a command string containing
  7170. \"%1\", i.e., using at least one subexpression match as
  7171. a parameter."
  7172. (pcase entry
  7173. (`(,selector . ,action)
  7174. (and (stringp selector)
  7175. (> (regexp-opt-depth selector) 0)
  7176. (or (and (stringp action)
  7177. (string-match "%[0-9]" action))
  7178. (functionp action))))
  7179. (_ nil)))
  7180. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7181. "Convert extensions to regular expressions in the cars of LIST.
  7182. Also, weed out any non-string entries, because the return value
  7183. is used only for regexp matching.
  7184. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7185. point to the symbol `emacs', indicating that the file should be
  7186. opened in Emacs."
  7187. (append
  7188. (delq nil
  7189. (mapcar (lambda (x)
  7190. (unless (not (stringp (car x)))
  7191. (if (string-match "\\W" (car x))
  7192. x
  7193. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7194. list))
  7195. (when add-auto-mode
  7196. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7197. (defun org--open-file-format-command
  7198. (mailcap-command file link match-data)
  7199. "Format MAILCAP-COMMAND to launch viewer for the FILE.
  7200. MAILCAP-COMMAND may be an entry from the `org-file-apps' list or viewer
  7201. field from mailcap file loaded to `mailcap-mime-data'. See \"RFC
  7202. 1524. A User Agent Configuration Mechanism For Multimedia Mail Format
  7203. Information\" (URL `https://www.rfc-editor.org/rfc/rfc1524.html') for
  7204. details, man page `mailcap(5)' for brief summary, and Info node
  7205. `(emacs-mime) mailcap' for specific related to Emacs. Only a part of
  7206. mailcap specification is supported.
  7207. The following substitutions are interpolated in the MAILCAP-COMMAND
  7208. string:
  7209. - \"%s\" to FILE name passed through
  7210. `convert-standard-filename', so it must be absolute path.
  7211. - \"%1\" to \"%9\" groups from MATCH-DATA found in the LINK string by
  7212. the regular expression in the key part of the `org-file-apps' entry.
  7213. (performed by caller). Not recommended, consider a lisp function
  7214. instead of a shell command. For example, the following link in an
  7215. Org file
  7216. <file:///usr/share/doc/bash/bashref.pdf::#Redirections::allocate a file>
  7217. may be handled by an `org-file-apps' entry like
  7218. (\"\\\\.pdf\\\\(?:\\\\.[gx]z\\\\|\\\\.bz2\\\\)?::\\\\(#[^:]+\\\\)::\\\\(.+\\\\)\\\\\\='\"
  7219. . \"okular --find %2 %s%1\")
  7220. Use backslash \"\\\" to quote percent \"%\" or any other character
  7221. including backslash itself.
  7222. In addition, each argument is passed through `shell-quote-argument',
  7223. so quotes around substitutions should not be used. For compliance
  7224. with mailcap files shipped e.g. in Debian GNU/Linux, single or double
  7225. quotes around substitutions are stripped. It deviates from mailcap
  7226. specification that requires file name to be safe for shell and for the
  7227. application."
  7228. (let ((spec (list (cons ?s (convert-standard-filename file))))
  7229. (ngroups (min 9 (- (/ (length match-data) 2) 1))))
  7230. (when (> ngroups 0)
  7231. (set-match-data match-data)
  7232. (dolist (i (number-sequence 1 ngroups))
  7233. (push (cons (+ ?0 i) (match-string-no-properties i link)) spec)))
  7234. (replace-regexp-in-string
  7235. (rx (or (and "\\" (or (group anything) string-end))
  7236. (and (optional (group (any "'\"")))
  7237. "%"
  7238. (or (group anything) string-end)
  7239. (optional (group (backref 2))))))
  7240. (lambda (fmt)
  7241. (let* ((backslash (match-string-no-properties 1 fmt))
  7242. (key (match-string 3 fmt))
  7243. (value (and key (alist-get (string-to-char key) spec))))
  7244. (cond
  7245. (backslash)
  7246. (value (let ((quot (match-string 2 fmt))
  7247. (subst (shell-quote-argument value)))
  7248. ;; Remove quotes around the file name - we use
  7249. ;; `shell-quote-argument'.
  7250. (if (match-string 4 fmt)
  7251. subst
  7252. (concat quot subst))))
  7253. (t (error "Invalid format `%s'" fmt)))))
  7254. mailcap-command nil 'literal)))
  7255. ;;;###autoload
  7256. (defun org-open-file (path &optional in-emacs line search)
  7257. "Open the file at PATH.
  7258. First, this expands any special file name abbreviations. Then the
  7259. configuration variable `org-file-apps' is checked if it contains an
  7260. entry for this file type, and if yes, the corresponding command is launched.
  7261. If no application is found, Emacs simply visits the file.
  7262. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7263. With a double \\[universal-argument] \\[universal-argument] \
  7264. prefix arg, Org tries to avoid opening in Emacs
  7265. and to use an external application to visit the file.
  7266. Optional LINE specifies a line to go to, optional SEARCH a string
  7267. to search for. If LINE or SEARCH is given, the file will be
  7268. opened in Emacs, unless an entry from `org-file-apps' that makes
  7269. use of groups in a regexp matches.
  7270. If you want to change the way frames are used when following a
  7271. link, please customize `org-link-frame-setup'.
  7272. If the file does not exist, throw an error."
  7273. (let* ((file (if (equal path "") buffer-file-name
  7274. (substitute-in-file-name (expand-file-name path))))
  7275. (file-apps (append org-file-apps (org--file-default-apps)))
  7276. (apps (cl-remove-if #'org--file-apps-entry-locator-p file-apps))
  7277. (apps-locator (cl-remove-if-not #'org--file-apps-entry-locator-p
  7278. file-apps))
  7279. (remp (and (assq 'remote apps) (file-remote-p file)))
  7280. (dirp (unless remp (file-directory-p file)))
  7281. (file (if (and dirp org-open-directory-means-index-dot-org)
  7282. (concat (file-name-as-directory file) "index.org")
  7283. file))
  7284. (a-m-a-p (assq 'auto-mode apps))
  7285. (dfile (downcase file))
  7286. ;; Reconstruct the original link from the PATH, LINE and
  7287. ;; SEARCH args.
  7288. (link (cond (line (concat file "::" (number-to-string line)))
  7289. (search (concat file "::" search))
  7290. (t file)))
  7291. (ext
  7292. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7293. (match-string 1 dfile)))
  7294. (save-position-maybe
  7295. (let ((old-buffer (current-buffer))
  7296. (old-pos (point))
  7297. (old-mode major-mode))
  7298. (lambda ()
  7299. (and (derived-mode-p 'org-mode)
  7300. (eq old-mode 'org-mode)
  7301. (or (not (eq old-buffer (current-buffer)))
  7302. (not (eq old-pos (point))))
  7303. (org-mark-ring-push old-pos old-buffer)))))
  7304. cmd link-match-data)
  7305. (cond
  7306. ((member in-emacs '((16) system))
  7307. (setq cmd (cdr (assq 'system apps))))
  7308. (in-emacs (setq cmd 'emacs))
  7309. (t
  7310. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7311. (and dirp (cdr (assq 'directory apps)))
  7312. ;; First, try matching against apps-locator if we
  7313. ;; get a match here, store the match data for
  7314. ;; later.
  7315. (let* ((case-fold-search t)
  7316. (match (assoc-default link apps-locator
  7317. 'string-match)))
  7318. (if match
  7319. (progn (setq link-match-data (match-data))
  7320. match)
  7321. (progn (setq in-emacs (or in-emacs line search))
  7322. nil))) ; if we have no match in apps-locator,
  7323. ; always open the file in emacs if line or search
  7324. ; is given (for backwards compatibility)
  7325. (assoc-default dfile
  7326. (org--file-apps-regexp-alist apps a-m-a-p)
  7327. 'string-match)
  7328. (cdr (assoc ext apps))
  7329. (cdr (assq t apps))))))
  7330. (when (eq cmd 'system)
  7331. (setq cmd (cdr (assq 'system apps))))
  7332. (when (eq cmd 'default)
  7333. (setq cmd (cdr (assoc t apps))))
  7334. (when (eq cmd 'mailcap)
  7335. (require 'mailcap)
  7336. (mailcap-parse-mailcaps)
  7337. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7338. (command (mailcap-mime-info mime-type)))
  7339. (if (stringp command)
  7340. (setq cmd command)
  7341. (setq cmd 'emacs))))
  7342. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7343. (not (file-exists-p file))
  7344. (not org-open-non-existing-files))
  7345. (user-error "No such file: %s" file))
  7346. (cond
  7347. ((org-string-nw-p cmd)
  7348. (setq cmd (org--open-file-format-command cmd file link link-match-data))
  7349. (save-window-excursion
  7350. (message "Running %s...done" cmd)
  7351. ;; Handlers such as "gio open" and kde-open5 start viewer in background
  7352. ;; and exit immediately. Use pipe connection type instead of pty to
  7353. ;; avoid killing children processes with SIGHUP when temporary terminal
  7354. ;; session is finished.
  7355. ;;
  7356. ;; TODO: Once minimum Emacs version is 25.1 or above, consider using
  7357. ;; the `make-process' invocation from 5db61eb0f929 to get more helpful
  7358. ;; error messages.
  7359. (let ((process-connection-type nil))
  7360. (start-process-shell-command cmd nil cmd))
  7361. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7362. ((or (stringp cmd)
  7363. (eq cmd 'emacs))
  7364. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7365. (widen)
  7366. (cond (line (org-goto-line line)
  7367. (when (derived-mode-p 'org-mode) (org-fold-reveal)))
  7368. (search (condition-case err
  7369. (org-link-search search)
  7370. ;; Save position before error-ing out so user
  7371. ;; can easily move back to the original buffer.
  7372. (error (funcall save-position-maybe)
  7373. (error (nth 1 err)))))))
  7374. ((functionp cmd)
  7375. (save-match-data
  7376. (set-match-data link-match-data)
  7377. (condition-case nil
  7378. (funcall cmd file link)
  7379. ;; FIXME: Remove this check when most default installations
  7380. ;; of Emacs have at least Org 9.0.
  7381. ((debug wrong-number-of-arguments wrong-type-argument
  7382. invalid-function)
  7383. (user-error "Please see Org News for version 9.0 about \
  7384. `org-file-apps'--Lisp error: %S" cmd)))))
  7385. ((consp cmd)
  7386. ;; FIXME: Remove this check when most default installations of
  7387. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7388. ;; fall back to `org-link-frame-setup' for an old usage of
  7389. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7390. (user-error "Please see Org News for version 9.0 about \
  7391. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7392. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7393. (funcall save-position-maybe)))
  7394. ;;;###autoload
  7395. (defun org-open-at-point-global ()
  7396. "Follow a link or a time-stamp like Org mode does.
  7397. Also follow links and emails as seen by `thing-at-point'.
  7398. This command can be called in any mode to follow an external
  7399. link or a time-stamp that has Org mode syntax. Its behavior
  7400. is undefined when called on internal links like fuzzy links.
  7401. Raise a user error when there is nothing to follow."
  7402. (interactive)
  7403. (let ((tap-url (thing-at-point 'url))
  7404. (tap-email (thing-at-point 'email)))
  7405. (cond ((org-in-regexp org-link-any-re)
  7406. (org-link-open-from-string (match-string-no-properties 0)))
  7407. ((or (org-in-regexp org-ts-regexp-both nil t)
  7408. (org-in-regexp org-tsr-regexp-both nil t))
  7409. (org-follow-timestamp-link))
  7410. (tap-url (org-link-open-from-string tap-url))
  7411. (tap-email (org-link-open-from-string
  7412. (concat "mailto:" tap-email)))
  7413. (t (user-error "No link found")))))
  7414. (defvar org-open-at-point-functions nil
  7415. "Hook that is run when following a link at point.
  7416. Functions in this hook must return t if they identify and follow
  7417. a link at point. If they don't find anything interesting at point,
  7418. they must return nil.")
  7419. (defun org-open-at-point (&optional arg)
  7420. "Open thing at point.
  7421. The thing can be a link, citation, timestamp, footnote, src-block or
  7422. tags.
  7423. When point is on a link, follow it. Normally, files will be
  7424. opened by an appropriate application. If the optional prefix
  7425. argument ARG is non-nil, Emacs will visit the file. With
  7426. a double prefix argument, try to open outside of Emacs, in the
  7427. application the system uses for this file type.
  7428. When point is on a timestamp, open the agenda at the day
  7429. specified.
  7430. When point is a footnote definition, move to the first reference
  7431. found. If it is on a reference, move to the associated
  7432. definition.
  7433. When point is on a src-block of inline src-block, open its result.
  7434. When point is on a citation, follow it.
  7435. When point is on a headline, display a list of every link in the
  7436. entry, so it is possible to pick one, or all, of them. If point
  7437. is on a tag, call `org-tags-view' instead.
  7438. On top of syntactically correct links, this function also tries
  7439. to open links and time-stamps in comments, node properties, and
  7440. keywords if point is on something looking like a timestamp or
  7441. a link."
  7442. (interactive "P")
  7443. (org-load-modules-maybe)
  7444. (setq org-window-config-before-follow-link (current-window-configuration))
  7445. (org-remove-occur-highlights nil nil t)
  7446. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  7447. (let* ((context
  7448. ;; Only consider supported types, even if they are not the
  7449. ;; closest one.
  7450. (org-element-lineage
  7451. (org-element-context)
  7452. '(citation citation-reference clock comment comment-block
  7453. footnote-definition footnote-reference headline
  7454. inline-src-block inlinetask keyword link node-property
  7455. planning src-block timestamp)
  7456. t))
  7457. (type (org-element-type context))
  7458. (value (org-element-property :value context)))
  7459. (cond
  7460. ((not type) (user-error "No link found"))
  7461. ;; No valid link at point. For convenience, look if something
  7462. ;; looks like a link under point in some specific places.
  7463. ((memq type '(comment comment-block node-property keyword))
  7464. (call-interactively #'org-open-at-point-global))
  7465. ;; On a headline or an inlinetask, but not on a timestamp,
  7466. ;; a link, a footnote reference or a citation.
  7467. ((memq type '(headline inlinetask))
  7468. (org-match-line org-complex-heading-regexp)
  7469. (let ((tags-beg (match-beginning 5))
  7470. (tags-end (match-end 5)))
  7471. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  7472. ;; On tags.
  7473. (org-tags-view
  7474. arg
  7475. (save-excursion
  7476. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  7477. (end-tag (search-forward ":" tags-end nil 2)))
  7478. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  7479. ;; Not on tags.
  7480. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  7481. (`(nil . ,_)
  7482. (require 'org-attach)
  7483. (when (org-attach-dir)
  7484. (message "Opening attachment")
  7485. (if (equal arg '(4))
  7486. (org-attach-reveal-in-emacs)
  7487. (org-attach-reveal))))
  7488. (`(,links . ,links-end)
  7489. (dolist (link (if (stringp links) (list links) links))
  7490. (search-forward link nil links-end)
  7491. (goto-char (match-beginning 0))
  7492. (org-open-at-point arg)))))))
  7493. ;; On a footnote reference or at definition's label.
  7494. ((or (eq type 'footnote-reference)
  7495. (and (eq type 'footnote-definition)
  7496. (save-excursion
  7497. ;; Do not validate action when point is on the
  7498. ;; spaces right after the footnote label, in order
  7499. ;; to be on par with behavior on links.
  7500. (skip-chars-forward " \t")
  7501. (let ((begin
  7502. (org-element-property :contents-begin context)))
  7503. (if begin (< (point) begin)
  7504. (= (org-element-property :post-affiliated context)
  7505. (line-beginning-position)))))))
  7506. (org-footnote-action))
  7507. ;; On a planning line. Check if we are really on a timestamp.
  7508. ((and (eq type 'planning)
  7509. (org-in-regexp org-ts-regexp-both nil t))
  7510. (org-follow-timestamp-link))
  7511. ;; On a clock line, make sure point is on the timestamp
  7512. ;; before opening it.
  7513. ((and (eq type 'clock)
  7514. value
  7515. (>= (point) (org-element-property :begin value))
  7516. (<= (point) (org-element-property :end value)))
  7517. (org-follow-timestamp-link))
  7518. ((eq type 'src-block) (org-babel-open-src-block-result))
  7519. ;; Do nothing on white spaces after an object.
  7520. ((>= (point)
  7521. (save-excursion
  7522. (goto-char (org-element-property :end context))
  7523. (skip-chars-backward " \t")
  7524. (point)))
  7525. (user-error "No link found"))
  7526. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  7527. ((eq type 'timestamp) (org-follow-timestamp-link))
  7528. ((eq type 'link) (org-link-open context arg))
  7529. ((memq type '(citation citation-reference)) (org-cite-follow context arg))
  7530. (t (user-error "No link found")))))
  7531. (run-hook-with-args 'org-follow-link-hook))
  7532. ;;;###autoload
  7533. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  7534. "Offer links in the current entry and return the selected link.
  7535. If there is only one link, return it.
  7536. If NTH is an integer, return the NTH link found.
  7537. If ZERO is a string, check also this string for a link, and if
  7538. there is one, return it."
  7539. (with-current-buffer buffer
  7540. (org-with-wide-buffer
  7541. (goto-char marker)
  7542. (let ((cnt ?0)
  7543. have-zero end links link c)
  7544. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  7545. (push (match-string 0 zero) links)
  7546. (setq cnt (1- cnt) have-zero t))
  7547. (save-excursion
  7548. (org-back-to-heading t)
  7549. (setq end (save-excursion (outline-next-heading) (point)))
  7550. (while (re-search-forward org-link-any-re end t)
  7551. ;; Only consider valid links or links openable via
  7552. ;; `org-open-at-point'.
  7553. (when (memq (org-element-type (org-element-context)) '(link comment comment-block node-property keyword))
  7554. (push (match-string 0) links)))
  7555. (setq links (org-uniquify (reverse links))))
  7556. (cond
  7557. ((null links)
  7558. (message "No links"))
  7559. ((equal (length links) 1)
  7560. (setq link (car links)))
  7561. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  7562. (setq link (nth (if have-zero nth (1- nth)) links)))
  7563. (t ; we have to select a link
  7564. (save-excursion
  7565. (save-window-excursion
  7566. (delete-other-windows)
  7567. (with-output-to-temp-buffer "*Select Link*"
  7568. (dolist (l links)
  7569. (cond
  7570. ((not (string-match org-link-bracket-re l))
  7571. (princ (format "[%c] %s\n" (cl-incf cnt)
  7572. (org-unbracket-string "<" ">" l))))
  7573. ((match-end 2)
  7574. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  7575. (match-string 2 l) (match-string 1 l))))
  7576. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  7577. (match-string 1 l)))))))
  7578. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  7579. (message "Select link to open, RET to open all:")
  7580. (setq c (read-char-exclusive))
  7581. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  7582. (when (equal c ?q) (user-error "Abort"))
  7583. (if (equal c ?\C-m)
  7584. (setq link links)
  7585. (setq nth (- c ?0))
  7586. (when have-zero (setq nth (1+ nth)))
  7587. (unless (and (integerp nth) (>= (length links) nth))
  7588. (user-error "Invalid link selection"))
  7589. (setq link (nth (1- nth) links)))))
  7590. (cons link end)))))
  7591. ;;; File search
  7592. (defun org-do-occur (regexp &optional cleanup)
  7593. "Call the Emacs command `occur'.
  7594. If CLEANUP is non-nil, remove the printout of the regular expression
  7595. in the *Occur* buffer. This is useful if the regex is long and not useful
  7596. to read."
  7597. (occur regexp)
  7598. (when cleanup
  7599. (let ((cwin (selected-window)) win beg end)
  7600. (when (setq win (get-buffer-window "*Occur*"))
  7601. (select-window win))
  7602. (goto-char (point-min))
  7603. (when (re-search-forward "match[a-z]+" nil t)
  7604. (setq beg (match-end 0))
  7605. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  7606. (setq end (1- (match-beginning 0)))))
  7607. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  7608. (goto-char (point-min))
  7609. (select-window cwin))))
  7610. ;;; The Mark Ring
  7611. (defvar org-mark-ring nil
  7612. "Mark ring for positions before jumps in Org mode.")
  7613. (defvar org-mark-ring-last-goto nil
  7614. "Last position in the mark ring used to go back.")
  7615. ;; Fill and close the ring
  7616. (setq org-mark-ring nil)
  7617. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  7618. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  7619. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  7620. org-mark-ring)
  7621. (defun org-mark-ring-push (&optional pos buffer)
  7622. "Put the current position into the mark ring and rotate it.
  7623. Also push position into the Emacs mark ring. If optional
  7624. argument POS and BUFFER are not nil, mark this location instead."
  7625. (interactive)
  7626. (let ((pos (or pos (point)))
  7627. (buffer (or buffer (current-buffer))))
  7628. (with-current-buffer buffer
  7629. (org-with-point-at pos (push-mark nil t)))
  7630. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  7631. (move-marker (car org-mark-ring) pos buffer))
  7632. (message
  7633. (substitute-command-keys
  7634. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  7635. (defun org-mark-ring-goto (&optional n)
  7636. "Jump to the previous position in the mark ring.
  7637. With prefix arg N, jump back that many stored positions. When
  7638. called several times in succession, walk through the entire ring.
  7639. Org mode commands jumping to a different position in the current file,
  7640. or to another Org file, automatically push the old position onto the ring."
  7641. (interactive "p")
  7642. (let (p m)
  7643. (if (eq last-command this-command)
  7644. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  7645. (setq p org-mark-ring))
  7646. (setq org-mark-ring-last-goto p)
  7647. (setq m (car p))
  7648. (pop-to-buffer-same-window (marker-buffer m))
  7649. (goto-char m)
  7650. (when (or (org-invisible-p) (org-invisible-p2)) (org-fold-show-context 'mark-goto))))
  7651. ;;; Following specific links
  7652. (defvar org-agenda-buffer-tmp-name)
  7653. (defvar org-agenda-start-on-weekday)
  7654. (defvar org-agenda-buffer-name)
  7655. (defun org-follow-timestamp-link ()
  7656. "Open an agenda view for the time-stamp date/range at point."
  7657. ;; Avoid changing the global value.
  7658. (let ((org-agenda-buffer-name org-agenda-buffer-name))
  7659. (cond
  7660. ((org-at-date-range-p t)
  7661. (let ((org-agenda-start-on-weekday)
  7662. (t1 (match-string 1))
  7663. (t2 (match-string 2)) tt1 tt2)
  7664. (setq tt1 (time-to-days (org-time-string-to-time t1))
  7665. tt2 (time-to-days (org-time-string-to-time t2)))
  7666. (let ((org-agenda-buffer-tmp-name
  7667. (format "*Org Agenda(a:%s)"
  7668. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  7669. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  7670. ((org-at-timestamp-p 'lax)
  7671. (let ((org-agenda-buffer-tmp-name
  7672. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  7673. (org-agenda-list nil (time-to-days (org-time-string-to-time
  7674. (substring (match-string 1) 0 10)))
  7675. 1)))
  7676. (t (error "This should not happen")))))
  7677. ;;; Following file links
  7678. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  7679. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  7680. (declare-function mailcap-mime-info
  7681. "mailcap" (string &optional request no-decode))
  7682. (defvar org-wait nil)
  7683. ;;;; Refiling
  7684. (defun org-get-org-file ()
  7685. "Read a filename, with default directory `org-directory'."
  7686. (let ((default (or org-default-notes-file remember-data-file)))
  7687. (read-file-name (format "File name [%s]: " default)
  7688. (file-name-as-directory org-directory)
  7689. default)))
  7690. (defun org-notes-order-reversed-p ()
  7691. "Check if the current file should receive notes in reversed order."
  7692. (cond
  7693. ((not org-reverse-note-order) nil)
  7694. ((eq t org-reverse-note-order) t)
  7695. ((not (listp org-reverse-note-order)) nil)
  7696. (t (catch 'exit
  7697. (dolist (entry org-reverse-note-order)
  7698. (when (string-match (car entry) buffer-file-name)
  7699. (throw 'exit (cdr entry))))))))
  7700. (defvar org-agenda-new-buffers nil
  7701. "Buffers created to visit agenda files.")
  7702. (declare-function org-string-nw-p "org-macs" (s))
  7703. ;;;; Dynamic blocks
  7704. (defun org-find-dblock (name)
  7705. "Find the first dynamic block with name NAME in the buffer.
  7706. If not found, stay at current position and return nil."
  7707. (let ((case-fold-search t) pos)
  7708. (save-excursion
  7709. (goto-char (point-min))
  7710. (setq pos (and (re-search-forward
  7711. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  7712. (match-beginning 0))))
  7713. (when pos (goto-char pos))
  7714. pos))
  7715. (defun org-create-dblock (plist)
  7716. "Create a dynamic block section, with parameters taken from PLIST.
  7717. PLIST must contain a :name entry which is used as the name of the block."
  7718. (when (string-match "\\S-" (buffer-substring (line-beginning-position) (line-end-position)))
  7719. (end-of-line 1)
  7720. (newline))
  7721. (let ((col (current-column))
  7722. (name (plist-get plist :name)))
  7723. (insert "#+BEGIN: " name)
  7724. (while plist
  7725. (if (eq (car plist) :name)
  7726. (setq plist (cddr plist))
  7727. (insert " " (prin1-to-string (pop plist)))))
  7728. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  7729. (beginning-of-line -2)))
  7730. (defun org-prepare-dblock ()
  7731. "Prepare dynamic block for refresh.
  7732. This empties the block, puts the cursor at the insert position and returns
  7733. the property list including an extra property :name with the block name."
  7734. (unless (looking-at org-dblock-start-re)
  7735. (user-error "Not at a dynamic block"))
  7736. (let* ((begdel (1+ (match-end 0)))
  7737. (name (org-no-properties (match-string 1)))
  7738. (params (append (list :name name)
  7739. (read (concat "(" (match-string 3) ")")))))
  7740. (save-excursion
  7741. (beginning-of-line 1)
  7742. (skip-chars-forward " \t")
  7743. (setq params (plist-put params :indentation-column (current-column))))
  7744. (unless (re-search-forward org-dblock-end-re nil t)
  7745. (error "Dynamic block not terminated"))
  7746. (setq params
  7747. (append params
  7748. (list :content (buffer-substring
  7749. begdel (match-beginning 0)))))
  7750. (delete-region begdel (match-beginning 0))
  7751. (goto-char begdel)
  7752. (open-line 1)
  7753. params))
  7754. (defun org-map-dblocks (&optional command)
  7755. "Apply COMMAND to all dynamic blocks in the current buffer.
  7756. If COMMAND is not given, use `org-update-dblock'."
  7757. (let ((cmd (or command 'org-update-dblock)))
  7758. (save-excursion
  7759. (goto-char (point-min))
  7760. (while (re-search-forward org-dblock-start-re nil t)
  7761. (goto-char (match-beginning 0))
  7762. (save-excursion
  7763. (condition-case nil
  7764. (funcall cmd)
  7765. (error (message "Error during update of dynamic block"))))
  7766. (unless (re-search-forward org-dblock-end-re nil t)
  7767. (error "Dynamic block not terminated"))))))
  7768. (defvar org-dynamic-block-alist nil
  7769. "Alist defining all the Org dynamic blocks.
  7770. The key is the dynamic block type name, as a string. The value
  7771. is the function used to insert the dynamic block.
  7772. Use `org-dynamic-block-define' to populate it.")
  7773. (defun org-dynamic-block-function (type)
  7774. "Return function associated to a given dynamic block type.
  7775. TYPE is the dynamic block type, as a string."
  7776. (cdr (assoc type org-dynamic-block-alist)))
  7777. (defun org-dynamic-block-types ()
  7778. "List all defined dynamic block types."
  7779. (mapcar #'car org-dynamic-block-alist))
  7780. (defun org-dynamic-block-define (type func)
  7781. "Define dynamic block TYPE with FUNC.
  7782. TYPE is a string. FUNC is the function creating the dynamic
  7783. block of such type."
  7784. (pcase (assoc type org-dynamic-block-alist)
  7785. (`nil (push (cons type func) org-dynamic-block-alist))
  7786. (def (setcdr def func))))
  7787. (defun org-dynamic-block-insert-dblock (type &optional interactive-p)
  7788. "Insert a dynamic block of type TYPE.
  7789. When used interactively, select the dynamic block types among
  7790. defined types, per `org-dynamic-block-define'. If INTERACTIVE-P
  7791. is non-nil, call the dynamic block function interactively."
  7792. (interactive (list (completing-read "Dynamic block: "
  7793. (org-dynamic-block-types))
  7794. t))
  7795. (pcase (org-dynamic-block-function type)
  7796. (`nil (error "No such dynamic block: %S" type))
  7797. ((and f (pred functionp))
  7798. (if interactive-p (call-interactively f) (funcall f)))
  7799. (_ (error "Invalid function for dynamic block %S" type))))
  7800. (defun org-dblock-update (&optional arg)
  7801. "User command for updating dynamic blocks.
  7802. Update the dynamic block at point. With prefix ARG, update all dynamic
  7803. blocks in the buffer."
  7804. (interactive "P")
  7805. (if arg
  7806. (org-update-all-dblocks)
  7807. (or (looking-at org-dblock-start-re)
  7808. (org-beginning-of-dblock))
  7809. (org-update-dblock)))
  7810. (defun org-update-dblock ()
  7811. "Update the dynamic block at point.
  7812. This means to empty the block, parse for parameters and then call
  7813. the correct writing function."
  7814. (interactive)
  7815. (save-excursion
  7816. (let* ((win (selected-window))
  7817. (pos (point))
  7818. (line (org-current-line))
  7819. (params (org-prepare-dblock))
  7820. (name (plist-get params :name))
  7821. (indent (plist-get params :indentation-column))
  7822. (cmd (intern (concat "org-dblock-write:" name))))
  7823. (message "Updating dynamic block `%s' at line %d..." name line)
  7824. (funcall cmd params)
  7825. (message "Updating dynamic block `%s' at line %d...done" name line)
  7826. (goto-char pos)
  7827. (when (and indent (> indent 0))
  7828. (setq indent (make-string indent ?\ ))
  7829. (save-excursion
  7830. (select-window win)
  7831. (org-beginning-of-dblock)
  7832. (forward-line 1)
  7833. (while (not (looking-at org-dblock-end-re))
  7834. (insert indent)
  7835. (beginning-of-line 2))
  7836. (when (looking-at org-dblock-end-re)
  7837. (and (looking-at "[ \t]+")
  7838. (replace-match ""))
  7839. (insert indent)))))))
  7840. (defun org-beginning-of-dblock ()
  7841. "Find the beginning of the dynamic block at point.
  7842. Error if there is no such block at point."
  7843. (let ((pos (point))
  7844. beg)
  7845. (end-of-line 1)
  7846. (if (and (re-search-backward org-dblock-start-re nil t)
  7847. (setq beg (match-beginning 0))
  7848. (re-search-forward org-dblock-end-re nil t)
  7849. (> (match-end 0) pos))
  7850. (goto-char beg)
  7851. (goto-char pos)
  7852. (error "Not in a dynamic block"))))
  7853. (defun org-update-all-dblocks ()
  7854. "Update all dynamic blocks in the buffer.
  7855. This function can be used in a hook."
  7856. (interactive)
  7857. (when (derived-mode-p 'org-mode)
  7858. (org-map-dblocks 'org-update-dblock)))
  7859. ;;;; Completion
  7860. (declare-function org-export-backend-options "ox" (cl-x) t)
  7861. (defun org-get-export-keywords ()
  7862. "Return a list of all currently understood export keywords.
  7863. Export keywords include options, block names, attributes and
  7864. keywords relative to each registered export back-end."
  7865. (let (keywords)
  7866. (dolist (backend
  7867. (bound-and-true-p org-export-registered-backends)
  7868. (delq nil keywords))
  7869. ;; Back-end name (for keywords, like #+LATEX:)
  7870. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  7871. (dolist (option-entry (org-export-backend-options backend))
  7872. ;; Back-end options.
  7873. (push (nth 1 option-entry) keywords)))))
  7874. (defconst org-options-keywords
  7875. '("ARCHIVE:" "AUTHOR:" "BIBLIOGRAPHY:" "BIND:" "CATEGORY:" "CITE_EXPORT:"
  7876. "COLUMNS:" "CREATOR:" "DATE:" "DESCRIPTION:" "DRAWERS:" "EMAIL:"
  7877. "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:" "INDEX:" "KEYWORDS:" "LANGUAGE:"
  7878. "MACRO:" "OPTIONS:" "PROPERTY:" "PRINT_BIBLIOGRAPHY" "PRIORITIES:"
  7879. "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:" "TITLE:" "TODO:"
  7880. "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  7881. (defcustom org-structure-template-alist
  7882. '(("a" . "export ascii")
  7883. ("c" . "center")
  7884. ("C" . "comment")
  7885. ("e" . "example")
  7886. ("E" . "export")
  7887. ("h" . "export html")
  7888. ("l" . "export latex")
  7889. ("q" . "quote")
  7890. ("s" . "src")
  7891. ("v" . "verse"))
  7892. "An alist of keys and block types.
  7893. `org-insert-structure-template' will display a menu with this list of
  7894. templates to choose from. The block type is inserted, with
  7895. \"#+begin_\" and \"#+end_\" added automatically. If the block type
  7896. consists of just uppercase letters, \"#+BEGIN_\" and \"#+END_\" are
  7897. added instead.
  7898. The menu keys are defined by the car of each entry in this alist.
  7899. If two entries have the keys \"a\" and \"aa\" respectively, the
  7900. former will be inserted by typing \"a TAB/RET/SPC\" and the
  7901. latter will be inserted by typing \"aa\". If an entry with the
  7902. key \"aab\" is later added, it can be inserted by typing \"ab\".
  7903. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  7904. block can be inserted by pressing TAB after the string \"<KEY\"."
  7905. :group 'org-edit-structure
  7906. :type '(repeat
  7907. (cons (string :tag "Key")
  7908. (string :tag "Template")))
  7909. :package-version '(Org . "9.2"))
  7910. (defun org--check-org-structure-template-alist (&optional checklist)
  7911. "Check whether `org-structure-template-alist' is set up correctly.
  7912. In particular, check if the Org 9.2 format is used as opposed to
  7913. previous format."
  7914. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  7915. (or (symbol-value checklist)
  7916. org-structure-template-alist))))
  7917. (when elm
  7918. (org-display-warning
  7919. (format "
  7920. Please update the entries of `%s'.
  7921. In Org 9.2 the format was changed from something like
  7922. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  7923. to something like
  7924. (\"s\" . \"src\")
  7925. Please refer to the documentation of `org-structure-template-alist'.
  7926. The following entries must be updated:
  7927. %s"
  7928. (or checklist 'org-structure-template-alist)
  7929. (pp-to-string elm))))))
  7930. (defun org--insert-structure-template-mks ()
  7931. "Present `org-structure-template-alist' with `org-mks'.
  7932. Menus are added if keys require more than one keystroke. Tabs
  7933. are added to single key entries when more than one stroke is
  7934. needed. Keys longer than two characters are reduced to two
  7935. characters."
  7936. (org--check-org-structure-template-alist)
  7937. (let* (case-fold-search
  7938. (templates (append org-structure-template-alist
  7939. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  7940. (keys (mapcar #'car templates))
  7941. (start-letters
  7942. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  7943. ;; Sort each element of `org-structure-template-alist' into
  7944. ;; sublists according to the first letter.
  7945. (superlist
  7946. (mapcar (lambda (letter)
  7947. (list letter
  7948. (cl-remove-if-not
  7949. (apply-partially #'string-match-p (concat "^" letter))
  7950. templates :key #'car)))
  7951. start-letters)))
  7952. (org-mks
  7953. (apply #'append
  7954. ;; Make an `org-mks' table. If only one element is
  7955. ;; present in a sublist, make it part of the top-menu,
  7956. ;; otherwise make a submenu according to the starting
  7957. ;; letter and populate it.
  7958. (mapcar (lambda (sublist)
  7959. (if (eq 1 (length (cadr sublist)))
  7960. (mapcar (lambda (elm)
  7961. (list (substring (car elm) 0 1)
  7962. (cdr elm) ""))
  7963. (cadr sublist))
  7964. ;; Create submenu.
  7965. (let* ((topkey (car sublist))
  7966. (elms (cadr sublist))
  7967. (keys (mapcar #'car elms))
  7968. (long (> (length elms) 3)))
  7969. (append
  7970. (list
  7971. ;; Make a description of the submenu.
  7972. (list topkey
  7973. (concat
  7974. (mapconcat #'cdr
  7975. (cl-subseq elms 0 (if long 3 (length elms)))
  7976. ", ")
  7977. (when long ", ..."))))
  7978. ;; List of entries in submenu.
  7979. (cl-mapcar #'list
  7980. (org--insert-structure-template-unique-keys keys)
  7981. (mapcar #'cdr elms)
  7982. (make-list (length elms) ""))))))
  7983. superlist))
  7984. "Select a key\n============"
  7985. "Key: ")))
  7986. (defun org--insert-structure-template-unique-keys (keys)
  7987. "Make a list of unique, two characters long elements from KEYS.
  7988. Elements of length one have a tab appended. Elements of length
  7989. two are kept as is. Longer elements are truncated to length two.
  7990. If an element cannot be made unique, an error is raised."
  7991. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  7992. menu-keys)
  7993. (dolist (key ordered-keys)
  7994. (let ((potential-key
  7995. (cl-case (length key)
  7996. (1 (concat key "\t"))
  7997. (2 key)
  7998. (otherwise
  7999. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  8000. (mapcar (apply-partially #'concat (substring key 0 1))
  8001. (split-string (substring key 1) "" t)))))))
  8002. (if (or (not potential-key) (assoc potential-key menu-keys))
  8003. (user-error "Could not make unique key for `%s'" key)
  8004. (push (cons potential-key key) menu-keys))))
  8005. (mapcar #'car
  8006. (cl-sort menu-keys #'<
  8007. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8008. (defun org-insert-structure-template (type)
  8009. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8010. Select a block from `org-structure-template-alist' then type
  8011. either RET, TAB or SPC to write the block type. With an active
  8012. region, wrap the region in the block. Otherwise, insert an empty
  8013. block.
  8014. When foo is written as FOO, upcase the #+BEGIN/END as well."
  8015. (interactive
  8016. (list (pcase (org--insert-structure-template-mks)
  8017. (`("\t" . ,_) (read-string "Structure type: "))
  8018. (`(,_ ,choice . ,_) choice))))
  8019. (let* ((case-fold-search t) ; Make sure that matches are case-insensitive.
  8020. (region? (use-region-p))
  8021. (region-start (and region? (region-beginning)))
  8022. (region-end (and region? (copy-marker (region-end))))
  8023. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8024. (verbatim? (string-match-p
  8025. (concat "\\`" (regexp-opt '("example" "export"
  8026. "src" "comment")))
  8027. type))
  8028. (upcase? (string= (car (split-string type))
  8029. (upcase (car (split-string type))))))
  8030. (when region? (goto-char region-start))
  8031. (let ((column (current-indentation)))
  8032. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8033. (beginning-of-line)
  8034. (insert "\n"))
  8035. (save-excursion
  8036. (indent-to column)
  8037. (insert (format "#+%s_%s%s\n" (if upcase? "BEGIN" "begin") type (if extended? " " "")))
  8038. (when region?
  8039. (when verbatim? (org-escape-code-in-region (point) region-end))
  8040. (goto-char region-end)
  8041. ;; Ignore empty lines at the end of the region.
  8042. (skip-chars-backward " \r\t\n")
  8043. (end-of-line))
  8044. (unless (bolp) (insert "\n"))
  8045. (indent-to column)
  8046. (insert (format "#+%s_%s" (if upcase? "END" "end") (car (split-string type))))
  8047. (if (looking-at "[ \t]*$") (replace-match "")
  8048. (insert "\n"))
  8049. (when (and (eobp) (not (bolp))) (insert "\n")))
  8050. (if extended? (end-of-line)
  8051. (forward-line)
  8052. (skip-chars-forward " \t")))))
  8053. ;;;; TODO, DEADLINE, Comments
  8054. (defun org-toggle-comment ()
  8055. "Change the COMMENT state of an entry."
  8056. (interactive)
  8057. (save-excursion
  8058. (org-back-to-heading)
  8059. (let ((case-fold-search nil))
  8060. (looking-at org-complex-heading-regexp))
  8061. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8062. (skip-chars-forward " \t")
  8063. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8064. (if (org-in-commented-heading-p t)
  8065. (delete-region (point)
  8066. (progn (search-forward " " (line-end-position) 'move)
  8067. (skip-chars-forward " \t")
  8068. (point)))
  8069. (insert org-comment-string)
  8070. (unless (eolp) (insert " ")))))
  8071. (defvar org-last-todo-state-is-todo nil
  8072. "This is non-nil when the last TODO state change led to a TODO state.
  8073. If the last change removed the TODO tag or switched to DONE, then
  8074. this is nil.")
  8075. (defvar org-todo-setup-filter-hook nil
  8076. "Hook for functions that pre-filter todo specs.
  8077. Each function takes a todo spec and returns either nil or the spec
  8078. transformed into canonical form." )
  8079. (defvar org-todo-get-default-hook nil
  8080. "Hook for functions that get a default item for todo.
  8081. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  8082. nil or a string to be used for the todo mark." )
  8083. (defvar org-agenda-headline-snapshot-before-repeat)
  8084. (defun org-current-effective-time ()
  8085. "Return current time adjusted for `org-extend-today-until' variable."
  8086. (let* ((ct (org-current-time))
  8087. (dct (decode-time ct))
  8088. (ct1
  8089. (cond
  8090. (org-use-last-clock-out-time-as-effective-time
  8091. (or (org-clock-get-last-clock-out-time) ct))
  8092. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8093. (org-encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8094. (t ct))))
  8095. ct1))
  8096. (defun org-todo-yesterday (&optional arg)
  8097. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  8098. (interactive "P")
  8099. (if (eq major-mode 'org-agenda-mode)
  8100. (org-agenda-todo-yesterday arg)
  8101. (let* ((org-use-effective-time t)
  8102. (hour (nth 2 (decode-time (org-current-time))))
  8103. (org-extend-today-until (1+ hour)))
  8104. (org-todo arg))))
  8105. (defvar org-block-entry-blocking ""
  8106. "First entry preventing the TODO state change.")
  8107. (defun org-cancel-repeater ()
  8108. "Cancel a repeater by setting its numeric value to zero."
  8109. (interactive)
  8110. (save-excursion
  8111. (org-back-to-heading t)
  8112. (let ((bound1 (point))
  8113. (bound0 (save-excursion (outline-next-heading) (point))))
  8114. (when (and (re-search-forward
  8115. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  8116. org-deadline-time-regexp "\\)\\|\\("
  8117. org-ts-regexp "\\)")
  8118. bound0 t)
  8119. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  8120. bound1 t))
  8121. (replace-match "0" t nil nil 1)))))
  8122. (defvar org-state)
  8123. (defvar org-blocked-by-checkboxes)
  8124. (defun org-todo (&optional arg)
  8125. "Change the TODO state of an item.
  8126. The state of an item is given by a keyword at the start of the heading,
  8127. like
  8128. *** TODO Write paper
  8129. *** DONE Call mom
  8130. The different keywords are specified in the variable `org-todo-keywords'.
  8131. By default the available states are \"TODO\" and \"DONE\". So, for this
  8132. example: when the item starts with TODO, it is changed to DONE.
  8133. When it starts with DONE, the DONE is removed. And when neither TODO nor
  8134. DONE are present, add TODO at the beginning of the heading.
  8135. You can set up single-character keys to fast-select the new state. See the
  8136. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  8137. With `\\[universal-argument]' prefix ARG, force logging the state change \
  8138. and take a
  8139. logging note.
  8140. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  8141. next set of TODO \
  8142. keywords (nextset).
  8143. Another way to achieve this is `S-C-<right>'.
  8144. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8145. prefix, circumvent any state blocking.
  8146. With numeric prefix arg, switch to the Nth state.
  8147. With a numeric prefix arg of 0, inhibit note taking for the change.
  8148. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  8149. When called through ELisp, arg is also interpreted in the following way:
  8150. `none' -> empty state
  8151. \"\" -> switch to empty state
  8152. `done' -> switch to DONE
  8153. `nextset' -> switch to the next set of keywords
  8154. `previousset' -> switch to the previous set of keywords
  8155. \"WAITING\" -> switch to the specified keyword, but only if it
  8156. really is a member of `org-todo-keywords'."
  8157. (interactive "P")
  8158. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8159. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8160. 'region-start-level 'region))
  8161. org-loop-over-headlines-in-active-region)
  8162. (org-map-entries
  8163. (lambda () (org-todo arg))
  8164. nil cl
  8165. (when (org-invisible-p) (org-end-of-subtree nil t))))
  8166. (when (equal arg '(16)) (setq arg 'nextset))
  8167. (when (equal (prefix-numeric-value arg) -1) (org-cancel-repeater) (setq arg nil))
  8168. (when (< (prefix-numeric-value arg) -1) (user-error "Prefix argument %d not supported" arg))
  8169. (let ((org-blocker-hook org-blocker-hook)
  8170. commentp
  8171. case-fold-search)
  8172. (when (equal arg '(64))
  8173. (setq arg nil org-blocker-hook nil))
  8174. (when (and org-blocker-hook
  8175. (or org-inhibit-blocking
  8176. (org-entry-get nil "NOBLOCKING")))
  8177. (setq org-blocker-hook nil))
  8178. (save-excursion
  8179. (catch 'exit
  8180. (org-back-to-heading t)
  8181. (when (org-in-commented-heading-p t)
  8182. (org-toggle-comment)
  8183. (setq commentp t))
  8184. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  8185. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  8186. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  8187. (let* ((match-data (match-data))
  8188. (startpos (copy-marker (line-beginning-position)))
  8189. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  8190. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  8191. (org-log-done org-log-done)
  8192. (org-log-repeat org-log-repeat)
  8193. (org-todo-log-states org-todo-log-states)
  8194. (org-inhibit-logging
  8195. (if (equal arg 0)
  8196. (progn (setq arg nil) 'note) org-inhibit-logging))
  8197. (this (match-string 1))
  8198. (hl-pos (match-beginning 0))
  8199. (head (org-get-todo-sequence-head this))
  8200. (ass (assoc head org-todo-kwd-alist))
  8201. (interpret (nth 1 ass))
  8202. (done-word (nth 3 ass))
  8203. (final-done-word (nth 4 ass))
  8204. (org-last-state (or this ""))
  8205. (completion-ignore-case t)
  8206. (member (member this org-todo-keywords-1))
  8207. (tail (cdr member))
  8208. (org-state (cond
  8209. ((eq arg 'right)
  8210. ;; Next state
  8211. (if this
  8212. (if tail (car tail) nil)
  8213. (car org-todo-keywords-1)))
  8214. ((eq arg 'left)
  8215. ;; Previous state
  8216. (unless (equal member org-todo-keywords-1)
  8217. (if this
  8218. (nth (- (length org-todo-keywords-1)
  8219. (length tail) 2)
  8220. org-todo-keywords-1)
  8221. (org-last org-todo-keywords-1))))
  8222. (arg
  8223. ;; User or caller requests a specific state.
  8224. (cond
  8225. ((equal arg "") nil)
  8226. ((eq arg 'none) nil)
  8227. ((eq arg 'done) (or done-word (car org-done-keywords)))
  8228. ((eq arg 'nextset)
  8229. (or (car (cdr (member head org-todo-heads)))
  8230. (car org-todo-heads)))
  8231. ((eq arg 'previousset)
  8232. (let ((org-todo-heads (reverse org-todo-heads)))
  8233. (or (car (cdr (member head org-todo-heads)))
  8234. (car org-todo-heads))))
  8235. ((car (member arg org-todo-keywords-1)))
  8236. ((stringp arg)
  8237. (user-error "State `%s' not valid in this file" arg))
  8238. ((nth (1- (prefix-numeric-value arg))
  8239. org-todo-keywords-1))))
  8240. ((and org-todo-key-trigger org-use-fast-todo-selection)
  8241. ;; Use fast selection.
  8242. (org-fast-todo-selection this))
  8243. ((null member) (or head (car org-todo-keywords-1)))
  8244. ((equal this final-done-word) nil) ;-> make empty
  8245. ((null tail) nil) ;-> first entry
  8246. ((memq interpret '(type priority))
  8247. (if (eq this-command last-command)
  8248. (car tail)
  8249. (if (> (length tail) 0)
  8250. (or done-word (car org-done-keywords))
  8251. nil)))
  8252. (t
  8253. (car tail))))
  8254. (org-state (or
  8255. (run-hook-with-args-until-success
  8256. 'org-todo-get-default-hook org-state org-last-state)
  8257. org-state))
  8258. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  8259. (change-plist (list :type 'todo-state-change :from this :to org-state
  8260. :position startpos))
  8261. dolog now-done-p)
  8262. (when org-blocker-hook
  8263. (let (org-blocked-by-checkboxes block-reason)
  8264. (setq org-last-todo-state-is-todo
  8265. (not (member this org-done-keywords)))
  8266. (unless (save-excursion
  8267. (save-match-data
  8268. (org-with-wide-buffer
  8269. (run-hook-with-args-until-failure
  8270. 'org-blocker-hook change-plist))))
  8271. (setq block-reason (if org-blocked-by-checkboxes
  8272. "contained checkboxes"
  8273. (format "\"%s\"" org-block-entry-blocking)))
  8274. (if (called-interactively-p 'interactive)
  8275. (user-error "TODO state change from %s to %s blocked (by %s)"
  8276. this org-state block-reason)
  8277. ;; Fail silently.
  8278. (message "TODO state change from %s to %s blocked (by %s)"
  8279. this org-state block-reason)
  8280. (throw 'exit nil)))))
  8281. (store-match-data match-data)
  8282. (org-fold-core-ignore-modifications
  8283. (goto-char (match-beginning 0))
  8284. (replace-match "")
  8285. ;; We need to use `insert-before-markers-and-inherit'
  8286. ;; because: (1) We want to preserve the folding state
  8287. ;; text properties; (2) We do not want to make point
  8288. ;; move before new todo state when inserting a new todo
  8289. ;; into an empty heading. In (2), the above
  8290. ;; `save-excursion' is relying on markers saved before.
  8291. (insert-before-markers-and-inherit next)
  8292. (unless (org-invisible-p (line-beginning-position))
  8293. (org-fold-region (line-beginning-position)
  8294. (line-end-position)
  8295. nil)))
  8296. (cond ((and org-state (equal this org-state))
  8297. (message "TODO state was already %s" (org-trim next)))
  8298. ((not (pos-visible-in-window-p hl-pos))
  8299. (message "TODO state changed to %s" (org-trim next))))
  8300. (unless head
  8301. (setq head (org-get-todo-sequence-head org-state)
  8302. ass (assoc head org-todo-kwd-alist)
  8303. interpret (nth 1 ass)
  8304. done-word (nth 3 ass)
  8305. final-done-word (nth 4 ass)))
  8306. (when (memq arg '(nextset previousset))
  8307. (message "Keyword-Set %d/%d: %s"
  8308. (- (length org-todo-sets) -1
  8309. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  8310. (length org-todo-sets)
  8311. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  8312. (setq org-last-todo-state-is-todo
  8313. (not (member org-state org-done-keywords)))
  8314. (setq now-done-p (and (member org-state org-done-keywords)
  8315. (not (member this org-done-keywords))))
  8316. (and logging (org-local-logging logging))
  8317. (when (or (and (or org-todo-log-states org-log-done)
  8318. (not (eq org-inhibit-logging t))
  8319. (not (memq arg '(nextset previousset))))
  8320. force-log)
  8321. ;; We need to look at recording a time and note.
  8322. (setq dolog (or (if force-log 'note)
  8323. (nth 1 (assoc org-state org-todo-log-states))
  8324. (nth 2 (assoc this org-todo-log-states))))
  8325. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  8326. (setq dolog 'time))
  8327. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  8328. (and org-state
  8329. (member org-state org-not-done-keywords)
  8330. (not (member this org-not-done-keywords))))
  8331. ;; This is now a todo state and was not one before
  8332. ;; If there was a CLOSED time stamp, get rid of it.
  8333. (org-add-planning-info nil nil 'closed))
  8334. (when (and now-done-p org-log-done)
  8335. ;; It is now done, and it was not done before.
  8336. (org-add-planning-info 'closed (org-current-effective-time))
  8337. (when (and (not dolog) (eq 'note org-log-done))
  8338. (org-add-log-setup 'done org-state this 'note)))
  8339. (when (and org-state dolog)
  8340. ;; This is a non-nil state, and we need to log it.
  8341. (org-add-log-setup 'state org-state this dolog)))
  8342. ;; Fixup tag positioning.
  8343. (org-todo-trigger-tag-changes org-state)
  8344. (when org-auto-align-tags (org-align-tags))
  8345. (when org-provide-todo-statistics
  8346. (org-update-parent-todo-statistics))
  8347. (when (bound-and-true-p org-clock-out-when-done)
  8348. (org-clock-out-if-current))
  8349. (run-hooks 'org-after-todo-state-change-hook)
  8350. (when (and arg (not (member org-state org-done-keywords)))
  8351. (setq head (org-get-todo-sequence-head org-state)))
  8352. (put-text-property (line-beginning-position) (line-end-position) 'org-todo-head head)
  8353. ;; Do we need to trigger a repeat?
  8354. (when now-done-p
  8355. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  8356. ;; This is for the agenda, take a snapshot of the headline.
  8357. (save-match-data
  8358. (setq org-agenda-headline-snapshot-before-repeat
  8359. (org-get-heading))))
  8360. (org-auto-repeat-maybe org-state))
  8361. ;; Fixup cursor location if close to the keyword.
  8362. (when (and (outline-on-heading-p)
  8363. (not (bolp))
  8364. (save-excursion (beginning-of-line 1)
  8365. (looking-at org-todo-line-regexp))
  8366. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  8367. (goto-char (or (match-end 2) (match-end 1)))
  8368. (and (looking-at " ")
  8369. (not (looking-at " *:"))
  8370. (just-one-space)))
  8371. (when org-trigger-hook
  8372. (save-excursion
  8373. (run-hook-with-args 'org-trigger-hook change-plist)))
  8374. (when commentp (org-toggle-comment))))))))
  8375. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  8376. "Block turning an entry into a TODO, using the hierarchy.
  8377. This checks whether the current task should be blocked from state
  8378. changes. Such blocking occurs when:
  8379. 1. The task has children which are not all in a completed state.
  8380. 2. A task has a parent with the property :ORDERED:, and there
  8381. are siblings prior to the current task with incomplete
  8382. status.
  8383. 3. The parent of the task is blocked because it has siblings that should
  8384. be done first, or is child of a block grandparent TODO entry."
  8385. (if (not org-enforce-todo-dependencies)
  8386. t ; if locally turned off don't block
  8387. (catch 'dont-block
  8388. ;; If this is not a todo state change, or if this entry is already DONE,
  8389. ;; do not block
  8390. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8391. (member (plist-get change-plist :from)
  8392. (cons 'done org-done-keywords))
  8393. (member (plist-get change-plist :to)
  8394. (cons 'todo org-not-done-keywords))
  8395. (not (plist-get change-plist :to)))
  8396. (throw 'dont-block t))
  8397. ;; If this task has children, and any are undone, it's blocked
  8398. (save-excursion
  8399. (org-back-to-heading t)
  8400. (let ((this-level (funcall outline-level)))
  8401. (outline-next-heading)
  8402. (let ((child-level (funcall outline-level)))
  8403. (while (and (not (eobp))
  8404. (> child-level this-level))
  8405. ;; this todo has children, check whether they are all
  8406. ;; completed
  8407. (when (and (not (org-entry-is-done-p))
  8408. (org-entry-is-todo-p))
  8409. (setq org-block-entry-blocking (org-get-heading))
  8410. (throw 'dont-block nil))
  8411. (outline-next-heading)
  8412. (setq child-level (funcall outline-level))))))
  8413. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  8414. ;; any previous siblings are undone, it's blocked
  8415. (save-excursion
  8416. (org-back-to-heading t)
  8417. (let* ((pos (point))
  8418. (parent-pos (and (org-up-heading-safe) (point)))
  8419. (case-fold-search nil))
  8420. (unless parent-pos (throw 'dont-block t)) ; no parent
  8421. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8422. (forward-line 1)
  8423. (re-search-forward org-not-done-heading-regexp pos t))
  8424. (setq org-block-entry-blocking (match-string 0))
  8425. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  8426. ;; Search further up the hierarchy, to see if an ancestor is blocked
  8427. (while t
  8428. (goto-char parent-pos)
  8429. (unless (looking-at org-not-done-heading-regexp)
  8430. (throw 'dont-block t)) ; do not block, parent is not a TODO
  8431. (setq pos (point))
  8432. (setq parent-pos (and (org-up-heading-safe) (point)))
  8433. (unless parent-pos (throw 'dont-block t)) ; no parent
  8434. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8435. (forward-line 1)
  8436. (re-search-forward org-not-done-heading-regexp pos t)
  8437. (setq org-block-entry-blocking (org-get-heading)))
  8438. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  8439. (defcustom org-track-ordered-property-with-tag nil
  8440. "Should the ORDERED property also be shown as a tag?
  8441. The ORDERED property decides if an entry should require subtasks to be
  8442. completed in sequence. Since a property is not very visible, setting
  8443. this option means that toggling the ORDERED property with the command
  8444. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  8445. not relevant for the behavior, but it makes things more visible.
  8446. Note that toggling the tag with tags commands will not change the property
  8447. and therefore not influence behavior!
  8448. This can be t, meaning the tag ORDERED should be used. It can also be a
  8449. string to select a different tag for this task."
  8450. :group 'org-todo
  8451. :type '(choice
  8452. (const :tag "No tracking" nil)
  8453. (const :tag "Track with ORDERED tag" t)
  8454. (string :tag "Use other tag")))
  8455. (defun org-toggle-ordered-property ()
  8456. "Toggle the ORDERED property of the current entry.
  8457. For better visibility, you can track the value of this property with a tag.
  8458. See variable `org-track-ordered-property-with-tag'."
  8459. (interactive)
  8460. (let* ((t1 org-track-ordered-property-with-tag)
  8461. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  8462. (save-excursion
  8463. (org-back-to-heading)
  8464. (if (org-entry-get nil "ORDERED")
  8465. (progn
  8466. (org-delete-property "ORDERED")
  8467. (and tag (org-toggle-tag tag 'off))
  8468. (message "Subtasks can be completed in arbitrary order"))
  8469. (org-entry-put nil "ORDERED" "t")
  8470. (and tag (org-toggle-tag tag 'on))
  8471. (message "Subtasks must be completed in sequence")))))
  8472. (defun org-block-todo-from-checkboxes (change-plist)
  8473. "Block turning an entry into a TODO, using checkboxes.
  8474. This checks whether the current task should be blocked from state
  8475. changes because there are unchecked boxes in this entry."
  8476. (if (not org-enforce-todo-checkbox-dependencies)
  8477. t ; if locally turned off don't block
  8478. (catch 'dont-block
  8479. ;; If this is not a todo state change, or if this entry is already DONE,
  8480. ;; do not block
  8481. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8482. (member (plist-get change-plist :from)
  8483. (cons 'done org-done-keywords))
  8484. (member (plist-get change-plist :to)
  8485. (cons 'todo org-not-done-keywords))
  8486. (not (plist-get change-plist :to)))
  8487. (throw 'dont-block t))
  8488. ;; If this task has checkboxes that are not checked, it's blocked
  8489. (save-excursion
  8490. (org-back-to-heading t)
  8491. (let ((beg (point)) end)
  8492. (outline-next-heading)
  8493. (setq end (point))
  8494. (goto-char beg)
  8495. (when (org-list-search-forward
  8496. (concat (org-item-beginning-re)
  8497. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  8498. "\\[[- ]\\]")
  8499. end t)
  8500. (when (boundp 'org-blocked-by-checkboxes)
  8501. (setq org-blocked-by-checkboxes t))
  8502. (throw 'dont-block nil))))
  8503. t))) ; do not block
  8504. (defun org-entry-blocked-p ()
  8505. "Non-nil if entry at point is blocked."
  8506. (and (not (org-entry-get nil "NOBLOCKING"))
  8507. (member (org-entry-get nil "TODO") org-not-done-keywords)
  8508. (not (run-hook-with-args-until-failure
  8509. 'org-blocker-hook
  8510. (list :type 'todo-state-change
  8511. :position (point)
  8512. :from 'todo
  8513. :to 'done)))))
  8514. (defun org-update-statistics-cookies (all)
  8515. "Update the statistics cookie, either from TODO or from checkboxes.
  8516. This should be called with the cursor in a line with a statistics
  8517. cookie. When called with a \\[universal-argument] prefix, update
  8518. all statistics cookies in the buffer."
  8519. (interactive "P")
  8520. (if all
  8521. (progn
  8522. (org-update-checkbox-count 'all)
  8523. (org-map-region 'org-update-parent-todo-statistics
  8524. (point-min) (point-max)))
  8525. (if (not (org-at-heading-p))
  8526. (org-update-checkbox-count)
  8527. (let ((pos (point-marker))
  8528. end l1 l2)
  8529. (ignore-errors (org-back-to-heading t))
  8530. (if (not (org-at-heading-p))
  8531. (org-update-checkbox-count)
  8532. (setq l1 (org-outline-level))
  8533. (setq end
  8534. (save-excursion
  8535. (outline-next-heading)
  8536. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  8537. (point)))
  8538. (if (and (save-excursion
  8539. (re-search-forward
  8540. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  8541. (not (save-excursion
  8542. (re-search-forward
  8543. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  8544. (org-update-checkbox-count)
  8545. (if (and l2 (> l2 l1))
  8546. (progn
  8547. (goto-char end)
  8548. (org-update-parent-todo-statistics))
  8549. (goto-char pos)
  8550. (beginning-of-line 1)
  8551. (while (re-search-forward
  8552. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  8553. (line-end-position) t)
  8554. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  8555. (goto-char pos)
  8556. (move-marker pos nil)))))
  8557. (defvar org-entry-property-inherited-from) ;; defined below
  8558. (defun org-update-parent-todo-statistics ()
  8559. "Update any statistics cookie in the parent of the current headline.
  8560. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  8561. the entire subtree and this will travel up the hierarchy and update
  8562. statistics everywhere."
  8563. (let* ((prop (save-excursion
  8564. (org-up-heading-safe)
  8565. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  8566. (recursive (or (not org-hierarchical-todo-statistics)
  8567. (and prop (string-match "\\<recursive\\>" prop))))
  8568. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  8569. 0))
  8570. (first t)
  8571. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  8572. level ltoggle l1 new ndel
  8573. (cnt-all 0) (cnt-done 0) is-percent kwd
  8574. checkbox-beg cookie-present)
  8575. (catch 'exit
  8576. (save-excursion
  8577. (beginning-of-line 1)
  8578. (setq ltoggle (funcall outline-level))
  8579. ;; Three situations are to consider:
  8580. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  8581. ;; to the top-level ancestor on the headline;
  8582. ;; 2. If parent has "recursive" property, repeat up to the
  8583. ;; headline setting that property, taking inheritance into
  8584. ;; account;
  8585. ;; 3. Else, move up to direct parent and proceed only once.
  8586. (while (and (setq level (org-up-heading-safe))
  8587. (or recursive first)
  8588. (>= (point) lim))
  8589. (setq first nil cookie-present nil)
  8590. (unless (and level
  8591. (not (string-match
  8592. "\\<checkbox\\>"
  8593. (downcase (or (org-entry-get nil "COOKIE_DATA")
  8594. "")))))
  8595. (throw 'exit nil))
  8596. (while (re-search-forward box-re (line-end-position) t)
  8597. (setq cnt-all 0 cnt-done 0 cookie-present t)
  8598. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  8599. (save-match-data
  8600. (unless (outline-next-heading) (throw 'exit nil))
  8601. (while (and (looking-at org-complex-heading-regexp)
  8602. (> (setq l1 (length (match-string 1))) level))
  8603. (setq kwd (and (or recursive (= l1 ltoggle))
  8604. (match-string 2)))
  8605. (if (or (eq org-provide-todo-statistics 'all-headlines)
  8606. (and (eq org-provide-todo-statistics t)
  8607. (or (member kwd org-done-keywords)))
  8608. (and (listp org-provide-todo-statistics)
  8609. (stringp (car org-provide-todo-statistics))
  8610. (or (member kwd org-provide-todo-statistics)
  8611. (member kwd org-done-keywords)))
  8612. (and (listp org-provide-todo-statistics)
  8613. (listp (car org-provide-todo-statistics))
  8614. (or (member kwd (car org-provide-todo-statistics))
  8615. (and (member kwd org-done-keywords)
  8616. (member kwd (cadr org-provide-todo-statistics))))))
  8617. (setq cnt-all (1+ cnt-all))
  8618. (and (eq org-provide-todo-statistics t)
  8619. kwd
  8620. (setq cnt-all (1+ cnt-all))))
  8621. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  8622. (member kwd org-done-keywords))
  8623. (and (listp org-provide-todo-statistics)
  8624. (listp (car org-provide-todo-statistics))
  8625. (member kwd org-done-keywords)
  8626. (member kwd (cadr org-provide-todo-statistics)))
  8627. (and (listp org-provide-todo-statistics)
  8628. (stringp (car org-provide-todo-statistics))
  8629. (member kwd org-done-keywords)))
  8630. (setq cnt-done (1+ cnt-done)))
  8631. (outline-next-heading)))
  8632. (setq new
  8633. (if is-percent
  8634. (format "[%d%%]" (floor (* 100.0 cnt-done)
  8635. (max 1 cnt-all)))
  8636. (format "[%d/%d]" cnt-done cnt-all))
  8637. ndel (- (match-end 0) checkbox-beg))
  8638. (goto-char checkbox-beg)
  8639. (insert new)
  8640. (delete-region (point) (+ (point) ndel))
  8641. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  8642. (when cookie-present
  8643. (run-hook-with-args 'org-after-todo-statistics-hook
  8644. cnt-done (- cnt-all cnt-done))))))
  8645. (run-hooks 'org-todo-statistics-hook)))
  8646. (defvar org-after-todo-statistics-hook nil
  8647. "Hook that is called after a TODO statistics cookie has been updated.
  8648. Each function is called with two arguments: the number of not-done entries
  8649. and the number of done entries.
  8650. For example, the following function, when added to this hook, will switch
  8651. an entry to DONE when all children are done, and back to TODO when new
  8652. entries are set to a TODO status. Note that this hook is only called
  8653. when there is a statistics cookie in the headline!
  8654. (defun org-summary-todo (n-done n-not-done)
  8655. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  8656. (let (org-log-done org-log-states) ; turn off logging
  8657. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))")
  8658. (defvar org-todo-statistics-hook nil
  8659. "Hook that is run whenever Org thinks TODO statistics should be updated.
  8660. This hook runs even if there is no statistics cookie present, in which case
  8661. `org-after-todo-statistics-hook' would not run.")
  8662. (defun org-todo-trigger-tag-changes (state)
  8663. "Apply the changes defined in `org-todo-state-tags-triggers'."
  8664. (let ((l org-todo-state-tags-triggers)
  8665. changes)
  8666. (when (or (not state) (equal state ""))
  8667. (setq changes (append changes (cdr (assoc "" l)))))
  8668. (when (and (stringp state) (> (length state) 0))
  8669. (setq changes (append changes (cdr (assoc state l)))))
  8670. (when (member state org-not-done-keywords)
  8671. (setq changes (append changes (cdr (assq 'todo l)))))
  8672. (when (member state org-done-keywords)
  8673. (setq changes (append changes (cdr (assq 'done l)))))
  8674. (dolist (c changes)
  8675. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  8676. (defun org-local-logging (value)
  8677. "Get logging settings from a property VALUE."
  8678. ;; Directly set the variables, they are already local.
  8679. (setq org-log-done nil
  8680. org-log-repeat nil
  8681. org-todo-log-states nil)
  8682. (dolist (w (split-string value))
  8683. (let (a)
  8684. (cond
  8685. ((setq a (assoc w org-startup-options))
  8686. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  8687. (set (nth 1 a) (nth 2 a))))
  8688. ((setq a (org-extract-log-state-settings w))
  8689. (and (member (car a) org-todo-keywords-1)
  8690. (push a org-todo-log-states)))))))
  8691. (defun org-get-todo-sequence-head (kwd)
  8692. "Return the head of the TODO sequence to which KWD belongs.
  8693. If KWD is not set, check if there is a text property remembering the
  8694. right sequence."
  8695. (let (p)
  8696. (cond
  8697. ((not kwd)
  8698. (or (get-text-property (line-beginning-position) 'org-todo-head)
  8699. (progn
  8700. (setq p (next-single-property-change (line-beginning-position) 'org-todo-head
  8701. nil (line-end-position)))
  8702. (get-text-property p 'org-todo-head))))
  8703. ((not (member kwd org-todo-keywords-1))
  8704. (car org-todo-keywords-1))
  8705. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  8706. (defun org-fast-todo-selection (&optional current-state)
  8707. "Fast TODO keyword selection with single keys.
  8708. Returns the new TODO keyword, or nil if no state change should occur.
  8709. When CURRENT-STATE is given and selection letters are not unique globally,
  8710. prefer a state in the current sequence over on in another sequence."
  8711. (let* ((fulltable org-todo-key-alist)
  8712. (head (org-get-todo-sequence-head current-state))
  8713. (done-keywords org-done-keywords) ;; needed for the faces.
  8714. (maxlen (apply 'max (mapcar
  8715. (lambda (x)
  8716. (if (stringp (car x)) (string-width (car x)) 0))
  8717. fulltable)))
  8718. (expert (equal org-use-fast-todo-selection 'expert))
  8719. (prompt "")
  8720. (fwidth (+ maxlen 3 1 3))
  8721. (ncol (/ (- (window-width) 4) fwidth))
  8722. tg cnt e c tbl subtable
  8723. groups ingroup in-current-sequence)
  8724. (save-excursion
  8725. (save-window-excursion
  8726. (if expert
  8727. (set-buffer (get-buffer-create " *Org todo*"))
  8728. (delete-other-windows)
  8729. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  8730. (org-switch-to-buffer-other-window " *Org todo*"))
  8731. (erase-buffer)
  8732. (setq-local org-done-keywords done-keywords)
  8733. (setq tbl fulltable cnt 0)
  8734. (while (setq e (pop tbl))
  8735. (cond
  8736. ((equal e '(:startgroup))
  8737. (push '() groups) (setq ingroup t)
  8738. (unless (= cnt 0)
  8739. (setq cnt 0)
  8740. (insert "\n"))
  8741. (setq prompt (concat prompt "{"))
  8742. (insert "{ "))
  8743. ((equal e '(:endgroup))
  8744. (setq ingroup nil cnt 0 in-current-sequence nil)
  8745. (setq prompt (concat prompt "}"))
  8746. (insert "}\n"))
  8747. ((equal e '(:newline))
  8748. (unless (= cnt 0)
  8749. (setq cnt 0)
  8750. (insert "\n")
  8751. (setq e (car tbl))
  8752. (while (equal (car tbl) '(:newline))
  8753. (insert "\n")
  8754. (setq tbl (cdr tbl)))))
  8755. (t
  8756. (setq tg (car e) c (cdr e))
  8757. (if (equal tg head) (setq in-current-sequence t))
  8758. (when ingroup (push tg (car groups)))
  8759. (when in-current-sequence (push e subtable))
  8760. (setq tg (org-add-props tg nil 'face
  8761. (org-get-todo-face tg)))
  8762. (when (and (= cnt 0) (not ingroup)) (insert " "))
  8763. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  8764. (insert "[" c "] " tg (make-string
  8765. (- fwidth 4 (length tg)) ?\ ))
  8766. (when (and (= (setq cnt (1+ cnt)) ncol)
  8767. ;; Avoid lines with just a closing delimiter.
  8768. (not (equal (car tbl) '(:endgroup))))
  8769. (insert "\n")
  8770. (when ingroup (insert " "))
  8771. (setq cnt 0)))))
  8772. (insert "\n")
  8773. (goto-char (point-min))
  8774. (unless expert (org-fit-window-to-buffer))
  8775. (message (concat "[a-z..]:Set [SPC]:clear"
  8776. (if expert (concat "\n" prompt) "")))
  8777. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  8778. (setq subtable (nreverse subtable))
  8779. (cond
  8780. ((or (= c ?\C-g)
  8781. (and (= c ?q) (not (rassoc c fulltable))))
  8782. (setq quit-flag t))
  8783. ((= c ?\ ) nil)
  8784. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  8785. tg (car e))
  8786. tg)
  8787. (t (setq quit-flag t)))))))
  8788. (defun org-entry-is-todo-p ()
  8789. (member (org-get-todo-state) org-not-done-keywords))
  8790. (defun org-entry-is-done-p ()
  8791. (member (org-get-todo-state) org-done-keywords))
  8792. (defun org-get-todo-state ()
  8793. "Return the TODO keyword of the current subtree."
  8794. (save-excursion
  8795. (org-back-to-heading t)
  8796. (and (let ((case-fold-search nil))
  8797. (looking-at org-todo-line-regexp))
  8798. (match-end 2)
  8799. (match-string 2))))
  8800. (defun org-at-date-range-p (&optional inactive-ok)
  8801. "Non-nil if point is inside a date range.
  8802. When optional argument INACTIVE-OK is non-nil, also consider
  8803. inactive time ranges.
  8804. When this function returns a non-nil value, match data is set
  8805. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  8806. on INACTIVE-OK."
  8807. (interactive)
  8808. (save-excursion
  8809. (catch 'exit
  8810. (let ((pos (point)))
  8811. (skip-chars-backward "^[<\r\n")
  8812. (skip-chars-backward "<[")
  8813. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  8814. (>= (match-end 0) pos)
  8815. (throw 'exit t))
  8816. (skip-chars-backward "^<[\r\n")
  8817. (skip-chars-backward "<[")
  8818. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  8819. (>= (match-end 0) pos)
  8820. (throw 'exit t)))
  8821. nil)))
  8822. (defun org-get-repeat (&optional timestamp)
  8823. "Check if there is a time-stamp with repeater in this entry.
  8824. Return the repeater, as a string, or nil. Also return nil when
  8825. this function is called before first heading.
  8826. When optional argument TIMESTAMP is a string, extract the
  8827. repeater from there instead."
  8828. (save-match-data
  8829. (cond
  8830. (timestamp
  8831. (and (string-match org-repeat-re timestamp)
  8832. (match-string-no-properties 1 timestamp)))
  8833. ((org-before-first-heading-p) nil)
  8834. (t
  8835. (save-excursion
  8836. (org-back-to-heading t)
  8837. (let ((end (org-entry-end-position)))
  8838. (catch :repeat
  8839. (while (re-search-forward org-repeat-re end t)
  8840. (when (save-match-data (org-at-timestamp-p 'agenda))
  8841. (throw :repeat (match-string-no-properties 1)))))))))))
  8842. (defvar org-last-changed-timestamp)
  8843. (defvar org-last-inserted-timestamp)
  8844. (defvar org-log-post-message)
  8845. (defvar org-log-note-purpose)
  8846. (defvar org-log-note-how nil)
  8847. (defvar org-log-note-extra)
  8848. (defvar org-log-setup nil)
  8849. (defun org-auto-repeat-maybe (done-word)
  8850. "Check if the current headline contains a repeated time-stamp.
  8851. If yes, set TODO state back to what it was and change the base date
  8852. of repeating deadline/scheduled time stamps to new date.
  8853. This function is run automatically after each state change to a DONE state."
  8854. (let* ((repeat (org-get-repeat))
  8855. (aa (assoc org-last-state org-todo-kwd-alist))
  8856. (interpret (nth 1 aa))
  8857. (head (nth 2 aa))
  8858. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  8859. (msg "Entry repeats: ")
  8860. (org-log-done nil)
  8861. (org-todo-log-states nil)
  8862. (end (copy-marker (org-entry-end-position))))
  8863. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  8864. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  8865. (let ((to-state
  8866. (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  8867. (and (stringp org-todo-repeat-to-state)
  8868. org-todo-repeat-to-state)
  8869. (and org-todo-repeat-to-state org-last-state))))
  8870. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  8871. to-state)
  8872. ((eq interpret 'type) org-last-state)
  8873. (head)
  8874. (t 'none))))
  8875. (org-back-to-heading t)
  8876. (org-add-planning-info nil nil 'closed)
  8877. ;; When `org-log-repeat' is non-nil or entry contains
  8878. ;; a clock, set LAST_REPEAT property.
  8879. (when (or org-log-repeat
  8880. (catch :clock
  8881. (save-excursion
  8882. (while (re-search-forward org-clock-line-re end t)
  8883. (when (org-at-clock-log-p) (throw :clock t))))))
  8884. (org-entry-put nil "LAST_REPEAT" (format-time-string
  8885. (org-time-stamp-format t t)
  8886. (org-current-effective-time))))
  8887. (when org-log-repeat
  8888. (if org-log-setup
  8889. ;; We are already setup for some record.
  8890. (when (eq org-log-repeat 'note)
  8891. ;; Make sure we take a note, not only a time stamp.
  8892. (setq org-log-note-how 'note))
  8893. ;; Set up for taking a record.
  8894. (org-add-log-setup 'state
  8895. (or done-word (car org-done-keywords))
  8896. org-last-state
  8897. org-log-repeat)))
  8898. ;; Time-stamps without a repeater are usually skipped. However,
  8899. ;; a SCHEDULED time-stamp without one is removed, as they are no
  8900. ;; longer relevant.
  8901. (save-excursion
  8902. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  8903. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  8904. (org-remove-timestamp-with-keyword org-scheduled-string))))
  8905. ;; Update every time-stamp with a repeater in the entry.
  8906. (let ((planning-re (regexp-opt
  8907. (list org-scheduled-string org-deadline-string))))
  8908. (while (re-search-forward org-repeat-re end t)
  8909. (let* ((ts (match-string 0))
  8910. (type (if (not (org-at-planning-p)) "Plain:"
  8911. (save-excursion
  8912. (re-search-backward
  8913. planning-re (line-beginning-position) t)
  8914. (match-string 0)))))
  8915. (when (and (org-at-timestamp-p 'agenda)
  8916. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  8917. (let ((n (string-to-number (match-string 2 ts)))
  8918. (what (match-string 3 ts)))
  8919. (when (equal what "w") (setq n (* n 7) what "d"))
  8920. (when (and (equal what "h")
  8921. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  8922. ts)))
  8923. (user-error
  8924. "Cannot repeat in %d hour(s) because no hour has been set"
  8925. n))
  8926. ;; Preparation, see if we need to modify the start
  8927. ;; date for the change.
  8928. (when (match-end 1)
  8929. (let ((time (save-match-data (org-time-string-to-time ts)))
  8930. (repeater-type (match-string 1 ts)))
  8931. (cond
  8932. ((equal "." repeater-type)
  8933. ;; Shift starting date to today, or now if
  8934. ;; repeater is by hours.
  8935. (if (equal what "h")
  8936. (org-timestamp-change
  8937. (floor (- (org-time-stamp-to-now ts t)) 60) 'minute)
  8938. (org-timestamp-change
  8939. (- (org-today) (time-to-days time)) 'day)))
  8940. ((equal "+" repeater-type)
  8941. (let ((nshiftmax 10)
  8942. (nshift 0))
  8943. (while (or (= nshift 0)
  8944. (not (time-less-p nil time)))
  8945. (when (= nshiftmax (cl-incf nshift))
  8946. (or (y-or-n-p
  8947. (format "%d repeater intervals were not \
  8948. enough to shift date past today. Continue? "
  8949. nshift))
  8950. (user-error "Abort")))
  8951. (org-timestamp-change n (cdr (assoc what whata)))
  8952. (org-in-regexp org-ts-regexp3)
  8953. (setq ts (match-string 1))
  8954. (setq time
  8955. (save-match-data
  8956. (org-time-string-to-time ts)))))
  8957. (org-timestamp-change (- n) (cdr (assoc what whata)))
  8958. ;; Rematch, so that we have everything in place
  8959. ;; for the real shift.
  8960. (org-in-regexp org-ts-regexp3)
  8961. (setq ts (match-string 1))
  8962. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  8963. ts)))))
  8964. (save-excursion
  8965. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  8966. (setq msg
  8967. (concat msg type " " org-last-changed-timestamp " ")))))))
  8968. (run-hooks 'org-todo-repeat-hook)
  8969. (setq org-log-post-message msg)
  8970. (message msg))))
  8971. (defun org-show-todo-tree (arg)
  8972. "Make a compact tree which shows all headlines marked with TODO.
  8973. The tree will show the lines where the regexp matches, and all higher
  8974. headlines above the match.
  8975. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  8976. With a numeric prefix N, construct a sparse tree for the Nth element
  8977. of `org-todo-keywords-1'."
  8978. (interactive "P")
  8979. (let ((case-fold-search nil)
  8980. (kwd-re
  8981. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  8982. ((equal arg '(4))
  8983. (let ((kwd
  8984. (completing-read "Keyword (or KWD1|KWD2|...): "
  8985. (mapcar #'list org-todo-keywords-1))))
  8986. (concat "\\("
  8987. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  8988. "\\)\\>")))
  8989. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  8990. (regexp-quote (nth (1- (prefix-numeric-value arg))
  8991. org-todo-keywords-1)))
  8992. (t (user-error "Invalid prefix argument: %s" arg)))))
  8993. (message "%d TODO entries found"
  8994. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  8995. (defun org--deadline-or-schedule (arg type time)
  8996. "Insert DEADLINE or SCHEDULE information in current entry.
  8997. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  8998. `org-schedule' for information about ARG and TIME arguments."
  8999. (org-fold-core-ignore-modifications
  9000. (let* ((deadline? (eq type 'deadline))
  9001. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9002. (log (if deadline? org-log-redeadline org-log-reschedule))
  9003. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9004. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9005. ;; Save repeater cookie from either TIME or current scheduled
  9006. ;; time stamp. We are going to insert it back at the end of
  9007. ;; the process.
  9008. (repeater (or (and (org-string-nw-p time)
  9009. ;; We use `org-ts-regexp-both' because we
  9010. ;; need to tell the difference between a
  9011. ;; real repeater and a time delta, e.g.
  9012. ;; "+2d".
  9013. (string-match-p org-ts-regexp-both time)
  9014. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9015. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9016. time)
  9017. (match-string 1 time))
  9018. (and (org-string-nw-p old-date)
  9019. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9020. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9021. old-date)
  9022. (match-string 1 old-date)))))
  9023. (pcase arg
  9024. (`(4)
  9025. (if (not old-date)
  9026. (message (if deadline? "Entry had no deadline to remove"
  9027. "Entry was not scheduled"))
  9028. (when (and old-date log)
  9029. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9030. nil old-date log))
  9031. (org-remove-timestamp-with-keyword keyword)
  9032. (message (if deadline? "Entry no longer has a deadline."
  9033. "Entry is no longer scheduled."))))
  9034. (`(16)
  9035. (save-excursion
  9036. (org-back-to-heading t)
  9037. (let ((regexp (if deadline? org-deadline-time-regexp
  9038. org-scheduled-time-regexp)))
  9039. (if (not (re-search-forward regexp (line-end-position 2) t))
  9040. (user-error (if deadline? "No deadline information to update"
  9041. "No scheduled information to update"))
  9042. (let* ((rpl0 (match-string 1))
  9043. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9044. (msg (if deadline? "Warn starting from" "Delay until")))
  9045. (replace-match
  9046. (concat keyword
  9047. " <" rpl
  9048. (format " -%dd"
  9049. (abs (- (time-to-days
  9050. (save-match-data
  9051. (org-read-date
  9052. nil t nil msg old-date-time)))
  9053. (time-to-days old-date-time))))
  9054. ">") t t))))))
  9055. (_
  9056. (org-add-planning-info type time 'closed)
  9057. (when (and old-date
  9058. log
  9059. (not (equal old-date org-last-inserted-timestamp)))
  9060. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9061. org-last-inserted-timestamp
  9062. old-date
  9063. log))
  9064. (when repeater
  9065. (save-excursion
  9066. (org-back-to-heading t)
  9067. (when (re-search-forward
  9068. (concat keyword " " org-last-inserted-timestamp)
  9069. (line-end-position 2)
  9070. t)
  9071. (goto-char (1- (match-end 0)))
  9072. (insert-and-inherit " " repeater)
  9073. (setq org-last-inserted-timestamp
  9074. (concat (substring org-last-inserted-timestamp 0 -1)
  9075. " " repeater
  9076. (substring org-last-inserted-timestamp -1))))))
  9077. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9078. org-last-inserted-timestamp))))))
  9079. (defun org-deadline (arg &optional time)
  9080. "Insert a \"DEADLINE:\" string with a timestamp to make a deadline.
  9081. When called interactively, this command pops up the Emacs calendar to let
  9082. the user select a date.
  9083. With one universal prefix argument, remove any deadline from the item.
  9084. With two universal prefix arguments, prompt for a warning delay.
  9085. With argument TIME, set the deadline at the corresponding date. TIME
  9086. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9087. (interactive "P")
  9088. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9089. (org-map-entries
  9090. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9091. nil
  9092. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9093. 'region-start-level
  9094. 'region)
  9095. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9096. (org--deadline-or-schedule arg 'deadline time)))
  9097. (defun org-schedule (arg &optional time)
  9098. "Insert a \"SCHEDULED:\" string with a timestamp to schedule an item.
  9099. When called interactively, this command pops up the Emacs calendar to let
  9100. the user select a date.
  9101. With one universal prefix argument, remove any scheduling date from the item.
  9102. With two universal prefix arguments, prompt for a delay cookie.
  9103. With argument TIME, scheduled at the corresponding date. TIME can
  9104. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9105. (interactive "P")
  9106. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9107. (org-map-entries
  9108. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9109. nil
  9110. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9111. 'region-start-level
  9112. 'region)
  9113. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9114. (org--deadline-or-schedule arg 'scheduled time)))
  9115. (defun org-get-scheduled-time (pom &optional inherit)
  9116. "Get the scheduled time as a time tuple, of a format suitable
  9117. for calling org-schedule with, or if there is no scheduling,
  9118. returns nil."
  9119. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9120. (when time
  9121. (org-time-string-to-time time))))
  9122. (defun org-get-deadline-time (pom &optional inherit)
  9123. "Get the deadline as a time tuple, of a format suitable for
  9124. calling org-deadline with, or if there is no scheduling, returns
  9125. nil."
  9126. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9127. (when time
  9128. (org-time-string-to-time time))))
  9129. (defun org-remove-timestamp-with-keyword (keyword)
  9130. "Remove all time stamps with KEYWORD in the current entry."
  9131. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  9132. beg)
  9133. (save-excursion
  9134. (org-back-to-heading t)
  9135. (setq beg (point))
  9136. (outline-next-heading)
  9137. (while (re-search-backward re beg t)
  9138. (replace-match "")
  9139. (if (and (string-match "\\S-" (buffer-substring (line-beginning-position) (point)))
  9140. (equal (char-before) ?\ ))
  9141. (backward-delete-char 1)
  9142. (when (string-match "^[ \t]*$" (buffer-substring
  9143. (line-beginning-position) (line-end-position)))
  9144. (delete-region (line-beginning-position)
  9145. (min (point-max) (1+ (line-end-position))))))))))
  9146. (defvar org-time-was-given) ; dynamically scoped parameter
  9147. (defvar org-end-time-was-given) ; dynamically scoped parameter
  9148. (defun org-at-planning-p ()
  9149. "Non-nil when point is on a planning info line."
  9150. ;; This is as accurate and faster than `org-element-at-point' since
  9151. ;; planning info location is fixed in the section.
  9152. (or (let ((cached (org-element-at-point nil 'cached)))
  9153. (and cached
  9154. (eq 'planning (org-element-type cached))))
  9155. (org-with-wide-buffer
  9156. (beginning-of-line)
  9157. (and (looking-at-p org-planning-line-re)
  9158. (eq (point)
  9159. (ignore-errors
  9160. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  9161. (org-back-to-heading t)
  9162. (org-with-limited-levels (org-back-to-heading t)))
  9163. (line-beginning-position 2)))))))
  9164. (defun org-add-planning-info (what &optional time &rest remove)
  9165. "Insert new timestamp with keyword in the planning line.
  9166. WHAT indicates what kind of time stamp to add. It is a symbol
  9167. among `closed', `deadline', `scheduled' and nil. TIME indicates
  9168. the time to use. If none is given, the user is prompted for
  9169. a date. REMOVE indicates what kind of entries to remove. An old
  9170. WHAT entry will also be removed."
  9171. (org-fold-core-ignore-modifications
  9172. (let (org-time-was-given org-end-time-was-given default-time default-input)
  9173. (when (and (memq what '(scheduled deadline))
  9174. (or (not time)
  9175. (and (stringp time)
  9176. (string-match "^[-+]+[0-9]" time))))
  9177. ;; Try to get a default date/time from existing timestamp
  9178. (save-excursion
  9179. (org-back-to-heading t)
  9180. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  9181. (when (re-search-forward (if (eq what 'scheduled)
  9182. org-scheduled-time-regexp
  9183. org-deadline-time-regexp)
  9184. end t)
  9185. (setq ts (match-string 1)
  9186. default-time (org-time-string-to-time ts)
  9187. default-input (and ts (org-get-compact-tod ts)))))))
  9188. (when what
  9189. (setq time
  9190. (if (stringp time)
  9191. ;; This is a string (relative or absolute), set
  9192. ;; proper date.
  9193. (org-encode-time
  9194. (org-read-date-analyze
  9195. time default-time (decode-time default-time)))
  9196. ;; If necessary, get the time from the user
  9197. (or time (org-read-date nil 'to-time nil
  9198. (cl-case what
  9199. (deadline "DEADLINE")
  9200. (scheduled "SCHEDULED")
  9201. (otherwise nil))
  9202. default-time default-input)))))
  9203. (org-with-wide-buffer
  9204. (org-back-to-heading t)
  9205. (let ((planning? (save-excursion
  9206. (forward-line)
  9207. (looking-at-p org-planning-line-re))))
  9208. (cond
  9209. (planning?
  9210. (forward-line)
  9211. ;; Move to current indentation.
  9212. (skip-chars-forward " \t")
  9213. ;; Check if we have to remove something.
  9214. (dolist (type (if what (cons what remove) remove))
  9215. (save-excursion
  9216. (when (re-search-forward
  9217. (cl-case type
  9218. (closed org-closed-time-regexp)
  9219. (deadline org-deadline-time-regexp)
  9220. (scheduled org-scheduled-time-regexp)
  9221. (otherwise (error "Invalid planning type: %s" type)))
  9222. (line-end-position)
  9223. t)
  9224. ;; Delete until next keyword or end of line.
  9225. (delete-region
  9226. (match-beginning 0)
  9227. (if (re-search-forward org-keyword-time-not-clock-regexp
  9228. (line-end-position)
  9229. t)
  9230. (match-beginning 0)
  9231. (line-end-position))))))
  9232. ;; If there is nothing more to add and no more keyword is
  9233. ;; left, remove the line completely.
  9234. (if (and (looking-at-p "[ \t]*$") (not what))
  9235. (delete-region (line-end-position 0)
  9236. (line-end-position))
  9237. ;; If we removed last keyword, do not leave trailing white
  9238. ;; space at the end of line.
  9239. (let ((p (point)))
  9240. (save-excursion
  9241. (end-of-line)
  9242. (unless (= (skip-chars-backward " \t" p) 0)
  9243. (delete-region (point) (line-end-position)))))))
  9244. (what
  9245. (end-of-line)
  9246. (insert-and-inherit "\n")
  9247. (when org-adapt-indentation
  9248. (indent-to-column (1+ (org-outline-level)))))
  9249. (t nil)))
  9250. (when what
  9251. ;; Insert planning keyword.
  9252. (insert-and-inherit (cl-case what
  9253. (closed org-closed-string)
  9254. (deadline org-deadline-string)
  9255. (scheduled org-scheduled-string)
  9256. (otherwise (error "Invalid planning type: %s" what)))
  9257. " ")
  9258. ;; Insert associated timestamp.
  9259. (let ((ts (org-insert-time-stamp
  9260. time
  9261. (or org-time-was-given
  9262. (and (eq what 'closed) org-log-done-with-time))
  9263. (eq what 'closed)
  9264. nil nil (list org-end-time-was-given))))
  9265. (unless (eolp) (insert " "))
  9266. ts))))))
  9267. (defvar org-log-note-marker (make-marker)
  9268. "Marker pointing at the entry where the note is to be inserted.")
  9269. (defvar org-log-note-purpose nil)
  9270. (defvar org-log-note-state nil)
  9271. (defvar org-log-note-previous-state nil)
  9272. (defvar org-log-note-extra nil)
  9273. (defvar org-log-note-window-configuration nil)
  9274. (defvar org-log-note-return-to (make-marker))
  9275. (defvar org-log-note-effective-time nil
  9276. "Remembered current time.
  9277. So that dynamically scoped `org-extend-today-until' affects
  9278. timestamps in state change log.")
  9279. (defvar org-log-post-message nil
  9280. "Message to be displayed after a log note has been stored.
  9281. The auto-repeater uses this.")
  9282. (defun org-add-note ()
  9283. "Add a note to the current entry.
  9284. This is done in the same way as adding a state change note."
  9285. (interactive)
  9286. (org-add-log-setup 'note))
  9287. (defun org-log-beginning (&optional create)
  9288. "Return expected start of log notes in current entry.
  9289. When optional argument CREATE is non-nil, the function creates
  9290. a drawer to store notes, if necessary. Returned position ignores
  9291. narrowing."
  9292. (org-with-wide-buffer
  9293. (let ((drawer (org-log-into-drawer)))
  9294. (cond
  9295. (drawer
  9296. (org-end-of-meta-data)
  9297. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  9298. (end (if (org-at-heading-p) (point)
  9299. (save-excursion (outline-next-heading) (point))))
  9300. (case-fold-search t))
  9301. (catch 'exit
  9302. ;; Try to find existing drawer.
  9303. (while (re-search-forward regexp end t)
  9304. (let ((element (org-element-at-point)))
  9305. (when (eq (org-element-type element) 'drawer)
  9306. (let ((cend (org-element-property :contents-end element)))
  9307. (when (and (not org-log-states-order-reversed) cend)
  9308. (goto-char cend)))
  9309. (throw 'exit nil))))
  9310. ;; No drawer found. Create one, if permitted.
  9311. (when create
  9312. ;; Unless current heading is the last heading in buffer
  9313. ;; and does not have a newline, `org-end-of-meta-data'
  9314. ;; should move us somewhere below the heading.
  9315. ;; Avoid situation when we insert drawer right before
  9316. ;; first "*". Otherwise, if the previous heading is
  9317. ;; folded, we are inserting after visible newline at
  9318. ;; the end of the fold, thus breaking the fold
  9319. ;; continuity.
  9320. (unless (eobp)
  9321. (when (org-at-heading-p) (backward-char)))
  9322. (org-fold-core-ignore-modifications
  9323. (unless (bolp) (insert-and-inherit "\n"))
  9324. (let ((beg (point)))
  9325. (insert-and-inherit ":" drawer ":\n:END:\n")
  9326. (org-indent-region beg (point))
  9327. (org-fold-region (line-end-position -1) (1- (point)) t (if (eq org-fold-core-style 'text-properties) 'drawer 'outline)))))
  9328. (end-of-line -1))))
  9329. (t
  9330. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  9331. (let ((endpos (point)))
  9332. (skip-chars-forward " \t\n")
  9333. (beginning-of-line)
  9334. (unless org-log-states-order-reversed
  9335. (org-skip-over-state-notes)
  9336. (skip-chars-backward " \t\n")
  9337. (beginning-of-line 2))
  9338. ;; When current headline is at the end of buffer and does not
  9339. ;; end with trailing newline the above can move to the
  9340. ;; beginning of the headline.
  9341. (when (< (point) endpos) (goto-char endpos))))))
  9342. (if (bolp) (point) (line-beginning-position 2))))
  9343. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  9344. "Set up the post command hook to take a note.
  9345. If this is about to TODO state change, the new state is expected in STATE.
  9346. HOW is an indicator what kind of note should be created.
  9347. EXTRA is additional text that will be inserted into the notes buffer."
  9348. (move-marker org-log-note-marker (point))
  9349. (setq org-log-note-purpose purpose
  9350. org-log-note-state state
  9351. org-log-note-previous-state prev-state
  9352. org-log-note-how how
  9353. org-log-note-extra extra
  9354. org-log-note-effective-time (org-current-effective-time)
  9355. org-log-setup t)
  9356. (add-hook 'post-command-hook 'org-add-log-note 'append))
  9357. (defun org-skip-over-state-notes ()
  9358. "Skip past the list of State notes in an entry."
  9359. (when (ignore-errors (goto-char (org-in-item-p)))
  9360. (let* ((struct (org-list-struct))
  9361. (prevs (org-list-prevs-alist struct))
  9362. (regexp
  9363. (concat "[ \t]*- +"
  9364. (replace-regexp-in-string
  9365. " +" " +"
  9366. (org-replace-escapes
  9367. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  9368. `(("%d" . ,org-ts-regexp-inactive)
  9369. ("%D" . ,org-ts-regexp)
  9370. ("%s" . "\\(?:\"\\S-+\"\\)?")
  9371. ("%S" . "\\(?:\"\\S-+\"\\)?")
  9372. ("%t" . ,org-ts-regexp-inactive)
  9373. ("%T" . ,org-ts-regexp)
  9374. ("%u" . ".*?")
  9375. ("%U" . ".*?")))))))
  9376. (while (looking-at-p regexp)
  9377. (goto-char (or (org-list-get-next-item (point) struct prevs)
  9378. (org-list-get-item-end (point) struct)))))))
  9379. (defun org-add-log-note (&optional _purpose)
  9380. "Pop up a window for taking a note, and add this note later."
  9381. (remove-hook 'post-command-hook 'org-add-log-note)
  9382. (setq org-log-setup nil)
  9383. (setq org-log-note-window-configuration (current-window-configuration))
  9384. (delete-other-windows)
  9385. (move-marker org-log-note-return-to (point))
  9386. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  9387. (goto-char org-log-note-marker)
  9388. (org-switch-to-buffer-other-window "*Org Note*")
  9389. (erase-buffer)
  9390. (if (memq org-log-note-how '(time state))
  9391. (org-store-log-note)
  9392. (let ((org-inhibit-startup t)) (org-mode))
  9393. (insert (format "# Insert note for %s.
  9394. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  9395. (cl-case org-log-note-purpose
  9396. (clock-out "stopped clock")
  9397. (done "closed todo item")
  9398. (reschedule "rescheduling")
  9399. (delschedule "no longer scheduled")
  9400. (redeadline "changing deadline")
  9401. (deldeadline "removing deadline")
  9402. (refile "refiling")
  9403. (note "this entry")
  9404. (state
  9405. (format "state change from \"%s\" to \"%s\""
  9406. (or org-log-note-previous-state "")
  9407. (or org-log-note-state "")))
  9408. (t (error "This should not happen")))))
  9409. (when org-log-note-extra (insert org-log-note-extra))
  9410. (setq-local org-finish-function 'org-store-log-note)
  9411. (run-hooks 'org-log-buffer-setup-hook)))
  9412. (defvar org-note-abort nil) ; dynamically scoped
  9413. (defun org-store-log-note ()
  9414. "Finish taking a log note, and insert it to where it belongs."
  9415. (let ((txt (prog1 (buffer-string)
  9416. (kill-buffer)))
  9417. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  9418. lines)
  9419. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  9420. (setq txt (replace-match "" t t txt)))
  9421. (when (string-match "\\s-+\\'" txt)
  9422. (setq txt (replace-match "" t t txt)))
  9423. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  9424. (when (org-string-nw-p note)
  9425. (setq note
  9426. (org-replace-escapes
  9427. note
  9428. (list (cons "%u" (user-login-name))
  9429. (cons "%U" user-full-name)
  9430. (cons "%t" (format-time-string
  9431. (org-time-stamp-format 'long 'inactive)
  9432. org-log-note-effective-time))
  9433. (cons "%T" (format-time-string
  9434. (org-time-stamp-format 'long nil)
  9435. org-log-note-effective-time))
  9436. (cons "%d" (format-time-string
  9437. (org-time-stamp-format nil 'inactive)
  9438. org-log-note-effective-time))
  9439. (cons "%D" (format-time-string
  9440. (org-time-stamp-format nil nil)
  9441. org-log-note-effective-time))
  9442. (cons "%s" (cond
  9443. ((not org-log-note-state) "")
  9444. ((string-match-p org-ts-regexp
  9445. org-log-note-state)
  9446. (format "\"[%s]\""
  9447. (substring org-log-note-state 1 -1)))
  9448. (t (format "\"%s\"" org-log-note-state))))
  9449. (cons "%S"
  9450. (cond
  9451. ((not org-log-note-previous-state) "")
  9452. ((string-match-p org-ts-regexp
  9453. org-log-note-previous-state)
  9454. (format "\"[%s]\""
  9455. (substring
  9456. org-log-note-previous-state 1 -1)))
  9457. (t (format "\"%s\""
  9458. org-log-note-previous-state)))))))
  9459. (when lines (setq note (concat note " \\\\")))
  9460. (push note lines))
  9461. (when (and lines (not org-note-abort))
  9462. (with-current-buffer (marker-buffer org-log-note-marker)
  9463. (org-fold-core-ignore-modifications
  9464. (org-with-wide-buffer
  9465. ;; Find location for the new note.
  9466. (goto-char org-log-note-marker)
  9467. (set-marker org-log-note-marker nil)
  9468. ;; Note associated to a clock is to be located right after
  9469. ;; the clock. Do not move point.
  9470. (unless (eq org-log-note-purpose 'clock-out)
  9471. (goto-char (org-log-beginning t)))
  9472. ;; Make sure point is at the beginning of an empty line.
  9473. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert-and-inherit "\n")))
  9474. ((looking-at "[ \t]*\\S-") (save-excursion (insert-and-inherit "\n"))))
  9475. ;; In an existing list, add a new item at the top level.
  9476. ;; Otherwise, indent line like a regular one.
  9477. (let ((itemp (org-in-item-p)))
  9478. (if itemp
  9479. (indent-line-to
  9480. (let ((struct (save-excursion
  9481. (goto-char itemp) (org-list-struct))))
  9482. (org-list-get-ind (org-list-get-top-point struct) struct)))
  9483. (org-indent-line)))
  9484. (insert-and-inherit (org-list-bullet-string "-") (pop lines))
  9485. (let ((ind (org-list-item-body-column (line-beginning-position))))
  9486. (dolist (line lines)
  9487. (insert-and-inherit "\n")
  9488. (unless (string-empty-p line)
  9489. (indent-line-to ind)
  9490. (insert-and-inherit line))))
  9491. (message "Note stored")
  9492. (org-back-to-heading t))))))
  9493. ;; Don't add undo information when called from `org-agenda-todo'.
  9494. (set-window-configuration org-log-note-window-configuration)
  9495. (with-current-buffer (marker-buffer org-log-note-return-to)
  9496. (goto-char org-log-note-return-to))
  9497. (move-marker org-log-note-return-to nil)
  9498. (when org-log-post-message (message "%s" org-log-post-message)))
  9499. (defun org-remove-empty-drawer-at (pos)
  9500. "Remove an empty drawer at position POS.
  9501. POS may also be a marker."
  9502. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  9503. (org-with-wide-buffer
  9504. (goto-char pos)
  9505. (let ((drawer (org-element-at-point)))
  9506. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  9507. (not (org-element-property :contents-begin drawer)))
  9508. (delete-region (org-element-property :begin drawer)
  9509. (progn (goto-char (org-element-property :end drawer))
  9510. (skip-chars-backward " \r\t\n")
  9511. (forward-line)
  9512. (point))))))))
  9513. (defvar org-ts-type nil)
  9514. (defun org-sparse-tree (&optional arg type)
  9515. "Create a sparse tree, prompt for the details.
  9516. This command can create sparse trees. You first need to select the type
  9517. of match used to create the tree:
  9518. t Show all TODO entries.
  9519. T Show entries with a specific TODO keyword.
  9520. m Show entries selected by a tags/property match.
  9521. p Enter a property name and its value (both with completion on existing
  9522. names/values) and show entries with that property.
  9523. r Show entries matching a regular expression (`/' can be used as well).
  9524. b Show deadlines and scheduled items before a date.
  9525. a Show deadlines and scheduled items after a date.
  9526. d Show deadlines due within `org-deadline-warning-days'.
  9527. D Show deadlines and scheduled items between a date range."
  9528. (interactive "P")
  9529. (setq type (or type org-sparse-tree-default-date-type))
  9530. (setq org-ts-type type)
  9531. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  9532. [d]eadlines [b]efore-date [a]fter-date [D]ates range
  9533. [c]ycle through date types: %s"
  9534. (cl-case type
  9535. (all "all timestamps")
  9536. (scheduled "only scheduled")
  9537. (deadline "only deadline")
  9538. (active "only active timestamps")
  9539. (inactive "only inactive timestamps")
  9540. (closed "with a closed time-stamp")
  9541. (otherwise "scheduled/deadline")))
  9542. (let ((answer (read-char-exclusive)))
  9543. (cl-case answer
  9544. (?c
  9545. (org-sparse-tree
  9546. arg
  9547. (cadr
  9548. (memq type '(nil all scheduled deadline active inactive closed)))))
  9549. (?d (call-interactively 'org-check-deadlines))
  9550. (?b (call-interactively 'org-check-before-date))
  9551. (?a (call-interactively 'org-check-after-date))
  9552. (?D (call-interactively 'org-check-dates-range))
  9553. (?t (call-interactively 'org-show-todo-tree))
  9554. (?T (org-show-todo-tree '(4)))
  9555. (?m (call-interactively 'org-match-sparse-tree))
  9556. ((?p ?P)
  9557. (let* ((kwd (completing-read
  9558. "Property: " (mapcar #'list (org-buffer-property-keys))))
  9559. (value (completing-read
  9560. "Value: " (mapcar #'list (org-property-values kwd)))))
  9561. (unless (string-match "\\`{.*}\\'" value)
  9562. (setq value (concat "\"" value "\"")))
  9563. (org-match-sparse-tree arg (concat kwd "=" value))))
  9564. ((?r ?R ?/) (call-interactively 'org-occur))
  9565. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  9566. (defvar-local org-occur-highlights nil
  9567. "List of overlays used for occur matches.")
  9568. (defvar-local org-occur-parameters nil
  9569. "Parameters of the active org-occur calls.
  9570. This is a list, each call to org-occur pushes as cons cell,
  9571. containing the regular expression and the callback, onto the list.
  9572. The list can contain several entries if `org-occur' has been called
  9573. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  9574. will only contain one set of parameters. When the highlights are
  9575. removed (for example with `C-c C-c', or with the next edit (depending
  9576. on `org-remove-highlights-with-change'), this variable is emptied
  9577. as well.")
  9578. (defun org-occur (regexp &optional keep-previous callback)
  9579. "Make a compact tree showing all matches of REGEXP.
  9580. The tree will show the lines where the regexp matches, and any other context
  9581. defined in `org-fold-show-context-detail', which see.
  9582. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  9583. done by a previous call to `org-occur' will be kept, to allow stacking of
  9584. calls to this command.
  9585. Optional argument CALLBACK can be a function of no argument. In this case,
  9586. it is called with point at the end of the match, match data being set
  9587. accordingly. Current match is shown only if the return value is non-nil.
  9588. The function must neither move point nor alter narrowing."
  9589. (interactive "sRegexp: \nP")
  9590. (when (equal regexp "")
  9591. (user-error "Regexp cannot be empty"))
  9592. (unless keep-previous
  9593. (org-remove-occur-highlights nil nil t))
  9594. (push (cons regexp callback) org-occur-parameters)
  9595. (let ((cnt 0))
  9596. (save-excursion
  9597. (goto-char (point-min))
  9598. (when (or (not keep-previous) ; do not want to keep
  9599. (not org-occur-highlights)) ; no previous matches
  9600. ;; hide everything
  9601. (org-cycle-overview))
  9602. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  9603. (isearch-no-upper-case-p regexp t)
  9604. org-occur-case-fold-search)))
  9605. (while (re-search-forward regexp nil t)
  9606. (when (or (not callback)
  9607. (save-match-data (funcall callback)))
  9608. (setq cnt (1+ cnt))
  9609. (when org-highlight-sparse-tree-matches
  9610. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  9611. (org-fold-show-context 'occur-tree)))))
  9612. (when org-remove-highlights-with-change
  9613. (add-hook 'before-change-functions 'org-remove-occur-highlights
  9614. nil 'local))
  9615. (unless org-sparse-tree-open-archived-trees
  9616. (org-fold-hide-archived-subtrees (point-min) (point-max)))
  9617. (run-hooks 'org-occur-hook)
  9618. (when (called-interactively-p 'interactive)
  9619. (message "%d match(es) for regexp %s" cnt regexp))
  9620. cnt))
  9621. (defun org-occur-next-match (&optional n _reset)
  9622. "Function for `next-error-function' to find sparse tree matches.
  9623. N is the number of matches to move, when negative move backwards.
  9624. This function always goes back to the starting point when no
  9625. match is found."
  9626. (let* ((limit (if (< n 0) (point-min) (point-max)))
  9627. (search-func (if (< n 0)
  9628. 'previous-single-char-property-change
  9629. 'next-single-char-property-change))
  9630. (n (abs n))
  9631. (pos (point))
  9632. p1)
  9633. (catch 'exit
  9634. (while (setq p1 (funcall search-func (point) 'org-type))
  9635. (when (equal p1 limit)
  9636. (goto-char pos)
  9637. (user-error "No more matches"))
  9638. (when (equal (get-char-property p1 'org-type) 'org-occur)
  9639. (setq n (1- n))
  9640. (when (= n 0)
  9641. (goto-char p1)
  9642. (throw 'exit (point))))
  9643. (goto-char p1))
  9644. (goto-char p1)
  9645. (user-error "No more matches"))))
  9646. (defun org-highlight-new-match (beg end)
  9647. "Highlight from BEG to END and mark the highlight is an occur headline."
  9648. (let ((ov (make-overlay beg end)))
  9649. (overlay-put ov 'face 'secondary-selection)
  9650. (overlay-put ov 'org-type 'org-occur)
  9651. (push ov org-occur-highlights)))
  9652. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  9653. "Remove the occur highlights from the buffer.
  9654. BEG and END are ignored. If NOREMOVE is nil, remove this function
  9655. from the `before-change-functions' in the current buffer."
  9656. (interactive)
  9657. (unless org-inhibit-highlight-removal
  9658. (mapc #'delete-overlay org-occur-highlights)
  9659. (setq org-occur-highlights nil)
  9660. (setq org-occur-parameters nil)
  9661. (unless noremove
  9662. (remove-hook 'before-change-functions
  9663. 'org-remove-occur-highlights 'local))))
  9664. ;;;; Priorities
  9665. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  9666. "Regular expression matching the priority indicator.
  9667. A priority indicator can be e.g. [#A] or [#1].
  9668. This regular expression matches these groups:
  9669. 0 : the whole match, e.g. \"TODO [#A] Hack\"
  9670. 1 : the priority cookie, e.g. \"[#A]\"
  9671. 2 : the value of the priority cookie, e.g. \"A\".")
  9672. (defun org-priority-up ()
  9673. "Increase the priority of the current item."
  9674. (interactive)
  9675. (org-priority 'up))
  9676. (defun org-priority-down ()
  9677. "Decrease the priority of the current item."
  9678. (interactive)
  9679. (org-priority 'down))
  9680. (defun org-priority (&optional action show)
  9681. "Change the priority of an item.
  9682. When called interactively with a `\\[universal-argument]' prefix,
  9683. show the priority in the minibuffer instead of changing it.
  9684. When called programmatically, ACTION can be `set', `up', `down',
  9685. or a character."
  9686. (interactive "P")
  9687. (when show
  9688. ;; Deprecation warning inserted for Org 9.2; once enough time has
  9689. ;; passed the SHOW argument should be removed.
  9690. (warn "`org-priority' called with deprecated SHOW argument"))
  9691. (if (equal action '(4))
  9692. (org-priority-show)
  9693. (unless org-priority-enable-commands
  9694. (user-error "Priority commands are disabled"))
  9695. (setq action (or action 'set))
  9696. (let ((nump (< org-priority-lowest 65))
  9697. current new news have remove)
  9698. (save-excursion
  9699. (org-back-to-heading t)
  9700. (when (looking-at org-priority-regexp)
  9701. (let ((ms (match-string 2)))
  9702. (setq current (org-priority-to-value ms)
  9703. have t)))
  9704. (cond
  9705. ((eq action 'remove)
  9706. (setq remove t new ?\ ))
  9707. ((or (eq action 'set)
  9708. (integerp action))
  9709. (if (not (eq action 'set))
  9710. (setq new action)
  9711. (setq
  9712. new
  9713. (if nump
  9714. (let* ((msg (format "Priority %s-%s, SPC to remove: "
  9715. (number-to-string org-priority-highest)
  9716. (number-to-string org-priority-lowest)))
  9717. (s (if (< 9 org-priority-lowest)
  9718. (read-string msg)
  9719. (message msg)
  9720. (char-to-string (read-char-exclusive)))))
  9721. (if (equal s " ") ?\s (string-to-number s)))
  9722. (progn (message "Priority %c-%c, SPC to remove: "
  9723. org-priority-highest org-priority-lowest)
  9724. (save-match-data
  9725. (setq new (read-char-exclusive)))))))
  9726. (when (and (= (upcase org-priority-highest) org-priority-highest)
  9727. (= (upcase org-priority-lowest) org-priority-lowest))
  9728. (setq new (upcase new)))
  9729. (cond ((equal new ?\s) (setq remove t))
  9730. ((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  9731. (user-error
  9732. (if nump
  9733. "Priority must be between `%s' and `%s'"
  9734. "Priority must be between `%c' and `%c'")
  9735. org-priority-highest org-priority-lowest))))
  9736. ((eq action 'up)
  9737. (setq new (if have
  9738. (1- current) ; normal cycling
  9739. ;; last priority was empty
  9740. (if (eq last-command this-command)
  9741. org-priority-lowest ; wrap around empty to lowest
  9742. ;; default
  9743. (if org-priority-start-cycle-with-default
  9744. org-priority-default
  9745. (1- org-priority-default))))))
  9746. ((eq action 'down)
  9747. (setq new (if have
  9748. (1+ current) ; normal cycling
  9749. ;; last priority was empty
  9750. (if (eq last-command this-command)
  9751. org-priority-highest ; wrap around empty to highest
  9752. ;; default
  9753. (if org-priority-start-cycle-with-default
  9754. org-priority-default
  9755. (1+ org-priority-default))))))
  9756. (t (user-error "Invalid action")))
  9757. (when (or (< (upcase new) org-priority-highest)
  9758. (> (upcase new) org-priority-lowest))
  9759. (if (and (memq action '(up down))
  9760. (not have) (not (eq last-command this-command)))
  9761. ;; `new' is from default priority
  9762. (error
  9763. "The default can not be set, see `org-priority-default' why")
  9764. ;; normal cycling: `new' is beyond highest/lowest priority
  9765. ;; and is wrapped around to the empty priority
  9766. (setq remove t)))
  9767. ;; Numerical priorities are limited to 64, beyond that number,
  9768. ;; assume the priority cookie is a character.
  9769. (setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  9770. (if have
  9771. (if remove
  9772. (replace-match "" t t nil 1)
  9773. (replace-match news t t nil 2))
  9774. (if remove
  9775. (user-error "No priority cookie found in line")
  9776. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9777. (if (match-end 2)
  9778. (progn
  9779. (goto-char (match-end 2))
  9780. (insert " [#" news "]"))
  9781. (goto-char (match-beginning 3))
  9782. (insert "[#" news "] "))))
  9783. (org-align-tags))
  9784. (if remove
  9785. (message "Priority removed")
  9786. (message "Priority of current item set to %s" news)))))
  9787. (defalias 'org-show-priority 'org-priority-show)
  9788. (defun org-priority-show ()
  9789. "Show the priority of the current item.
  9790. This priority is composed of the main priority given with the [#A] cookies,
  9791. and by additional input from the age of a schedules or deadline entry."
  9792. (interactive)
  9793. (let ((pri (if (eq major-mode 'org-agenda-mode)
  9794. (org-get-at-bol 'priority)
  9795. (save-excursion
  9796. (save-match-data
  9797. (beginning-of-line)
  9798. (and (looking-at org-heading-regexp)
  9799. (org-get-priority (match-string 0))))))))
  9800. (message "Priority is %d" (if pri pri -1000))))
  9801. (defun org-get-priority (s)
  9802. "Find priority cookie and return priority.
  9803. S is a string against which you can match `org-priority-regexp'.
  9804. If `org-priority-get-priority-function' is set to a custom
  9805. function, use it. Otherwise process S and output the priority
  9806. value, an integer."
  9807. (save-match-data
  9808. (if (functionp org-priority-get-priority-function)
  9809. (funcall org-priority-get-priority-function s)
  9810. (if (not (string-match org-priority-regexp s))
  9811. (* 1000 (- org-priority-lowest org-priority-default))
  9812. (* 1000 (- org-priority-lowest
  9813. (org-priority-to-value (match-string 2 s))))))))
  9814. ;;;; Tags
  9815. (defvar org-agenda-archives-mode)
  9816. (defvar org-map-continue-from nil
  9817. "Position from where mapping should continue.
  9818. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  9819. (defvar org-scanner-tags nil
  9820. "The current tag list while the tags scanner is running.")
  9821. (defvar org-trust-scanner-tags nil
  9822. "Should `org-get-tags' use the tags for the scanner.
  9823. This is for internal dynamical scoping only.
  9824. When this is non-nil, the function `org-get-tags' will return the value
  9825. of `org-scanner-tags' instead of building the list by itself. This
  9826. can lead to large speed-ups when the tags scanner is used in a file with
  9827. many entries, and when the list of tags is retrieved, for example to
  9828. obtain a list of properties. Building the tags list for each entry in such
  9829. a file becomes an N^2 operation - but with this variable set, it scales
  9830. as N.")
  9831. (defvar org--matcher-tags-todo-only nil)
  9832. (defun org-scan-tags (action matcher todo-only &optional start-level)
  9833. "Scan headline tags with inheritance and produce output ACTION.
  9834. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  9835. or `agenda' to produce an entry list for an agenda view. It can also be
  9836. a Lisp form or a function that should be called at each matched headline, in
  9837. this case the return value is a list of all return values from these calls.
  9838. MATCHER is a function accepting three arguments, returning
  9839. a non-nil value whenever a given set of tags qualifies a headline
  9840. for inclusion. See `org-make-tags-matcher' for more information.
  9841. As a special case, it can also be set to t (respectively nil) in
  9842. order to match all (respectively none) headline.
  9843. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  9844. included in the output.
  9845. START-LEVEL can be a string with asterisks, reducing the scope to
  9846. headlines matching this string."
  9847. (require 'org-agenda)
  9848. (let* ((re (concat "^"
  9849. (if start-level
  9850. ;; Get the correct level to match
  9851. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  9852. org-outline-regexp)
  9853. " *\\(?:\\(" (regexp-opt org-todo-keywords-1 t) "\\) \\)?"
  9854. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  9855. (props (list 'face 'default
  9856. 'done-face 'org-agenda-done
  9857. 'undone-face 'default
  9858. 'mouse-face 'highlight
  9859. 'org-not-done-regexp org-not-done-regexp
  9860. 'org-todo-regexp org-todo-regexp
  9861. 'org-complex-heading-regexp org-complex-heading-regexp
  9862. 'help-echo
  9863. (format "mouse-2 or RET jump to Org file %S"
  9864. (abbreviate-file-name
  9865. (or (buffer-file-name (buffer-base-buffer))
  9866. (buffer-name (buffer-base-buffer)))))))
  9867. (org-map-continue-from nil)
  9868. lspos tags tags-list
  9869. (tags-alist (list (cons 0 org-file-tags)))
  9870. (llast 0) rtn rtn1 level category i txt
  9871. todo marker entry priority
  9872. ts-date ts-date-type ts-date-pair)
  9873. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  9874. (setq action (list 'lambda nil action)))
  9875. (save-excursion
  9876. (goto-char (point-min))
  9877. (when (eq action 'sparse-tree)
  9878. (org-cycle-overview)
  9879. (org-remove-occur-highlights))
  9880. (if (org-element--cache-active-p)
  9881. (let ((fast-re (concat "^"
  9882. (if start-level
  9883. ;; Get the correct level to match
  9884. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  9885. org-outline-regexp))))
  9886. (org-element-cache-map
  9887. (lambda (el)
  9888. (goto-char (org-element-property :begin el))
  9889. (setq todo (org-element-property :todo-keyword el)
  9890. level (org-element-property :level el)
  9891. category (org-entry-get-with-inheritance "CATEGORY" nil el)
  9892. tags-list (org-get-tags el)
  9893. org-scanner-tags tags-list)
  9894. (when (eq action 'agenda)
  9895. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  9896. ts-date (car ts-date-pair)
  9897. ts-date-type (cdr ts-date-pair)))
  9898. (catch :skip
  9899. (when (and
  9900. ;; eval matcher only when the todo condition is OK
  9901. (and (or (not todo-only) (member todo org-todo-keywords-1))
  9902. (if (functionp matcher)
  9903. (let ((case-fold-search t) (org-trust-scanner-tags t))
  9904. (funcall matcher todo tags-list level))
  9905. matcher))
  9906. ;; Call the skipper, but return t if it does not
  9907. ;; skip, so that the `and' form continues evaluating.
  9908. (progn
  9909. (unless (eq action 'sparse-tree) (org-agenda-skip el))
  9910. t)
  9911. ;; Check if timestamps are deselecting this entry
  9912. (or (not todo-only)
  9913. (and (member todo org-todo-keywords-1)
  9914. (or (not org-agenda-tags-todo-honor-ignore-options)
  9915. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  9916. ;; select this headline
  9917. (cond
  9918. ((eq action 'sparse-tree)
  9919. (and org-highlight-sparse-tree-matches
  9920. (org-get-heading) (match-end 0)
  9921. (org-highlight-new-match
  9922. (match-beginning 1) (match-end 1)))
  9923. (org-fold-show-context 'tags-tree))
  9924. ((eq action 'agenda)
  9925. (let* ((effort (org-entry-get (point) org-effort-property))
  9926. (effort-minutes (when effort (save-match-data (org-duration-to-minutes effort)))))
  9927. (setq txt (org-agenda-format-item
  9928. ""
  9929. ;; Add `effort' and `effort-minutes'
  9930. ;; properties for prefix format.
  9931. (org-add-props
  9932. (concat
  9933. (if (eq org-tags-match-list-sublevels 'indented)
  9934. (make-string (1- level) ?.) "")
  9935. (org-get-heading))
  9936. nil
  9937. 'effort effort
  9938. 'effort-minutes effort-minutes)
  9939. (make-string level ?\s)
  9940. category
  9941. tags-list)
  9942. priority (org-get-priority txt))
  9943. ;; Now add `effort' and `effort-minutes' to
  9944. ;; full agenda line.
  9945. (setq txt (org-add-props txt nil
  9946. 'effort effort
  9947. 'effort-minutes effort-minutes)))
  9948. (goto-char (org-element-property :begin el))
  9949. (setq marker (org-agenda-new-marker))
  9950. (org-add-props txt props
  9951. 'org-marker marker 'org-hd-marker marker 'org-category category
  9952. 'todo-state todo
  9953. 'ts-date ts-date
  9954. 'priority priority
  9955. 'type (concat "tagsmatch" ts-date-type))
  9956. (push txt rtn))
  9957. ((functionp action)
  9958. (setq org-map-continue-from nil)
  9959. (save-excursion
  9960. (setq rtn1 (funcall action))
  9961. (push rtn1 rtn)))
  9962. (t (user-error "Invalid action")))
  9963. ;; if we are to skip sublevels, jump to end of subtree
  9964. (unless org-tags-match-list-sublevels
  9965. (goto-char (1- (org-element-property :end el))))))
  9966. ;; Get the correct position from where to continue
  9967. (when org-map-continue-from
  9968. (setq org-element-cache-map-continue-from org-map-continue-from)
  9969. (goto-char org-map-continue-from))
  9970. ;; Return nil.
  9971. nil)
  9972. :next-re fast-re
  9973. :fail-re fast-re
  9974. :narrow t))
  9975. (while (let (case-fold-search)
  9976. (re-search-forward re nil t))
  9977. (setq org-map-continue-from nil)
  9978. (catch :skip
  9979. ;; Ignore closing parts of inline tasks.
  9980. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  9981. (throw :skip t))
  9982. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  9983. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  9984. (goto-char (setq lspos (match-beginning 0)))
  9985. (setq level (org-reduced-level (org-outline-level))
  9986. category (org-get-category))
  9987. (when (eq action 'agenda)
  9988. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  9989. ts-date (car ts-date-pair)
  9990. ts-date-type (cdr ts-date-pair)))
  9991. (setq i llast llast level)
  9992. ;; remove tag lists from same and sublevels
  9993. (while (>= i level)
  9994. (when (setq entry (assoc i tags-alist))
  9995. (setq tags-alist (delete entry tags-alist)))
  9996. (setq i (1- i)))
  9997. ;; add the next tags
  9998. (when tags
  9999. (setq tags (org-split-string tags ":")
  10000. tags-alist
  10001. (cons (cons level tags) tags-alist)))
  10002. ;; compile tags for current headline
  10003. (setq tags-list
  10004. (if org-use-tag-inheritance
  10005. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10006. tags)
  10007. org-scanner-tags tags-list)
  10008. (when org-use-tag-inheritance
  10009. (setcdr (car tags-alist)
  10010. (mapcar (lambda (x)
  10011. (setq x (copy-sequence x))
  10012. (org-add-prop-inherited x))
  10013. (cdar tags-alist))))
  10014. (when (and tags org-use-tag-inheritance
  10015. (or (not (eq t org-use-tag-inheritance))
  10016. org-tags-exclude-from-inheritance))
  10017. ;; Selective inheritance, remove uninherited ones.
  10018. (setcdr (car tags-alist)
  10019. (org-remove-uninherited-tags (cdar tags-alist))))
  10020. (when (and
  10021. ;; eval matcher only when the todo condition is OK
  10022. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10023. (if (functionp matcher)
  10024. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10025. (funcall matcher todo tags-list level))
  10026. matcher))
  10027. ;; Call the skipper, but return t if it does not
  10028. ;; skip, so that the `and' form continues evaluating.
  10029. (progn
  10030. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10031. t)
  10032. ;; Check if timestamps are deselecting this entry
  10033. (or (not todo-only)
  10034. (and (member todo org-todo-keywords-1)
  10035. (or (not org-agenda-tags-todo-honor-ignore-options)
  10036. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10037. ;; select this headline
  10038. (cond
  10039. ((eq action 'sparse-tree)
  10040. (and org-highlight-sparse-tree-matches
  10041. (org-get-heading) (match-end 0)
  10042. (org-highlight-new-match
  10043. (match-beginning 1) (match-end 1)))
  10044. (org-fold-show-context 'tags-tree))
  10045. ((eq action 'agenda)
  10046. (setq txt (org-agenda-format-item
  10047. ""
  10048. (concat
  10049. (if (eq org-tags-match-list-sublevels 'indented)
  10050. (make-string (1- level) ?.) "")
  10051. (org-get-heading))
  10052. (make-string level ?\s)
  10053. category
  10054. tags-list)
  10055. priority (org-get-priority txt))
  10056. (goto-char lspos)
  10057. (setq marker (org-agenda-new-marker))
  10058. (org-add-props txt props
  10059. 'org-marker marker 'org-hd-marker marker 'org-category category
  10060. 'todo-state todo
  10061. 'ts-date ts-date
  10062. 'priority priority
  10063. 'type (concat "tagsmatch" ts-date-type))
  10064. (push txt rtn))
  10065. ((functionp action)
  10066. (setq org-map-continue-from nil)
  10067. (save-excursion
  10068. (setq rtn1 (funcall action))
  10069. (push rtn1 rtn)))
  10070. (t (user-error "Invalid action")))
  10071. ;; if we are to skip sublevels, jump to end of subtree
  10072. (unless org-tags-match-list-sublevels
  10073. (org-end-of-subtree t)
  10074. (backward-char 1))))
  10075. ;; Get the correct position from where to continue
  10076. (if org-map-continue-from
  10077. (goto-char org-map-continue-from)
  10078. (and (= (point) lspos) (end-of-line 1))))))
  10079. (when (and (eq action 'sparse-tree)
  10080. (not org-sparse-tree-open-archived-trees))
  10081. (org-fold-hide-archived-subtrees (point-min) (point-max)))
  10082. (nreverse rtn)))
  10083. (defun org-remove-uninherited-tags (tags)
  10084. "Remove all tags that are not inherited from the list TAGS."
  10085. (cond
  10086. ((eq org-use-tag-inheritance t)
  10087. (if org-tags-exclude-from-inheritance
  10088. (org-delete-all org-tags-exclude-from-inheritance tags)
  10089. tags))
  10090. ((not org-use-tag-inheritance) nil)
  10091. ((stringp org-use-tag-inheritance)
  10092. (delq nil (mapcar
  10093. (lambda (x)
  10094. (if (and (string-match org-use-tag-inheritance x)
  10095. (not (member x org-tags-exclude-from-inheritance)))
  10096. x nil))
  10097. tags)))
  10098. ((listp org-use-tag-inheritance)
  10099. (delq nil (mapcar
  10100. (lambda (x)
  10101. (if (member x org-use-tag-inheritance) x nil))
  10102. tags)))))
  10103. (defun org-match-sparse-tree (&optional todo-only match)
  10104. "Create a sparse tree according to tags string MATCH.
  10105. MATCH is a string with match syntax. It can contain a selection
  10106. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10107. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10108. those. See the manual for details.
  10109. If optional argument TODO-ONLY is non-nil, only select lines that
  10110. are also TODO tasks."
  10111. (interactive "P")
  10112. (org-agenda-prepare-buffers (list (current-buffer)))
  10113. (let ((org--matcher-tags-todo-only todo-only))
  10114. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match t))
  10115. org--matcher-tags-todo-only)))
  10116. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10117. (defvar org-cached-props nil)
  10118. (defun org-cached-entry-get (pom property)
  10119. (if (or (eq t org-use-property-inheritance)
  10120. (and (stringp org-use-property-inheritance)
  10121. (let ((case-fold-search t))
  10122. (string-match-p org-use-property-inheritance property)))
  10123. (and (listp org-use-property-inheritance)
  10124. (member-ignore-case property org-use-property-inheritance)))
  10125. ;; Caching is not possible, check it directly.
  10126. (org-entry-get pom property 'inherit)
  10127. ;; Get all properties, so we can do complicated checks easily.
  10128. (cdr (assoc-string property
  10129. (or org-cached-props
  10130. (setq org-cached-props (org-entry-properties pom)))
  10131. t))))
  10132. (defun org-global-tags-completion-table (&optional files)
  10133. "Return the list of all tags in all agenda buffer/files.
  10134. Optional FILES argument is a list of files which can be used
  10135. instead of the agenda files."
  10136. (save-excursion
  10137. (org-uniquify
  10138. (delq nil
  10139. (apply #'append
  10140. (mapcar
  10141. (lambda (file)
  10142. (set-buffer (find-file-noselect file))
  10143. (org--tag-add-to-alist
  10144. (org-get-buffer-tags)
  10145. (mapcar (lambda (x)
  10146. (and (stringp (car-safe x))
  10147. (list (car-safe x))))
  10148. org-current-tag-alist)))
  10149. (if (car-safe files) files
  10150. (org-agenda-files))))))))
  10151. (defun org-make-tags-matcher (match &optional only-local-tags)
  10152. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10153. Returns a cons of the selection string MATCH and a function
  10154. implementing the matcher.
  10155. The matcher is to be called at an Org entry, with point on the
  10156. headline, and returns non-nil if the entry matches the selection
  10157. string MATCH. It must be called with three arguments: the TODO
  10158. keyword at the entry (or nil if none), the list of all tags at
  10159. the entry including inherited ones and the reduced level of the
  10160. headline. Additionally, the category of the entry, if any, must
  10161. be specified as the text property `org-category' on the headline.
  10162. This function sets the variable `org--matcher-tags-todo-only' to
  10163. a non-nil value if the matcher restricts matching to TODO
  10164. entries, otherwise it is not touched.
  10165. When ONLY-LOCAL-TAGS is non-nil, ignore the global tag completion
  10166. table, only get buffer tags.
  10167. See also `org-scan-tags'."
  10168. (unless match
  10169. ;; Get a new match request, with completion against the global
  10170. ;; tags table and the local tags in current buffer.
  10171. (let ((org-last-tags-completion-table
  10172. (org--tag-add-to-alist
  10173. (org-get-buffer-tags)
  10174. (unless only-local-tags
  10175. (org-global-tags-completion-table)))))
  10176. (setq match
  10177. (completing-read
  10178. "Match: "
  10179. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10180. (let ((match0 match)
  10181. (re (concat
  10182. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10183. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10184. "\\([<>=]\\{1,2\\}\\)"
  10185. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10186. "\\|" org-tag-re "\\)"))
  10187. (start 0)
  10188. tagsmatch todomatch tagsmatcher todomatcher)
  10189. ;; Expand group tags.
  10190. (setq match (org-tags-expand match))
  10191. ;; Check if there is a TODO part of this match, which would be the
  10192. ;; part after a "/". To make sure that this slash is not part of
  10193. ;; a property value to be matched against, we also check that
  10194. ;; there is no / after that slash. First, find the last slash.
  10195. (let ((s 0))
  10196. (while (string-match "/+" match s)
  10197. (setq start (match-beginning 0))
  10198. (setq s (match-end 0))))
  10199. (if (and (string-match "/+" match start)
  10200. (not (string-match-p "\"" match start)))
  10201. ;; Match contains also a TODO-matching request.
  10202. (progn
  10203. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10204. (setq todomatch (substring match (match-end 0)))
  10205. (when (string-prefix-p "!" todomatch)
  10206. (setq org--matcher-tags-todo-only t)
  10207. (setq todomatch (substring todomatch 1)))
  10208. (when (string-match "\\`\\s-*\\'" todomatch)
  10209. (setq todomatch nil)))
  10210. ;; Only matching tags.
  10211. (setq tagsmatch match)
  10212. (setq todomatch nil))
  10213. ;; Make the tags matcher.
  10214. (when (org-string-nw-p tagsmatch)
  10215. (let ((orlist nil)
  10216. (orterms (org-split-string tagsmatch "|"))
  10217. term)
  10218. (while (setq term (pop orterms))
  10219. (while (and (equal (substring term -1) "\\") orterms)
  10220. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10221. (while (string-match re term)
  10222. (let* ((rest (substring term (match-end 0)))
  10223. (minus (and (match-end 1)
  10224. (equal (match-string 1 term) "-")))
  10225. (tag (save-match-data
  10226. (replace-regexp-in-string
  10227. "\\\\-" "-" (match-string 2 term))))
  10228. (regexp (eq (string-to-char tag) ?{))
  10229. (levelp (match-end 4))
  10230. (propp (match-end 5))
  10231. (mm
  10232. (cond
  10233. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10234. (levelp
  10235. `(,(org-op-to-function (match-string 3 term))
  10236. level
  10237. ,(string-to-number (match-string 4 term))))
  10238. (propp
  10239. (let* ((gv (pcase (upcase (match-string 5 term))
  10240. ("CATEGORY"
  10241. '(org-get-category (point)))
  10242. ("TODO" 'todo)
  10243. (p `(org-cached-entry-get nil ,p))))
  10244. (pv (match-string 7 term))
  10245. (regexp (eq (string-to-char pv) ?{))
  10246. (strp (eq (string-to-char pv) ?\"))
  10247. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10248. (po (org-op-to-function (match-string 6 term)
  10249. (if timep 'time strp))))
  10250. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10251. (when timep (setq pv (org-matcher-time pv)))
  10252. (cond ((and regexp (eq po '/=))
  10253. `(not (string-match ,pv (or ,gv ""))))
  10254. (regexp `(string-match ,pv (or ,gv "")))
  10255. (strp `(,po (or ,gv "") ,pv))
  10256. (t
  10257. `(,po
  10258. (string-to-number (or ,gv ""))
  10259. ,(string-to-number pv))))))
  10260. (t `(member ,tag tags-list)))))
  10261. (push (if minus `(not ,mm) mm) tagsmatcher)
  10262. (setq term rest)))
  10263. (push `(and ,@tagsmatcher) orlist)
  10264. (setq tagsmatcher nil))
  10265. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10266. ;; Make the TODO matcher.
  10267. (when (org-string-nw-p todomatch)
  10268. (let ((orlist nil))
  10269. (dolist (term (org-split-string todomatch "|"))
  10270. (while (string-match re term)
  10271. (let* ((minus (and (match-end 1)
  10272. (equal (match-string 1 term) "-")))
  10273. (kwd (match-string 2 term))
  10274. (regexp (eq (string-to-char kwd) ?{))
  10275. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10276. `(equal todo ,kwd))))
  10277. (push (if minus `(not ,mm) mm) todomatcher))
  10278. (setq term (substring term (match-end 0))))
  10279. (push (if (> (length todomatcher) 1)
  10280. (cons 'and todomatcher)
  10281. (car todomatcher))
  10282. orlist)
  10283. (setq todomatcher nil))
  10284. (setq todomatcher (cons 'or orlist))))
  10285. ;; Return the string and function of the matcher. If no
  10286. ;; tags-specific or todo-specific matcher exists, match
  10287. ;; everything.
  10288. (let ((matcher (if (and tagsmatcher todomatcher)
  10289. `(and ,tagsmatcher ,todomatcher)
  10290. (or tagsmatcher todomatcher t))))
  10291. (when org--matcher-tags-todo-only
  10292. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10293. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10294. (defun org--tags-expand-group (group tag-groups expanded)
  10295. "Recursively expand all tags in GROUP, according to TAG-GROUPS.
  10296. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10297. an accumulator used in recursive calls."
  10298. (dolist (tag group)
  10299. (unless (member tag expanded)
  10300. (let ((group (assoc tag tag-groups)))
  10301. (push tag expanded)
  10302. (when group
  10303. (setq expanded
  10304. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10305. expanded)
  10306. (defun org-tags-expand (match &optional single-as-list)
  10307. "Expand group tags in MATCH.
  10308. This replaces every group tag in MATCH with a regexp tag search.
  10309. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10310. will be replaced like this:
  10311. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10312. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10313. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10314. Replacing by a regexp preserves the structure of the match.
  10315. E.g., this expansion
  10316. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10317. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10318. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10319. A group tag in MATCH can contain regular expressions of its own.
  10320. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10321. will be replaced like this:
  10322. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10323. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10324. assumed to be a single group tag, and the function will return
  10325. the list of tags in this group."
  10326. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10327. (let ((tag-groups
  10328. (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10329. (cond
  10330. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  10331. (org-group-tags
  10332. (let* ((case-fold-search t)
  10333. (tag-syntax org-mode-syntax-table)
  10334. (group-keys (mapcar #'car tag-groups))
  10335. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  10336. (return-match match))
  10337. ;; Mark regexp-expressions in the match-expression so that we
  10338. ;; do not replace them later on.
  10339. (let ((s 0))
  10340. (while (string-match "{.+?}" return-match s)
  10341. (setq s (match-end 0))
  10342. (add-text-properties
  10343. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  10344. ;; @ and _ are allowed as word-components in tags.
  10345. (modify-syntax-entry ?@ "w" tag-syntax)
  10346. (modify-syntax-entry ?_ "w" tag-syntax)
  10347. ;; For each tag token found in MATCH, compute a regexp and it
  10348. (with-syntax-table tag-syntax
  10349. (replace-regexp-in-string
  10350. key-regexp
  10351. (lambda (m)
  10352. (if (get-text-property (match-beginning 2) 'regexp m)
  10353. m ;regexp tag: ignore
  10354. (let* ((operator (match-string 1 m))
  10355. (tag-token (let ((tag (match-string 2 m)))
  10356. (list tag)))
  10357. regexp-tags regular-tags)
  10358. ;; Partition tags between regexp and regular tags.
  10359. ;; Remove curly bracket syntax from regexp tags.
  10360. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  10361. (save-match-data
  10362. (if (string-match "{\\(.+?\\)}" tag)
  10363. (push (match-string 1 tag) regexp-tags)
  10364. (push tag regular-tags))))
  10365. ;; Replace tag token by the appropriate regexp.
  10366. ;; Regular tags need to be regexp-quoted, whereas
  10367. ;; regexp-tags are inserted as-is.
  10368. (let ((regular (regexp-opt regular-tags))
  10369. (regexp (mapconcat #'identity regexp-tags "\\|")))
  10370. (concat operator
  10371. (cond
  10372. ((null regular-tags) (format "{%s}" regexp))
  10373. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  10374. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  10375. return-match
  10376. t t))))
  10377. (t match))))
  10378. (defun org-op-to-function (op &optional stringp)
  10379. "Turn an operator into the appropriate function."
  10380. (setq op
  10381. (cond
  10382. ((equal op "<" ) '(< org-string< org-time<))
  10383. ((equal op ">" ) '(> org-string> org-time>))
  10384. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  10385. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  10386. ((member op '("=" "==")) '(= string= org-time=))
  10387. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  10388. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  10389. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  10390. (defvar org-tags-overlay (make-overlay 1 1))
  10391. (delete-overlay org-tags-overlay)
  10392. (defun org-add-prop-inherited (s)
  10393. (add-text-properties 0 (length s) '(inherited t) s)
  10394. s)
  10395. (defun org-toggle-tag (tag &optional onoff)
  10396. "Toggle the tag TAG for the current line.
  10397. If ONOFF is `on' or `off', don't toggle but set to this state."
  10398. (save-excursion
  10399. (org-back-to-heading t)
  10400. (let ((current
  10401. ;; Reverse the tags list so any new tag is appended to the
  10402. ;; current list of tags.
  10403. (nreverse (org-get-tags nil t)))
  10404. res)
  10405. (pcase onoff
  10406. (`off (setq current (delete tag current)))
  10407. ((or `on (guard (not (member tag current))))
  10408. (setq res t)
  10409. (cl-pushnew tag current :test #'equal))
  10410. (_ (setq current (delete tag current))))
  10411. (org-set-tags (nreverse current))
  10412. res)))
  10413. (defun org--align-tags-here (to-col)
  10414. "Align tags on the current headline to TO-COL.
  10415. Assume point is on a headline. Preserve point when aligning
  10416. tags."
  10417. (when (org-match-line org-tag-line-re)
  10418. (let* ((tags-start (match-beginning 1))
  10419. (blank-start (save-excursion
  10420. (goto-char tags-start)
  10421. (skip-chars-backward " \t")
  10422. (point)))
  10423. (new (max (if (>= to-col 0) to-col
  10424. (- (abs to-col) (string-width (match-string 1))))
  10425. ;; Introduce at least one space after the heading
  10426. ;; or the stars.
  10427. (save-excursion
  10428. (goto-char blank-start)
  10429. (1+ (current-column)))))
  10430. (current
  10431. (save-excursion (goto-char tags-start) (current-column)))
  10432. (origin (point-marker))
  10433. (column (current-column))
  10434. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  10435. (when (/= new current)
  10436. (delete-region blank-start tags-start)
  10437. (goto-char blank-start)
  10438. (let ((indent-tabs-mode nil)) (indent-to new))
  10439. ;; Try to move back to original position. If point was in the
  10440. ;; blanks before the tags, ORIGIN marker is of no use because
  10441. ;; it now points to BLANK-START. Use COLUMN instead.
  10442. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  10443. (defun org-set-tags-command (&optional arg)
  10444. "Set the tags for the current visible entry.
  10445. When called with `\\[universal-argument]' prefix argument ARG, \
  10446. realign all tags
  10447. in the current buffer.
  10448. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  10449. unconditionally do not
  10450. offer the fast tag selection interface.
  10451. If a region is active, set tags in the region according to the
  10452. setting of `org-loop-over-headlines-in-active-region'.
  10453. This function is for interactive use only;
  10454. in Lisp code use `org-set-tags' instead."
  10455. (interactive "P")
  10456. (let ((org-use-fast-tag-selection
  10457. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  10458. (cond
  10459. ((equal '(4) arg) (org-align-tags t))
  10460. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10461. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  10462. (org-map-entries
  10463. #'org-set-tags-command
  10464. nil
  10465. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10466. 'region-start-level
  10467. 'region)
  10468. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  10469. (t
  10470. (save-excursion
  10471. (org-back-to-heading)
  10472. (let* ((all-tags (org-get-tags))
  10473. (local-table (or org-current-tag-alist (org-get-buffer-tags)))
  10474. (table (setq org-last-tags-completion-table
  10475. (append
  10476. ;; Put local tags in front.
  10477. local-table
  10478. (cl-set-difference
  10479. (org--tag-add-to-alist
  10480. (and org-complete-tags-always-offer-all-agenda-tags
  10481. (org-global-tags-completion-table
  10482. (org-agenda-files)))
  10483. local-table)
  10484. local-table))))
  10485. (current-tags
  10486. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  10487. all-tags))
  10488. (inherited-tags
  10489. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  10490. all-tags))
  10491. (tags
  10492. (replace-regexp-in-string
  10493. ;; Ignore all forbidden characters in tags.
  10494. "[^[:alnum:]_@#%]+" ":"
  10495. (if (or (eq t org-use-fast-tag-selection)
  10496. (and org-use-fast-tag-selection
  10497. (delq nil (mapcar #'cdr table))))
  10498. (org-fast-tag-selection
  10499. current-tags
  10500. inherited-tags
  10501. table
  10502. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  10503. (let ((org-add-colon-after-tag-completion (< 1 (length table)))
  10504. (crm-separator "[ \t]*:[ \t]*"))
  10505. (mapconcat #'identity
  10506. (completing-read-multiple
  10507. "Tags: "
  10508. org-last-tags-completion-table
  10509. nil nil (org-make-tag-string current-tags)
  10510. 'org-tags-history)
  10511. ":"))))))
  10512. (org-set-tags tags)))))
  10513. ;; `save-excursion' may not replace the point at the right
  10514. ;; position.
  10515. (when (and (save-excursion (skip-chars-backward "*") (bolp))
  10516. (looking-at-p " "))
  10517. (forward-char))))
  10518. (defun org-align-tags (&optional all)
  10519. "Align tags in current entry.
  10520. When optional argument ALL is non-nil, align all tags in the
  10521. visible part of the buffer."
  10522. (let ((get-indent-column
  10523. (lambda ()
  10524. (let ((offset (if (bound-and-true-p org-indent-mode)
  10525. (save-excursion
  10526. (org-back-to-heading-or-point-min)
  10527. (length
  10528. (get-text-property
  10529. (line-end-position)
  10530. 'line-prefix)))
  10531. 0)))
  10532. (+ org-tags-column
  10533. (if (> org-tags-column 0) (- offset) offset))))))
  10534. (if (and (not all) (org-at-heading-p))
  10535. (org--align-tags-here (funcall get-indent-column))
  10536. (save-excursion
  10537. (if all
  10538. (progn
  10539. (goto-char (point-min))
  10540. (while (re-search-forward org-tag-line-re nil t)
  10541. (org--align-tags-here (funcall get-indent-column))))
  10542. (org-back-to-heading t)
  10543. (org--align-tags-here (funcall get-indent-column)))))))
  10544. (defun org-set-tags (tags)
  10545. "Set the tags of the current entry to TAGS, replacing current tags.
  10546. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  10547. If TAGS is nil or the empty string, all tags are removed.
  10548. This function assumes point is on a headline."
  10549. (org-with-wide-buffer
  10550. (org-fold-core-ignore-modifications
  10551. (let ((tags (pcase tags
  10552. ((pred listp) tags)
  10553. ((pred stringp) (split-string (org-trim tags) ":" t))
  10554. (_ (error "Invalid tag specification: %S" tags))))
  10555. (old-tags (org-get-tags nil t))
  10556. (tags-change? nil))
  10557. (when (functionp org-tags-sort-function)
  10558. (setq tags (sort tags org-tags-sort-function)))
  10559. (setq tags-change? (not (equal tags old-tags)))
  10560. (when tags-change?
  10561. ;; Delete previous tags and any trailing white space.
  10562. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  10563. (line-end-position)))
  10564. (skip-chars-backward " \t")
  10565. (delete-region (point) (line-end-position))
  10566. ;; Deleting white spaces may break an otherwise empty headline.
  10567. ;; Re-introduce one space in this case.
  10568. (unless (org-at-heading-p) (insert " "))
  10569. (when tags
  10570. (save-excursion (insert-and-inherit " " (org-make-tag-string tags)))
  10571. ;; When text is being inserted on an invisible region
  10572. ;; boundary, it can be inadvertently sucked into
  10573. ;; invisibility.
  10574. (unless (org-invisible-p (line-beginning-position))
  10575. (org-fold-region (point) (line-end-position) nil 'outline))))
  10576. ;; Align tags, if any.
  10577. (when tags (org-align-tags))
  10578. (when tags-change? (run-hooks 'org-after-tags-change-hook))))))
  10579. (defun org-change-tag-in-region (beg end tag off)
  10580. "Add or remove TAG for each entry in the region.
  10581. This works in the agenda, and also in an Org buffer."
  10582. (interactive
  10583. (list (region-beginning) (region-end)
  10584. (let ((org-last-tags-completion-table
  10585. (if (derived-mode-p 'org-mode)
  10586. (org--tag-add-to-alist
  10587. (org-get-buffer-tags)
  10588. (org-global-tags-completion-table))
  10589. (org-global-tags-completion-table))))
  10590. (completing-read
  10591. "Tag: " org-last-tags-completion-table nil nil nil
  10592. 'org-tags-history))
  10593. (progn
  10594. (message "[s]et or [r]emove? ")
  10595. (equal (read-char-exclusive) ?r))))
  10596. (deactivate-mark)
  10597. (let ((agendap (equal major-mode 'org-agenda-mode))
  10598. l1 l2 m buf pos newhead (cnt 0))
  10599. (goto-char end)
  10600. (setq l2 (1- (org-current-line)))
  10601. (goto-char beg)
  10602. (setq l1 (org-current-line))
  10603. (cl-loop for l from l1 to l2 do
  10604. (org-goto-line l)
  10605. (setq m (get-text-property (point) 'org-hd-marker))
  10606. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  10607. (and agendap m))
  10608. (setq buf (if agendap (marker-buffer m) (current-buffer))
  10609. pos (if agendap m (point)))
  10610. (with-current-buffer buf
  10611. (save-excursion
  10612. (save-restriction
  10613. (goto-char pos)
  10614. (setq cnt (1+ cnt))
  10615. (org-toggle-tag tag (if off 'off 'on))
  10616. (setq newhead (org-get-heading)))))
  10617. (and agendap (org-agenda-change-all-lines newhead m))))
  10618. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  10619. (defun org-tags-completion-function (string _predicate &optional flag)
  10620. "Complete tag STRING.
  10621. FLAG specifies the type of completion operation to perform. This
  10622. function is passed as a collection function to `completing-read',
  10623. which see."
  10624. (let ((completion-ignore-case nil) ;tags are case-sensitive
  10625. (confirm (lambda (x) (stringp (car x))))
  10626. (prefix ""))
  10627. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  10628. (setq prefix (match-string 1 string))
  10629. (setq string (match-string 2 string)))
  10630. (pcase flag
  10631. (`t (all-completions string org-last-tags-completion-table confirm))
  10632. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  10633. (`nil
  10634. (pcase (try-completion string org-last-tags-completion-table confirm)
  10635. ((and completion (pred stringp))
  10636. (concat prefix
  10637. completion
  10638. (if (and org-add-colon-after-tag-completion
  10639. (assoc completion org-last-tags-completion-table))
  10640. ":"
  10641. "")))
  10642. (completion completion)))
  10643. (_ nil))))
  10644. (defun org-fast-tag-insert (kwd tags face &optional end)
  10645. "Insert KWD, and the TAGS, the latter with face FACE.
  10646. Also insert END."
  10647. (insert (format "%-12s" (concat kwd ":"))
  10648. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  10649. (or end "")))
  10650. (defun org-fast-tag-show-exit (flag)
  10651. (save-excursion
  10652. (org-goto-line 3)
  10653. (when (re-search-forward "[ \t]+Next change exits" (line-end-position) t)
  10654. (replace-match ""))
  10655. (when flag
  10656. (end-of-line 1)
  10657. (org-move-to-column (- (window-width) 19) t)
  10658. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  10659. (defun org-set-current-tags-overlay (current prefix)
  10660. "Add an overlay to CURRENT tag with PREFIX."
  10661. (let ((s (org-make-tag-string current)))
  10662. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  10663. (org-overlay-display org-tags-overlay (concat prefix s))))
  10664. (defvar org-last-tag-selection-key nil)
  10665. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  10666. "Fast tag selection with single keys.
  10667. CURRENT is the current list of tags in the headline, INHERITED is the
  10668. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  10669. possibly with grouping information. TODO-TABLE is a similar table with
  10670. TODO keywords, should these have keys assigned to them.
  10671. If the keys are nil, a-z are automatically assigned.
  10672. Returns the new tags string, or nil to not change the current settings."
  10673. (let* ((fulltable (append table todo-table))
  10674. (maxlen (if (null fulltable) 0
  10675. (apply #'max
  10676. (mapcar (lambda (x)
  10677. (if (stringp (car x)) (string-width (car x))
  10678. 0))
  10679. fulltable))))
  10680. (buf (current-buffer))
  10681. (expert (eq org-fast-tag-selection-single-key 'expert))
  10682. (tab-tags nil)
  10683. (fwidth (+ maxlen 3 1 3))
  10684. (ncol (/ (- (window-width) 4) fwidth))
  10685. (i-face 'org-done)
  10686. (c-face 'org-todo)
  10687. tg cnt e c char c1 c2 ntable tbl rtn
  10688. ov-start ov-end ov-prefix
  10689. (exit-after-next org-fast-tag-selection-single-key)
  10690. (done-keywords org-done-keywords)
  10691. groups ingroup intaggroup)
  10692. (save-excursion
  10693. (beginning-of-line)
  10694. (if (looking-at org-tag-line-re)
  10695. (setq ov-start (match-beginning 1)
  10696. ov-end (match-end 1)
  10697. ov-prefix "")
  10698. (setq ov-start (1- (line-end-position))
  10699. ov-end (1+ ov-start))
  10700. (skip-chars-forward "^\n\r")
  10701. (setq ov-prefix
  10702. (concat
  10703. (buffer-substring (1- (point)) (point))
  10704. (if (> (current-column) org-tags-column)
  10705. " "
  10706. (make-string (- org-tags-column (current-column)) ?\ ))))))
  10707. (move-overlay org-tags-overlay ov-start ov-end)
  10708. (save-excursion
  10709. (save-window-excursion
  10710. (if expert
  10711. (set-buffer (get-buffer-create " *Org tags*"))
  10712. (delete-other-windows)
  10713. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  10714. (org-switch-to-buffer-other-window " *Org tags*"))
  10715. (erase-buffer)
  10716. (setq-local org-done-keywords done-keywords)
  10717. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  10718. (org-fast-tag-insert "Current" current c-face "\n\n")
  10719. (org-fast-tag-show-exit exit-after-next)
  10720. (org-set-current-tags-overlay current ov-prefix)
  10721. (setq tbl fulltable char ?a cnt 0)
  10722. (while (setq e (pop tbl))
  10723. (cond
  10724. ((eq (car e) :startgroup)
  10725. (push '() groups) (setq ingroup t)
  10726. (unless (zerop cnt)
  10727. (setq cnt 0)
  10728. (insert "\n"))
  10729. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  10730. ((eq (car e) :endgroup)
  10731. (setq ingroup nil cnt 0)
  10732. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  10733. ((eq (car e) :startgrouptag)
  10734. (setq intaggroup t)
  10735. (unless (zerop cnt)
  10736. (setq cnt 0)
  10737. (insert "\n"))
  10738. (insert "[ "))
  10739. ((eq (car e) :endgrouptag)
  10740. (setq intaggroup nil cnt 0)
  10741. (insert "]\n"))
  10742. ((equal e '(:newline))
  10743. (unless (zerop cnt)
  10744. (setq cnt 0)
  10745. (insert "\n")
  10746. (setq e (car tbl))
  10747. (while (equal (car tbl) '(:newline))
  10748. (insert "\n")
  10749. (setq tbl (cdr tbl)))))
  10750. ((equal e '(:grouptags))
  10751. (delete-char -3)
  10752. (insert " : "))
  10753. (t
  10754. (setq tg (copy-sequence (car e)) c2 nil)
  10755. (if (cdr e)
  10756. (setq c (cdr e))
  10757. ;; automatically assign a character.
  10758. (setq c1 (string-to-char
  10759. (downcase (substring
  10760. tg (if (= (string-to-char tg) ?@) 1 0)))))
  10761. (if (or (rassoc c1 ntable) (rassoc c1 table))
  10762. (while (or (rassoc char ntable) (rassoc char table))
  10763. (setq char (1+ char)))
  10764. (setq c2 c1))
  10765. (setq c (or c2
  10766. (if (> char ?~)
  10767. ?\s
  10768. char)))
  10769. ;; Consider characters A-Z after a-z.
  10770. (if (equal char ?z)
  10771. (setq char ?A)))
  10772. (when ingroup (push tg (car groups)))
  10773. (setq tg (org-add-props tg nil 'face
  10774. (cond
  10775. ((not (assoc tg table))
  10776. (org-get-todo-face tg))
  10777. ((member tg current) c-face)
  10778. ((member tg inherited) i-face))))
  10779. (when (equal (caar tbl) :grouptags)
  10780. (org-add-props tg nil 'face 'org-tag-group))
  10781. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  10782. (insert "[" c "] " tg (make-string
  10783. (- fwidth 4 (length tg)) ?\ ))
  10784. (push (cons tg c) ntable)
  10785. (when (= (cl-incf cnt) ncol)
  10786. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  10787. (insert "\n")
  10788. (when (or ingroup intaggroup) (insert " ")))
  10789. (setq cnt 0)))))
  10790. (setq ntable (nreverse ntable))
  10791. (insert "\n")
  10792. (goto-char (point-min))
  10793. (unless expert (org-fit-window-to-buffer))
  10794. (setq rtn
  10795. (catch 'exit
  10796. (while t
  10797. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  10798. (if (not groups) "no " "")
  10799. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  10800. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  10801. (setq org-last-tag-selection-key c)
  10802. (cond
  10803. ((= c ?\r) (throw 'exit t))
  10804. ((= c ?!)
  10805. (setq groups (not groups))
  10806. (goto-char (point-min))
  10807. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  10808. ((= c ?\C-c)
  10809. (if (not expert)
  10810. (org-fast-tag-show-exit
  10811. (setq exit-after-next (not exit-after-next)))
  10812. (setq expert nil)
  10813. (delete-other-windows)
  10814. (set-window-buffer (split-window-vertically) " *Org tags*")
  10815. (org-switch-to-buffer-other-window " *Org tags*")
  10816. (org-fit-window-to-buffer)))
  10817. ((or (= c ?\C-g)
  10818. (and (= c ?q) (not (rassoc c ntable))))
  10819. (delete-overlay org-tags-overlay)
  10820. (setq quit-flag t))
  10821. ((= c ?\ )
  10822. (setq current nil)
  10823. (when exit-after-next (setq exit-after-next 'now)))
  10824. ((= c ?\t)
  10825. (condition-case nil
  10826. (unless tab-tags
  10827. (setq tab-tags
  10828. (delq nil
  10829. (mapcar (lambda (x)
  10830. (let ((item (car-safe x)))
  10831. (and (stringp item)
  10832. (list item))))
  10833. (org--tag-add-to-alist
  10834. (with-current-buffer buf
  10835. (org-get-buffer-tags))
  10836. table))))))
  10837. (setq tg (completing-read "Tag: " tab-tags))
  10838. (when (string-match "\\S-" tg)
  10839. (cl-pushnew (list tg) tab-tags :test #'equal)
  10840. (if (member tg current)
  10841. (setq current (delete tg current))
  10842. (push tg current)))
  10843. (when exit-after-next (setq exit-after-next 'now)))
  10844. ((setq e (rassoc c todo-table) tg (car e))
  10845. (with-current-buffer buf
  10846. (save-excursion (org-todo tg)))
  10847. (when exit-after-next (setq exit-after-next 'now)))
  10848. ((setq e (rassoc c ntable) tg (car e))
  10849. (if (member tg current)
  10850. (setq current (delete tg current))
  10851. (cl-loop for g in groups do
  10852. (when (member tg g)
  10853. (dolist (x g) (setq current (delete x current)))))
  10854. (push tg current))
  10855. (when exit-after-next (setq exit-after-next 'now))))
  10856. ;; Create a sorted list
  10857. (setq current
  10858. (sort current
  10859. (lambda (a b)
  10860. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  10861. (when (eq exit-after-next 'now) (throw 'exit t))
  10862. (goto-char (point-min))
  10863. (beginning-of-line 2)
  10864. (delete-region (point) (line-end-position))
  10865. (org-fast-tag-insert "Current" current c-face)
  10866. (org-set-current-tags-overlay current ov-prefix)
  10867. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  10868. (while (re-search-forward tag-re nil t)
  10869. (let ((tag (match-string 1)))
  10870. (add-text-properties
  10871. (match-beginning 1) (match-end 1)
  10872. (list 'face
  10873. (cond
  10874. ((member tag current) c-face)
  10875. ((member tag inherited) i-face)
  10876. (t 'default)))))))
  10877. (goto-char (point-min)))))
  10878. (delete-overlay org-tags-overlay)
  10879. (if rtn
  10880. (mapconcat 'identity current ":")
  10881. nil)))))
  10882. (defun org-make-tag-string (tags)
  10883. "Return string associated to TAGS.
  10884. TAGS is a list of strings."
  10885. (if (null tags) ""
  10886. (format ":%s:" (mapconcat #'identity tags ":"))))
  10887. (defun org--get-local-tags ()
  10888. "Return list of tags for the current headline.
  10889. Assume point is at the beginning of the headline."
  10890. (let* ((cached (and (org-element--cache-active-p) (org-element-at-point nil 'cached)))
  10891. (cached-tags (org-element-property :tags cached)))
  10892. (if cached
  10893. ;; If we do not explicitly copy the result, reference would
  10894. ;; be returned and cache element might be modified directly.
  10895. (mapcar #'copy-sequence cached-tags)
  10896. ;; Parse tags manually.
  10897. (and (looking-at org-tag-line-re)
  10898. (split-string (match-string-no-properties 2) ":" t)))))
  10899. (defun org-get-tags (&optional pos-or-element local)
  10900. "Get the list of tags specified in the current headline.
  10901. When argument POS-OR-ELEMENT is non-nil, retrieve tags for headline at
  10902. POS.
  10903. According to `org-use-tag-inheritance', tags may be inherited
  10904. from parent headlines, and from the whole document, through
  10905. `org-file-tags'. In this case, the returned list of tags
  10906. contains tags in this order: file tags, tags inherited from
  10907. parent headlines, local tags. If a tag appears multiple times,
  10908. only the most local tag is returned.
  10909. However, when optional argument LOCAL is non-nil, only return
  10910. tags specified at the headline.
  10911. Inherited tags have the `inherited' text property."
  10912. (save-match-data
  10913. (if (and org-trust-scanner-tags
  10914. (or (not pos-or-element) (eq pos-or-element (point)))
  10915. (not local))
  10916. org-scanner-tags
  10917. (org-with-point-at (unless (org-element-type pos-or-element)
  10918. (or pos-or-element (point)))
  10919. (unless (or (org-element-type pos-or-element)
  10920. (org-before-first-heading-p))
  10921. (org-back-to-heading t))
  10922. (let ((ltags (if (org-element-type pos-or-element)
  10923. (org-element-property :tags (org-element-lineage pos-or-element '(headline inlinetask) t))
  10924. (org--get-local-tags)))
  10925. itags)
  10926. (if (or local (not org-use-tag-inheritance)) ltags
  10927. (let ((cached (and (org-element--cache-active-p)
  10928. (if (org-element-type pos-or-element)
  10929. (org-element-lineage pos-or-element '(headline org-data inlinetask) t)
  10930. (org-element-at-point nil 'cached)))))
  10931. (if cached
  10932. (while (setq cached (org-element-property :parent cached))
  10933. (setq itags (nconc (mapcar #'org-add-prop-inherited
  10934. ;; If we do explicitly copy the result, reference would
  10935. ;; be returned and cache element might be modified directly.
  10936. (mapcar #'copy-sequence (org-element-property :tags cached)))
  10937. itags)))
  10938. (while (org-up-heading-safe)
  10939. (setq itags (nconc (mapcar #'org-add-prop-inherited
  10940. (org--get-local-tags))
  10941. itags)))))
  10942. (setq itags (append org-file-tags itags))
  10943. (nreverse
  10944. (delete-dups
  10945. (nreverse (nconc (org-remove-uninherited-tags itags) ltags))))))))))
  10946. (defun org-get-buffer-tags ()
  10947. "Get a table of all tags used in the buffer, for completion."
  10948. (if (org-element--cache-active-p)
  10949. ;; `org-element-cache-map' is about 2x faster compared to regexp
  10950. ;; search.
  10951. (let ((hashed (make-hash-table :test #'equal)))
  10952. (org-element-cache-map
  10953. (lambda (el)
  10954. (dolist (tag (org-element-property :tags el))
  10955. ;; Do not carry over the text properties. They may look
  10956. ;; ugly in the completion.
  10957. (puthash (list (substring-no-properties tag)) t hashed))))
  10958. (dolist (tag org-file-tags) (puthash (list tag) t hashed))
  10959. (hash-table-keys hashed))
  10960. (org-with-point-at 1
  10961. (let (tags)
  10962. (while (re-search-forward org-tag-line-re nil t)
  10963. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  10964. tags)))
  10965. (mapcar #'list (delete-dups (append org-file-tags tags)))))))
  10966. ;;;; The mapping API
  10967. (defvar org-agenda-skip-comment-trees)
  10968. (defvar org-agenda-skip-function)
  10969. (defun org-map-entries (func &optional match scope &rest skip)
  10970. "Call FUNC at each headline selected by MATCH in SCOPE.
  10971. FUNC is a function or a Lisp form. The function will be called without
  10972. arguments, with the cursor positioned at the beginning of the headline.
  10973. The return values of all calls to the function will be collected and
  10974. returned as a list.
  10975. The call to FUNC will be wrapped into a `save-excursion' form, so FUNC
  10976. does not need to preserve point. After evaluation, the cursor will be
  10977. moved to the end of the line (presumably of the headline of the
  10978. processed entry) and search continues from there. Under some
  10979. circumstances, this may not produce the wanted results. For example,
  10980. if you have removed (e.g. archived) the current (sub)tree it could
  10981. mean that the next entry will be skipped entirely. In such cases, you
  10982. can specify the position from where search should continue by making
  10983. FUNC set the variable `org-map-continue-from' to the desired buffer
  10984. position.
  10985. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  10986. Only headlines that are matched by this query will be considered during
  10987. the iteration. When MATCH is nil or t, all headlines will be
  10988. visited by the iteration.
  10989. SCOPE determines the scope of this command. It can be any of:
  10990. nil The current buffer, respecting the restriction if any
  10991. tree The subtree started with the entry at point
  10992. region The entries within the active region, if any
  10993. region-start-level
  10994. The entries within the active region, but only those at
  10995. the same level than the first one.
  10996. file The current buffer, without restriction
  10997. file-with-archives
  10998. The current buffer, and any archives associated with it
  10999. agenda All agenda files
  11000. agenda-with-archives
  11001. All agenda files with any archive files associated with them
  11002. \(file1 file2 ...)
  11003. If this is a list, all files in the list will be scanned
  11004. The remaining args are treated as settings for the skipping facilities of
  11005. the scanner. The following items can be given here:
  11006. archive skip trees with the archive tag
  11007. comment skip trees with the COMMENT keyword
  11008. function or Emacs Lisp form:
  11009. will be used as value for `org-agenda-skip-function', so
  11010. whenever the function returns a position, FUNC will not be
  11011. called for that entry and search will continue from the
  11012. position returned
  11013. If your function needs to retrieve the tags including inherited tags
  11014. at the *current* entry, you can use the value of the variable
  11015. `org-scanner-tags' which will be much faster than getting the value
  11016. with `org-get-tags'. If your function gets properties with
  11017. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  11018. to t around the call to `org-entry-properties' to get the same speedup.
  11019. Note that if your function moves around to retrieve tags and properties at
  11020. a *different* entry, you cannot use these techniques."
  11021. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  11022. (not (org-region-active-p)))
  11023. (let* ((org-agenda-archives-mode nil) ; just to make sure
  11024. (org-agenda-skip-archived-trees (memq 'archive skip))
  11025. (org-agenda-skip-comment-trees (memq 'comment skip))
  11026. (org-agenda-skip-function
  11027. (car (org-delete-all '(comment archive) skip)))
  11028. (org-tags-match-list-sublevels t)
  11029. (start-level (eq scope 'region-start-level))
  11030. matcher res
  11031. org-todo-keywords-for-agenda
  11032. org-done-keywords-for-agenda
  11033. org-todo-keyword-alist-for-agenda
  11034. org-tag-alist-for-agenda
  11035. org--matcher-tags-todo-only)
  11036. (cond
  11037. ((eq match t) (setq matcher t))
  11038. ((eq match nil) (setq matcher t))
  11039. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  11040. (save-excursion
  11041. (save-restriction
  11042. (cond ((eq scope 'tree)
  11043. (org-back-to-heading t)
  11044. (org-narrow-to-subtree)
  11045. (setq scope nil))
  11046. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11047. (org-region-active-p))
  11048. ;; If needed, set start-level to a string like "2"
  11049. (when start-level
  11050. (save-excursion
  11051. (goto-char (region-beginning))
  11052. (unless (org-at-heading-p) (outline-next-heading))
  11053. (setq start-level (org-current-level))))
  11054. (narrow-to-region (region-beginning)
  11055. (save-excursion
  11056. (goto-char (region-end))
  11057. (unless (and (bolp) (org-at-heading-p))
  11058. (outline-next-heading))
  11059. (point)))
  11060. (setq scope nil)))
  11061. (if (not scope)
  11062. (progn
  11063. (org-agenda-prepare-buffers
  11064. (and buffer-file-name (list buffer-file-name)))
  11065. (setq res
  11066. (org-scan-tags
  11067. func matcher org--matcher-tags-todo-only start-level)))
  11068. ;; Get the right scope
  11069. (cond
  11070. ((and scope (listp scope) (symbolp (car scope)))
  11071. (setq scope (eval scope t)))
  11072. ((eq scope 'agenda)
  11073. (setq scope (org-agenda-files t)))
  11074. ((eq scope 'agenda-with-archives)
  11075. (setq scope (org-agenda-files t))
  11076. (setq scope (org-add-archive-files scope)))
  11077. ((eq scope 'file)
  11078. (setq scope (and buffer-file-name (list buffer-file-name))))
  11079. ((eq scope 'file-with-archives)
  11080. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11081. (org-agenda-prepare-buffers scope)
  11082. (dolist (file scope)
  11083. (with-current-buffer (org-find-base-buffer-visiting file)
  11084. (org-with-wide-buffer
  11085. (goto-char (point-min))
  11086. (setq res
  11087. (append
  11088. res
  11089. (org-scan-tags
  11090. func matcher org--matcher-tags-todo-only)))))))))
  11091. res)))
  11092. ;;; Properties API
  11093. (defconst org-special-properties
  11094. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11095. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11096. "The special properties valid in Org mode.
  11097. These are properties that are not defined in the property drawer,
  11098. but in some other way.")
  11099. (defconst org-default-properties
  11100. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11101. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11102. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11103. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11104. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11105. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11106. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  11107. "Some properties that are used by Org mode for various purposes.
  11108. Being in this list makes sure that they are offered for completion.")
  11109. (defun org--valid-property-p (property)
  11110. "Non-nil when string PROPERTY is a valid property name."
  11111. (not
  11112. (or (equal property "")
  11113. (string-match-p "\\s-" property))))
  11114. (defun org--update-property-plist (key val props)
  11115. "Associate KEY to VAL in alist PROPS.
  11116. Modifications are made by side-effect. Return new alist."
  11117. (let* ((appending (string= (substring key -1) "+"))
  11118. (key (if appending (substring key 0 -1) key))
  11119. (old (assoc-string key props t)))
  11120. (if (not old) (cons (cons key val) props)
  11121. (setcdr old (if appending (concat (cdr old) " " val) val))
  11122. props)))
  11123. (defun org-get-property-block (&optional beg force)
  11124. "Return the (beg . end) range of the body of the property drawer.
  11125. BEG is the beginning of the current subtree or the beginning of
  11126. the document if before the first headline. If it is not given,
  11127. it will be found. If the drawer does not exist, create it if
  11128. FORCE is non-nil, or return nil."
  11129. (org-with-wide-buffer
  11130. (let ((beg (cond (beg (goto-char beg))
  11131. ((or (not (featurep 'org-inlinetask))
  11132. (org-inlinetask-in-task-p))
  11133. (org-back-to-heading-or-point-min t) (point))
  11134. (t (org-with-limited-levels
  11135. (org-back-to-heading-or-point-min t))
  11136. (point)))))
  11137. ;; Move point to its position according to its positional rules.
  11138. (cond ((org-before-first-heading-p)
  11139. (while (and (org-at-comment-p) (bolp)) (forward-line)))
  11140. (t (forward-line)
  11141. (when (looking-at-p org-planning-line-re) (forward-line))))
  11142. (cond ((looking-at org-property-drawer-re)
  11143. (forward-line)
  11144. (cons (point) (progn (goto-char (match-end 0))
  11145. (line-beginning-position))))
  11146. (force
  11147. (goto-char beg)
  11148. (org-insert-property-drawer)
  11149. (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  11150. (line-beginning-position))))
  11151. (cons pos pos)))))))
  11152. (defun org-at-property-drawer-p ()
  11153. "Non-nil when point is at the first line of a property drawer."
  11154. (org-with-wide-buffer
  11155. (beginning-of-line)
  11156. (and (looking-at org-property-drawer-re)
  11157. (or (bobp)
  11158. (progn
  11159. (forward-line -1)
  11160. (cond ((org-at-heading-p))
  11161. ((looking-at org-planning-line-re)
  11162. (forward-line -1)
  11163. (org-at-heading-p))
  11164. ((looking-at org-comment-regexp)
  11165. (forward-line -1)
  11166. (while (and (not (bobp)) (looking-at org-comment-regexp))
  11167. (forward-line -1))
  11168. (looking-at org-comment-regexp))
  11169. (t nil)))))))
  11170. (defun org-at-property-p ()
  11171. "Non-nil when point is inside a property drawer.
  11172. See `org-property-re' for match data, if applicable."
  11173. (save-excursion
  11174. (beginning-of-line)
  11175. (and (looking-at org-property-re)
  11176. (let ((property-drawer (save-match-data (org-get-property-block))))
  11177. (and property-drawer
  11178. (>= (point) (car property-drawer))
  11179. (< (point) (cdr property-drawer)))))))
  11180. (defun org-property-action ()
  11181. "Do an action on properties."
  11182. (interactive)
  11183. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11184. (let ((c (read-char-exclusive)))
  11185. (cl-case c
  11186. (?s (call-interactively #'org-set-property))
  11187. (?d (call-interactively #'org-delete-property))
  11188. (?D (call-interactively #'org-delete-property-globally))
  11189. (?c (call-interactively #'org-compute-property-at-point))
  11190. (otherwise (user-error "No such property action %c" c)))))
  11191. (defun org-inc-effort ()
  11192. "Increment the value of the effort property in the current entry."
  11193. (interactive)
  11194. (org-set-effort t))
  11195. (defvar org-clock-effort) ; Defined in org-clock.el.
  11196. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11197. (defun org-set-effort (&optional increment value)
  11198. "Set the effort property of the current entry.
  11199. If INCREMENT is non-nil, set the property to the next allowed
  11200. value. Otherwise, if optional argument VALUE is provided, use
  11201. it. Eventually, prompt for the new value if none of the previous
  11202. variables is set."
  11203. (interactive "P")
  11204. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11205. (current (org-entry-get nil org-effort-property))
  11206. (value
  11207. (cond
  11208. (increment
  11209. (unless allowed (user-error "Allowed effort values are not set"))
  11210. (or (cl-caadr (member (list current) allowed))
  11211. (user-error "Unknown value %S among allowed values" current)))
  11212. (value
  11213. (if (stringp value) value
  11214. (error "Invalid effort value: %S" value)))
  11215. (t
  11216. (let ((must-match
  11217. (and allowed
  11218. (not (get-text-property 0 'org-unrestricted
  11219. (caar allowed))))))
  11220. (completing-read "Effort: " allowed nil must-match))))))
  11221. ;; Test whether the value can be interpreted as a duration before
  11222. ;; inserting it in the buffer:
  11223. (org-duration-to-minutes value)
  11224. ;; Maybe update the effort value:
  11225. (unless (equal current value)
  11226. (org-entry-put nil org-effort-property value))
  11227. (unless (org-element--cache-active-p)
  11228. (org-refresh-property '((effort . identity)
  11229. (effort-minutes . org-duration-to-minutes))
  11230. value))
  11231. (when (equal (org-get-heading t t t t)
  11232. (bound-and-true-p org-clock-current-task))
  11233. (setq org-clock-effort value)
  11234. (org-clock-update-mode-line))
  11235. (message "%s is now %s" org-effort-property value)))
  11236. (defun org-entry-properties (&optional pom which)
  11237. "Get all properties of the current entry.
  11238. When POM is a buffer position, get all properties from the entry
  11239. there instead.
  11240. This includes the TODO keyword, the tags, time strings for
  11241. deadline, scheduled, and clocking, and any additional properties
  11242. defined in the entry.
  11243. If WHICH is nil or `all', get all properties. If WHICH is
  11244. `special' or `standard', only get that subclass. If WHICH is
  11245. a string, only get that property.
  11246. Return value is an alist. Keys are properties, as upcased
  11247. strings."
  11248. (org-with-point-at pom
  11249. (when (and (derived-mode-p 'org-mode)
  11250. (org-back-to-heading-or-point-min t))
  11251. (catch 'exit
  11252. (let* ((beg (point))
  11253. (specific (and (stringp which) (upcase which)))
  11254. (which (cond ((not specific) which)
  11255. ((member specific org-special-properties) 'special)
  11256. (t 'standard)))
  11257. props)
  11258. ;; Get the special properties, like TODO and TAGS.
  11259. (when (memq which '(nil all special))
  11260. (when (or (not specific) (string= specific "CLOCKSUM"))
  11261. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11262. (when clocksum
  11263. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11264. props)))
  11265. (when specific (throw 'exit props)))
  11266. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11267. (let ((clocksumt (get-text-property (point)
  11268. :org-clock-minutes-today)))
  11269. (when clocksumt
  11270. (push (cons "CLOCKSUM_T"
  11271. (org-duration-from-minutes clocksumt))
  11272. props)))
  11273. (when specific (throw 'exit props)))
  11274. (when (or (not specific) (string= specific "ITEM"))
  11275. (let ((case-fold-search nil))
  11276. (when (looking-at org-complex-heading-regexp)
  11277. (push (cons "ITEM"
  11278. (let ((title (match-string-no-properties 4)))
  11279. (if (org-string-nw-p title)
  11280. (org-remove-tabs title)
  11281. "")))
  11282. props)))
  11283. (when specific (throw 'exit props)))
  11284. (when (or (not specific) (string= specific "TODO"))
  11285. (let ((case-fold-search nil))
  11286. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11287. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11288. (when specific (throw 'exit props)))
  11289. (when (or (not specific) (string= specific "PRIORITY"))
  11290. (push (cons "PRIORITY"
  11291. (if (looking-at org-priority-regexp)
  11292. (match-string-no-properties 2)
  11293. (char-to-string org-priority-default)))
  11294. props)
  11295. (when specific (throw 'exit props)))
  11296. (when (or (not specific) (string= specific "FILE"))
  11297. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11298. props)
  11299. (when specific (throw 'exit props)))
  11300. (when (or (not specific) (string= specific "TAGS"))
  11301. (let ((tags (org-get-tags nil t)))
  11302. (when tags
  11303. (push (cons "TAGS" (org-make-tag-string tags))
  11304. props)))
  11305. (when specific (throw 'exit props)))
  11306. (when (or (not specific) (string= specific "ALLTAGS"))
  11307. (let ((tags (org-get-tags)))
  11308. (when tags
  11309. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11310. props)))
  11311. (when specific (throw 'exit props)))
  11312. (when (or (not specific) (string= specific "BLOCKED"))
  11313. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11314. (when specific (throw 'exit props)))
  11315. (when (or (not specific)
  11316. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11317. (forward-line)
  11318. (when (looking-at-p org-planning-line-re)
  11319. (end-of-line)
  11320. (let ((bol (line-beginning-position))
  11321. ;; Backward compatibility: time keywords used to
  11322. ;; be configurable (before 8.3). Make sure we
  11323. ;; get the correct keyword.
  11324. (key-assoc `(("CLOSED" . ,org-closed-string)
  11325. ("DEADLINE" . ,org-deadline-string)
  11326. ("SCHEDULED" . ,org-scheduled-string))))
  11327. (dolist (pair (if specific (list (assoc specific key-assoc))
  11328. key-assoc))
  11329. (save-excursion
  11330. (when (search-backward (cdr pair) bol t)
  11331. (goto-char (match-end 0))
  11332. (skip-chars-forward " \t")
  11333. (and (looking-at org-ts-regexp-both)
  11334. (push (cons (car pair)
  11335. (match-string-no-properties 0))
  11336. props)))))))
  11337. (when specific (throw 'exit props)))
  11338. (when (or (not specific)
  11339. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11340. (let ((find-ts
  11341. (lambda (end ts)
  11342. ;; Fix next time-stamp before END. TS is the
  11343. ;; list of time-stamps found so far.
  11344. (let ((ts ts)
  11345. (regexp (cond
  11346. ((string= specific "TIMESTAMP")
  11347. org-ts-regexp)
  11348. ((string= specific "TIMESTAMP_IA")
  11349. org-ts-regexp-inactive)
  11350. ((assoc "TIMESTAMP_IA" ts)
  11351. org-ts-regexp)
  11352. ((assoc "TIMESTAMP" ts)
  11353. org-ts-regexp-inactive)
  11354. (t org-ts-regexp-both))))
  11355. (catch 'next
  11356. (while (re-search-forward regexp end t)
  11357. (backward-char)
  11358. (let ((object (org-element-context)))
  11359. ;; Accept to match timestamps in node
  11360. ;; properties, too.
  11361. (when (memq (org-element-type object)
  11362. '(node-property timestamp))
  11363. (let ((type
  11364. (org-element-property :type object)))
  11365. (cond
  11366. ((and (memq type '(active active-range))
  11367. (not (equal specific "TIMESTAMP_IA")))
  11368. (unless (assoc "TIMESTAMP" ts)
  11369. (push (cons "TIMESTAMP"
  11370. (org-element-property
  11371. :raw-value object))
  11372. ts)
  11373. (when specific (throw 'exit ts))))
  11374. ((and (memq type '(inactive inactive-range))
  11375. (not (string= specific "TIMESTAMP")))
  11376. (unless (assoc "TIMESTAMP_IA" ts)
  11377. (push (cons "TIMESTAMP_IA"
  11378. (org-element-property
  11379. :raw-value object))
  11380. ts)
  11381. (when specific (throw 'exit ts))))))
  11382. ;; Both timestamp types are found,
  11383. ;; move to next part.
  11384. (when (= (length ts) 2) (throw 'next ts)))))
  11385. ts)))))
  11386. (goto-char beg)
  11387. ;; First look for timestamps within headline.
  11388. (let ((ts (funcall find-ts (line-end-position) nil)))
  11389. (if (= (length ts) 2) (setq props (nconc ts props))
  11390. ;; Then find timestamps in the section, skipping
  11391. ;; planning line.
  11392. (let ((end (save-excursion (outline-next-heading))))
  11393. (forward-line)
  11394. (when (looking-at-p org-planning-line-re) (forward-line))
  11395. (setq props (nconc (funcall find-ts end ts) props))))))))
  11396. ;; Get the standard properties, like :PROP:.
  11397. (when (memq which '(nil all standard))
  11398. ;; If we are looking after a specific property, delegate
  11399. ;; to `org-entry-get', which is faster. However, make an
  11400. ;; exception for "CATEGORY", since it can be also set
  11401. ;; through keywords (i.e. #+CATEGORY).
  11402. (if (and specific (not (equal specific "CATEGORY")))
  11403. (let ((value (org-entry-get beg specific nil t)))
  11404. (throw 'exit (and value (list (cons specific value)))))
  11405. (let ((range (org-get-property-block beg)))
  11406. (when range
  11407. (let ((end (cdr range)) seen-base)
  11408. (goto-char (car range))
  11409. ;; Unlike to `org--update-property-plist', we
  11410. ;; handle the case where base values is found
  11411. ;; after its extension. We also forbid standard
  11412. ;; properties to be named as special properties.
  11413. (while (re-search-forward org-property-re end t)
  11414. (let* ((key (upcase (match-string-no-properties 2)))
  11415. (extendp (string-match-p "\\+\\'" key))
  11416. (key-base (if extendp (substring key 0 -1) key))
  11417. (value (match-string-no-properties 3)))
  11418. (cond
  11419. ((member-ignore-case key-base org-special-properties))
  11420. (extendp
  11421. (setq props
  11422. (org--update-property-plist key value props)))
  11423. ((member key seen-base))
  11424. (t (push key seen-base)
  11425. (let ((p (assoc-string key props t)))
  11426. (if p (setcdr p (concat value " " (cdr p)))
  11427. (push (cons key value) props))))))))))))
  11428. (unless (assoc "CATEGORY" props)
  11429. (push (cons "CATEGORY" (org-get-category beg)) props)
  11430. (when (string= specific "CATEGORY") (throw 'exit props)))
  11431. ;; Return value.
  11432. props)))))
  11433. (defun org--property-local-values (property literal-nil &optional element)
  11434. "Return value for PROPERTY in current entry or ELEMENT.
  11435. Value is a list whose car is the base value for PROPERTY and cdr
  11436. a list of accumulated values. Return nil if neither is found in
  11437. the entry. Also return nil when PROPERTY is set to \"nil\",
  11438. unless LITERAL-NIL is non-nil."
  11439. (let ((element (or element
  11440. (and (org-element--cache-active-p)
  11441. (org-element-at-point nil 'cached)))))
  11442. (if element
  11443. (let* ((element (org-element-lineage element '(headline org-data inlinetask) 'with-self))
  11444. (base-value (org-element-property (intern (concat ":" (upcase property))) element))
  11445. (base-value (if literal-nil base-value (org-not-nil base-value)))
  11446. (extra-value (org-element-property (intern (concat ":" (upcase property) "+")) element))
  11447. (extra-value (if (listp extra-value) extra-value (list extra-value)))
  11448. (value (cons base-value extra-value)))
  11449. (and (not (equal value '(nil))) value))
  11450. (let ((range (org-get-property-block)))
  11451. (when range
  11452. (goto-char (car range))
  11453. (let* ((case-fold-search t)
  11454. (end (cdr range))
  11455. (value
  11456. ;; Base value.
  11457. (save-excursion
  11458. (let ((v (and (re-search-forward
  11459. (org-re-property property nil t) end t)
  11460. (match-string-no-properties 3))))
  11461. (list (if literal-nil v (org-not-nil v)))))))
  11462. ;; Find additional values.
  11463. (let* ((property+ (org-re-property (concat property "+") nil t)))
  11464. (while (re-search-forward property+ end t)
  11465. (push (match-string-no-properties 3) value)))
  11466. ;; Return final values.
  11467. (and (not (equal value '(nil))) (nreverse value))))))))
  11468. (defun org--property-global-or-keyword-value (property literal-nil)
  11469. "Return value for PROPERTY as defined by global properties or by keyword.
  11470. Return value is a string. Return nil if property is not set
  11471. globally or by keyword. Also return nil when PROPERTY is set to
  11472. \"nil\", unless LITERAL-NIL is non-nil."
  11473. (let ((global
  11474. (cdr (or (assoc-string property org-keyword-properties t)
  11475. (assoc-string property org-global-properties t)
  11476. (assoc-string property org-global-properties-fixed t)))))
  11477. (if literal-nil global (org-not-nil global))))
  11478. (defun org-entry-get (pom property &optional inherit literal-nil)
  11479. "Get value of PROPERTY for entry or content at point-or-marker POM.
  11480. If INHERIT is non-nil and the entry does not have the property,
  11481. then also check higher levels of the hierarchy. If INHERIT is
  11482. the symbol `selective', use inheritance only if the setting in
  11483. `org-use-property-inheritance' selects PROPERTY for inheritance.
  11484. If the property is present but empty, the return value is the
  11485. empty string. If the property is not present at all, nil is
  11486. returned. In any other case, return the value as a string.
  11487. Search is case-insensitive.
  11488. If LITERAL-NIL is set, return the string value \"nil\" as
  11489. a string, do not interpret it as the list atom nil. This is used
  11490. for inheritance when a \"nil\" value can supersede a non-nil
  11491. value higher up the hierarchy."
  11492. (org-with-point-at pom
  11493. (cond
  11494. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  11495. ;; We need a special property. Use `org-entry-properties' to
  11496. ;; retrieve it, but specify the wanted property.
  11497. (cdr (assoc-string property (org-entry-properties nil property))))
  11498. ((and inherit
  11499. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  11500. (org-entry-get-with-inheritance property literal-nil))
  11501. (t
  11502. (let* ((local (org--property-local-values property literal-nil))
  11503. (value (and local (mapconcat #'identity
  11504. (delq nil local)
  11505. (org--property-get-separator property)))))
  11506. (if literal-nil value (org-not-nil value)))))))
  11507. (defun org-property-or-variable-value (var &optional inherit)
  11508. "Check if there is a property fixing the value of VAR.
  11509. If yes, return this value. If not, return the current value of the variable."
  11510. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  11511. (if (and prop (stringp prop) (string-match "\\S-" prop))
  11512. (read prop)
  11513. (symbol-value var))))
  11514. (defun org-entry-delete (pom property)
  11515. "Delete PROPERTY from entry at point-or-marker POM.
  11516. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  11517. non-nil when a property was removed."
  11518. (org-with-point-at pom
  11519. (pcase (org-get-property-block)
  11520. (`(,begin . ,origin)
  11521. (let* ((end (copy-marker origin))
  11522. (re (org-re-property
  11523. (concat (regexp-quote property) "\\+?") t t)))
  11524. (goto-char begin)
  11525. (while (re-search-forward re end t)
  11526. (delete-region (match-beginning 0) (line-beginning-position 2)))
  11527. ;; If drawer is empty, remove it altogether.
  11528. (when (= begin end)
  11529. (delete-region (line-beginning-position 0)
  11530. (line-beginning-position 2)))
  11531. ;; Return non-nil if some property was removed.
  11532. (prog1 (/= end origin) (set-marker end nil))))
  11533. (_ nil))))
  11534. ;; Multi-values properties are properties that contain multiple values
  11535. ;; These values are assumed to be single words, separated by whitespace.
  11536. (defun org-entry-add-to-multivalued-property (pom property value)
  11537. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  11538. (let* ((old (org-entry-get pom property))
  11539. (values (and old (split-string old))))
  11540. (setq value (org-entry-protect-space value))
  11541. (unless (member value values)
  11542. (setq values (append values (list value)))
  11543. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11544. (defun org-entry-remove-from-multivalued-property (pom property value)
  11545. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  11546. (let* ((old (org-entry-get pom property))
  11547. (values (and old (split-string old))))
  11548. (setq value (org-entry-protect-space value))
  11549. (when (member value values)
  11550. (setq values (delete value values))
  11551. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11552. (defun org-entry-member-in-multivalued-property (pom property value)
  11553. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  11554. (let* ((old (org-entry-get pom property))
  11555. (values (and old (split-string old))))
  11556. (setq value (org-entry-protect-space value))
  11557. (member value values)))
  11558. (defun org-entry-get-multivalued-property (pom property)
  11559. "Return a list of values in a multivalued property."
  11560. (let* ((value (org-entry-get pom property))
  11561. (values (and value (split-string value))))
  11562. (mapcar #'org-entry-restore-space values)))
  11563. (defun org-entry-put-multivalued-property (pom property &rest values)
  11564. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  11565. VALUES should be a list of strings. Spaces will be protected."
  11566. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  11567. (let* ((value (org-entry-get pom property))
  11568. (values (and value (split-string value))))
  11569. (mapcar #'org-entry-restore-space values)))
  11570. (defun org-entry-protect-space (s)
  11571. "Protect spaces and newline in string S."
  11572. (while (string-match " " s)
  11573. (setq s (replace-match "%20" t t s)))
  11574. (while (string-match "\n" s)
  11575. (setq s (replace-match "%0A" t t s)))
  11576. s)
  11577. (defun org-entry-restore-space (s)
  11578. "Restore spaces and newline in string S."
  11579. (while (string-match "%20" s)
  11580. (setq s (replace-match " " t t s)))
  11581. (while (string-match "%0A" s)
  11582. (setq s (replace-match "\n" t t s)))
  11583. s)
  11584. (defvar org-entry-property-inherited-from (make-marker)
  11585. "Marker pointing to the entry from where a property was inherited.
  11586. Each call to `org-entry-get-with-inheritance' will set this marker to the
  11587. location of the entry where the inheritance search matched. If there was
  11588. no match, the marker will point nowhere.
  11589. Note that also `org-entry-get' calls this function, if the INHERIT flag
  11590. is set.")
  11591. (defun org-entry-get-with-inheritance (property &optional literal-nil element)
  11592. "Get PROPERTY of entry or content at point, search higher levels if needed.
  11593. The search will stop at the first ancestor which has the property defined.
  11594. If the value found is \"nil\", return nil to show that the property
  11595. should be considered as undefined (this is the meaning of nil here).
  11596. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  11597. (move-marker org-entry-property-inherited-from nil)
  11598. (org-with-wide-buffer
  11599. (let (value at-bob-no-heading)
  11600. (catch 'exit
  11601. (let ((element (or element
  11602. (and (org-element--cache-active-p)
  11603. (org-element-at-point nil 'cached))))
  11604. (separator (org--property-get-separator property)))
  11605. (if element
  11606. (let ((element (org-element-lineage element '(headline org-data inlinetask) 'with-self)))
  11607. (while t
  11608. (let* ((v (org--property-local-values property literal-nil element))
  11609. (v (if (listp v) v (list v))))
  11610. (when v
  11611. (setq value
  11612. (concat (mapconcat #'identity (delq nil v) separator)
  11613. (and value separator)
  11614. value)))
  11615. (cond
  11616. ((car v)
  11617. (move-marker org-entry-property-inherited-from (org-element-property :begin element))
  11618. (throw 'exit nil))
  11619. ((org-element-property :parent element)
  11620. (setq element (org-element-property :parent element)))
  11621. (t
  11622. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11623. (cond ((not global))
  11624. (value (setq value (concat global separator value)))
  11625. (t (setq value global))))
  11626. (throw 'exit nil))))))
  11627. (while t
  11628. (let ((v (org--property-local-values property literal-nil)))
  11629. (when v
  11630. (setq value
  11631. (concat (mapconcat #'identity (delq nil v) separator)
  11632. (and value separator)
  11633. value)))
  11634. (cond
  11635. ((car v)
  11636. (org-back-to-heading-or-point-min t)
  11637. (move-marker org-entry-property-inherited-from (point))
  11638. (throw 'exit nil))
  11639. ((or (org-up-heading-safe)
  11640. (and (not (bobp))
  11641. (goto-char (point-min))
  11642. nil)
  11643. ;; `org-up-heading-safe' returned nil. We are at low
  11644. ;; level heading or bob. If there is headline
  11645. ;; there, do not try to fetch its properties.
  11646. (and (bobp)
  11647. (not at-bob-no-heading)
  11648. (not (org-at-heading-p))
  11649. (setq at-bob-no-heading t))))
  11650. (t
  11651. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11652. (cond ((not global))
  11653. (value (setq value (concat global separator value)))
  11654. (t (setq value global))))
  11655. (throw 'exit nil))))))))
  11656. (if literal-nil value (org-not-nil value)))))
  11657. (defvar org-property-changed-functions nil
  11658. "Hook called when the value of a property has changed.
  11659. Each hook function should accept two arguments, the name of the property
  11660. and the new value.")
  11661. (defun org-entry-put (pom property value)
  11662. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  11663. If the value is nil, it is converted to the empty string. If it
  11664. is not a string, an error is raised. Also raise an error on
  11665. invalid property names.
  11666. PROPERTY can be any regular property (see
  11667. `org-special-properties'). It can also be \"TODO\",
  11668. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  11669. For the last two properties, VALUE may have any of the special
  11670. values \"earlier\" and \"later\". The function then increases or
  11671. decreases scheduled or deadline date by one day."
  11672. (cond ((null value) (setq value ""))
  11673. ((not (stringp value)) (error "Properties values should be strings"))
  11674. ((not (org--valid-property-p property))
  11675. (user-error "Invalid property name: \"%s\"" property)))
  11676. (org-no-read-only
  11677. (org-with-point-at pom
  11678. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11679. (org-back-to-heading-or-point-min t)
  11680. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11681. (let ((beg (point)))
  11682. (cond
  11683. ((equal property "TODO")
  11684. (cond ((not (org-string-nw-p value)) (setq value 'none))
  11685. ((not (member value org-todo-keywords-1))
  11686. (user-error "\"%s\" is not a valid TODO state" value)))
  11687. (org-todo value)
  11688. (org-align-tags))
  11689. ((equal property "PRIORITY")
  11690. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  11691. (org-align-tags))
  11692. ((equal property "SCHEDULED")
  11693. (forward-line)
  11694. (if (and (looking-at-p org-planning-line-re)
  11695. (re-search-forward
  11696. org-scheduled-time-regexp (line-end-position) t))
  11697. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11698. ((string= value "later") (org-timestamp-change 1 'day))
  11699. ((string= value "") (org-schedule '(4)))
  11700. (t (org-schedule nil value)))
  11701. (if (member value '("earlier" "later" ""))
  11702. (call-interactively #'org-schedule)
  11703. (org-schedule nil value))))
  11704. ((equal property "DEADLINE")
  11705. (forward-line)
  11706. (if (and (looking-at-p org-planning-line-re)
  11707. (re-search-forward
  11708. org-deadline-time-regexp (line-end-position) t))
  11709. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11710. ((string= value "later") (org-timestamp-change 1 'day))
  11711. ((string= value "") (org-deadline '(4)))
  11712. (t (org-deadline nil value)))
  11713. (if (member value '("earlier" "later" ""))
  11714. (call-interactively #'org-deadline)
  11715. (org-deadline nil value))))
  11716. ((member property org-special-properties)
  11717. (error "The %s property cannot be set with `org-entry-put'" property))
  11718. (t
  11719. (org-fold-core-ignore-modifications
  11720. (let* ((range (org-get-property-block beg 'force))
  11721. (end (cdr range))
  11722. (case-fold-search t))
  11723. (goto-char (car range))
  11724. (if (re-search-forward (org-re-property property nil t) end t)
  11725. (progn (delete-region (match-beginning 0) (match-end 0))
  11726. (goto-char (match-beginning 0)))
  11727. (goto-char end)
  11728. (insert-and-inherit "\n")
  11729. (backward-char))
  11730. (insert-and-inherit ":" property ":")
  11731. (when value (insert-and-inherit " " value))
  11732. (org-indent-line))))))
  11733. (run-hook-with-args 'org-property-changed-functions property value))))
  11734. (defun org-buffer-property-keys (&optional specials defaults columns)
  11735. "Get all property keys in the current buffer.
  11736. When SPECIALS is non-nil, also list the special properties that
  11737. reflect things like tags and TODO state.
  11738. When DEFAULTS is non-nil, also include properties that has
  11739. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  11740. DESCRIPTION, LOCATION, and LOGGING and others.
  11741. When COLUMNS in non-nil, also include property names given in
  11742. COLUMN formats in the current buffer."
  11743. (let ((case-fold-search t)
  11744. (props (append
  11745. (and specials org-special-properties)
  11746. (and defaults (cons org-effort-property org-default-properties))
  11747. ;; Get property names from #+PROPERTY keywords as well
  11748. (mapcar (lambda (s)
  11749. (nth 0 (split-string s)))
  11750. (cdar (org-collect-keywords '("PROPERTY")))))))
  11751. (org-with-wide-buffer
  11752. (goto-char (point-min))
  11753. (while (re-search-forward org-property-start-re nil t)
  11754. (catch :skip
  11755. (let ((range (org-get-property-block)))
  11756. (unless range (throw :skip nil))
  11757. (goto-char (car range))
  11758. (let ((begin (car range))
  11759. (end (cdr range)))
  11760. ;; Make sure that found property block is not located
  11761. ;; before current point, as it would generate an infloop.
  11762. ;; It can happen, for example, in the following
  11763. ;; situation:
  11764. ;;
  11765. ;; * Headline
  11766. ;; :PROPERTIES:
  11767. ;; ...
  11768. ;; :END:
  11769. ;; *************** Inlinetask
  11770. ;; #+BEGIN_EXAMPLE
  11771. ;; :PROPERTIES:
  11772. ;; #+END_EXAMPLE
  11773. ;;
  11774. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  11775. (while (< (point) end)
  11776. (let ((p (progn (looking-at org-property-re)
  11777. (match-string-no-properties 2))))
  11778. ;; Only add true property name, not extension symbol.
  11779. (push (if (not (string-match-p "\\+\\'" p)) p
  11780. (substring p 0 -1))
  11781. props))
  11782. (forward-line))))
  11783. (outline-next-heading)))
  11784. (when columns
  11785. (goto-char (point-min))
  11786. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  11787. (let ((element (org-element-at-point)))
  11788. (when (memq (org-element-type element) '(keyword node-property))
  11789. (let ((value (org-element-property :value element))
  11790. (start 0))
  11791. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  11792. \\(?:{[^}]+}\\)?"
  11793. value start)
  11794. (setq start (match-end 0))
  11795. (let ((p (match-string-no-properties 1 value)))
  11796. (unless (member-ignore-case p org-special-properties)
  11797. (push p props))))))))))
  11798. (sort (delete-dups
  11799. (append props
  11800. ;; for each xxx_ALL property, make sure the bare
  11801. ;; xxx property is also included
  11802. (delq nil (mapcar (lambda (p)
  11803. (and (string-match-p "._ALL\\'" p)
  11804. (substring p 0 -4)))
  11805. props))))
  11806. (lambda (a b) (string< (upcase a) (upcase b))))))
  11807. (defun org-property-values (key)
  11808. "List all non-nil values of property KEY in current buffer."
  11809. (org-with-wide-buffer
  11810. (goto-char (point-min))
  11811. (let ((case-fold-search t)
  11812. (re (org-re-property key))
  11813. values)
  11814. (while (re-search-forward re nil t)
  11815. (push (org-entry-get (point) key) values))
  11816. (delete-dups values))))
  11817. (defun org-insert-property-drawer ()
  11818. "Insert a property drawer into the current entry.
  11819. Do nothing if the drawer already exists. The newly created
  11820. drawer is immediately hidden."
  11821. (org-with-wide-buffer
  11822. ;; Set point to the position where the drawer should be inserted.
  11823. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11824. (org-back-to-heading-or-point-min t)
  11825. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11826. (if (org-before-first-heading-p)
  11827. (while (and (org-at-comment-p) (bolp)) (forward-line))
  11828. (forward-line)
  11829. (when (looking-at-p org-planning-line-re) (forward-line)))
  11830. (unless (looking-at-p org-property-drawer-re)
  11831. ;; Make sure we start editing a line from current entry, not from
  11832. ;; next one. It prevents extending text properties or overlays
  11833. ;; belonging to the latter.
  11834. (when (and (bolp) (> (point) (point-min))) (backward-char))
  11835. (let ((begin (if (bobp) (point) (1+ (point))))
  11836. (inhibit-read-only t))
  11837. (unless (bobp) (insert "\n"))
  11838. (insert ":PROPERTIES:\n:END:")
  11839. (org-fold-region (line-end-position 0) (point) t (if (eq org-fold-core-style 'text-properties) 'drawer 'outline))
  11840. (when (or (eobp) (= begin (point-min))) (insert "\n"))
  11841. (org-indent-region begin (point))))))
  11842. (defun org-insert-drawer (&optional arg drawer)
  11843. "Insert a drawer at point.
  11844. When optional argument ARG is non-nil, insert a property drawer.
  11845. Optional argument DRAWER, when non-nil, is a string representing
  11846. drawer's name. Otherwise, the user is prompted for a name.
  11847. If a region is active, insert the drawer around that region
  11848. instead.
  11849. Point is left between drawer's boundaries."
  11850. (interactive "P")
  11851. (let* ((drawer (if arg "PROPERTIES"
  11852. (or drawer (read-from-minibuffer "Drawer: ")))))
  11853. (cond
  11854. ;; With C-u, fall back on `org-insert-property-drawer'
  11855. (arg (org-insert-property-drawer))
  11856. ;; Check validity of suggested drawer's name.
  11857. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  11858. (user-error "Invalid drawer name"))
  11859. ;; With an active region, insert a drawer at point.
  11860. ((not (org-region-active-p))
  11861. (progn
  11862. (unless (bolp) (insert "\n"))
  11863. (insert (format ":%s:\n\n:END:\n" drawer))
  11864. (forward-line -2)))
  11865. ;; Otherwise, insert the drawer at point
  11866. (t
  11867. (let ((rbeg (region-beginning))
  11868. (rend (copy-marker (region-end))))
  11869. (unwind-protect
  11870. (progn
  11871. (goto-char rbeg)
  11872. (beginning-of-line)
  11873. (when (save-excursion
  11874. (re-search-forward org-outline-regexp-bol rend t))
  11875. (user-error "Drawers cannot contain headlines"))
  11876. ;; Position point at the beginning of the first
  11877. ;; non-blank line in region. Insert drawer's opening
  11878. ;; there, then indent it.
  11879. (org-skip-whitespace)
  11880. (beginning-of-line)
  11881. (insert ":" drawer ":\n")
  11882. (forward-line -1)
  11883. (indent-for-tab-command)
  11884. ;; Move point to the beginning of the first blank line
  11885. ;; after the last non-blank line in region. Insert
  11886. ;; drawer's closing, then indent it.
  11887. (goto-char rend)
  11888. (skip-chars-backward " \r\t\n")
  11889. (insert "\n:END:")
  11890. (deactivate-mark t)
  11891. (indent-for-tab-command)
  11892. (unless (eolp) (insert "\n")))
  11893. ;; Clear marker, whatever the outcome of insertion is.
  11894. (set-marker rend nil)))))))
  11895. (defvar org-property-set-functions-alist nil
  11896. "Property set function alist.
  11897. Each entry should have the following format:
  11898. (PROPERTY . READ-FUNCTION)
  11899. The read function will be called with the same argument as
  11900. `org-completing-read'.")
  11901. (defun org-set-property-function (property)
  11902. "Get the function that should be used to set PROPERTY.
  11903. This is computed according to `org-property-set-functions-alist'."
  11904. (or (cdr (assoc property org-property-set-functions-alist))
  11905. 'org-completing-read))
  11906. (defun org-read-property-value (property &optional pom default)
  11907. "Read value for PROPERTY, as a string.
  11908. When optional argument POM is non-nil, completion uses additional
  11909. information, i.e., allowed or existing values at point or marker
  11910. POM.
  11911. Optional argument DEFAULT provides a default value for PROPERTY."
  11912. (let* ((completion-ignore-case t)
  11913. (allowed
  11914. (or (org-property-get-allowed-values nil property 'table)
  11915. (and pom (org-property-get-allowed-values pom property 'table))))
  11916. (current (org-entry-get nil property))
  11917. (prompt (format "%s value%s: "
  11918. property
  11919. (if (org-string-nw-p current)
  11920. (format " [%s]" current)
  11921. "")))
  11922. (set-function (org-set-property-function property)))
  11923. (org-trim
  11924. (if allowed
  11925. (funcall set-function
  11926. prompt allowed nil
  11927. (not (get-text-property 0 'org-unrestricted (caar allowed)))
  11928. default nil default)
  11929. (let ((all (mapcar #'list
  11930. (append (org-property-values property)
  11931. (and pom
  11932. (org-with-point-at pom
  11933. (org-property-values property)))))))
  11934. (funcall set-function prompt all nil nil "" nil current))))))
  11935. (defvar org-last-set-property nil)
  11936. (defvar org-last-set-property-value nil)
  11937. (defun org-read-property-name ()
  11938. "Read a property name."
  11939. (let ((completion-ignore-case t)
  11940. (default-prop (or (and (org-at-property-p)
  11941. (match-string-no-properties 2))
  11942. org-last-set-property)))
  11943. (org-completing-read
  11944. (concat "Property"
  11945. (if default-prop (concat " [" default-prop "]") "")
  11946. ": ")
  11947. (mapcar #'list (org-buffer-property-keys nil t t))
  11948. nil nil nil nil default-prop)))
  11949. (defun org-set-property-and-value (use-last)
  11950. "Allow to set [PROPERTY]: [value] direction from prompt.
  11951. When use-default, don't even ask, just use the last
  11952. \"[PROPERTY]: [value]\" string from the history."
  11953. (interactive "P")
  11954. (let* ((completion-ignore-case t)
  11955. (pv (or (and use-last org-last-set-property-value)
  11956. (org-completing-read
  11957. "Enter a \"[Property]: [value]\" pair: "
  11958. nil nil nil nil nil
  11959. org-last-set-property-value)))
  11960. prop val)
  11961. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  11962. (setq prop (match-string 1 pv)
  11963. val (match-string 2 pv))
  11964. (org-set-property prop val))))
  11965. (defun org-set-property (property value)
  11966. "In the current entry, set PROPERTY to VALUE.
  11967. When called interactively, this will prompt for a property name, offering
  11968. completion on existing and default properties. And then it will prompt
  11969. for a value, offering completion either on allowed values (via an inherited
  11970. xxx_ALL property) or on existing values in other instances of this property
  11971. in the current file.
  11972. Throw an error when trying to set a property with an invalid name."
  11973. (interactive (list nil nil))
  11974. (let ((property (or property (org-read-property-name))))
  11975. ;; `org-entry-put' also makes the following check, but this one
  11976. ;; avoids polluting `org-last-set-property' and
  11977. ;; `org-last-set-property-value' needlessly.
  11978. (unless (org--valid-property-p property)
  11979. (user-error "Invalid property name: \"%s\"" property))
  11980. (let ((value (or value (org-read-property-value property)))
  11981. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  11982. (setq org-last-set-property property)
  11983. (setq org-last-set-property-value (concat property ": " value))
  11984. ;; Possibly postprocess the inserted value:
  11985. (when fn (setq value (funcall fn value)))
  11986. (unless (equal (org-entry-get nil property) value)
  11987. (org-entry-put nil property value)))))
  11988. (defun org-find-property (property &optional value)
  11989. "Find first entry in buffer that sets PROPERTY.
  11990. When optional argument VALUE is non-nil, only consider an entry
  11991. if it contains PROPERTY set to this value. If PROPERTY should be
  11992. explicitly set to nil, use string \"nil\" for VALUE.
  11993. Return position where the entry begins, or nil if there is no
  11994. such entry. If narrowing is in effect, only search the visible
  11995. part of the buffer."
  11996. (save-excursion
  11997. (goto-char (point-min))
  11998. (let ((case-fold-search t)
  11999. (re (org-re-property property nil (not value) value)))
  12000. (catch 'exit
  12001. (while (re-search-forward re nil t)
  12002. (when (if value (org-at-property-p)
  12003. (org-entry-get (point) property nil t))
  12004. (throw 'exit (progn (org-back-to-heading-or-point-min t)
  12005. (point)))))))))
  12006. (defun org-delete-property (property)
  12007. "In the current entry, delete PROPERTY."
  12008. (interactive
  12009. (let* ((completion-ignore-case t)
  12010. (cat (org-entry-get (point) "CATEGORY"))
  12011. (props0 (org-entry-properties nil 'standard))
  12012. (props (if cat props0
  12013. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  12014. (prop (if (< 1 (length props))
  12015. (completing-read "Property: " props nil t)
  12016. (caar props))))
  12017. (list prop)))
  12018. (if (not property)
  12019. (message "No property to delete in this entry")
  12020. (org-entry-delete nil property)
  12021. (message "Property \"%s\" deleted" property)))
  12022. (defun org-delete-property-globally (property)
  12023. "Remove PROPERTY globally, from all entries.
  12024. This function ignores narrowing, if any."
  12025. (interactive
  12026. (let* ((completion-ignore-case t)
  12027. (prop (completing-read
  12028. "Globally remove property: "
  12029. (mapcar #'list (org-buffer-property-keys)))))
  12030. (list prop)))
  12031. (org-with-wide-buffer
  12032. (goto-char (point-min))
  12033. (let ((count 0)
  12034. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  12035. (while (re-search-forward re nil t)
  12036. (when (org-entry-delete (point) property) (cl-incf count)))
  12037. (message "Property \"%s\" removed from %d entries" property count))))
  12038. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  12039. (defun org-compute-property-at-point ()
  12040. "Compute the property at point.
  12041. This looks for an enclosing column format, extracts the operator and
  12042. then applies it to the property in the column format's scope."
  12043. (interactive)
  12044. (unless (org-at-property-p)
  12045. (user-error "Not at a property"))
  12046. (let ((prop (match-string-no-properties 2)))
  12047. (org-columns-get-format-and-top-level)
  12048. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  12049. (user-error "No operator defined for property %s" prop))
  12050. (org-columns-compute prop)))
  12051. (defvar org-property-allowed-value-functions nil
  12052. "Hook for functions supplying allowed values for a specific property.
  12053. The functions must take a single argument, the name of the property, and
  12054. return a flat list of allowed values. If \":ETC\" is one of
  12055. the values, this means that these values are intended as defaults for
  12056. completion, but that other values should be allowed too.
  12057. The functions must return nil if they are not responsible for this
  12058. property.")
  12059. (defun org-property-get-allowed-values (pom property &optional table)
  12060. "Get allowed values for the property PROPERTY.
  12061. When TABLE is non-nil, return an alist that can directly be used for
  12062. completion."
  12063. (let (vals)
  12064. (cond
  12065. ((equal property "TODO")
  12066. (setq vals (org-with-point-at pom
  12067. (append org-todo-keywords-1 '("")))))
  12068. ((equal property "PRIORITY")
  12069. (let ((n org-priority-lowest))
  12070. (while (>= n org-priority-highest)
  12071. (push (char-to-string n) vals)
  12072. (setq n (1- n)))))
  12073. ((equal property "CATEGORY"))
  12074. ((member property org-special-properties))
  12075. ((setq vals (run-hook-with-args-until-success
  12076. 'org-property-allowed-value-functions property)))
  12077. (t
  12078. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  12079. (when (and vals (string-match "\\S-" vals))
  12080. (setq vals (car (read-from-string (concat "(" vals ")"))))
  12081. (setq vals (mapcar (lambda (x)
  12082. (cond ((stringp x) x)
  12083. ((numberp x) (number-to-string x))
  12084. ((symbolp x) (symbol-name x))
  12085. (t "???")))
  12086. vals)))))
  12087. (when (member ":ETC" vals)
  12088. (setq vals (remove ":ETC" vals))
  12089. (org-add-props (car vals) '(org-unrestricted t)))
  12090. (if table (mapcar 'list vals) vals)))
  12091. (defun org-property-previous-allowed-value (&optional _previous)
  12092. "Switch to the next allowed value for this property."
  12093. (interactive)
  12094. (org-property-next-allowed-value t))
  12095. (defun org-property-next-allowed-value (&optional previous)
  12096. "Switch to the next allowed value for this property."
  12097. (interactive)
  12098. (unless (org-at-property-p)
  12099. (user-error "Not at a property"))
  12100. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  12101. (key (match-string 2))
  12102. (value (match-string 3))
  12103. (allowed (or (org-property-get-allowed-values (point) key)
  12104. (and (member value '("[ ]" "[-]" "[X]"))
  12105. '("[ ]" "[X]"))))
  12106. (heading (save-match-data (nth 4 (org-heading-components))))
  12107. nval)
  12108. (unless allowed
  12109. (user-error "Allowed values for this property have not been defined"))
  12110. (when previous (setq allowed (reverse allowed)))
  12111. (when (member value allowed)
  12112. (setq nval (car (cdr (member value allowed)))))
  12113. (setq nval (or nval (car allowed)))
  12114. (when (equal nval value)
  12115. (user-error "Only one allowed value for this property"))
  12116. (org-at-property-p)
  12117. (replace-match (concat " :" key ": " nval) t t)
  12118. (org-indent-line)
  12119. (beginning-of-line 1)
  12120. (skip-chars-forward " \t")
  12121. (when (equal prop org-effort-property)
  12122. (unless (org-element--cache-active-p)
  12123. (org-refresh-property
  12124. '((effort . identity)
  12125. (effort-minutes . org-duration-to-minutes))
  12126. nval))
  12127. (when (string= org-clock-current-task heading)
  12128. (setq org-clock-effort nval)
  12129. (org-clock-update-mode-line)))
  12130. (run-hook-with-args 'org-property-changed-functions key nval)))
  12131. (defun org-find-olp (path &optional this-buffer)
  12132. "Return a marker pointing to the entry at outline path OLP.
  12133. If anything goes wrong, throw an error, and if you need to do
  12134. something based on this error, you can catch it with
  12135. `condition-case'.
  12136. If THIS-BUFFER is set, the outline path does not contain a file,
  12137. only headings."
  12138. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12139. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12140. (level 1)
  12141. (lmin 1)
  12142. (lmax 1)
  12143. end found flevel)
  12144. (unless buffer (error "File not found :%s" file))
  12145. (with-current-buffer buffer
  12146. (unless (derived-mode-p 'org-mode)
  12147. (error "Buffer %s needs to be in Org mode" buffer))
  12148. (org-with-wide-buffer
  12149. (goto-char (point-min))
  12150. (dolist (heading path)
  12151. (let ((re (format org-complex-heading-regexp-format
  12152. (regexp-quote heading)))
  12153. (cnt 0))
  12154. (while (re-search-forward re end t)
  12155. (setq level (- (match-end 1) (match-beginning 1)))
  12156. (when (and (>= level lmin) (<= level lmax))
  12157. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12158. (when (= cnt 0)
  12159. (error "Heading not found on level %d: %s" lmax heading))
  12160. (when (> cnt 1)
  12161. (error "Heading not unique on level %d: %s" lmax heading))
  12162. (goto-char found)
  12163. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12164. (setq end (save-excursion (org-end-of-subtree t t)))))
  12165. (when (org-at-heading-p)
  12166. (point-marker))))))
  12167. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12168. "Find node HEADING in BUFFER.
  12169. Return a marker to the heading if it was found, or nil if not.
  12170. If POS-ONLY is set, return just the position instead of a marker.
  12171. The heading text must match exact, but it may have a TODO keyword,
  12172. a priority cookie and tags in the standard locations."
  12173. (with-current-buffer (or buffer (current-buffer))
  12174. (org-with-wide-buffer
  12175. (goto-char (point-min))
  12176. (let (case-fold-search)
  12177. (when (re-search-forward
  12178. (format org-complex-heading-regexp-format
  12179. (regexp-quote heading)) nil t)
  12180. (if pos-only
  12181. (match-beginning 0)
  12182. (move-marker (make-marker) (match-beginning 0))))))))
  12183. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12184. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12185. When the target headline is found, return a marker to this location."
  12186. (let ((files (directory-files (or dir default-directory)
  12187. t "\\`[^.#].*\\.org\\'"))
  12188. visiting m buffer)
  12189. (catch 'found
  12190. (dolist (file files)
  12191. (message "trying %s" file)
  12192. (setq visiting (org-find-base-buffer-visiting file))
  12193. (setq buffer (or visiting (find-file-noselect file)))
  12194. (setq m (org-find-exact-headline-in-buffer
  12195. heading buffer))
  12196. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12197. (and m (throw 'found m))))))
  12198. (defun org-find-entry-with-id (ident)
  12199. "Locate the entry that contains the ID property with exact value IDENT.
  12200. IDENT can be a string, a symbol or a number, this function will search for
  12201. the string representation of it.
  12202. Return the position where this entry starts, or nil if there is no such entry."
  12203. (interactive "sID: ")
  12204. (let ((id (cond
  12205. ((stringp ident) ident)
  12206. ((symbolp ident) (symbol-name ident))
  12207. ((numberp ident) (number-to-string ident))
  12208. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12209. (org-with-wide-buffer (org-find-property "ID" id))))
  12210. ;;;; Timestamps
  12211. (defvar org-last-changed-timestamp nil)
  12212. (defvar org-last-inserted-timestamp nil
  12213. "The last time stamp inserted with `org-insert-time-stamp'.")
  12214. (defun org-time-stamp (arg &optional inactive)
  12215. "Prompt for a date/time and insert a time stamp.
  12216. If the user specifies a time like HH:MM or if this command is
  12217. called with at least one prefix argument, the time stamp contains
  12218. the date and the time. Otherwise, only the date is included.
  12219. All parts of a date not specified by the user are filled in from
  12220. the timestamp at point, if any, or the current date/time
  12221. otherwise.
  12222. If there is already a timestamp at the cursor, it is replaced.
  12223. With two universal prefix arguments, insert an active timestamp
  12224. with the current time without prompting the user.
  12225. When called from Lisp, the timestamp is inactive if INACTIVE is
  12226. non-nil."
  12227. (interactive "P")
  12228. (let* ((ts (cond
  12229. ((org-at-date-range-p t)
  12230. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12231. ((org-at-timestamp-p 'lax) (match-string 0))))
  12232. ;; Default time is either the timestamp at point or today.
  12233. ;; When entering a range, only the range start is considered.
  12234. (default-time (and ts (org-time-string-to-time ts)))
  12235. (default-input (and ts (org-get-compact-tod ts)))
  12236. (repeater (and ts
  12237. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12238. (match-string 0 ts)))
  12239. org-time-was-given
  12240. org-end-time-was-given
  12241. (time
  12242. (if (equal arg '(16)) (current-time)
  12243. ;; Preserve `this-command' and `last-command'.
  12244. (let ((this-command this-command)
  12245. (last-command last-command))
  12246. (org-read-date
  12247. arg 'totime nil nil default-time default-input
  12248. inactive)))))
  12249. (cond
  12250. ((and ts
  12251. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12252. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12253. (insert "--")
  12254. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12255. (ts
  12256. ;; Make sure we're on a timestamp. When in the middle of a date
  12257. ;; range, move arbitrarily to range end.
  12258. (unless (org-at-timestamp-p 'lax)
  12259. (skip-chars-forward "-")
  12260. (org-at-timestamp-p 'lax))
  12261. (replace-match "")
  12262. (setq org-last-changed-timestamp
  12263. (org-insert-time-stamp
  12264. time (or org-time-was-given arg)
  12265. inactive nil nil (list org-end-time-was-given)))
  12266. (when repeater
  12267. (backward-char)
  12268. (insert " " repeater)
  12269. (setq org-last-changed-timestamp
  12270. (concat (substring org-last-inserted-timestamp 0 -1)
  12271. " " repeater ">")))
  12272. (message "Timestamp updated"))
  12273. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12274. (t (org-insert-time-stamp
  12275. time (or org-time-was-given arg) inactive nil nil
  12276. (list org-end-time-was-given))))))
  12277. ;; FIXME: can we use this for something else, like computing time differences?
  12278. (defun org-get-compact-tod (s)
  12279. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12280. (let* ((t1 (match-string 1 s))
  12281. (h1 (string-to-number (match-string 2 s)))
  12282. (m1 (string-to-number (match-string 3 s)))
  12283. (t2 (and (match-end 4) (match-string 5 s)))
  12284. (h2 (and t2 (string-to-number (match-string 6 s))))
  12285. (m2 (and t2 (string-to-number (match-string 7 s))))
  12286. dh dm)
  12287. (if (not t2)
  12288. t1
  12289. (setq dh (- h2 h1) dm (- m2 m1))
  12290. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12291. (concat t1 "+" (number-to-string dh)
  12292. (and (/= 0 dm) (format ":%02d" dm)))))))
  12293. (defun org-time-stamp-inactive (&optional arg)
  12294. "Insert an inactive time stamp.
  12295. An inactive time stamp is enclosed in square brackets instead of
  12296. angle brackets. It is inactive in the sense that it does not
  12297. trigger agenda entries. So these are more for recording a
  12298. certain time/date.
  12299. If the user specifies a time like HH:MM or if this command is called with
  12300. at least one prefix argument, the time stamp contains the date and the time.
  12301. Otherwise, only the date is included.
  12302. When called with two universal prefix arguments, insert an inactive time stamp
  12303. with the current time without prompting the user."
  12304. (interactive "P")
  12305. (org-time-stamp arg 'inactive))
  12306. (defvar org-date-ovl (make-overlay 1 1))
  12307. (overlay-put org-date-ovl 'face 'org-date-selected)
  12308. (delete-overlay org-date-ovl)
  12309. (defvar org-ans1) ; dynamically scoped parameter
  12310. (defvar org-ans2) ; dynamically scoped parameter
  12311. (defvar org-plain-time-of-day-regexp) ; defined below
  12312. (defvar org-overriding-default-time nil) ; dynamically scoped
  12313. (defvar org-read-date-overlay nil)
  12314. (defvar org-read-date-history nil)
  12315. (defvar org-read-date-final-answer nil)
  12316. (defvar org-read-date-analyze-futurep nil)
  12317. (defvar org-read-date-analyze-forced-year nil)
  12318. (defvar org-read-date-inactive)
  12319. (defvar org-def)
  12320. (defvar org-defdecode)
  12321. (defvar org-with-time)
  12322. (defvar calendar-setup) ; Dynamically scoped.
  12323. (defun org-read-date (&optional with-time to-time from-string prompt
  12324. default-time default-input inactive)
  12325. "Read a date, possibly a time, and make things smooth for the user.
  12326. The prompt will suggest to enter an ISO date, but you can also enter anything
  12327. which will at least partially be understood by `parse-time-string'.
  12328. Unrecognized parts of the date will default to the current day, month, year,
  12329. hour and minute. If this command is called to replace a timestamp at point,
  12330. or to enter the second timestamp of a range, the default time is taken
  12331. from the existing stamp. Furthermore, the command prefers the future,
  12332. so if you are giving a date where the year is not given, and the day-month
  12333. combination is already past in the current year, it will assume you
  12334. mean next year. For details, see the manual. A few examples:
  12335. 3-2-5 --> 2003-02-05
  12336. feb 15 --> currentyear-02-15
  12337. 2/15 --> currentyear-02-15
  12338. sep 12 9 --> 2009-09-12
  12339. 12:45 --> today 12:45
  12340. 22 sept 0:34 --> currentyear-09-22 0:34
  12341. 12 --> currentyear-currentmonth-12
  12342. Fri --> nearest Friday after today
  12343. -Tue --> last Tuesday
  12344. etc.
  12345. Furthermore you can specify a relative date by giving, as the *first* thing
  12346. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12347. change in days weeks, months, years.
  12348. With a single plus or minus, the date is relative to today. With a double
  12349. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12350. +4d --> four days from today
  12351. +4 --> same as above
  12352. +2w --> two weeks from today
  12353. ++5 --> five days from default date
  12354. The function understands only English month and weekday abbreviations.
  12355. While prompting, a calendar is popped up - you can also select the
  12356. date with the mouse (button 1). The calendar shows a period of three
  12357. months. To scroll it to other months, use the keys `>' and `<'.
  12358. There are many other calendar navigation commands available, see
  12359. Info node `(org) The date/time prompt' for a full list.
  12360. If you don't like the calendar, turn it off with
  12361. (setq org-read-date-popup-calendar nil)
  12362. With optional argument TO-TIME, the date will immediately be converted
  12363. to an internal time.
  12364. With an optional argument WITH-TIME, the prompt will suggest to
  12365. also insert a time. Note that when WITH-TIME is not set, you can
  12366. still enter a time, and this function will inform the calling routine
  12367. about this change. The calling routine may then choose to change the
  12368. format used to insert the time stamp into the buffer to include the time.
  12369. With optional argument FROM-STRING, read from this string instead from
  12370. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12371. the time/date that is used for everything that is not specified by the
  12372. user."
  12373. (require 'parse-time)
  12374. (let* ((org-with-time with-time)
  12375. (org-time-stamp-rounding-minutes
  12376. (if (equal org-with-time '(16))
  12377. '(0 0)
  12378. org-time-stamp-rounding-minutes))
  12379. (ct (org-current-time))
  12380. (org-def (or org-overriding-default-time default-time ct))
  12381. (org-defdecode (decode-time org-def))
  12382. (cur-frame (selected-frame))
  12383. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12384. (calendar-setup
  12385. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12386. (calendar-move-hook nil)
  12387. (calendar-view-diary-initially-flag nil)
  12388. (calendar-view-holidays-initially-flag nil)
  12389. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12390. ;; Rationalize `org-def' and `org-defdecode', if required.
  12391. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12392. (setf (nth 2 org-defdecode) -1)
  12393. (setf (nth 1 org-defdecode) 59)
  12394. (setq org-def (org-encode-time org-defdecode))
  12395. (setq org-defdecode (decode-time org-def)))
  12396. (let* ((timestr (format-time-string
  12397. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12398. org-def))
  12399. (prompt (concat (if prompt (concat prompt " ") "")
  12400. (format "Date+time [%s]: " timestr))))
  12401. (cond
  12402. (from-string (setq ans from-string))
  12403. (org-read-date-popup-calendar
  12404. (save-excursion
  12405. (save-window-excursion
  12406. (calendar)
  12407. (when (eq calendar-setup 'calendar-only)
  12408. (setq cal-frame
  12409. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12410. (select-frame cal-frame))
  12411. (org-eval-in-calendar '(setq cursor-type nil) t)
  12412. (unwind-protect
  12413. (progn
  12414. (calendar-forward-day (- (time-to-days org-def)
  12415. (calendar-absolute-from-gregorian
  12416. (calendar-current-date))))
  12417. (org-eval-in-calendar nil t)
  12418. (let* ((old-map (current-local-map))
  12419. (map (copy-keymap calendar-mode-map))
  12420. (minibuffer-local-map
  12421. (copy-keymap org-read-date-minibuffer-local-map)))
  12422. (org-defkey map (kbd "RET") 'org-calendar-select)
  12423. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12424. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12425. (unwind-protect
  12426. (progn
  12427. (use-local-map map)
  12428. (setq org-read-date-inactive inactive)
  12429. (add-hook 'post-command-hook 'org-read-date-display)
  12430. (setq org-ans0
  12431. (read-string prompt
  12432. default-input
  12433. 'org-read-date-history
  12434. nil))
  12435. ;; org-ans0: from prompt
  12436. ;; org-ans1: from mouse click
  12437. ;; org-ans2: from calendar motion
  12438. (setq ans
  12439. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12440. (remove-hook 'post-command-hook 'org-read-date-display)
  12441. (use-local-map old-map)
  12442. (when org-read-date-overlay
  12443. (delete-overlay org-read-date-overlay)
  12444. (setq org-read-date-overlay nil)))))
  12445. (bury-buffer "*Calendar*")
  12446. (when cal-frame
  12447. (delete-frame cal-frame)
  12448. (select-frame-set-input-focus cur-frame))))))
  12449. (t ; Naked prompt only
  12450. (unwind-protect
  12451. (setq ans (read-string prompt default-input
  12452. 'org-read-date-history timestr))
  12453. (when org-read-date-overlay
  12454. (delete-overlay org-read-date-overlay)
  12455. (setq org-read-date-overlay nil))))))
  12456. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12457. (when org-read-date-analyze-forced-year
  12458. (message "Year was forced into %s"
  12459. (if org-read-date-force-compatible-dates
  12460. "compatible range (1970-2037)"
  12461. "range representable on this machine"))
  12462. (ding))
  12463. (setq final (org-encode-time final))
  12464. (setq org-read-date-final-answer ans)
  12465. (if to-time
  12466. final
  12467. ;; This round-trip gets rid of 34th of August and stuff like that....
  12468. (setq final (decode-time final))
  12469. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12470. (format "%04d-%02d-%02d %02d:%02d"
  12471. (nth 5 final) (nth 4 final) (nth 3 final)
  12472. (nth 2 final) (nth 1 final))
  12473. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12474. (defun org-read-date-display ()
  12475. "Display the current date prompt interpretation in the minibuffer."
  12476. (when org-read-date-display-live
  12477. (when org-read-date-overlay
  12478. (delete-overlay org-read-date-overlay))
  12479. (when (minibufferp (current-buffer))
  12480. (save-excursion
  12481. (end-of-line 1)
  12482. (while (not (equal (buffer-substring
  12483. (max (point-min) (- (point) 4)) (point))
  12484. " "))
  12485. (insert " ")))
  12486. (let* ((ans (concat (buffer-substring (line-beginning-position) (point-max))
  12487. " " (or org-ans1 org-ans2)))
  12488. (org-end-time-was-given nil)
  12489. (f (org-read-date-analyze ans org-def org-defdecode))
  12490. (fmts (if org-display-custom-times
  12491. org-time-stamp-custom-formats
  12492. org-time-stamp-formats))
  12493. (fmt (if (or org-with-time
  12494. (and (boundp 'org-time-was-given) org-time-was-given))
  12495. (cdr fmts)
  12496. (car fmts)))
  12497. (txt (format-time-string fmt (org-encode-time f)))
  12498. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  12499. (txt (concat "=> " txt)))
  12500. (when (and org-end-time-was-given
  12501. (string-match org-plain-time-of-day-regexp txt))
  12502. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  12503. org-end-time-was-given
  12504. (substring txt (match-end 0)))))
  12505. (when org-read-date-analyze-futurep
  12506. (setq txt (concat txt " (=>F)")))
  12507. (setq org-read-date-overlay
  12508. (make-overlay (1- (line-end-position)) (line-end-position)))
  12509. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  12510. (defun org-read-date-analyze (ans def defdecode)
  12511. "Analyze the combined answer of the date prompt."
  12512. ;; FIXME: cleanup and comment
  12513. (let ((org-def def)
  12514. (org-defdecode defdecode)
  12515. (nowdecode (decode-time))
  12516. delta deltan deltaw deltadef year month day
  12517. hour minute second wday pm h2 m2 tl wday1
  12518. iso-year iso-weekday iso-week iso-date futurep kill-year)
  12519. (setq org-read-date-analyze-futurep nil
  12520. org-read-date-analyze-forced-year nil)
  12521. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  12522. (setq ans "+0"))
  12523. (when (setq delta (org-read-date-get-relative ans nil org-def))
  12524. (setq ans (replace-match "" t t ans)
  12525. deltan (car delta)
  12526. deltaw (nth 1 delta)
  12527. deltadef (nth 2 delta)))
  12528. ;; Check if there is an iso week date in there. If yes, store the
  12529. ;; info and postpone interpreting it until the rest of the parsing
  12530. ;; is done.
  12531. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  12532. (setq iso-year (when (match-end 1)
  12533. (org-small-year-to-year
  12534. (string-to-number (match-string 1 ans))))
  12535. iso-weekday (when (match-end 3)
  12536. (string-to-number (match-string 3 ans)))
  12537. iso-week (string-to-number (match-string 2 ans)))
  12538. (setq ans (replace-match "" t t ans)))
  12539. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  12540. (when (string-match
  12541. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  12542. (setq year (if (match-end 2)
  12543. (string-to-number (match-string 2 ans))
  12544. (progn (setq kill-year t)
  12545. (string-to-number (format-time-string "%Y"))))
  12546. month (string-to-number (match-string 3 ans))
  12547. day (string-to-number (match-string 4 ans)))
  12548. (setq year (org-small-year-to-year year))
  12549. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12550. t nil ans)))
  12551. ;; Help matching dotted european dates
  12552. (when (string-match
  12553. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  12554. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  12555. (setq kill-year t)
  12556. (string-to-number (format-time-string "%Y")))
  12557. day (string-to-number (match-string 1 ans))
  12558. month (string-to-number (match-string 2 ans))
  12559. ans (replace-match (format "%04d-%02d-%02d" year month day)
  12560. t nil ans)))
  12561. ;; Help matching american dates, like 5/30 or 5/30/7
  12562. (when (string-match
  12563. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  12564. (setq year (if (match-end 4)
  12565. (string-to-number (match-string 4 ans))
  12566. (progn (setq kill-year t)
  12567. (string-to-number (format-time-string "%Y"))))
  12568. month (string-to-number (match-string 1 ans))
  12569. day (string-to-number (match-string 2 ans)))
  12570. (setq year (org-small-year-to-year year))
  12571. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12572. t nil ans)))
  12573. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  12574. ;; If there is a time with am/pm, and *no* time without it, we convert
  12575. ;; so that matching will be successful.
  12576. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12577. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12578. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  12579. (setq hour (string-to-number (match-string 1 ans))
  12580. minute (if (match-end 3)
  12581. (string-to-number (match-string 3 ans))
  12582. 0)
  12583. pm (equal ?p
  12584. (string-to-char (downcase (match-string 4 ans)))))
  12585. (if (and (= hour 12) (not pm))
  12586. (setq hour 0)
  12587. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  12588. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12589. t t ans))))
  12590. ;; Help matching HHhMM times, similarly as for am/pm times.
  12591. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12592. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12593. (string-match "\\(?:\\(?1:[012]?[0-9]\\)?h\\(?2:[0-5][0-9]\\)\\)\\|\\(?:\\(?1:[012]?[0-9]\\)h\\(?2:[0-5][0-9]\\)?\\)\\>" ans))
  12594. (setq hour (if (match-end 1)
  12595. (string-to-number (match-string 1 ans))
  12596. 0)
  12597. minute (if (match-end 2)
  12598. (string-to-number (match-string 2 ans))
  12599. 0))
  12600. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12601. t t ans))))
  12602. ;; Check if a time range is given as a duration
  12603. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  12604. (setq hour (string-to-number (match-string 1 ans))
  12605. h2 (+ hour (string-to-number (match-string 3 ans)))
  12606. minute (string-to-number (match-string 2 ans))
  12607. m2 (+ minute (if (match-end 5) (string-to-number
  12608. (match-string 5 ans))0)))
  12609. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  12610. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  12611. t t ans)))
  12612. ;; Check if there is a time range
  12613. (when (boundp 'org-end-time-was-given)
  12614. (setq org-time-was-given nil)
  12615. (when (and (string-match org-plain-time-of-day-regexp ans)
  12616. (match-end 8))
  12617. (setq org-end-time-was-given (match-string 8 ans))
  12618. (setq ans (concat (substring ans 0 (match-beginning 7))
  12619. (substring ans (match-end 7))))))
  12620. (setq tl (parse-time-string ans)
  12621. day (or (nth 3 tl) (nth 3 org-defdecode))
  12622. month
  12623. (cond ((nth 4 tl))
  12624. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  12625. ;; Day was specified. Make sure DAY+MONTH
  12626. ;; combination happens in the future.
  12627. ((nth 3 tl)
  12628. (setq futurep t)
  12629. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  12630. (nth 4 nowdecode)))
  12631. (t (nth 4 org-defdecode)))
  12632. year
  12633. (cond ((and (not kill-year) (nth 5 tl)))
  12634. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  12635. ;; Month was guessed in the future and is at least
  12636. ;; equal to NOWDECODE's. Fix year accordingly.
  12637. (futurep
  12638. (if (or (> month (nth 4 nowdecode))
  12639. (>= day (nth 3 nowdecode)))
  12640. (nth 5 nowdecode)
  12641. (1+ (nth 5 nowdecode))))
  12642. ;; Month was specified. Make sure MONTH+YEAR
  12643. ;; combination happens in the future.
  12644. ((nth 4 tl)
  12645. (setq futurep t)
  12646. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  12647. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  12648. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  12649. (t (nth 5 nowdecode))))
  12650. (t (nth 5 org-defdecode)))
  12651. hour (or (nth 2 tl) (nth 2 org-defdecode))
  12652. minute (or (nth 1 tl) (nth 1 org-defdecode))
  12653. second (or (nth 0 tl) 0)
  12654. wday (nth 6 tl))
  12655. (when (and (eq org-read-date-prefer-future 'time)
  12656. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  12657. (equal day (nth 3 nowdecode))
  12658. (equal month (nth 4 nowdecode))
  12659. (equal year (nth 5 nowdecode))
  12660. (nth 2 tl)
  12661. (or (< (nth 2 tl) (nth 2 nowdecode))
  12662. (and (= (nth 2 tl) (nth 2 nowdecode))
  12663. (nth 1 tl)
  12664. (< (nth 1 tl) (nth 1 nowdecode)))))
  12665. (setq day (1+ day)
  12666. futurep t))
  12667. ;; Special date definitions below
  12668. (cond
  12669. (iso-week
  12670. ;; There was an iso week
  12671. (require 'cal-iso)
  12672. (setq futurep nil)
  12673. (setq year (or iso-year year)
  12674. day (or iso-weekday wday 1)
  12675. wday nil ; to make sure that the trigger below does not match
  12676. iso-date (calendar-gregorian-from-absolute
  12677. (calendar-iso-to-absolute
  12678. (list iso-week day year))))
  12679. ; FIXME: Should we also push ISO weeks into the future?
  12680. ; (when (and org-read-date-prefer-future
  12681. ; (not iso-year)
  12682. ; (< (calendar-absolute-from-gregorian iso-date)
  12683. ; (time-to-days nil)))
  12684. ; (setq year (1+ year)
  12685. ; iso-date (calendar-gregorian-from-absolute
  12686. ; (calendar-iso-to-absolute
  12687. ; (list iso-week day year)))))
  12688. (setq month (car iso-date)
  12689. year (nth 2 iso-date)
  12690. day (nth 1 iso-date)))
  12691. (deltan
  12692. (setq futurep nil)
  12693. (unless deltadef
  12694. (let ((now (decode-time)))
  12695. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  12696. (cond ((member deltaw '("h" ""))
  12697. (when (boundp 'org-time-was-given)
  12698. (setq org-time-was-given t))
  12699. (setq hour (+ hour deltan)))
  12700. ((member deltaw '("d" "")) (setq day (+ day deltan)))
  12701. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  12702. ((equal deltaw "m") (setq month (+ month deltan)))
  12703. ((equal deltaw "y") (setq year (+ year deltan)))))
  12704. ((and wday (not (nth 3 tl)))
  12705. ;; Weekday was given, but no day, so pick that day in the week
  12706. ;; on or after the derived date.
  12707. (setq wday1 (nth 6 (decode-time (org-encode-time 0 0 0 day month year))))
  12708. (unless (equal wday wday1)
  12709. (setq day (+ day (% (- wday wday1 -7) 7))))))
  12710. (when (and (boundp 'org-time-was-given)
  12711. (nth 2 tl))
  12712. (setq org-time-was-given t))
  12713. (when (< year 100) (setq year (+ 2000 year)))
  12714. ;; Check of the date is representable
  12715. (if org-read-date-force-compatible-dates
  12716. (progn
  12717. (when (< year 1970)
  12718. (setq year 1970 org-read-date-analyze-forced-year t))
  12719. (when (> year 2037)
  12720. (setq year 2037 org-read-date-analyze-forced-year t)))
  12721. (condition-case nil
  12722. (ignore (org-encode-time second minute hour day month year))
  12723. (error
  12724. (setq year (nth 5 org-defdecode))
  12725. (setq org-read-date-analyze-forced-year t))))
  12726. (setq org-read-date-analyze-futurep futurep)
  12727. (list second minute hour day month year nil -1 nil)))
  12728. (defvar parse-time-weekdays)
  12729. (defun org-read-date-get-relative (s today default)
  12730. "Check string S for special relative date string.
  12731. TODAY and DEFAULT are internal times, for today and for a default.
  12732. Return shift list (N what def-flag)
  12733. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  12734. N is the number of WHATs to shift.
  12735. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  12736. the DEFAULT date rather than TODAY."
  12737. (require 'parse-time)
  12738. (when (and
  12739. (string-match
  12740. (concat
  12741. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  12742. "\\([0-9]+\\)?"
  12743. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  12744. "\\([ \t]\\|$\\)") s)
  12745. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  12746. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  12747. (string-to-char (substring (match-string 1 s) -1))
  12748. ?+))
  12749. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  12750. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  12751. (what (if (match-end 3) (match-string 3 s) "d"))
  12752. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  12753. (date (if rel default today))
  12754. (wday (nth 6 (decode-time date)))
  12755. delta)
  12756. (if wday1
  12757. (progn
  12758. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  12759. (when (= delta 0) (setq delta 7))
  12760. (when (= dir ?-)
  12761. (setq delta (- delta 7))
  12762. (when (= delta 0) (setq delta -7)))
  12763. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  12764. (list delta "d" rel))
  12765. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  12766. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  12767. "Turn a user-specified date into the internal representation.
  12768. The internal representation needed by the calendar is (month day year).
  12769. This is a wrapper to handle the brain-dead convention in calendar that
  12770. user function argument order change dependent on argument order."
  12771. (pcase calendar-date-style
  12772. (`american (list arg1 arg2 arg3))
  12773. (`european (list arg2 arg1 arg3))
  12774. (`iso (list arg2 arg3 arg1))))
  12775. (defun org-eval-in-calendar (form &optional keepdate)
  12776. "Eval FORM in the calendar window and return to current window.
  12777. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  12778. (let ((sf (selected-frame))
  12779. (sw (selected-window)))
  12780. (select-window (get-buffer-window "*Calendar*" t))
  12781. (eval form t)
  12782. (when (and (not keepdate) (calendar-cursor-to-date))
  12783. (let* ((date (calendar-cursor-to-date))
  12784. (time (org-encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12785. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  12786. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  12787. (select-window sw)
  12788. (select-frame-set-input-focus sf)))
  12789. (defun org-calendar-select ()
  12790. "Return to `org-read-date' with the date currently selected.
  12791. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12792. (interactive)
  12793. (when (calendar-cursor-to-date)
  12794. (let* ((date (calendar-cursor-to-date))
  12795. (time (org-encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12796. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12797. (when (active-minibuffer-window) (exit-minibuffer))))
  12798. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  12799. "Insert a date stamp for the date given by the internal TIME.
  12800. See `format-time-string' for the format of TIME.
  12801. WITH-HM means use the stamp format that includes the time of the day.
  12802. INACTIVE means use square brackets instead of angular ones, so that the
  12803. stamp will not contribute to the agenda.
  12804. PRE and POST are optional strings to be inserted before and after the
  12805. stamp.
  12806. The command returns the inserted time stamp."
  12807. (org-fold-core-ignore-modifications
  12808. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  12809. stamp)
  12810. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  12811. (insert-before-markers-and-inherit (or pre ""))
  12812. (when (listp extra)
  12813. (setq extra (car extra))
  12814. (if (and (stringp extra)
  12815. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  12816. (setq extra (format "-%02d:%02d"
  12817. (string-to-number (match-string 1 extra))
  12818. (string-to-number (match-string 2 extra))))
  12819. (setq extra nil)))
  12820. (when extra
  12821. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  12822. (insert-before-markers-and-inherit (setq stamp (format-time-string fmt time)))
  12823. (insert-before-markers-and-inherit (or post ""))
  12824. (setq org-last-inserted-timestamp stamp))))
  12825. (defun org-toggle-time-stamp-overlays ()
  12826. "Toggle the use of custom time stamp formats."
  12827. (interactive)
  12828. (setq org-display-custom-times (not org-display-custom-times))
  12829. (unless org-display-custom-times
  12830. (let ((p (point-min)) (bmp (buffer-modified-p)))
  12831. (while (setq p (next-single-property-change p 'display))
  12832. (when (and (get-text-property p 'display)
  12833. (eq (get-text-property p 'face) 'org-date))
  12834. (remove-text-properties
  12835. p (setq p (next-single-property-change p 'display))
  12836. '(display t))))
  12837. (set-buffer-modified-p bmp)))
  12838. (org-restart-font-lock)
  12839. (setq org-table-may-need-update t)
  12840. (if org-display-custom-times
  12841. (message "Time stamps are overlaid with custom format")
  12842. (message "Time stamp overlays removed")))
  12843. (defun org-display-custom-time (beg end)
  12844. "Overlay modified time stamp format over timestamp between BEG and END."
  12845. (let* ((ts (buffer-substring beg end))
  12846. t1 with-hm tf time str (off 0))
  12847. (save-match-data
  12848. (setq t1 (org-parse-time-string ts t))
  12849. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  12850. (setq off (- (match-end 0) (match-beginning 0)))))
  12851. (setq end (- end off))
  12852. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  12853. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  12854. time (org-fix-decoded-time t1)
  12855. str (org-add-props
  12856. (format-time-string
  12857. (substring tf 1 -1) (org-encode-time time))
  12858. nil 'mouse-face 'highlight))
  12859. (put-text-property beg end 'display str)))
  12860. (defun org-fix-decoded-time (time)
  12861. "Set 0 instead of nil for the first 6 elements of time.
  12862. Don't touch the rest."
  12863. (let ((n 0))
  12864. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  12865. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  12866. "Difference between TIMESTAMP-STRING and now in days.
  12867. If SECONDS is non-nil, return the difference in seconds."
  12868. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  12869. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  12870. (funcall fdiff nil))))
  12871. (defun org-deadline-close-p (timestamp-string &optional ndays)
  12872. "Is the time in TIMESTAMP-STRING close to the current date?"
  12873. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  12874. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  12875. (not (org-entry-is-done-p))))
  12876. (defun org-get-wdays (ts &optional delay zero-delay)
  12877. "Get the deadline lead time appropriate for timestring TS.
  12878. When DELAY is non-nil, get the delay time for scheduled items
  12879. instead of the deadline lead time. When ZERO-DELAY is non-nil
  12880. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  12881. don't try to find the delay cookie in the scheduled timestamp."
  12882. (let ((tv (if delay org-scheduled-delay-days
  12883. org-deadline-warning-days)))
  12884. (cond
  12885. ((or (and delay (< tv 0))
  12886. (and delay zero-delay (<= tv 0))
  12887. (and (not delay) (<= tv 0)))
  12888. ;; Enforce this value no matter what
  12889. (- tv))
  12890. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  12891. ;; lead time is specified.
  12892. (floor (* (string-to-number (match-string 1 ts))
  12893. (cdr (assoc (match-string 2 ts)
  12894. '(("d" . 1) ("w" . 7)
  12895. ("m" . 30.4) ("y" . 365.25)
  12896. ("h" . 0.041667)))))))
  12897. ;; go for the default.
  12898. (t tv))))
  12899. (defun org-calendar-select-mouse (ev)
  12900. "Return to `org-read-date' with the date currently selected.
  12901. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12902. (interactive "e")
  12903. (mouse-set-point ev)
  12904. (when (calendar-cursor-to-date)
  12905. (let* ((date (calendar-cursor-to-date))
  12906. (time (org-encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12907. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12908. (when (active-minibuffer-window) (exit-minibuffer))))
  12909. (defun org-check-deadlines (ndays)
  12910. "Check if there are any deadlines due or past due.
  12911. A deadline is considered due if it happens within `org-deadline-warning-days'
  12912. days from today's date. If the deadline appears in an entry marked DONE,
  12913. it is not shown. A numeric prefix argument NDAYS can be used to test that
  12914. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  12915. are shown."
  12916. (interactive "P")
  12917. (let* ((org-warn-days
  12918. (cond
  12919. ((equal ndays '(4)) 100000)
  12920. (ndays (prefix-numeric-value ndays))
  12921. (t (abs org-deadline-warning-days))))
  12922. (case-fold-search nil)
  12923. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  12924. (callback
  12925. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  12926. (message "%d deadlines past-due or due within %d days"
  12927. (org-occur regexp nil callback)
  12928. org-warn-days)))
  12929. (defsubst org-re-timestamp (type)
  12930. "Return a regexp for timestamp TYPE.
  12931. Allowed values for TYPE are:
  12932. all: all timestamps
  12933. active: only active timestamps (<...>)
  12934. inactive: only inactive timestamps ([...])
  12935. scheduled: only scheduled timestamps
  12936. deadline: only deadline timestamps
  12937. closed: only closed time-stamps
  12938. When TYPE is nil, fall back on returning a regexp that matches
  12939. both scheduled and deadline timestamps."
  12940. (cl-case type
  12941. (all org-ts-regexp-both)
  12942. (active org-ts-regexp)
  12943. (inactive org-ts-regexp-inactive)
  12944. (scheduled org-scheduled-time-regexp)
  12945. (deadline org-deadline-time-regexp)
  12946. (closed org-closed-time-regexp)
  12947. (otherwise
  12948. (concat "\\<"
  12949. (regexp-opt (list org-deadline-string org-scheduled-string))
  12950. " *<\\([^>]+\\)>"))))
  12951. (defun org-check-before-date (d)
  12952. "Check if there are deadlines or scheduled entries before date D."
  12953. (interactive (list (org-read-date)))
  12954. (let* ((case-fold-search nil)
  12955. (regexp (org-re-timestamp org-ts-type))
  12956. (ts-type org-ts-type)
  12957. (callback
  12958. (lambda ()
  12959. (let ((match (match-string 1)))
  12960. (and (if (memq ts-type '(active inactive all))
  12961. (eq (org-element-type (save-excursion
  12962. (backward-char)
  12963. (org-element-context)))
  12964. 'timestamp)
  12965. (org-at-planning-p))
  12966. (time-less-p
  12967. (org-time-string-to-time match)
  12968. (org-time-string-to-time d)))))))
  12969. (message "%d entries before %s"
  12970. (org-occur regexp nil callback)
  12971. d)))
  12972. (defun org-check-after-date (d)
  12973. "Check if there are deadlines or scheduled entries after date D."
  12974. (interactive (list (org-read-date)))
  12975. (let* ((case-fold-search nil)
  12976. (regexp (org-re-timestamp org-ts-type))
  12977. (ts-type org-ts-type)
  12978. (callback
  12979. (lambda ()
  12980. (let ((match (match-string 1)))
  12981. (and (if (memq ts-type '(active inactive all))
  12982. (eq (org-element-type (save-excursion
  12983. (backward-char)
  12984. (org-element-context)))
  12985. 'timestamp)
  12986. (org-at-planning-p))
  12987. (not (time-less-p
  12988. (org-time-string-to-time match)
  12989. (org-time-string-to-time d))))))))
  12990. (message "%d entries after %s"
  12991. (org-occur regexp nil callback)
  12992. d)))
  12993. (defun org-check-dates-range (start-date end-date)
  12994. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  12995. (interactive (list (org-read-date nil nil nil "Range starts")
  12996. (org-read-date nil nil nil "Range end")))
  12997. (let ((case-fold-search nil)
  12998. (regexp (org-re-timestamp org-ts-type))
  12999. (callback
  13000. (let ((type org-ts-type))
  13001. (lambda ()
  13002. (let ((match (match-string 1)))
  13003. (and
  13004. (if (memq type '(active inactive all))
  13005. (eq (org-element-type (save-excursion
  13006. (backward-char)
  13007. (org-element-context)))
  13008. 'timestamp)
  13009. (org-at-planning-p))
  13010. (not (time-less-p
  13011. (org-time-string-to-time match)
  13012. (org-time-string-to-time start-date)))
  13013. (time-less-p
  13014. (org-time-string-to-time match)
  13015. (org-time-string-to-time end-date))))))))
  13016. (message "%d entries between %s and %s"
  13017. (org-occur regexp nil callback) start-date end-date)))
  13018. (defun org-evaluate-time-range (&optional to-buffer)
  13019. "Evaluate a time range by computing the difference between start and end.
  13020. Normally the result is just printed in the echo area, but with prefix arg
  13021. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  13022. If the time range is actually in a table, the result is inserted into the
  13023. next column.
  13024. For time difference computation, a year is assumed to be exactly 365
  13025. days in order to avoid rounding problems."
  13026. (interactive "P")
  13027. (or
  13028. (org-clock-update-time-maybe)
  13029. (save-excursion
  13030. (unless (org-at-date-range-p t)
  13031. (goto-char (line-beginning-position))
  13032. (re-search-forward org-tr-regexp-both (line-end-position) t))
  13033. (unless (org-at-date-range-p t)
  13034. (user-error "Not at a time-stamp range, and none found in current line")))
  13035. (let* ((ts1 (match-string 1))
  13036. (ts2 (match-string 2))
  13037. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  13038. (match-end (match-end 0))
  13039. (time1 (org-time-string-to-time ts1))
  13040. (time2 (org-time-string-to-time ts2))
  13041. (diff (abs (float-time (time-subtract time2 time1))))
  13042. (negative (time-less-p time2 time1))
  13043. ;; (ys (floor (* 365 24 60 60)))
  13044. (ds (* 24 60 60))
  13045. (hs (* 60 60))
  13046. (fy "%dy %dd %02d:%02d")
  13047. (fy1 "%dy %dd")
  13048. (fd "%dd %02d:%02d")
  13049. (fd1 "%dd")
  13050. (fh "%02d:%02d")
  13051. y d h m align)
  13052. (if havetime
  13053. (setq ; y (floor diff ys) diff (mod diff ys)
  13054. y 0
  13055. d (floor diff ds) diff (mod diff ds)
  13056. h (floor diff hs) diff (mod diff hs)
  13057. m (floor diff 60))
  13058. (setq ; y (floor diff ys) diff (mod diff ys)
  13059. y 0
  13060. d (round diff ds)
  13061. h 0 m 0))
  13062. (if (not to-buffer)
  13063. (message "%s" (org-make-tdiff-string y d h m))
  13064. (if (org-at-table-p)
  13065. (progn
  13066. (goto-char match-end)
  13067. (setq align t)
  13068. (and (looking-at " *|") (goto-char (match-end 0))))
  13069. (goto-char match-end))
  13070. (when (looking-at
  13071. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  13072. (replace-match ""))
  13073. (when negative (insert " -"))
  13074. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  13075. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  13076. (insert " " (format fh h m))))
  13077. (when align (org-table-align))
  13078. (message "Time difference inserted")))))
  13079. (defun org-make-tdiff-string (y d h m)
  13080. (let ((fmt "")
  13081. (l nil))
  13082. (when (> y 0)
  13083. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  13084. (push y l))
  13085. (when (> d 0)
  13086. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  13087. (push d l))
  13088. (when (> h 0)
  13089. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  13090. (push h l))
  13091. (when (> m 0)
  13092. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  13093. (push m l))
  13094. (apply 'format fmt (nreverse l))))
  13095. (defun org-time-string-to-time (s)
  13096. "Convert timestamp string S into internal time."
  13097. (org-encode-time (org-parse-time-string s)))
  13098. (defun org-time-string-to-seconds (s)
  13099. "Convert a timestamp string S into a number of seconds."
  13100. (float-time (org-time-string-to-time s)))
  13101. (define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  13102. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  13103. "Convert time stamp S to an absolute day number.
  13104. If DAYNR in non-nil, and there is a specifier for a cyclic time
  13105. stamp, get the closest date to DAYNR. If PREFER is
  13106. `past' (respectively `future') return a date past (respectively
  13107. after) or equal to DAYNR.
  13108. POS is the location of time stamp S, as a buffer position in
  13109. BUFFER.
  13110. Diary sexp timestamps are matched against DAYNR, when non-nil.
  13111. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  13112. signaled."
  13113. (cond
  13114. ((string-match "\\`%%\\((.*)\\)" s)
  13115. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13116. ;; only able to match individual dates. If it fails, raise an
  13117. ;; error.
  13118. (if (and daynr
  13119. (org-diary-sexp-entry
  13120. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13121. daynr
  13122. (signal 'org-diary-sexp-no-match (list s))))
  13123. (daynr (org-closest-date s daynr prefer))
  13124. (t (time-to-days
  13125. (condition-case errdata
  13126. (org-time-string-to-time s)
  13127. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13128. s
  13129. (if (not (and buffer pos)) ""
  13130. (format-message " at %d in buffer `%s'" pos buffer))
  13131. (cdr errdata))))))))
  13132. (defun org-days-to-iso-week (days)
  13133. "Return the ISO week number."
  13134. (require 'cal-iso)
  13135. (car (calendar-iso-from-absolute days)))
  13136. (defun org-small-year-to-year (year)
  13137. "Convert 2-digit years into 4-digit years.
  13138. YEAR is expanded into one of the 30 next years, if possible, or
  13139. into a past one. Any year larger than 99 is returned unchanged."
  13140. (if (>= year 100) year
  13141. (let* ((current (string-to-number (format-time-string "%Y")))
  13142. (century (/ current 100))
  13143. (offset (- year (% current 100))))
  13144. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13145. ((> offset -70) (+ (* century 100) year))
  13146. (t (+ (* (1+ century) 100) year))))))
  13147. (defun org-time-from-absolute (d)
  13148. "Return the time corresponding to date D.
  13149. D may be an absolute day number, or a calendar-type list (month day year)."
  13150. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13151. (org-encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13152. (defvar org-agenda-current-date)
  13153. (defun org-calendar-holiday ()
  13154. "List of holidays, for Diary display in Org mode."
  13155. (require 'holidays)
  13156. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13157. (and hl (mapconcat #'identity hl "; "))))
  13158. (defvar org--diary-sexp-entry-cache (make-hash-table :test #'equal)
  13159. "Hash table holding return values of `org-diary-sexp-entry'.")
  13160. (defun org-diary-sexp-entry (sexp entry d)
  13161. "Process a SEXP diary ENTRY for date D."
  13162. (require 'diary-lib)
  13163. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13164. ;; dynamically.
  13165. (or (gethash (list sexp entry d) org--diary-sexp-entry-cache)
  13166. (puthash (list sexp entry d)
  13167. (let* ((sexp `(let ((entry ,entry)
  13168. (date ',d))
  13169. ,(car (read-from-string sexp))))
  13170. ;; FIXME: Do not use (eval ... t) in the following sexp as
  13171. ;; diary vars are still using dynamic scope.
  13172. (result (if calendar-debug-sexp (eval sexp)
  13173. (condition-case nil
  13174. (eval sexp)
  13175. (error
  13176. (beep)
  13177. (message "Bad sexp at line %d in %s: %s"
  13178. (org-current-line)
  13179. (buffer-file-name) sexp)
  13180. (sleep-for 2))))))
  13181. (cond ((stringp result) (split-string result "; "))
  13182. ((and (consp result)
  13183. (not (consp (cdr result)))
  13184. (stringp (cdr result)))
  13185. (cdr result))
  13186. ((and (consp result)
  13187. (stringp (car result)))
  13188. result)
  13189. (result entry)))
  13190. org--diary-sexp-entry-cache)))
  13191. (defun org-diary-to-ical-string (frombuf)
  13192. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13193. This uses the icalendar.el library."
  13194. (let* ((tmpdir temporary-file-directory)
  13195. (tmpfile (make-temp-name
  13196. (expand-file-name "orgics" tmpdir)))
  13197. buf rtn b e)
  13198. (with-current-buffer frombuf
  13199. (icalendar-export-region (point-min) (point-max) tmpfile)
  13200. (setq buf (find-buffer-visiting tmpfile))
  13201. (set-buffer buf)
  13202. (goto-char (point-min))
  13203. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13204. (setq b (match-beginning 0)))
  13205. (goto-char (point-max))
  13206. (when (re-search-backward "^END:VEVENT" nil t)
  13207. (setq e (match-end 0)))
  13208. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13209. (kill-buffer buf)
  13210. (delete-file tmpfile)
  13211. rtn))
  13212. (defun org-closest-date (start current prefer)
  13213. "Return closest date to CURRENT starting from START.
  13214. CURRENT and START are both time stamps.
  13215. When PREFER is `past', return a date that is either CURRENT or
  13216. past. When PREFER is `future', return a date that is either
  13217. CURRENT or future.
  13218. Only time stamps with a repeater are modified. Any other time
  13219. stamp stay unchanged. In any case, return value is an absolute
  13220. day number."
  13221. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13222. ;; No repeater. Do not shift time stamp.
  13223. (time-to-days (org-time-string-to-time start))
  13224. (let ((value (string-to-number (match-string 1 start)))
  13225. (type (match-string 2 start)))
  13226. (if (= 0 value)
  13227. ;; Repeater with a 0-value is considered as void.
  13228. (time-to-days (org-time-string-to-time start))
  13229. (let* ((base (org-date-to-gregorian start))
  13230. (target (org-date-to-gregorian current))
  13231. (sday (calendar-absolute-from-gregorian base))
  13232. (cday (calendar-absolute-from-gregorian target))
  13233. n1 n2)
  13234. ;; If START is already past CURRENT, just return START.
  13235. (if (<= cday sday) sday
  13236. ;; Compute closest date before (N1) and closest date past
  13237. ;; (N2) CURRENT.
  13238. (pcase type
  13239. ("h"
  13240. (let ((missing-hours
  13241. (mod (+ (- (* 24 (- cday sday))
  13242. (nth 2 (org-parse-time-string start)))
  13243. org-extend-today-until)
  13244. value)))
  13245. (setf n1 (if (= missing-hours 0) cday
  13246. (- cday (1+ (/ missing-hours 24)))))
  13247. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13248. ((or "d" "w")
  13249. (let ((value (if (equal type "w") (* 7 value) value)))
  13250. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13251. (setf n2 (+ n1 value))))
  13252. ("m"
  13253. (let* ((add-months
  13254. (lambda (d n)
  13255. ;; Add N months to gregorian date D, i.e.,
  13256. ;; a list (MONTH DAY YEAR). Return a valid
  13257. ;; gregorian date.
  13258. (let ((m (+ (nth 0 d) n)))
  13259. (list (mod m 12)
  13260. (nth 1 d)
  13261. (+ (/ m 12) (nth 2 d))))))
  13262. (months ; Complete months to TARGET.
  13263. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13264. (- (nth 0 target) (nth 0 base))
  13265. ;; If START's day is greater than
  13266. ;; TARGET's, remove incomplete month.
  13267. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13268. value)
  13269. value))
  13270. (before (funcall add-months base months)))
  13271. (setf n1 (calendar-absolute-from-gregorian before))
  13272. (setf n2
  13273. (calendar-absolute-from-gregorian
  13274. (funcall add-months before value)))))
  13275. (_
  13276. (let* ((d (nth 1 base))
  13277. (m (nth 0 base))
  13278. (y (nth 2 base))
  13279. (years ; Complete years to TARGET.
  13280. (* (/ (- (nth 2 target)
  13281. y
  13282. ;; If START's month and day are
  13283. ;; greater than TARGET's, remove
  13284. ;; incomplete year.
  13285. (if (or (> (nth 0 target) m)
  13286. (and (= (nth 0 target) m)
  13287. (> (nth 1 target) d)))
  13288. 0
  13289. 1))
  13290. value)
  13291. value))
  13292. (before (list m d (+ y years))))
  13293. (setf n1 (calendar-absolute-from-gregorian before))
  13294. (setf n2 (calendar-absolute-from-gregorian
  13295. (list m d (+ (nth 2 before) value)))))))
  13296. ;; Handle PREFER parameter, if any.
  13297. (cond
  13298. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13299. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13300. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13301. (defun org-date-to-gregorian (d)
  13302. "Turn any specification of date D into a Gregorian date for the calendar."
  13303. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13304. ((and (listp d) (= (length d) 3)) d)
  13305. ((stringp d)
  13306. (let ((d (org-parse-time-string d)))
  13307. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13308. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13309. (defun org-timestamp-up (&optional arg)
  13310. "Increase the date item at the cursor by one.
  13311. If the cursor is on the year, change the year. If it is on the month,
  13312. the day or the time, change that. If the cursor is on the enclosing
  13313. bracket, change the timestamp type.
  13314. With prefix ARG, change by that many units."
  13315. (interactive "p")
  13316. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13317. (defun org-timestamp-down (&optional arg)
  13318. "Decrease the date item at the cursor by one.
  13319. If the cursor is on the year, change the year. If it is on the month,
  13320. the day or the time, change that. If the cursor is on the enclosing
  13321. bracket, change the timestamp type.
  13322. With prefix ARG, change by that many units."
  13323. (interactive "p")
  13324. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13325. (defun org-timestamp-up-day (&optional arg)
  13326. "Increase the date in the time stamp by one day.
  13327. With prefix ARG, change that many days."
  13328. (interactive "p")
  13329. (if (and (not (org-at-timestamp-p 'lax))
  13330. (org-at-heading-p))
  13331. (org-todo 'up)
  13332. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13333. (defun org-timestamp-down-day (&optional arg)
  13334. "Decrease the date in the time stamp by one day.
  13335. With prefix ARG, change that many days."
  13336. (interactive "p")
  13337. (if (and (not (org-at-timestamp-p 'lax))
  13338. (org-at-heading-p))
  13339. (org-todo 'down)
  13340. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13341. (defun org-at-timestamp-p (&optional extended)
  13342. "Non-nil if point is inside a timestamp.
  13343. By default, the function only consider syntactically valid active
  13344. timestamps. However, the caller may have a broader definition
  13345. for timestamps. As a consequence, optional argument EXTENDED can
  13346. be set to the following values
  13347. `inactive'
  13348. Include also syntactically valid inactive timestamps.
  13349. `agenda'
  13350. Include timestamps allowed in Agenda, i.e., those in
  13351. properties drawers, planning lines and clock lines.
  13352. `lax'
  13353. Ignore context. The function matches any part of the
  13354. document looking like a timestamp. This includes comments,
  13355. example blocks...
  13356. For backward-compatibility with Org 9.0, every other non-nil
  13357. value is equivalent to `inactive'.
  13358. When at a timestamp, return the position of the point as a symbol
  13359. among `bracket', `after', `year', `month', `hour', `minute',
  13360. `day' or a number of character from the last know part of the
  13361. time stamp. If diary sexp timestamps, any point inside the timestamp
  13362. is considered `day' (i.e. only `bracket', `day', and `after' return
  13363. values are possible).
  13364. When matching, the match groups are the following:
  13365. group 1: year, if any
  13366. group 2: month, if any
  13367. group 3: day number, if any
  13368. group 4: day name, if any
  13369. group 5: hours, if any
  13370. group 6: minutes, if any"
  13371. (let* ((regexp
  13372. (if extended
  13373. (if (eq extended 'agenda)
  13374. (rx-to-string
  13375. `(or (regexp ,org-ts-regexp3)
  13376. (regexp ,org-element--timestamp-regexp)))
  13377. org-ts-regexp3)
  13378. org-ts-regexp2))
  13379. (pos (point))
  13380. (match?
  13381. (let ((boundaries (org-in-regexp regexp)))
  13382. (save-match-data
  13383. (cond ((null boundaries) nil)
  13384. ((eq extended 'lax) t)
  13385. (t
  13386. (or (and (eq extended 'agenda)
  13387. (or (org-at-planning-p)
  13388. (org-at-property-p)
  13389. (and (bound-and-true-p
  13390. org-agenda-include-inactive-timestamps)
  13391. (org-at-clock-log-p))))
  13392. (eq 'timestamp
  13393. (save-excursion
  13394. (when (= pos (cdr boundaries)) (forward-char -1))
  13395. (org-element-type (org-element-context)))))))))))
  13396. (cond
  13397. ((not match?) nil)
  13398. ((= pos (match-beginning 0)) 'bracket)
  13399. ;; Distinguish location right before the closing bracket from
  13400. ;; right after it.
  13401. ((= pos (1- (match-end 0))) 'bracket)
  13402. ((= pos (match-end 0)) 'after)
  13403. ((org-pos-in-match-range pos 2) 'year)
  13404. ((org-pos-in-match-range pos 3) 'month)
  13405. ((org-pos-in-match-range pos 7) 'hour)
  13406. ((org-pos-in-match-range pos 8) 'minute)
  13407. ((or (org-pos-in-match-range pos 4)
  13408. (org-pos-in-match-range pos 5)) 'day)
  13409. ((and (or (match-end 8) (match-end 5))
  13410. (> pos (or (match-end 8) (match-end 5)))
  13411. (< pos (match-end 0)))
  13412. (- pos (or (match-end 8) (match-end 5))))
  13413. (t 'day))))
  13414. (defun org-toggle-timestamp-type ()
  13415. "Toggle the type (<active> or [inactive]) of a time stamp."
  13416. (interactive)
  13417. (when (org-at-timestamp-p 'lax)
  13418. (let ((beg (match-beginning 0)) (end (match-end 0))
  13419. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13420. (save-excursion
  13421. (goto-char beg)
  13422. (while (re-search-forward "[][<>]" end t)
  13423. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13424. t t)))
  13425. (message "Timestamp is now %sactive"
  13426. (if (equal (char-after beg) ?<) "" "in")))))
  13427. (defun org-at-clock-log-p ()
  13428. "Non-nil if point is on a clock log line."
  13429. (and (org-match-line org-clock-line-re)
  13430. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13431. (defvar org-clock-history) ; defined in org-clock.el
  13432. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13433. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13434. "Change the date in the time stamp at point.
  13435. The date is changed by N times WHAT. WHAT can be `day', `month',
  13436. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13437. position in the timestamp determines what is changed.
  13438. When optional argument UPDOWN is non-nil, minutes are rounded
  13439. according to `org-time-stamp-rounding-minutes'.
  13440. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13441. \"--2d\"."
  13442. (let ((origin (point))
  13443. (timestamp? (org-at-timestamp-p 'lax))
  13444. origin-cat
  13445. with-hm inactive
  13446. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13447. extra rem
  13448. ts time time0 fixnext clrgx)
  13449. (unless timestamp? (user-error "Not at a timestamp"))
  13450. (if (and (not what) (eq timestamp? 'bracket))
  13451. (org-toggle-timestamp-type)
  13452. ;; Point isn't on brackets. Remember the part of the time-stamp
  13453. ;; the point was in. Indeed, size of time-stamps may change,
  13454. ;; but point must be kept in the same category nonetheless.
  13455. (setq origin-cat timestamp?)
  13456. (when (and (not what) (not (eq timestamp? 'day))
  13457. org-display-custom-times
  13458. (get-text-property (point) 'display)
  13459. (not (get-text-property (1- (point)) 'display)))
  13460. (setq timestamp? 'day))
  13461. (setq timestamp? (or what timestamp?)
  13462. inactive (= (char-after (match-beginning 0)) ?\[)
  13463. ts (match-string 0))
  13464. (replace-match "")
  13465. (when (string-match
  13466. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13467. ts)
  13468. (setq extra (match-string 1 ts))
  13469. (when suppress-tmp-delay
  13470. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13471. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13472. (setq with-hm t))
  13473. (setq time0 (org-parse-time-string ts))
  13474. (when (and updown
  13475. (eq timestamp? 'minute)
  13476. (not current-prefix-arg))
  13477. ;; This looks like s-up and s-down. Change by one rounding step.
  13478. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13479. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13480. (setcar (cdr time0) (+ (nth 1 time0)
  13481. (if (> n 0) (- rem) (- dm rem))))))
  13482. (setq time
  13483. (org-encode-time
  13484. (apply #'list
  13485. (or (car time0) 0)
  13486. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13487. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13488. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13489. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13490. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13491. (nthcdr 6 time0))))
  13492. (when (and (memq timestamp? '(hour minute))
  13493. extra
  13494. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13495. (setq extra (org-modify-ts-extra
  13496. extra
  13497. (if (eq timestamp? 'hour) 2 5)
  13498. n dm)))
  13499. (when (integerp timestamp?)
  13500. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13501. (when (eq what 'calendar)
  13502. (let ((cal-date (org-get-date-from-calendar)))
  13503. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13504. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13505. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13506. (setcar time0 (or (car time0) 0))
  13507. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13508. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13509. (setq time (org-encode-time time0))))
  13510. ;; Insert the new time-stamp, and ensure point stays in the same
  13511. ;; category as before (i.e. not after the last position in that
  13512. ;; category).
  13513. (let ((pos (point)))
  13514. ;; Stay before inserted string. `save-excursion' is of no use.
  13515. (setq org-last-changed-timestamp
  13516. (org-insert-time-stamp time with-hm inactive nil nil extra))
  13517. (goto-char pos))
  13518. (save-match-data
  13519. (looking-at org-ts-regexp3)
  13520. (goto-char
  13521. (pcase origin-cat
  13522. ;; `day' category ends before `hour' if any, or at the end
  13523. ;; of the day name.
  13524. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  13525. (`hour (min (match-end 7) origin))
  13526. (`minute (min (1- (match-end 8)) origin))
  13527. ((pred integerp) (min (1- (match-end 0)) origin))
  13528. ;; Point was right after the time-stamp. However, the
  13529. ;; time-stamp length might have changed, so refer to
  13530. ;; (match-end 0) instead.
  13531. (`after (match-end 0))
  13532. ;; `year' and `month' have both fixed size: point couldn't
  13533. ;; have moved into another part.
  13534. (_ origin))))
  13535. ;; Update clock if on a CLOCK line.
  13536. (org-clock-update-time-maybe)
  13537. ;; Maybe adjust the closest clock in `org-clock-history'
  13538. (when org-clock-adjust-closest
  13539. (if (not (and (org-at-clock-log-p)
  13540. (< 1 (length (delq nil (mapcar 'marker-position
  13541. org-clock-history))))))
  13542. (message "No clock to adjust")
  13543. (cond ((save-excursion ; fix previous clock?
  13544. (re-search-backward org-ts-regexp0 nil t)
  13545. (looking-back (concat org-clock-string " \\[")
  13546. (line-beginning-position)))
  13547. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  13548. ((save-excursion ; fix next clock?
  13549. (re-search-backward org-ts-regexp0 nil t)
  13550. (looking-at (concat org-ts-regexp0 "\\] =>")))
  13551. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  13552. (save-window-excursion
  13553. ;; Find closest clock to point, adjust the previous/next one in history
  13554. (let* ((p (save-excursion (org-back-to-heading t)))
  13555. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  13556. (clfixnth
  13557. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  13558. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  13559. (if (not clfixpos)
  13560. (message "No clock to adjust")
  13561. (save-excursion
  13562. (org-goto-marker-or-bmk clfixpos)
  13563. (org-fold-show-subtree)
  13564. (when (re-search-forward clrgx nil t)
  13565. (goto-char (match-beginning 1))
  13566. (let (org-clock-adjust-closest)
  13567. (org-timestamp-change n timestamp? updown))
  13568. (message "Clock adjusted in %s for heading: %s"
  13569. (file-name-nondirectory (buffer-file-name))
  13570. (org-get-heading t t)))))))))
  13571. ;; Try to recenter the calendar window, if any.
  13572. (when (and org-calendar-follow-timestamp-change
  13573. (get-buffer-window "*Calendar*" t)
  13574. (memq timestamp? '(day month year)))
  13575. (org-recenter-calendar (time-to-days time))))))
  13576. (defun org-modify-ts-extra (s pos n dm)
  13577. "Change the different parts of the lead-time and repeat fields in timestamp."
  13578. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  13579. ng h m new rem)
  13580. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  13581. (cond
  13582. ((or (org-pos-in-match-range pos 2)
  13583. (org-pos-in-match-range pos 3))
  13584. (setq m (string-to-number (match-string 3 s))
  13585. h (string-to-number (match-string 2 s)))
  13586. (if (org-pos-in-match-range pos 2)
  13587. (setq h (+ h n))
  13588. (setq n (* dm (with-no-warnings (cl-signum n))))
  13589. (unless (= 0 (setq rem (% m dm)))
  13590. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  13591. (setq m (+ m n)))
  13592. (when (< m 0) (setq m (+ m 60) h (1- h)))
  13593. (when (> m 59) (setq m (- m 60) h (1+ h)))
  13594. (setq h (mod h 24))
  13595. (setq ng 1 new (format "-%02d:%02d" h m)))
  13596. ((org-pos-in-match-range pos 6)
  13597. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  13598. ((org-pos-in-match-range pos 5)
  13599. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  13600. ((org-pos-in-match-range pos 9)
  13601. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  13602. ((org-pos-in-match-range pos 8)
  13603. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  13604. (when ng
  13605. (setq s (concat
  13606. (substring s 0 (match-beginning ng))
  13607. new
  13608. (substring s (match-end ng))))))
  13609. s))
  13610. (defun org-recenter-calendar (d)
  13611. "If the calendar is visible, recenter it to date D."
  13612. (let ((cwin (get-buffer-window "*Calendar*" t)))
  13613. (when cwin
  13614. (let ((calendar-move-hook nil))
  13615. (with-selected-window cwin
  13616. (calendar-goto-date
  13617. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  13618. (defun org-goto-calendar (&optional arg)
  13619. "Go to the Emacs calendar at the current date.
  13620. If there is a time stamp in the current line, go to that date.
  13621. A prefix ARG can be used to force the current date."
  13622. (interactive "P")
  13623. (let ((calendar-move-hook nil)
  13624. (calendar-view-holidays-initially-flag nil)
  13625. (calendar-view-diary-initially-flag nil)
  13626. diff)
  13627. (when (or (org-at-timestamp-p 'lax)
  13628. (org-match-line (concat ".*" org-ts-regexp)))
  13629. (let ((d1 (time-to-days nil))
  13630. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  13631. (setq diff (- d2 d1))))
  13632. (calendar)
  13633. (calendar-goto-today)
  13634. (when (and diff (not arg)) (calendar-forward-day diff))))
  13635. (defun org-get-date-from-calendar ()
  13636. "Return a list (month day year) of date at point in calendar."
  13637. (with-current-buffer "*Calendar*"
  13638. (save-match-data
  13639. (calendar-cursor-to-date))))
  13640. (defun org-date-from-calendar ()
  13641. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  13642. If there is already a time stamp at the cursor position, update it."
  13643. (interactive)
  13644. (if (org-at-timestamp-p 'lax)
  13645. (org-timestamp-change 0 'calendar)
  13646. (let ((cal-date (org-get-date-from-calendar)))
  13647. (org-insert-time-stamp
  13648. (org-encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  13649. (defcustom org-image-actual-width t
  13650. "When non-nil, use the actual width of images when inlining them.
  13651. When set to a number, use imagemagick (when available) to set the
  13652. image's width to this value.
  13653. When set to a number in a list, try to get the width from any
  13654. #+ATTR.* keyword if it matches a width specification like
  13655. #+ATTR_HTML: :width 300px
  13656. and fall back on that number if none is found.
  13657. When set to nil, try to get the width from an #+ATTR.* keyword
  13658. and fall back on the original width if none is found.
  13659. When set to any other non-nil value, always use the image width.
  13660. This requires Emacs >= 24.1, built with imagemagick support."
  13661. :group 'org-appearance
  13662. :version "24.4"
  13663. :package-version '(Org . "8.0")
  13664. :type '(choice
  13665. (const :tag "Use the image width" t)
  13666. (integer :tag "Use a number of pixels")
  13667. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  13668. (const :tag "Use #+ATTR* or don't resize" nil)))
  13669. (defcustom org-agenda-inhibit-startup nil
  13670. "Inhibit startup when preparing agenda buffers.
  13671. When this variable is t, the initialization of the Org agenda
  13672. buffers is inhibited: e.g. the visibility state is not set, the
  13673. tables are not re-aligned, etc."
  13674. :type 'boolean
  13675. :version "24.3"
  13676. :group 'org-agenda)
  13677. (defcustom org-agenda-ignore-properties nil
  13678. "Avoid updating text properties when building the agenda.
  13679. Properties are used to prepare buffers for effort estimates,
  13680. appointments, statistics and subtree-local categories.
  13681. If you don't use these in the agenda, you can add them to this
  13682. list and agenda building will be a bit faster.
  13683. The value is a list, with zero or more of the symbols `effort', `appt',
  13684. `stats' or `category'."
  13685. :type '(set :greedy t
  13686. (const effort)
  13687. (const appt)
  13688. (const stats)
  13689. (const category))
  13690. :version "26.1"
  13691. :package-version '(Org . "8.3")
  13692. :group 'org-agenda)
  13693. ;;;; Files
  13694. (defun org-save-all-org-buffers ()
  13695. "Save all Org buffers without user confirmation."
  13696. (interactive)
  13697. (message "Saving all Org buffers...")
  13698. (save-some-buffers t (lambda () (and (derived-mode-p 'org-mode) t)))
  13699. (when (featurep 'org-id) (org-id-locations-save))
  13700. (message "Saving all Org buffers... done"))
  13701. (defun org-revert-all-org-buffers ()
  13702. "Revert all Org buffers.
  13703. Prompt for confirmation when there are unsaved changes.
  13704. Be sure you know what you are doing before letting this function
  13705. overwrite your changes.
  13706. This function is useful in a setup where one tracks Org files
  13707. with a version control system, to revert on one machine after pulling
  13708. changes from another. I believe the procedure must be like this:
  13709. 1. \\[org-save-all-org-buffers]
  13710. 2. Pull changes from the other machine, resolve conflicts
  13711. 3. \\[org-revert-all-org-buffers]"
  13712. (interactive)
  13713. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  13714. (user-error "Abort"))
  13715. (save-excursion
  13716. (save-window-excursion
  13717. (dolist (b (buffer-list))
  13718. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  13719. (with-current-buffer b buffer-file-name))
  13720. (pop-to-buffer-same-window b)
  13721. (revert-buffer t 'no-confirm)))
  13722. (when (and (featurep 'org-id) org-id-track-globally)
  13723. (org-id-locations-load)))))
  13724. ;;;; Agenda files
  13725. ;;;###autoload
  13726. (defun org-switchb (&optional arg)
  13727. "Switch between Org buffers.
  13728. With `\\[universal-argument]' prefix, restrict available buffers to files.
  13729. With `\\[universal-argument] \\[universal-argument]' \
  13730. prefix, restrict available buffers to agenda files."
  13731. (interactive "P")
  13732. (let ((blist (org-buffer-list
  13733. (cond ((equal arg '(4)) 'files)
  13734. ((equal arg '(16)) 'agenda)))))
  13735. (pop-to-buffer-same-window
  13736. (completing-read "Org buffer: "
  13737. (mapcar #'list (mapcar #'buffer-name blist))
  13738. nil t))))
  13739. (defun org-agenda-files (&optional unrestricted archives)
  13740. "Get the list of agenda files.
  13741. Optional UNRESTRICTED means return the full list even if a restriction
  13742. is currently in place.
  13743. When ARCHIVES is t, include all archive files that are really being
  13744. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  13745. `org-agenda-archives-mode' is t."
  13746. (let ((files
  13747. (cond
  13748. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  13749. ((stringp org-agenda-files) (org-read-agenda-file-list))
  13750. ((listp org-agenda-files) org-agenda-files)
  13751. (t (error "Invalid value of `org-agenda-files'")))))
  13752. (setq files (apply 'append
  13753. (mapcar (lambda (f)
  13754. (if (file-directory-p f)
  13755. (directory-files
  13756. f t org-agenda-file-regexp)
  13757. (list (expand-file-name f org-directory))))
  13758. files)))
  13759. (when org-agenda-skip-unavailable-files
  13760. (setq files (delq nil
  13761. (mapcar (lambda (file)
  13762. (and (file-readable-p file) file))
  13763. files))))
  13764. (when (or (eq archives t)
  13765. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  13766. (setq files (org-add-archive-files files)))
  13767. files))
  13768. (defun org-agenda-file-p (&optional file)
  13769. "Return non-nil, if FILE is an agenda file.
  13770. If FILE is omitted, use the file associated with the current
  13771. buffer."
  13772. (let ((fname (or file (buffer-file-name))))
  13773. (and fname
  13774. (member (file-truename fname)
  13775. (mapcar #'file-truename (org-agenda-files t))))))
  13776. (defun org-edit-agenda-file-list ()
  13777. "Edit the list of agenda files.
  13778. Depending on setup, this either uses customize to edit the variable
  13779. `org-agenda-files', or it visits the file that is holding the list. In the
  13780. latter case, the buffer is set up in a way that saving it automatically kills
  13781. the buffer and restores the previous window configuration."
  13782. (interactive)
  13783. (if (stringp org-agenda-files)
  13784. (let ((cw (current-window-configuration)))
  13785. (find-file org-agenda-files)
  13786. (setq-local org-window-configuration cw)
  13787. (add-hook 'after-save-hook
  13788. (lambda ()
  13789. (set-window-configuration
  13790. (prog1 org-window-configuration
  13791. (kill-buffer (current-buffer))))
  13792. (org-install-agenda-files-menu)
  13793. (message "New agenda file list installed"))
  13794. nil 'local)
  13795. (message "%s" (substitute-command-keys
  13796. "Edit list and finish with \\[save-buffer]")))
  13797. (customize-variable 'org-agenda-files)))
  13798. (defun org-store-new-agenda-file-list (list)
  13799. "Set new value for the agenda file list and save it correctly."
  13800. (if (stringp org-agenda-files)
  13801. (let ((fe (org-read-agenda-file-list t)) b u)
  13802. (while (setq b (find-buffer-visiting org-agenda-files))
  13803. (kill-buffer b))
  13804. (with-temp-file org-agenda-files
  13805. (insert
  13806. (mapconcat
  13807. (lambda (f) ;; Keep un-expanded entries.
  13808. (if (setq u (assoc f fe))
  13809. (cdr u)
  13810. f))
  13811. list "\n")
  13812. "\n")))
  13813. (let ((org-mode-hook nil) (org-inhibit-startup t)
  13814. (org-insert-mode-line-in-empty-file nil))
  13815. (setq org-agenda-files list)
  13816. (customize-save-variable 'org-agenda-files org-agenda-files))))
  13817. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  13818. "Read the list of agenda files from a file.
  13819. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  13820. filenames, used by `org-store-new-agenda-file-list' to write back
  13821. un-expanded file names."
  13822. (when (file-directory-p org-agenda-files)
  13823. (error "`org-agenda-files' cannot be a single directory"))
  13824. (when (stringp org-agenda-files)
  13825. (with-temp-buffer
  13826. (insert-file-contents org-agenda-files)
  13827. (mapcar
  13828. (lambda (f)
  13829. (let ((e (expand-file-name (substitute-in-file-name f)
  13830. org-directory)))
  13831. (if pair-with-expansion
  13832. (cons e f)
  13833. e)))
  13834. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  13835. ;;;###autoload
  13836. (defun org-cycle-agenda-files ()
  13837. "Cycle through the files in `org-agenda-files'.
  13838. If the current buffer visits an agenda file, find the next one in the list.
  13839. If the current buffer does not, find the first agenda file."
  13840. (interactive)
  13841. (let* ((fs (or (org-agenda-files t)
  13842. (user-error "No agenda files")))
  13843. (files (copy-sequence fs))
  13844. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  13845. file)
  13846. (when tcf
  13847. (while (and (setq file (pop files))
  13848. (not (equal (file-truename file) tcf)))))
  13849. (find-file (car (or files fs)))
  13850. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  13851. (defun org-agenda-file-to-front (&optional to-end)
  13852. "Move/add the current file to the top of the agenda file list.
  13853. If the file is not present in the list, it is added to the front. If it is
  13854. present, it is moved there. With optional argument TO-END, add/move to the
  13855. end of the list."
  13856. (interactive "P")
  13857. (let ((org-agenda-skip-unavailable-files nil)
  13858. (file-alist (mapcar (lambda (x)
  13859. (cons (file-truename x) x))
  13860. (org-agenda-files t)))
  13861. (ctf (file-truename
  13862. (or buffer-file-name
  13863. (user-error "Please save the current buffer to a file"))))
  13864. x had)
  13865. (setq x (assoc ctf file-alist) had x)
  13866. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  13867. (if to-end
  13868. (setq file-alist (append (delq x file-alist) (list x)))
  13869. (setq file-alist (cons x (delq x file-alist))))
  13870. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  13871. (org-install-agenda-files-menu)
  13872. (message "File %s to %s of agenda file list"
  13873. (if had "moved" "added") (if to-end "end" "front"))))
  13874. (defun org-remove-file (&optional file)
  13875. "Remove current file from the list of files in variable `org-agenda-files'.
  13876. These are the files which are being checked for agenda entries.
  13877. Optional argument FILE means use this file instead of the current."
  13878. (interactive)
  13879. (let* ((org-agenda-skip-unavailable-files nil)
  13880. (file (or file buffer-file-name
  13881. (user-error "Current buffer does not visit a file")))
  13882. (true-file (file-truename file))
  13883. (afile (abbreviate-file-name file))
  13884. (files (delq nil (mapcar
  13885. (lambda (x)
  13886. (unless (equal true-file
  13887. (file-truename x))
  13888. x))
  13889. (org-agenda-files t)))))
  13890. (if (not (= (length files) (length (org-agenda-files t))))
  13891. (progn
  13892. (org-store-new-agenda-file-list files)
  13893. (org-install-agenda-files-menu)
  13894. (message "Removed from Org Agenda list: %s" afile))
  13895. (message "File was not in list: %s (not removed)" afile))))
  13896. (defun org-file-menu-entry (file)
  13897. (vector file (list 'find-file file) t))
  13898. (defun org-check-agenda-file (file)
  13899. "Make sure FILE exists. If not, ask user what to do."
  13900. (unless (file-exists-p file)
  13901. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  13902. (abbreviate-file-name file))
  13903. (let ((r (downcase (read-char-exclusive))))
  13904. (cond
  13905. ((equal r ?r)
  13906. (org-remove-file file)
  13907. (throw 'nextfile t))
  13908. (t (user-error "Abort"))))))
  13909. (defun org-get-agenda-file-buffer (file)
  13910. "Get an agenda buffer visiting FILE.
  13911. If the buffer needs to be created, add it to the list of buffers
  13912. which might be released later."
  13913. (let ((buf (org-find-base-buffer-visiting file)))
  13914. (if buf
  13915. buf ; just return it
  13916. ;; Make a new buffer and remember it
  13917. (setq buf (find-file-noselect file))
  13918. (when buf (push buf org-agenda-new-buffers))
  13919. buf)))
  13920. (defun org-release-buffers (blist)
  13921. "Release all buffers in list, asking the user for confirmation when needed.
  13922. When a buffer is unmodified, it is just killed. When modified, it is saved
  13923. \(if the user agrees) and then killed."
  13924. (let (file)
  13925. (dolist (buf blist)
  13926. (setq file (buffer-file-name buf))
  13927. (when (and (buffer-modified-p buf)
  13928. file
  13929. (y-or-n-p (format "Save file %s? " file)))
  13930. (with-current-buffer buf (save-buffer)))
  13931. (kill-buffer buf))))
  13932. (defun org-agenda-prepare-buffers (files)
  13933. "Create buffers for all agenda files, protect archived trees and comments."
  13934. (interactive)
  13935. (let ((inhibit-read-only t)
  13936. (org-inhibit-startup org-agenda-inhibit-startup)
  13937. ;; Do not refresh list of agenda files in the menu when
  13938. ;; opening every new file.
  13939. (org-agenda-file-menu-enabled nil))
  13940. (setq org-tag-alist-for-agenda nil
  13941. org-tag-groups-alist-for-agenda nil)
  13942. (dolist (file files)
  13943. (catch 'nextfile
  13944. (with-current-buffer
  13945. (if (bufferp file)
  13946. file
  13947. (org-check-agenda-file file)
  13948. (org-get-agenda-file-buffer file))
  13949. (org-with-wide-buffer
  13950. (org-set-regexps-and-options 'tags-only)
  13951. (or (memq 'category org-agenda-ignore-properties)
  13952. (org-refresh-category-properties))
  13953. (or (memq 'stats org-agenda-ignore-properties)
  13954. (org-refresh-stats-properties))
  13955. (or (memq 'effort org-agenda-ignore-properties)
  13956. (unless org-element-use-cache
  13957. (org-refresh-effort-properties)))
  13958. (or (memq 'appt org-agenda-ignore-properties)
  13959. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  13960. (dolist (el org-todo-keywords-1)
  13961. (unless (member el org-todo-keywords-for-agenda)
  13962. (push el org-todo-keywords-for-agenda)))
  13963. (dolist (el org-done-keywords)
  13964. (unless (member el org-done-keywords-for-agenda)
  13965. (push el org-done-keywords-for-agenda)))
  13966. (setq org-todo-keyword-alist-for-agenda
  13967. (org--tag-add-to-alist
  13968. org-todo-key-alist
  13969. org-todo-keyword-alist-for-agenda))
  13970. (setq org-tag-alist-for-agenda
  13971. (org--tag-add-to-alist
  13972. org-current-tag-alist
  13973. org-tag-alist-for-agenda))
  13974. ;; Merge current file's tag groups into global
  13975. ;; `org-tag-groups-alist-for-agenda'.
  13976. (when org-group-tags
  13977. (dolist (alist org-tag-groups-alist)
  13978. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  13979. (if old
  13980. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  13981. (push alist org-tag-groups-alist-for-agenda)))))))))
  13982. ;; Refresh the menu once after loading all the agenda buffers.
  13983. (when org-agenda-file-menu-enabled
  13984. (org-install-agenda-files-menu))))
  13985. ;;;; CDLaTeX minor mode
  13986. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  13987. "Keymap for the minor `org-cdlatex-mode'.")
  13988. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  13989. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  13990. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  13991. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  13992. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  13993. (defvar org-cdlatex-texmathp-advice-is-done nil
  13994. "Flag remembering if we have applied the advice to texmathp already.")
  13995. (define-minor-mode org-cdlatex-mode
  13996. "Toggle the minor `org-cdlatex-mode'.
  13997. This mode supports entering LaTeX environment and math in LaTeX fragments
  13998. in Org mode.
  13999. \\{org-cdlatex-mode-map}"
  14000. :lighter " OCDL"
  14001. (when org-cdlatex-mode
  14002. (require 'cdlatex)
  14003. (run-hooks 'cdlatex-mode-hook)
  14004. (cdlatex-compute-tables))
  14005. (unless org-cdlatex-texmathp-advice-is-done
  14006. (setq org-cdlatex-texmathp-advice-is-done t)
  14007. (advice-add 'texmathp :around #'org--math-always-on)))
  14008. (defun org--math-always-on (orig-fun &rest args)
  14009. "Always return t in Org buffers.
  14010. This is because we want to insert math symbols without dollars even outside
  14011. the LaTeX math segments. If Org mode thinks that point is actually inside
  14012. an embedded LaTeX fragment, let `texmathp' do its job.
  14013. `\\[org-cdlatex-mode-map]'"
  14014. (interactive)
  14015. (cond
  14016. ((not (derived-mode-p 'org-mode)) (apply orig-fun args))
  14017. ((eq this-command 'cdlatex-math-symbol)
  14018. (setq texmathp-why '("cdlatex-math-symbol in org-mode" . 0))
  14019. t)
  14020. (t
  14021. (let ((p (org-inside-LaTeX-fragment-p)))
  14022. (when p ;; FIXME: Shouldn't we return t when `p' is nil?
  14023. (if (member (car p)
  14024. (plist-get org-format-latex-options :matchers))
  14025. (progn
  14026. (setq texmathp-why '("Org mode embedded math" . 0))
  14027. t)
  14028. (apply orig-fun args)))))))
  14029. (defun turn-on-org-cdlatex ()
  14030. "Unconditionally turn on `org-cdlatex-mode'."
  14031. (org-cdlatex-mode 1))
  14032. (defun org-try-cdlatex-tab ()
  14033. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  14034. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  14035. - inside a LaTeX fragment, or
  14036. - after the first word in a line, where an abbreviation expansion could
  14037. insert a LaTeX environment."
  14038. (when org-cdlatex-mode
  14039. (cond
  14040. ;; Before any word on the line: No expansion possible.
  14041. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  14042. ;; Just after first word on the line: Expand it. Make sure it
  14043. ;; cannot happen on headlines, though.
  14044. ((save-excursion
  14045. (skip-chars-backward "a-zA-Z0-9*")
  14046. (skip-chars-backward " \t")
  14047. (and (bolp) (not (org-at-heading-p))))
  14048. (cdlatex-tab) t)
  14049. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  14050. (defun org-cdlatex-underscore-caret (&optional _arg)
  14051. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  14052. Revert to the normal definition outside of these fragments."
  14053. (interactive "P")
  14054. (if (org-inside-LaTeX-fragment-p)
  14055. (call-interactively 'cdlatex-sub-superscript)
  14056. (let (org-cdlatex-mode)
  14057. (call-interactively (key-binding (vector last-input-event))))))
  14058. (defun org-cdlatex-math-modify (&optional _arg)
  14059. "Execute `cdlatex-math-modify' in LaTeX fragments.
  14060. Revert to the normal definition outside of these fragments."
  14061. (interactive "P")
  14062. (if (org-inside-LaTeX-fragment-p)
  14063. (call-interactively 'cdlatex-math-modify)
  14064. (let (org-cdlatex-mode)
  14065. (call-interactively (key-binding (vector last-input-event))))))
  14066. (defun org-cdlatex-environment-indent (&optional environment item)
  14067. "Execute `cdlatex-environment' and indent the inserted environment.
  14068. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  14069. The inserted environment is indented to current indentation
  14070. unless point is at the beginning of the line, in which the
  14071. environment remains unintended."
  14072. (interactive)
  14073. ;; cdlatex-environment always return nil. Therefore, capture output
  14074. ;; first and determine if an environment was selected.
  14075. (let* ((beg (point-marker))
  14076. (end (copy-marker (point) t))
  14077. (inserted (progn
  14078. (ignore-errors (cdlatex-environment environment item))
  14079. (< beg end)))
  14080. ;; Figure out how many lines to move forward after the
  14081. ;; environment has been inserted.
  14082. (lines (when inserted
  14083. (save-excursion
  14084. (- (cl-loop while (< beg (point))
  14085. with x = 0
  14086. do (forward-line -1)
  14087. (cl-incf x)
  14088. finally return x)
  14089. (if (progn (goto-char beg)
  14090. (and (progn (skip-chars-forward " \t") (eolp))
  14091. (progn (skip-chars-backward " \t") (bolp))))
  14092. 1 0)))))
  14093. (env (org-trim (delete-and-extract-region beg end))))
  14094. (when inserted
  14095. ;; Get indentation of next line unless at column 0.
  14096. (let ((ind (if (bolp) 0
  14097. (save-excursion
  14098. (org-return t)
  14099. (prog1 (current-indentation)
  14100. (when (progn (skip-chars-forward " \t") (eolp))
  14101. (delete-region beg (point)))))))
  14102. (bol (progn (skip-chars-backward " \t") (bolp))))
  14103. ;; Insert a newline before environment unless at column zero
  14104. ;; to "escape" the current line. Insert a newline if
  14105. ;; something is one the same line as \end{ENVIRONMENT}.
  14106. (insert
  14107. (concat (unless bol "\n") env
  14108. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14109. (unless (zerop ind)
  14110. (save-excursion
  14111. (goto-char beg)
  14112. (while (< (point) end)
  14113. (unless (eolp) (indent-line-to ind))
  14114. (forward-line))))
  14115. (goto-char beg)
  14116. (forward-line lines)
  14117. (indent-line-to ind)))
  14118. (set-marker beg nil)
  14119. (set-marker end nil)))
  14120. ;;;; LaTeX fragments
  14121. (defun org-inside-LaTeX-fragment-p ()
  14122. "Test if point is inside a LaTeX fragment.
  14123. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14124. sequence appearing also before point.
  14125. Even though the matchers for math are configurable, this function assumes
  14126. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14127. delimiters are skipped when they have been removed by customization.
  14128. The return value is nil, or a cons cell with the delimiter and the
  14129. position of this delimiter.
  14130. This function does a reasonably good job, but can locally be fooled by
  14131. for example currency specifications. For example it will assume being in
  14132. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14133. fragments that are properly closed, but during editing, we have to live
  14134. with the uncertainty caused by missing closing delimiters. This function
  14135. looks only before point, not after."
  14136. (catch 'exit
  14137. (let ((pos (point))
  14138. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14139. (lim (progn
  14140. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil
  14141. 'move)
  14142. (point)))
  14143. dd-on str (start 0) m re)
  14144. (goto-char pos)
  14145. (when dodollar
  14146. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14147. re (nth 1 (assoc "$" org-latex-regexps)))
  14148. (while (string-match re str start)
  14149. (cond
  14150. ((= (match-end 0) (length str))
  14151. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14152. ((= (match-end 0) (- (length str) 5))
  14153. (throw 'exit nil))
  14154. (t (setq start (match-end 0))))))
  14155. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14156. (goto-char pos)
  14157. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14158. (and (match-beginning 2) (throw 'exit nil))
  14159. ;; count $$
  14160. (while (re-search-backward "\\$\\$" lim t)
  14161. (setq dd-on (not dd-on)))
  14162. (goto-char pos)
  14163. (when dd-on (cons "$$" m))))))
  14164. (defun org-inside-latex-macro-p ()
  14165. "Is point inside a LaTeX macro or its arguments?"
  14166. (save-match-data
  14167. (org-in-regexp
  14168. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14169. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14170. "Build an overlay between BEG and END using IMAGE file.
  14171. Argument IMAGETYPE is the extension of the displayed image,
  14172. as a string. It defaults to \"png\"."
  14173. (let ((ov (make-overlay beg end))
  14174. (imagetype (or (intern imagetype) 'png)))
  14175. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14176. (overlay-put ov 'evaporate t)
  14177. (overlay-put ov
  14178. 'modification-hooks
  14179. (list (lambda (o _flag _beg _end &optional _l)
  14180. (delete-overlay o))))
  14181. (overlay-put ov
  14182. 'display
  14183. (list 'image :type imagetype :file image :ascent 'center))))
  14184. (defun org-clear-latex-preview (&optional beg end)
  14185. "Remove all overlays with LaTeX fragment images in current buffer.
  14186. When optional arguments BEG and END are non-nil, remove all
  14187. overlays between them instead. Return a non-nil value when some
  14188. overlays were removed, nil otherwise."
  14189. (let ((overlays
  14190. (cl-remove-if-not
  14191. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14192. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14193. (mapc #'delete-overlay overlays)
  14194. overlays))
  14195. (defun org--latex-preview-region (beg end)
  14196. "Preview LaTeX fragments between BEG and END.
  14197. BEG and END are buffer positions."
  14198. (let ((file (buffer-file-name (buffer-base-buffer))))
  14199. (save-excursion
  14200. (org-format-latex
  14201. (concat org-preview-latex-image-directory "org-ltximg")
  14202. beg end
  14203. ;; Emacs cannot overlay images from remote hosts. Create it in
  14204. ;; `temporary-file-directory' instead.
  14205. (if (or (not file) (file-remote-p file))
  14206. temporary-file-directory
  14207. default-directory)
  14208. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14209. (defun org-latex-preview (&optional arg)
  14210. "Toggle preview of the LaTeX fragment at point.
  14211. If the cursor is on a LaTeX fragment, create the image and
  14212. overlay it over the source code, if there is none. Remove it
  14213. otherwise. If there is no fragment at point, display images for
  14214. all fragments in the current section. With an active region,
  14215. display images for all fragments in the region.
  14216. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14217. for all fragments
  14218. in the current section.
  14219. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14220. argument ARG, display image for all
  14221. fragments in the buffer.
  14222. With a `\\[universal-argument] \\[universal-argument] \
  14223. \\[universal-argument]' prefix argument ARG, clear image for all
  14224. fragments in the buffer."
  14225. (interactive "P")
  14226. (cond
  14227. ((not (display-graphic-p)) nil)
  14228. ;; Clear whole buffer.
  14229. ((equal arg '(64))
  14230. (org-clear-latex-preview (point-min) (point-max))
  14231. (message "LaTeX previews removed from buffer"))
  14232. ;; Preview whole buffer.
  14233. ((equal arg '(16))
  14234. (message "Creating LaTeX previews in buffer...")
  14235. (org--latex-preview-region (point-min) (point-max))
  14236. (message "Creating LaTeX previews in buffer... done."))
  14237. ;; Clear current section.
  14238. ((equal arg '(4))
  14239. (org-clear-latex-preview
  14240. (if (use-region-p)
  14241. (region-beginning)
  14242. (if (org-before-first-heading-p) (point-min)
  14243. (save-excursion
  14244. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14245. (if (use-region-p)
  14246. (region-end)
  14247. (org-with-limited-levels (org-entry-end-position)))))
  14248. ((use-region-p)
  14249. (message "Creating LaTeX previews in region...")
  14250. (org--latex-preview-region (region-beginning) (region-end))
  14251. (message "Creating LaTeX previews in region... done."))
  14252. ;; Toggle preview on LaTeX code at point.
  14253. ((let ((datum (org-element-context)))
  14254. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14255. (let ((beg (org-element-property :begin datum))
  14256. (end (org-element-property :end datum)))
  14257. (if (org-clear-latex-preview beg end)
  14258. (message "LaTeX preview removed")
  14259. (message "Creating LaTeX preview...")
  14260. (org--latex-preview-region beg end)
  14261. (message "Creating LaTeX preview... done."))
  14262. t))))
  14263. ;; Preview current section.
  14264. (t
  14265. (let ((beg (if (org-before-first-heading-p) (point-min)
  14266. (save-excursion
  14267. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14268. (end (org-with-limited-levels (org-entry-end-position))))
  14269. (message "Creating LaTeX previews in section...")
  14270. (org--latex-preview-region beg end)
  14271. (message "Creating LaTeX previews in section... done.")))))
  14272. (defun org-format-latex
  14273. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14274. "Replace LaTeX fragments with links to an image.
  14275. The function takes care of creating the replacement image.
  14276. Only consider fragments between BEG and END when those are
  14277. provided.
  14278. When optional argument OVERLAYS is non-nil, display the image on
  14279. top of the fragment instead of replacing it.
  14280. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14281. Some of the options can be changed using the variable
  14282. `org-format-latex-options', which see."
  14283. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14284. (unless (eq processing-type 'verbatim)
  14285. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14286. (cnt 0)
  14287. checkdir-flag)
  14288. (goto-char (or beg (point-min)))
  14289. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14290. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14291. (overlay-recenter (or end (point-max))))
  14292. (while (re-search-forward math-regexp end t)
  14293. (unless (and overlays
  14294. (eq (get-char-property (point) 'org-overlay-type)
  14295. 'org-latex-overlay))
  14296. (let* ((context (org-element-context))
  14297. (type (org-element-type context)))
  14298. (when (memq type '(latex-environment latex-fragment))
  14299. (let ((block-type (eq type 'latex-environment))
  14300. (value (org-element-property :value context))
  14301. (beg (org-element-property :begin context))
  14302. (end (save-excursion
  14303. (goto-char (org-element-property :end context))
  14304. (skip-chars-backward " \r\t\n")
  14305. (point))))
  14306. (cond
  14307. ((eq processing-type 'mathjax)
  14308. ;; Prepare for MathJax processing.
  14309. (if (not (string-match "\\`\\$\\$?" value))
  14310. (goto-char end)
  14311. (delete-region beg end)
  14312. (if (string= (match-string 0 value) "$$")
  14313. (insert "\\[" (substring value 2 -2) "\\]")
  14314. (insert "\\(" (substring value 1 -1) "\\)"))))
  14315. ((eq processing-type 'html)
  14316. (goto-char beg)
  14317. (delete-region beg end)
  14318. (insert (org-format-latex-as-html value)))
  14319. ((assq processing-type org-preview-latex-process-alist)
  14320. ;; Process to an image.
  14321. (cl-incf cnt)
  14322. (goto-char beg)
  14323. (let* ((processing-info
  14324. (cdr (assq processing-type org-preview-latex-process-alist)))
  14325. (face (face-at-point))
  14326. ;; Get the colors from the face at point.
  14327. (fg
  14328. (let ((color (plist-get org-format-latex-options
  14329. :foreground)))
  14330. (if forbuffer
  14331. (cond
  14332. ((eq color 'auto)
  14333. (face-attribute face :foreground nil 'default))
  14334. ((eq color 'default)
  14335. (face-attribute 'default :foreground nil))
  14336. (t color))
  14337. color)))
  14338. (bg
  14339. (let ((color (plist-get org-format-latex-options
  14340. :background)))
  14341. (if forbuffer
  14342. (cond
  14343. ((eq color 'auto)
  14344. (face-attribute face :background nil 'default))
  14345. ((eq color 'default)
  14346. (face-attribute 'default :background nil))
  14347. (t color))
  14348. color)))
  14349. (hash (sha1 (prin1-to-string
  14350. (list org-format-latex-header
  14351. org-latex-default-packages-alist
  14352. org-latex-packages-alist
  14353. org-format-latex-options
  14354. forbuffer value fg bg))))
  14355. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14356. (absprefix (expand-file-name prefix dir))
  14357. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14358. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14359. (sep (and block-type "\n\n"))
  14360. (link (concat sep "[[file:" linkfile "]]" sep))
  14361. (options
  14362. (org-combine-plists
  14363. org-format-latex-options
  14364. `(:foreground ,fg :background ,bg))))
  14365. (when msg (message msg cnt))
  14366. (unless checkdir-flag ; Ensure the directory exists.
  14367. (setq checkdir-flag t)
  14368. (let ((todir (file-name-directory absprefix)))
  14369. (unless (file-directory-p todir)
  14370. (make-directory todir t))))
  14371. (unless (file-exists-p movefile)
  14372. (org-create-formula-image
  14373. value movefile options forbuffer processing-type))
  14374. (if overlays
  14375. (progn
  14376. (dolist (o (overlays-in beg end))
  14377. (when (eq (overlay-get o 'org-overlay-type)
  14378. 'org-latex-overlay)
  14379. (delete-overlay o)))
  14380. (org--make-preview-overlay beg end movefile imagetype)
  14381. (goto-char end))
  14382. (delete-region beg end)
  14383. (insert
  14384. (org-add-props link
  14385. (list 'org-latex-src
  14386. (replace-regexp-in-string "\"" "" value)
  14387. 'org-latex-src-embed-type
  14388. (if block-type 'paragraph 'character)))))))
  14389. ((eq processing-type 'mathml)
  14390. ;; Process to MathML.
  14391. (unless (org-format-latex-mathml-available-p)
  14392. (user-error "LaTeX to MathML converter not configured"))
  14393. (cl-incf cnt)
  14394. (when msg (message msg cnt))
  14395. (goto-char beg)
  14396. (delete-region beg end)
  14397. (insert (org-format-latex-as-mathml
  14398. value block-type prefix dir)))
  14399. (t
  14400. (error "Unknown conversion process %s for LaTeX fragments"
  14401. processing-type)))))))))))
  14402. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14403. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14404. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14405. successful, return the portion between \"<math...> </math>\"
  14406. elements otherwise return nil. When MATHML-FILE is specified,
  14407. write the results in to that file. When invoked as an
  14408. interactive command, prompt for LATEX-FRAG, with initial value
  14409. set to the current active region and echo the results for user
  14410. inspection."
  14411. (interactive (list (let ((frag (when (org-region-active-p)
  14412. (buffer-substring-no-properties
  14413. (region-beginning) (region-end)))))
  14414. (read-string "LaTeX Fragment: " frag nil frag))))
  14415. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14416. (let* ((tmp-in-file
  14417. (let ((file (file-relative-name
  14418. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14419. (write-region latex-frag nil file)
  14420. file))
  14421. (tmp-out-file (file-relative-name
  14422. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14423. (cmd (format-spec
  14424. org-latex-to-mathml-convert-command
  14425. `((?j . ,(and org-latex-to-mathml-jar-file
  14426. (shell-quote-argument
  14427. (expand-file-name
  14428. org-latex-to-mathml-jar-file))))
  14429. (?I . ,(shell-quote-argument tmp-in-file))
  14430. (?i . ,latex-frag)
  14431. (?o . ,(shell-quote-argument tmp-out-file)))))
  14432. mathml shell-command-output)
  14433. (when (called-interactively-p 'any)
  14434. (unless (org-format-latex-mathml-available-p)
  14435. (user-error "LaTeX to MathML converter not configured")))
  14436. (message "Running %s" cmd)
  14437. (setq shell-command-output (shell-command-to-string cmd))
  14438. (setq mathml
  14439. (when (file-readable-p tmp-out-file)
  14440. (with-current-buffer (find-file-noselect tmp-out-file t)
  14441. (goto-char (point-min))
  14442. (when (re-search-forward
  14443. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14444. (regexp-quote
  14445. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14446. nil t)
  14447. (prog1 (match-string 0) (kill-buffer))))))
  14448. (cond
  14449. (mathml
  14450. (setq mathml
  14451. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14452. (when mathml-file
  14453. (write-region mathml nil mathml-file))
  14454. (when (called-interactively-p 'any)
  14455. (message mathml)))
  14456. ((warn "LaTeX to MathML conversion failed")
  14457. (message shell-command-output)))
  14458. (delete-file tmp-in-file)
  14459. (when (file-exists-p tmp-out-file)
  14460. (delete-file tmp-out-file))
  14461. mathml))
  14462. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14463. prefix &optional dir)
  14464. "Use `org-create-math-formula' but check local cache first."
  14465. (let* ((absprefix (expand-file-name prefix dir))
  14466. (print-length nil) (print-level nil)
  14467. (formula-id (concat
  14468. "formula-"
  14469. (sha1
  14470. (prin1-to-string
  14471. (list latex-frag
  14472. org-latex-to-mathml-convert-command)))))
  14473. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14474. (formula-cache-dir (file-name-directory formula-cache)))
  14475. (unless (file-directory-p formula-cache-dir)
  14476. (make-directory formula-cache-dir t))
  14477. (unless (file-exists-p formula-cache)
  14478. (org-create-math-formula latex-frag formula-cache))
  14479. (if (file-exists-p formula-cache)
  14480. ;; Successful conversion. Return the link to MathML file.
  14481. (org-add-props
  14482. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14483. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14484. 'org-latex-src-embed-type (if latex-frag-type
  14485. 'paragraph 'character)))
  14486. ;; Failed conversion. Return the LaTeX fragment verbatim
  14487. latex-frag)))
  14488. (defun org-format-latex-as-html (latex-fragment)
  14489. "Convert LATEX-FRAGMENT to HTML.
  14490. This uses `org-latex-to-html-convert-command', which see."
  14491. (let ((cmd (format-spec org-latex-to-html-convert-command
  14492. `((?i . ,latex-fragment)))))
  14493. (message "Running %s" cmd)
  14494. (shell-command-to-string cmd)))
  14495. (defun org--get-display-dpi ()
  14496. "Get the DPI of the display.
  14497. The function assumes that the display has the same pixel width in
  14498. the horizontal and vertical directions."
  14499. (if (display-graphic-p)
  14500. (round (/ (display-pixel-height)
  14501. (/ (display-mm-height) 25.4)))
  14502. (error "Attempt to calculate the dpi of a non-graphic display")))
  14503. (defun org-create-formula-image
  14504. (string tofile options buffer &optional processing-type)
  14505. "Create an image from LaTeX source using external processes.
  14506. The LaTeX STRING is saved to a temporary LaTeX file, then
  14507. converted to an image file by process PROCESSING-TYPE defined in
  14508. `org-preview-latex-process-alist'. A nil value defaults to
  14509. `org-preview-latex-default-process'.
  14510. The generated image file is eventually moved to TOFILE.
  14511. The OPTIONS argument controls the size, foreground color and
  14512. background color of the generated image.
  14513. When BUFFER non-nil, this function is used for LaTeX previewing.
  14514. Otherwise, it is used to deal with LaTeX snippets showed in
  14515. a HTML file."
  14516. (let* ((processing-type (or processing-type
  14517. org-preview-latex-default-process))
  14518. (processing-info
  14519. (cdr (assq processing-type org-preview-latex-process-alist)))
  14520. (programs (plist-get processing-info :programs))
  14521. (error-message (or (plist-get processing-info :message) ""))
  14522. (image-input-type (plist-get processing-info :image-input-type))
  14523. (image-output-type (plist-get processing-info :image-output-type))
  14524. (post-clean (or (plist-get processing-info :post-clean)
  14525. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  14526. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  14527. (latex-header
  14528. (or (plist-get processing-info :latex-header)
  14529. (org-latex-make-preamble
  14530. (org-export-get-environment (org-export-get-backend 'latex))
  14531. org-format-latex-header
  14532. 'snippet)))
  14533. (latex-compiler (plist-get processing-info :latex-compiler))
  14534. (tmpdir temporary-file-directory)
  14535. (texfilebase (make-temp-name
  14536. (expand-file-name "orgtex" tmpdir)))
  14537. (texfile (concat texfilebase ".tex"))
  14538. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  14539. '(1.0 . 1.0)))
  14540. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  14541. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  14542. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  14543. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  14544. "Black"))
  14545. (bg (or (plist-get options (if buffer :background :html-background))
  14546. "Transparent"))
  14547. (image-converter
  14548. (or (and (string= bg "Transparent")
  14549. (plist-get processing-info :transparent-image-converter))
  14550. (plist-get processing-info :image-converter)))
  14551. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  14552. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  14553. (dolist (program programs)
  14554. (org-check-external-command program error-message))
  14555. (if (eq fg 'default)
  14556. (setq fg (org-latex-color :foreground))
  14557. (setq fg (org-latex-color-format fg)))
  14558. (setq bg (cond
  14559. ((eq bg 'default) (org-latex-color :background))
  14560. ((string= bg "Transparent") nil)
  14561. (t (org-latex-color-format bg))))
  14562. ;; Remove TeX \par at end of snippet to avoid trailing space.
  14563. (if (string-suffix-p string "\n")
  14564. (aset string (1- (length string)) ?%)
  14565. (setq string (concat string "%")))
  14566. (with-temp-file texfile
  14567. (insert latex-header)
  14568. (insert "\n\\begin{document}\n"
  14569. "\\definecolor{fg}{rgb}{" fg "}%\n"
  14570. (if bg
  14571. (concat "\\definecolor{bg}{rgb}{" bg "}%\n"
  14572. "\n\\pagecolor{bg}%\n")
  14573. "")
  14574. "\n{\\color{fg}\n"
  14575. string
  14576. "\n}\n"
  14577. "\n\\end{document}\n"))
  14578. (let* ((err-msg (format "Please adjust `%s' part of \
  14579. `org-preview-latex-process-alist'."
  14580. processing-type))
  14581. (image-input-file
  14582. (org-compile-file
  14583. texfile latex-compiler image-input-type err-msg log-buf))
  14584. (image-output-file
  14585. (org-compile-file
  14586. image-input-file image-converter image-output-type err-msg log-buf
  14587. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  14588. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  14589. (copy-file image-output-file tofile 'replace)
  14590. (dolist (e post-clean)
  14591. (when (file-exists-p (concat texfilebase e))
  14592. (delete-file (concat texfilebase e))))
  14593. image-output-file)))
  14594. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  14595. "Fill a LaTeX header template TPL.
  14596. In the template, the following place holders will be recognized:
  14597. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  14598. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  14599. [PACKAGES] \\usepackage statements for PKG
  14600. [NO-PACKAGES] do not include PKG
  14601. [EXTRA] the string EXTRA
  14602. [NO-EXTRA] do not include EXTRA
  14603. For backward compatibility, if both the positive and the negative place
  14604. holder is missing, the positive one (without the \"NO-\") will be
  14605. assumed to be present at the end of the template.
  14606. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  14607. EXTRA is a string.
  14608. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  14609. (let (rpl (end ""))
  14610. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  14611. (setq rpl (if (or (match-end 1) (not def-pkg))
  14612. "" (org-latex-packages-to-string def-pkg snippets-p t))
  14613. tpl (replace-match rpl t t tpl))
  14614. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  14615. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  14616. (setq rpl (if (or (match-end 1) (not pkg))
  14617. "" (org-latex-packages-to-string pkg snippets-p t))
  14618. tpl (replace-match rpl t t tpl))
  14619. (when pkg (setq end
  14620. (concat end "\n"
  14621. (org-latex-packages-to-string pkg snippets-p)))))
  14622. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  14623. (setq rpl (if (or (match-end 1) (not extra))
  14624. "" (concat extra "\n"))
  14625. tpl (replace-match rpl t t tpl))
  14626. (when (and extra (string-match "\\S-" extra))
  14627. (setq end (concat end "\n" extra))))
  14628. (if (string-match "\\S-" end)
  14629. (concat tpl "\n" end)
  14630. tpl)))
  14631. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  14632. "Turn an alist of packages into a string with the \\usepackage macros."
  14633. (setq pkg (mapconcat (lambda(p)
  14634. (cond
  14635. ((stringp p) p)
  14636. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  14637. (format "%% Package %s omitted" (cadr p)))
  14638. ((equal "" (car p))
  14639. (format "\\usepackage{%s}" (cadr p)))
  14640. (t
  14641. (format "\\usepackage[%s]{%s}"
  14642. (car p) (cadr p)))))
  14643. pkg
  14644. "\n"))
  14645. (if newline (concat pkg "\n") pkg))
  14646. (defun org-dvipng-color (attr)
  14647. "Return a RGB color specification for dvipng."
  14648. (org-dvipng-color-format (face-attribute 'default attr nil)))
  14649. (defun org-dvipng-color-format (color-name)
  14650. "Convert COLOR-NAME to a RGB color value for dvipng."
  14651. (apply #'format "rgb %s %s %s"
  14652. (mapcar 'org-normalize-color
  14653. (color-values color-name))))
  14654. (defun org-latex-color (attr)
  14655. "Return a RGB color for the LaTeX color package."
  14656. (org-latex-color-format (face-attribute 'default attr nil)))
  14657. (defun org-latex-color-format (color-name)
  14658. "Convert COLOR-NAME to a RGB color value."
  14659. (apply #'format "%s,%s,%s"
  14660. (mapcar 'org-normalize-color
  14661. (color-values color-name))))
  14662. (defun org-normalize-color (value)
  14663. "Return string to be used as color value for an RGB component."
  14664. (format "%g" (/ value 65535.0)))
  14665. ;; Image display
  14666. (defvar-local org-inline-image-overlays nil)
  14667. (defun org-toggle-inline-images (&optional include-linked)
  14668. "Toggle the display of inline images.
  14669. INCLUDE-LINKED is passed to `org-display-inline-images'."
  14670. (interactive "P")
  14671. (if org-inline-image-overlays
  14672. (progn
  14673. (org-remove-inline-images)
  14674. (when (called-interactively-p 'interactive)
  14675. (message "Inline image display turned off")))
  14676. (org-display-inline-images include-linked)
  14677. (when (called-interactively-p 'interactive)
  14678. (message (if org-inline-image-overlays
  14679. (format "%d images displayed inline"
  14680. (length org-inline-image-overlays))
  14681. "No images to display inline")))))
  14682. (defun org-redisplay-inline-images ()
  14683. "Assure display of inline images and refresh them."
  14684. (interactive)
  14685. (org-toggle-inline-images)
  14686. (unless org-inline-image-overlays
  14687. (org-toggle-inline-images)))
  14688. ;; For without-x builds.
  14689. (declare-function image-flush "image" (spec &optional frame))
  14690. (defcustom org-display-remote-inline-images 'skip
  14691. "How to display remote inline images.
  14692. Possible values of this option are:
  14693. skip Don't display remote images.
  14694. download Always download and display remote images.
  14695. cache Display remote images, and open them in separate buffers
  14696. for caching. Silently update the image buffer when a file
  14697. change is detected."
  14698. :group 'org-appearance
  14699. :package-version '(Org . "9.4")
  14700. :type '(choice
  14701. (const :tag "Ignore remote images" skip)
  14702. (const :tag "Always display remote images" download)
  14703. (const :tag "Display and silently update remote images" cache))
  14704. :safe #'symbolp)
  14705. (defun org--create-inline-image (file width)
  14706. "Create image located at FILE, or return nil.
  14707. WIDTH is the width of the image. The image may not be created
  14708. according to the value of `org-display-remote-inline-images'."
  14709. (let* ((remote? (file-remote-p file))
  14710. (file-or-data
  14711. (pcase org-display-remote-inline-images
  14712. ((guard (not remote?)) file)
  14713. (`download (with-temp-buffer
  14714. (set-buffer-multibyte nil)
  14715. (insert-file-contents-literally file)
  14716. (buffer-string)))
  14717. (`cache (let ((revert-without-query '(".")))
  14718. (with-current-buffer (find-file-noselect file)
  14719. (buffer-string))))
  14720. (`skip nil)
  14721. (other
  14722. (message "Invalid value of `org-display-remote-inline-images': %S"
  14723. other)
  14724. nil))))
  14725. (when file-or-data
  14726. (create-image file-or-data
  14727. (and (image-type-available-p 'imagemagick)
  14728. width
  14729. 'imagemagick)
  14730. remote?
  14731. :width width :scale 1))))
  14732. (defun org-display-inline-images (&optional include-linked refresh beg end)
  14733. "Display inline images.
  14734. An inline image is a link which follows either of these
  14735. conventions:
  14736. 1. Its path is a file with an extension matching return value
  14737. from `image-file-name-regexp' and it has no contents.
  14738. 2. Its description consists in a single link of the previous
  14739. type. In this case, that link must be a well-formed plain
  14740. or angle link, i.e., it must have an explicit \"file\" type.
  14741. Equip each image with the key-map `image-map'.
  14742. When optional argument INCLUDE-LINKED is non-nil, also links with
  14743. a text description part will be inlined. This can be nice for
  14744. a quick look at those images, but it does not reflect what
  14745. exported files will look like.
  14746. When optional argument REFRESH is non-nil, refresh existing
  14747. images between BEG and END. This will create new image displays
  14748. only if necessary.
  14749. BEG and END define the considered part. They default to the
  14750. buffer boundaries with possible narrowing."
  14751. (interactive "P")
  14752. (when (display-graphic-p)
  14753. (unless refresh
  14754. (org-remove-inline-images)
  14755. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  14756. (let ((end (or end (point-max))))
  14757. (org-with-point-at (or beg (point-min))
  14758. (let* ((case-fold-search t)
  14759. (file-extension-re (image-file-name-regexp))
  14760. (link-abbrevs (mapcar #'car
  14761. (append org-link-abbrev-alist-local
  14762. org-link-abbrev-alist)))
  14763. ;; Check absolute, relative file names and explicit
  14764. ;; "file:" links. Also check link abbreviations since
  14765. ;; some might expand to "file" links.
  14766. (file-types-re
  14767. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  14768. (if (not link-abbrevs) ""
  14769. (concat "\\|" (regexp-opt link-abbrevs))))))
  14770. (while (re-search-forward file-types-re end t)
  14771. (let* ((link (org-element-lineage
  14772. (save-match-data (org-element-context))
  14773. '(link) t))
  14774. (linktype (org-element-property :type link))
  14775. (inner-start (match-beginning 1))
  14776. (path
  14777. (cond
  14778. ;; No link at point; no inline image.
  14779. ((not link) nil)
  14780. ;; File link without a description. Also handle
  14781. ;; INCLUDE-LINKED here since it should have
  14782. ;; precedence over the next case. I.e., if link
  14783. ;; contains filenames in both the path and the
  14784. ;; description, prioritize the path only when
  14785. ;; INCLUDE-LINKED is non-nil.
  14786. ((or (not (org-element-property :contents-begin link))
  14787. include-linked)
  14788. (and (or (equal "file" linktype)
  14789. (equal "attachment" linktype))
  14790. (org-element-property :path link)))
  14791. ;; Link with a description. Check if description
  14792. ;; is a filename. Even if Org doesn't have syntax
  14793. ;; for those -- clickable image -- constructs, fake
  14794. ;; them, as in `org-export-insert-image-links'.
  14795. ((not inner-start) nil)
  14796. (t
  14797. (org-with-point-at inner-start
  14798. (and (looking-at
  14799. (if (char-equal ?< (char-after inner-start))
  14800. org-link-angle-re
  14801. org-link-plain-re))
  14802. ;; File name must fill the whole
  14803. ;; description.
  14804. (= (org-element-property :contents-end link)
  14805. (match-end 0))
  14806. (match-string 2)))))))
  14807. (when (and path (string-match-p file-extension-re path))
  14808. (let ((file (if (equal "attachment" linktype)
  14809. (progn
  14810. (require 'org-attach)
  14811. (ignore-errors (org-attach-expand path)))
  14812. (expand-file-name path))))
  14813. (when (and file (file-exists-p file))
  14814. (let ((width (org-display-inline-image--width link))
  14815. (old (get-char-property-and-overlay
  14816. (org-element-property :begin link)
  14817. 'org-image-overlay)))
  14818. (if (and (car-safe old) refresh)
  14819. (image-flush (overlay-get (cdr old) 'display))
  14820. (let ((image (org--create-inline-image file width)))
  14821. (when image
  14822. (let ((ov (make-overlay
  14823. (org-element-property :begin link)
  14824. (progn
  14825. (goto-char
  14826. (org-element-property :end link))
  14827. (skip-chars-backward " \t")
  14828. (point)))))
  14829. (overlay-put ov 'display image)
  14830. (overlay-put ov 'face 'default)
  14831. (overlay-put ov 'org-image-overlay t)
  14832. (overlay-put
  14833. ov 'modification-hooks
  14834. (list 'org-display-inline-remove-overlay))
  14835. (when (boundp 'image-map)
  14836. (overlay-put ov 'keymap image-map))
  14837. (push ov org-inline-image-overlays))))))))))))))))
  14838. (defvar visual-fill-column-width) ; Silence compiler warning
  14839. (defun org-display-inline-image--width (link)
  14840. "Determine the display width of the image LINK, in pixels.
  14841. - When `org-image-actual-width' is t, the image's pixel width is used.
  14842. - When `org-image-actual-width' is a number, that value will is used.
  14843. - When `org-image-actual-width' is nil or a list, the first :width attribute
  14844. set (if it exists) is used to set the image width. A width of X% is
  14845. divided by 100.
  14846. If no :width attribute is given and `org-image-actual-width' is a list with
  14847. a number as the car, then that number is used as the default value.
  14848. If the value is a float between 0 and 2, it interpreted as that proportion
  14849. of the text width in the buffer."
  14850. ;; Apply `org-image-actual-width' specifications.
  14851. (cond
  14852. ((eq org-image-actual-width t) nil)
  14853. ((listp org-image-actual-width)
  14854. (let* ((case-fold-search t)
  14855. (par (org-element-lineage link '(paragraph)))
  14856. (attr-re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)")
  14857. (par-end (org-element-property :post-affiliated par))
  14858. ;; Try to find an attribute providing a :width.
  14859. (attr-width
  14860. (when (and par (org-with-point-at
  14861. (org-element-property :begin par)
  14862. (re-search-forward attr-re par-end t)))
  14863. (match-string 1)))
  14864. (width
  14865. (cond
  14866. ;; Treat :width t as if `org-image-actual-width' were t.
  14867. ((string= attr-width "t") nil)
  14868. ;; Fallback to `org-image-actual-width' if no interprable width is given.
  14869. ((or (null attr-width)
  14870. (string-match-p "\\`[^0-9]" attr-width))
  14871. (car org-image-actual-width))
  14872. ;; Convert numeric widths to numbers, converting percentages.
  14873. ((string-match-p "\\`[0-9.]+%" attr-width)
  14874. (/ (string-to-number attr-width) 100.0))
  14875. (t (string-to-number attr-width)))))
  14876. (if (and (floatp width) (<= 0.0 width 2.0))
  14877. ;; A float in [0,2] should be interpereted as this portion of
  14878. ;; the text width in the window. This works well with cases like
  14879. ;; #+attr_latex: :width 0.X\{line,page,column,etc.}width,
  14880. ;; as the "0.X" is pulled out as a float. We use 2 as the upper
  14881. ;; bound as cases such as 1.2\linewidth are feasible.
  14882. (round (* width
  14883. (window-pixel-width)
  14884. (/ (or (and (bound-and-true-p visual-fill-column-mode)
  14885. (or visual-fill-column-width auto-fill-function))
  14886. (when auto-fill-function fill-column)
  14887. (- (window-text-width) (line-number-display-width)))
  14888. (float (window-total-width)))))
  14889. width)))
  14890. ((numberp org-image-actual-width)
  14891. org-image-actual-width)
  14892. (t nil)))
  14893. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  14894. "Remove inline-display overlay if a corresponding region is modified."
  14895. (let ((inhibit-modification-hooks t))
  14896. (when (and ov after)
  14897. (delete ov org-inline-image-overlays)
  14898. (delete-overlay ov))))
  14899. (defun org-remove-inline-images ()
  14900. "Remove inline display of images."
  14901. (interactive)
  14902. (mapc #'delete-overlay org-inline-image-overlays)
  14903. (setq org-inline-image-overlays nil))
  14904. (defvar org-self-insert-command-undo-counter 0)
  14905. (defvar org-speed-command nil)
  14906. (defun org-fix-tags-on-the-fly ()
  14907. "Align tags in headline at point.
  14908. Unlike `org-align-tags', this function does nothing if point is
  14909. either not currently on a tagged headline or on a tag."
  14910. (when (and (org-match-line org-tag-line-re)
  14911. (< (point) (match-beginning 1)))
  14912. (org-align-tags)))
  14913. (defun org-self-insert-command (N)
  14914. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  14915. If the cursor is in a table looking at whitespace, the whitespace is
  14916. overwritten, and the table is not marked as requiring realignment."
  14917. (interactive "p")
  14918. (org-fold-check-before-invisible-edit 'insert)
  14919. (cond
  14920. ((and org-use-speed-commands
  14921. (let ((kv (this-command-keys-vector)))
  14922. (setq org-speed-command
  14923. (run-hook-with-args-until-success
  14924. 'org-speed-command-hook
  14925. (make-string 1 (aref kv (1- (length kv))))))))
  14926. (cond
  14927. ((commandp org-speed-command)
  14928. (setq this-command org-speed-command)
  14929. (call-interactively org-speed-command))
  14930. ((functionp org-speed-command)
  14931. (funcall org-speed-command))
  14932. ((consp org-speed-command)
  14933. (eval org-speed-command t))
  14934. (t (let (org-use-speed-commands)
  14935. (call-interactively 'org-self-insert-command)))))
  14936. ((and
  14937. (= N 1)
  14938. (not (org-region-active-p))
  14939. (org-at-table-p)
  14940. (progn
  14941. ;; Check if we blank the field, and if that triggers align.
  14942. (and (featurep 'org-table)
  14943. org-table-auto-blank-field
  14944. (memq last-command
  14945. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  14946. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  14947. ;; Got extra space, this field does not determine
  14948. ;; column width.
  14949. (let (org-table-may-need-update) (org-table-blank-field))
  14950. ;; No extra space, this field may determine column
  14951. ;; width.
  14952. (org-table-blank-field)))
  14953. t)
  14954. (looking-at "[^|\n]* |"))
  14955. ;; There is room for insertion without re-aligning the table.
  14956. (self-insert-command N)
  14957. (org-table-with-shrunk-field
  14958. (save-excursion
  14959. (skip-chars-forward "^|")
  14960. ;; Do not delete last space, which is
  14961. ;; `org-table-separator-space', but the regular space before
  14962. ;; it.
  14963. (delete-region (- (point) 2) (1- (point))))))
  14964. (t
  14965. (setq org-table-may-need-update t)
  14966. (self-insert-command N)
  14967. (org-fix-tags-on-the-fly)
  14968. (when org-self-insert-cluster-for-undo
  14969. (if (not (eq last-command 'org-self-insert-command))
  14970. (setq org-self-insert-command-undo-counter 1)
  14971. (if (>= org-self-insert-command-undo-counter 20)
  14972. (setq org-self-insert-command-undo-counter 1)
  14973. (and (> org-self-insert-command-undo-counter 0)
  14974. buffer-undo-list (listp buffer-undo-list)
  14975. (not (cadr buffer-undo-list)) ; remove nil entry
  14976. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  14977. (setq org-self-insert-command-undo-counter
  14978. (1+ org-self-insert-command-undo-counter))))))))
  14979. (defun org-delete-backward-char (N)
  14980. "Like `delete-backward-char', insert whitespace at field end in tables.
  14981. When deleting backwards, in tables this function will insert whitespace in
  14982. front of the next \"|\" separator, to keep the table aligned. The table will
  14983. still be marked for re-alignment if the field did fill the entire column,
  14984. because, in this case the deletion might narrow the column."
  14985. (interactive "p")
  14986. (save-match-data
  14987. (org-fold-check-before-invisible-edit 'delete-backward)
  14988. (if (and (= N 1)
  14989. (not overwrite-mode)
  14990. (not (org-region-active-p))
  14991. (not (eq (char-before) ?|))
  14992. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  14993. (looking-at-p ".*?|")
  14994. (org-at-table-p))
  14995. (progn (forward-char -1) (org-delete-char 1))
  14996. (backward-delete-char N)
  14997. (org-fix-tags-on-the-fly))))
  14998. (defun org-delete-char (N)
  14999. "Like `delete-char', but insert whitespace at field end in tables.
  15000. When deleting characters, in tables this function will insert whitespace in
  15001. front of the next \"|\" separator, to keep the table aligned. The table will
  15002. still be marked for re-alignment if the field did fill the entire column,
  15003. because, in this case the deletion might narrow the column."
  15004. (interactive "p")
  15005. (save-match-data
  15006. (org-fold-check-before-invisible-edit 'delete)
  15007. (cond
  15008. ((or (/= N 1)
  15009. (eq (char-after) ?|)
  15010. (save-excursion (skip-chars-backward " \t") (bolp))
  15011. (not (org-at-table-p)))
  15012. (delete-char N)
  15013. (org-fix-tags-on-the-fly))
  15014. ((looking-at ".\\(.*?\\)|")
  15015. (let* ((update? org-table-may-need-update)
  15016. (noalign (looking-at-p ".*? |")))
  15017. (delete-char 1)
  15018. (org-table-with-shrunk-field
  15019. (save-excursion
  15020. ;; Last space is `org-table-separator-space', so insert
  15021. ;; a regular one before it instead.
  15022. (goto-char (- (match-end 0) 2))
  15023. (insert " ")))
  15024. ;; If there were two spaces at the end, this field does not
  15025. ;; determine the width of the column.
  15026. (when noalign (setq org-table-may-need-update update?))))
  15027. (t
  15028. (delete-char N)))))
  15029. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  15030. (put 'org-self-insert-command 'delete-selection
  15031. (lambda ()
  15032. (not (run-hook-with-args-until-success
  15033. 'self-insert-uses-region-functions))))
  15034. (put 'orgtbl-self-insert-command 'delete-selection
  15035. (lambda ()
  15036. (not (run-hook-with-args-until-success
  15037. 'self-insert-uses-region-functions))))
  15038. (put 'org-delete-char 'delete-selection 'supersede)
  15039. (put 'org-delete-backward-char 'delete-selection 'supersede)
  15040. (put 'org-yank 'delete-selection 'yank)
  15041. (put 'org-return 'delete-selection t)
  15042. ;; Make `flyspell-mode' delay after some commands
  15043. (put 'org-self-insert-command 'flyspell-delayed t)
  15044. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  15045. (put 'org-delete-char 'flyspell-delayed t)
  15046. (put 'org-delete-backward-char 'flyspell-delayed t)
  15047. ;; Make pabbrev-mode expand after Org mode commands
  15048. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  15049. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  15050. (defun org-transpose-words ()
  15051. "Transpose words for Org.
  15052. This uses the `org-mode-transpose-word-syntax-table' syntax
  15053. table, which interprets characters in `org-emphasis-alist' as
  15054. word constituents."
  15055. (interactive)
  15056. (with-syntax-table org-mode-transpose-word-syntax-table
  15057. (call-interactively 'transpose-words)))
  15058. (defvar org-ctrl-c-ctrl-c-hook nil
  15059. "Hook for functions attaching themselves to `C-c C-c'.
  15060. This can be used to add additional functionality to the `C-c C-c'
  15061. key which executes context-dependent commands. This hook is run
  15062. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  15063. run after the last test.
  15064. Each function will be called with no arguments. The function
  15065. must check if the context is appropriate for it to act. If yes,
  15066. it should do its thing and then return a non-nil value. If the
  15067. context is wrong, just do nothing and return nil.")
  15068. (defvar org-ctrl-c-ctrl-c-final-hook nil
  15069. "Hook for functions attaching themselves to `C-c C-c'.
  15070. This can be used to add additional functionality to the `C-c C-c'
  15071. key which executes context-dependent commands. This hook is run
  15072. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  15073. before the first test.
  15074. Each function will be called with no arguments. The function
  15075. must check if the context is appropriate for it to act. If yes,
  15076. it should do its thing and then return a non-nil value. If the
  15077. context is wrong, just do nothing and return nil.")
  15078. (defvar org-tab-after-check-for-table-hook nil
  15079. "Hook for functions to attach themselves to TAB.
  15080. See `org-ctrl-c-ctrl-c-hook' for more information.
  15081. This hook runs after it has been established that the cursor is not in a
  15082. table, but before checking if the cursor is in a headline or if global cycling
  15083. should be done.
  15084. If any function in this hook returns t, not other actions like visibility
  15085. cycling will be done.")
  15086. (defvar org-tab-after-check-for-cycling-hook nil
  15087. "Hook for functions to attach themselves to TAB.
  15088. See `org-ctrl-c-ctrl-c-hook' for more information.
  15089. This hook runs after it has been established that not table field motion and
  15090. not visibility should be done because of current context. This is probably
  15091. the place where a package like yasnippets can hook in.")
  15092. (defvar org-tab-before-tab-emulation-hook nil
  15093. "Hook for functions to attach themselves to TAB.
  15094. See `org-ctrl-c-ctrl-c-hook' for more information.
  15095. This hook runs after every other options for TAB have been exhausted, but
  15096. before indentation and \t insertion takes place.")
  15097. (defvar org-metaleft-hook nil
  15098. "Hook for functions attaching themselves to `M-left'.
  15099. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15100. (defvar org-metaright-hook nil
  15101. "Hook for functions attaching themselves to `M-right'.
  15102. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15103. (defvar org-metaup-hook nil
  15104. "Hook for functions attaching themselves to `M-up'.
  15105. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15106. (defvar org-metadown-hook nil
  15107. "Hook for functions attaching themselves to `M-down'.
  15108. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15109. (defvar org-shiftmetaleft-hook nil
  15110. "Hook for functions attaching themselves to `M-S-left'.
  15111. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15112. (defvar org-shiftmetaright-hook nil
  15113. "Hook for functions attaching themselves to `M-S-right'.
  15114. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15115. (defvar org-shiftmetaup-hook nil
  15116. "Hook for functions attaching themselves to `M-S-up'.
  15117. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15118. (defvar org-shiftmetadown-hook nil
  15119. "Hook for functions attaching themselves to `M-S-down'.
  15120. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15121. (defvar org-metareturn-hook nil
  15122. "Hook for functions attaching themselves to `M-RET'.
  15123. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15124. (defvar org-shiftup-hook nil
  15125. "Hook for functions attaching themselves to `S-up'.
  15126. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15127. (defvar org-shiftup-final-hook nil
  15128. "Hook for functions attaching themselves to `S-up'.
  15129. This one runs after all other options except shift-select have been excluded.
  15130. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15131. (defvar org-shiftdown-hook nil
  15132. "Hook for functions attaching themselves to `S-down'.
  15133. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15134. (defvar org-shiftdown-final-hook nil
  15135. "Hook for functions attaching themselves to `S-down'.
  15136. This one runs after all other options except shift-select have been excluded.
  15137. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15138. (defvar org-shiftleft-hook nil
  15139. "Hook for functions attaching themselves to `S-left'.
  15140. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15141. (defvar org-shiftleft-final-hook nil
  15142. "Hook for functions attaching themselves to `S-left'.
  15143. This one runs after all other options except shift-select have been excluded.
  15144. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15145. (defvar org-shiftright-hook nil
  15146. "Hook for functions attaching themselves to `S-right'.
  15147. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15148. (defvar org-shiftright-final-hook nil
  15149. "Hook for functions attaching themselves to `S-right'.
  15150. This one runs after all other options except shift-select have been excluded.
  15151. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15152. (defun org-modifier-cursor-error ()
  15153. "Throw an error, a modified cursor command was applied in wrong context."
  15154. (user-error "This command is active in special context like tables, headlines or items"))
  15155. (defun org-shiftselect-error ()
  15156. "Throw an error because Shift-Cursor command was applied in wrong context."
  15157. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15158. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15159. (user-error "This command works only in special context like headlines or timestamps")))
  15160. (defun org-call-for-shift-select (cmd)
  15161. (let ((this-command-keys-shift-translated t))
  15162. (call-interactively cmd)))
  15163. (defun org-shifttab (&optional arg)
  15164. "Global visibility cycling or move to previous table field.
  15165. Call `org-table-previous-field' within a table.
  15166. When ARG is nil, cycle globally through visibility states.
  15167. When ARG is a numeric prefix, show contents of this level."
  15168. (interactive "P")
  15169. (cond
  15170. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15171. ((integerp arg)
  15172. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15173. (message "Content view to level: %d" arg)
  15174. (org-cycle-content (prefix-numeric-value arg2))
  15175. (org-cycle-show-empty-lines t)
  15176. (setq org-cycle-global-status 'overview)
  15177. (run-hook-with-args 'org-cycle-hook 'overview)))
  15178. (t (call-interactively 'org-cycle-global))))
  15179. (defun org-shiftmetaleft ()
  15180. "Promote subtree or delete table column.
  15181. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15182. `org-table-delete-column', depending on context. See the
  15183. individual commands for more information."
  15184. (interactive)
  15185. (cond
  15186. ((and (eq system-type 'darwin)
  15187. (or (eq org-support-shift-select 'always)
  15188. (and org-support-shift-select (org-region-active-p))))
  15189. (org-call-for-shift-select 'backward-char))
  15190. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15191. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15192. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15193. ((if (not (org-region-active-p)) (org-at-item-p)
  15194. (save-excursion (goto-char (region-beginning))
  15195. (org-at-item-p)))
  15196. (call-interactively 'org-outdent-item-tree))
  15197. (t (org-modifier-cursor-error))))
  15198. (defun org-shiftmetaright ()
  15199. "Demote subtree or insert table column.
  15200. Calls `org-demote-subtree', `org-indent-item-tree', or
  15201. `org-table-insert-column', depending on context. See the
  15202. individual commands for more information."
  15203. (interactive)
  15204. (cond
  15205. ((and (eq system-type 'darwin)
  15206. (or (eq org-support-shift-select 'always)
  15207. (and org-support-shift-select (org-region-active-p))))
  15208. (org-call-for-shift-select 'forward-char))
  15209. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15210. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15211. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15212. ((if (not (org-region-active-p)) (org-at-item-p)
  15213. (save-excursion (goto-char (region-beginning))
  15214. (org-at-item-p)))
  15215. (call-interactively 'org-indent-item-tree))
  15216. (t (org-modifier-cursor-error))))
  15217. (defun org-shiftmetaup (&optional _arg)
  15218. "Drag the line at point up.
  15219. In a table, kill the current row.
  15220. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15221. but also adjust the previous clocked item in the clock history.
  15222. Everywhere else, drag the line at point up."
  15223. (interactive "P")
  15224. (cond
  15225. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15226. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15227. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15228. (call-interactively 'org-timestamp-up)))
  15229. (t (call-interactively 'org-drag-line-backward))))
  15230. (defun org-shiftmetadown (&optional _arg)
  15231. "Drag the line at point down.
  15232. In a table, insert an empty row at the current line.
  15233. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15234. but also adjust the previous clocked item in the clock history.
  15235. Everywhere else, drag the line at point down."
  15236. (interactive "P")
  15237. (cond
  15238. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15239. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15240. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15241. (call-interactively 'org-timestamp-down)))
  15242. (t (call-interactively 'org-drag-line-forward))))
  15243. (defsubst org-hidden-tree-error ()
  15244. (user-error
  15245. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15246. (defun org-metaleft (&optional _arg)
  15247. "Promote heading, list item at point or move table column left.
  15248. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15249. depending on context. With no specific context, calls the Emacs
  15250. default `backward-word'. See the individual commands for more
  15251. information.
  15252. This function runs the hook `org-metaleft-hook' as a first step,
  15253. and returns at first non-nil value."
  15254. (interactive "P")
  15255. (cond
  15256. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15257. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15258. ((org-with-limited-levels
  15259. (or (org-at-heading-p)
  15260. (and (org-region-active-p)
  15261. (save-excursion
  15262. (goto-char (region-beginning))
  15263. (org-at-heading-p)))))
  15264. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15265. (call-interactively 'org-do-promote))
  15266. ;; At an inline task.
  15267. ((org-at-heading-p)
  15268. (call-interactively 'org-inlinetask-promote))
  15269. ((or (org-at-item-p)
  15270. (and (org-region-active-p)
  15271. (save-excursion
  15272. (goto-char (region-beginning))
  15273. (org-at-item-p))))
  15274. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15275. (call-interactively 'org-outdent-item))
  15276. (t (call-interactively 'backward-word))))
  15277. (defun org-metaright (&optional _arg)
  15278. "Demote heading, list item at point or move table column right.
  15279. In front of a drawer or a block keyword, indent it correctly.
  15280. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15281. `org-indent-drawer' or `org-indent-block' depending on context.
  15282. With no specific context, calls the Emacs default `forward-word'.
  15283. See the individual commands for more information.
  15284. This function runs the hook `org-metaright-hook' as a first step,
  15285. and returns at first non-nil value."
  15286. (interactive "P")
  15287. (cond
  15288. ((run-hook-with-args-until-success 'org-metaright-hook))
  15289. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15290. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15291. ((org-at-block-p) (call-interactively 'org-indent-block))
  15292. ((org-with-limited-levels
  15293. (or (org-at-heading-p)
  15294. (and (org-region-active-p)
  15295. (save-excursion
  15296. (goto-char (region-beginning))
  15297. (org-at-heading-p)))))
  15298. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15299. (call-interactively 'org-do-demote))
  15300. ;; At an inline task.
  15301. ((org-at-heading-p)
  15302. (call-interactively 'org-inlinetask-demote))
  15303. ((or (org-at-item-p)
  15304. (and (org-region-active-p)
  15305. (save-excursion
  15306. (goto-char (region-beginning))
  15307. (org-at-item-p))))
  15308. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15309. (call-interactively 'org-indent-item))
  15310. (t (call-interactively 'forward-word))))
  15311. (defun org-check-for-hidden (what)
  15312. "Check if there are hidden headlines/items in the current visual line.
  15313. WHAT can be either `headlines' or `items'. If the current line is
  15314. an outline or item heading and it has a folded subtree below it,
  15315. this function returns t, nil otherwise."
  15316. (let ((re (cond
  15317. ((eq what 'headlines) org-outline-regexp-bol)
  15318. ((eq what 'items) (org-item-beginning-re))
  15319. (t (error "This should not happen"))))
  15320. beg end)
  15321. (save-excursion
  15322. (catch 'exit
  15323. (unless (org-region-active-p)
  15324. (setq beg (line-beginning-position))
  15325. (beginning-of-line 2)
  15326. (while (and (not (eobp)) ;; this is like `next-line'
  15327. (org-invisible-p (1- (point))))
  15328. (beginning-of-line 2))
  15329. (setq end (point))
  15330. (goto-char beg)
  15331. (goto-char (line-end-position))
  15332. (setq end (max end (point)))
  15333. (while (re-search-forward re end t)
  15334. (when (org-invisible-p (match-beginning 0))
  15335. (throw 'exit t))))
  15336. nil))))
  15337. (defun org-metaup (&optional _arg)
  15338. "Move subtree up or move table row up.
  15339. Calls `org-move-subtree-up' or `org-table-move-row' or
  15340. `org-move-item-up', depending on context. See the individual commands
  15341. for more information."
  15342. (interactive "P")
  15343. (cond
  15344. ((run-hook-with-args-until-success 'org-metaup-hook))
  15345. ((org-region-active-p)
  15346. (let* ((a (save-excursion
  15347. (goto-char (region-beginning))
  15348. (line-beginning-position)))
  15349. (b (save-excursion
  15350. (goto-char (region-end))
  15351. (if (bolp) (1- (point)) (line-end-position))))
  15352. (c (save-excursion
  15353. (goto-char a)
  15354. (move-beginning-of-line 0)
  15355. (point)))
  15356. (d (save-excursion
  15357. (goto-char a)
  15358. (move-end-of-line 0)
  15359. (point))))
  15360. (transpose-regions a b c d)
  15361. (goto-char c)))
  15362. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15363. ((and (featurep 'org-inlinetask)
  15364. (org-inlinetask-in-task-p))
  15365. (org-drag-element-backward))
  15366. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15367. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15368. (t (org-drag-element-backward))))
  15369. (defun org-metadown (&optional _arg)
  15370. "Move subtree down or move table row down.
  15371. Calls `org-move-subtree-down' or `org-table-move-row' or
  15372. `org-move-item-down', depending on context. See the individual
  15373. commands for more information."
  15374. (interactive "P")
  15375. (cond
  15376. ((run-hook-with-args-until-success 'org-metadown-hook))
  15377. ((org-region-active-p)
  15378. (let* ((a (save-excursion
  15379. (goto-char (region-beginning))
  15380. (line-beginning-position)))
  15381. (b (save-excursion
  15382. (goto-char (region-end))
  15383. (if (bolp) (1- (point)) (line-end-position))))
  15384. (c (save-excursion
  15385. (goto-char b)
  15386. (move-beginning-of-line (if (bolp) 1 2))
  15387. (point)))
  15388. (d (save-excursion
  15389. (goto-char b)
  15390. (move-end-of-line (if (bolp) 1 2))
  15391. (point))))
  15392. (transpose-regions a b c d)
  15393. (goto-char d)))
  15394. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15395. ((and (featurep 'org-inlinetask)
  15396. (org-inlinetask-in-task-p))
  15397. (org-drag-element-forward))
  15398. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15399. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15400. (t (org-drag-element-forward))))
  15401. (defun org-shiftup (&optional arg)
  15402. "Act on current element according to context.
  15403. Call `org-timestamp-up' or `org-priority-up', or
  15404. `org-previous-item', or `org-table-move-cell-up'. See the
  15405. individual commands for more information."
  15406. (interactive "P")
  15407. (cond
  15408. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15409. ((and org-support-shift-select (org-region-active-p))
  15410. (org-call-for-shift-select 'previous-line))
  15411. ((org-at-timestamp-p 'lax)
  15412. (call-interactively (if org-edit-timestamp-down-means-later
  15413. 'org-timestamp-down 'org-timestamp-up)))
  15414. ((and (not (eq org-support-shift-select 'always))
  15415. org-priority-enable-commands
  15416. (org-at-heading-p))
  15417. (call-interactively 'org-priority-up))
  15418. ((and (not org-support-shift-select) (org-at-item-p))
  15419. (call-interactively 'org-previous-item))
  15420. ((org-clocktable-try-shift 'up arg))
  15421. ((and (not (eq org-support-shift-select 'always))
  15422. (org-at-table-p))
  15423. (org-table-move-cell-up))
  15424. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15425. (org-support-shift-select
  15426. (org-call-for-shift-select 'previous-line))
  15427. (t (org-shiftselect-error))))
  15428. (defun org-shiftdown (&optional arg)
  15429. "Act on current element according to context.
  15430. Call `org-timestamp-down' or `org-priority-down', or
  15431. `org-next-item', or `org-table-move-cell-down'. See the
  15432. individual commands for more information."
  15433. (interactive "P")
  15434. (cond
  15435. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15436. ((and org-support-shift-select (org-region-active-p))
  15437. (org-call-for-shift-select 'next-line))
  15438. ((org-at-timestamp-p 'lax)
  15439. (call-interactively (if org-edit-timestamp-down-means-later
  15440. 'org-timestamp-up 'org-timestamp-down)))
  15441. ((and (not (eq org-support-shift-select 'always))
  15442. org-priority-enable-commands
  15443. (org-at-heading-p))
  15444. (call-interactively 'org-priority-down))
  15445. ((and (not org-support-shift-select) (org-at-item-p))
  15446. (call-interactively 'org-next-item))
  15447. ((org-clocktable-try-shift 'down arg))
  15448. ((and (not (eq org-support-shift-select 'always))
  15449. (org-at-table-p))
  15450. (org-table-move-cell-down))
  15451. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15452. (org-support-shift-select
  15453. (org-call-for-shift-select 'next-line))
  15454. (t (org-shiftselect-error))))
  15455. (defun org-shiftright (&optional arg)
  15456. "Act on the current element according to context.
  15457. This does one of the following:
  15458. - switch a timestamp at point one day into the future
  15459. - on a headline, switch to the next TODO keyword
  15460. - on an item, switch entire list to the next bullet type
  15461. - on a property line, switch to the next allowed value
  15462. - on a clocktable definition line, move time block into the future
  15463. - in a table, move a single cell right"
  15464. (interactive "P")
  15465. (cond
  15466. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15467. ((and org-support-shift-select (org-region-active-p))
  15468. (org-call-for-shift-select 'forward-char))
  15469. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15470. ((and (not (eq org-support-shift-select 'always))
  15471. (org-at-heading-p))
  15472. (let ((org-inhibit-logging
  15473. (not org-treat-S-cursor-todo-selection-as-state-change))
  15474. (org-inhibit-blocking
  15475. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15476. (org-call-with-arg 'org-todo 'right)))
  15477. ((or (and org-support-shift-select
  15478. (not (eq org-support-shift-select 'always))
  15479. (org-at-item-bullet-p))
  15480. (and (not org-support-shift-select) (org-at-item-p)))
  15481. (org-call-with-arg 'org-cycle-list-bullet nil))
  15482. ((and (not (eq org-support-shift-select 'always))
  15483. (org-at-property-p))
  15484. (call-interactively 'org-property-next-allowed-value))
  15485. ((org-clocktable-try-shift 'right arg))
  15486. ((and (not (eq org-support-shift-select 'always))
  15487. (org-at-table-p))
  15488. (org-table-move-cell-right))
  15489. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15490. (org-support-shift-select
  15491. (org-call-for-shift-select 'forward-char))
  15492. (t (org-shiftselect-error))))
  15493. (defun org-shiftleft (&optional arg)
  15494. "Act on current element according to context.
  15495. This does one of the following:
  15496. - switch a timestamp at point one day into the past
  15497. - on a headline, switch to the previous TODO keyword.
  15498. - on an item, switch entire list to the previous bullet type
  15499. - on a property line, switch to the previous allowed value
  15500. - on a clocktable definition line, move time block into the past
  15501. - in a table, move a single cell left"
  15502. (interactive "P")
  15503. (cond
  15504. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15505. ((and org-support-shift-select (org-region-active-p))
  15506. (org-call-for-shift-select 'backward-char))
  15507. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  15508. ((and (not (eq org-support-shift-select 'always))
  15509. (org-at-heading-p))
  15510. (let ((org-inhibit-logging
  15511. (not org-treat-S-cursor-todo-selection-as-state-change))
  15512. (org-inhibit-blocking
  15513. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15514. (org-call-with-arg 'org-todo 'left)))
  15515. ((or (and org-support-shift-select
  15516. (not (eq org-support-shift-select 'always))
  15517. (org-at-item-bullet-p))
  15518. (and (not org-support-shift-select) (org-at-item-p)))
  15519. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  15520. ((and (not (eq org-support-shift-select 'always))
  15521. (org-at-property-p))
  15522. (call-interactively 'org-property-previous-allowed-value))
  15523. ((org-clocktable-try-shift 'left arg))
  15524. ((and (not (eq org-support-shift-select 'always))
  15525. (org-at-table-p))
  15526. (org-table-move-cell-left))
  15527. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  15528. (org-support-shift-select
  15529. (org-call-for-shift-select 'backward-char))
  15530. (t (org-shiftselect-error))))
  15531. (defun org-shiftcontrolright ()
  15532. "Switch to next TODO set."
  15533. (interactive)
  15534. (cond
  15535. ((and org-support-shift-select (org-region-active-p))
  15536. (org-call-for-shift-select 'forward-word))
  15537. ((and (not (eq org-support-shift-select 'always))
  15538. (org-at-heading-p))
  15539. (org-call-with-arg 'org-todo 'nextset))
  15540. (org-support-shift-select
  15541. (org-call-for-shift-select 'forward-word))
  15542. (t (org-shiftselect-error))))
  15543. (defun org-shiftcontrolleft ()
  15544. "Switch to previous TODO set."
  15545. (interactive)
  15546. (cond
  15547. ((and org-support-shift-select (org-region-active-p))
  15548. (org-call-for-shift-select 'backward-word))
  15549. ((and (not (eq org-support-shift-select 'always))
  15550. (org-at-heading-p))
  15551. (org-call-with-arg 'org-todo 'previousset))
  15552. (org-support-shift-select
  15553. (org-call-for-shift-select 'backward-word))
  15554. (t (org-shiftselect-error))))
  15555. (defun org-shiftcontrolup (&optional n)
  15556. "Change timestamps synchronously up in CLOCK log lines.
  15557. Optional argument N tells to change by that many units."
  15558. (interactive "P")
  15559. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15560. (let (org-support-shift-select)
  15561. (org-clock-timestamps-up n))
  15562. (user-error "Not at a clock log")))
  15563. (defun org-shiftcontroldown (&optional n)
  15564. "Change timestamps synchronously down in CLOCK log lines.
  15565. Optional argument N tells to change by that many units."
  15566. (interactive "P")
  15567. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15568. (let (org-support-shift-select)
  15569. (org-clock-timestamps-down n))
  15570. (user-error "Not at a clock log")))
  15571. (defun org-increase-number-at-point (&optional inc)
  15572. "Increment the number at point.
  15573. With an optional prefix numeric argument INC, increment using
  15574. this numeric value."
  15575. (interactive "p")
  15576. (if (not (number-at-point))
  15577. (user-error "Not on a number")
  15578. (unless inc (setq inc 1))
  15579. (let ((pos (point))
  15580. (beg (skip-chars-backward "-+^/*0-9eE."))
  15581. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  15582. (setq nap (buffer-substring-no-properties
  15583. (+ pos beg) (+ pos beg end)))
  15584. (delete-region (+ pos beg) (+ pos beg end))
  15585. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  15586. (when (org-at-table-p)
  15587. (org-table-align)
  15588. (org-table-end-of-field 1))))
  15589. (defun org-decrease-number-at-point (&optional inc)
  15590. "Decrement the number at point.
  15591. With an optional prefix numeric argument INC, decrement using
  15592. this numeric value."
  15593. (interactive "p")
  15594. (org-increase-number-at-point (- (or inc 1))))
  15595. (defun org-ctrl-c-ret ()
  15596. "Call `org-table-hline-and-move' or `org-insert-heading'."
  15597. (interactive)
  15598. (cond
  15599. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  15600. (t (call-interactively 'org-insert-heading))))
  15601. (defun org-copy-visible (beg end)
  15602. "Copy the visible parts of the region."
  15603. (interactive "r")
  15604. (let ((result ""))
  15605. (while (/= beg end)
  15606. (if (eq org-fold-core-style 'text-properties)
  15607. (progn
  15608. (while (org-invisible-p beg)
  15609. (setq beg (org-fold-next-visibility-change beg end)))
  15610. (let ((next (org-fold-next-visibility-change beg end)))
  15611. (setq result (concat result (buffer-substring beg next)))
  15612. (setq beg next)))
  15613. (when (invisible-p beg)
  15614. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  15615. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  15616. (setq result (concat result (buffer-substring beg next)))
  15617. (setq beg next))))
  15618. ;; Prevent Emacs from adding full selected text to `kill-ring'
  15619. ;; when `select-enable-primary' is non-nil. This special value of
  15620. ;; `deactivate-mark' only works since Emacs 29.
  15621. (setq deactivate-mark 'dont-save)
  15622. (kill-new result)
  15623. (message "Visible strings have been copied to the kill ring.")))
  15624. (defun org-copy-special ()
  15625. "Copy region in table or copy current subtree.
  15626. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  15627. context. See the individual commands for more information."
  15628. (interactive)
  15629. (call-interactively
  15630. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  15631. (defun org-cut-special ()
  15632. "Cut region in table or cut current subtree.
  15633. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  15634. context. See the individual commands for more information."
  15635. (interactive)
  15636. (call-interactively
  15637. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  15638. (defun org-paste-special (arg)
  15639. "Paste rectangular region into table, or past subtree relative to level.
  15640. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  15641. See the individual commands for more information."
  15642. (interactive "P")
  15643. (if (org-at-table-p)
  15644. (org-table-paste-rectangle)
  15645. (org-paste-subtree arg)))
  15646. (defun org-edit-special (&optional arg)
  15647. "Call a special editor for the element at point.
  15648. When at a table, call the formula editor with `org-table-edit-formulas'.
  15649. When in a source code block, call `org-edit-src-code'.
  15650. When in a fixed-width region, call `org-edit-fixed-width-region'.
  15651. When in an export block, call `org-edit-export-block'.
  15652. When in a comment block, call `org-edit-comment-block'.
  15653. When in a LaTeX environment, call `org-edit-latex-environment'.
  15654. When at an INCLUDE, SETUPFILE or BIBLIOGRAPHY keyword, visit the included file.
  15655. When at a footnote reference, call `org-edit-footnote-reference'.
  15656. When at a planning line call, `org-deadline' and/or `org-schedule'.
  15657. When at an active timestamp, call `org-time-stamp'.
  15658. When at an inactive timestamp, call `org-time-stamp-inactive'.
  15659. On a link, call `ffap' to visit the link at point.
  15660. Otherwise, return a user error."
  15661. (interactive "P")
  15662. (let ((element (org-element-at-point)))
  15663. (barf-if-buffer-read-only)
  15664. (pcase (org-element-type element)
  15665. (`src-block
  15666. (if (not arg) (org-edit-src-code)
  15667. (let* ((info (org-babel-get-src-block-info))
  15668. (lang (nth 0 info))
  15669. (params (nth 2 info))
  15670. (session (cdr (assq :session params))))
  15671. (if (not session) (org-edit-src-code)
  15672. ;; At a source block with a session and function called
  15673. ;; with an ARG: switch to the buffer related to the
  15674. ;; inferior process.
  15675. (switch-to-buffer
  15676. (funcall (intern (concat "org-babel-prep-session:" lang))
  15677. session params))))))
  15678. (`keyword
  15679. (unless (member (org-element-property :key element)
  15680. '("BIBLIOGRAPHY" "INCLUDE" "SETUPFILE"))
  15681. (user-error "No special environment to edit here"))
  15682. (let ((value (org-element-property :value element)))
  15683. (unless (org-string-nw-p value) (user-error "No file to edit"))
  15684. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  15685. (or (match-string 1 value)
  15686. (match-string 0 value)))))
  15687. (when (org-url-p file)
  15688. (user-error "Files located with a URL cannot be edited"))
  15689. (org-link-open-from-string
  15690. (format "[[%s]]" (expand-file-name file))))))
  15691. (`table
  15692. (if (eq (org-element-property :type element) 'table.el)
  15693. (org-edit-table.el)
  15694. (call-interactively 'org-table-edit-formulas)))
  15695. ;; Only Org tables contain `table-row' type elements.
  15696. (`table-row (call-interactively 'org-table-edit-formulas))
  15697. (`example-block (org-edit-src-code))
  15698. (`export-block (org-edit-export-block))
  15699. (`comment-block (org-edit-comment-block))
  15700. (`fixed-width (org-edit-fixed-width-region))
  15701. (`latex-environment (org-edit-latex-environment))
  15702. (`planning
  15703. (let ((proplist (cadr element)))
  15704. (mapc #'call-interactively
  15705. (remq nil
  15706. (list
  15707. (when (plist-get proplist :deadline) #'org-deadline)
  15708. (when (plist-get proplist :scheduled) #'org-schedule))))))
  15709. (_
  15710. ;; No notable element at point. Though, we may be at a link or
  15711. ;; a footnote reference, which are objects. Thus, scan deeper.
  15712. (let ((context (org-element-context element)))
  15713. (pcase (org-element-type context)
  15714. (`footnote-reference (org-edit-footnote-reference))
  15715. (`inline-src-block (org-edit-inline-src-code))
  15716. (`latex-fragment (org-edit-latex-fragment))
  15717. (`timestamp (if (eq 'inactive (org-element-property :type context))
  15718. (call-interactively #'org-time-stamp-inactive)
  15719. (call-interactively #'org-time-stamp)))
  15720. (`link (call-interactively #'ffap))
  15721. (_ (user-error "No special environment to edit here"))))))))
  15722. (defun org-ctrl-c-ctrl-c (&optional arg)
  15723. "Set tags in headline, or update according to changed information at point.
  15724. This command does many different things, depending on context:
  15725. - If column view is active, in agenda or org buffers, quit it.
  15726. - If there are highlights, remove them.
  15727. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  15728. this is what we do.
  15729. - If the cursor is on a statistics cookie, update it.
  15730. - If the cursor is in a headline, in an agenda or an org buffer,
  15731. prompt for tags and insert them into the current line, aligned
  15732. to `org-tags-column'. When called with prefix arg, realign all
  15733. tags in the current buffer.
  15734. - If the cursor is in one of the special #+KEYWORD lines, this
  15735. triggers scanning the buffer for these lines and updating the
  15736. information.
  15737. - If the cursor is inside a table, realign the table. This command
  15738. works even if the automatic table editor has been turned off.
  15739. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  15740. the entire table.
  15741. - If the cursor is at a footnote reference or definition, jump to
  15742. the corresponding definition or references, respectively.
  15743. - If the cursor is a the beginning of a dynamic block, update it.
  15744. - If the current buffer is a capture buffer, close note and file it.
  15745. - If the cursor is on a <<<target>>>, update radio targets and
  15746. corresponding links in this buffer.
  15747. - If the cursor is on a numbered item in a plain list, renumber the
  15748. ordered list.
  15749. - If the cursor is on a checkbox, toggle it.
  15750. - If the cursor is on a code block, evaluate it. The variable
  15751. `org-confirm-babel-evaluate' can be used to control prompting
  15752. before code block evaluation, by default every code block
  15753. evaluation requires confirmation. Code block evaluation can be
  15754. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  15755. (interactive "P")
  15756. (cond
  15757. ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  15758. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  15759. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  15760. (org-remove-occur-highlights)
  15761. (message "Temporary highlights/overlays removed from current buffer"))
  15762. ((and (local-variable-p 'org-finish-function)
  15763. (fboundp org-finish-function))
  15764. (funcall org-finish-function))
  15765. ((org-babel-hash-at-point))
  15766. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  15767. (t
  15768. (let* ((context
  15769. (org-element-lineage
  15770. (org-element-context)
  15771. ;; Limit to supported contexts.
  15772. '(babel-call clock dynamic-block footnote-definition
  15773. footnote-reference inline-babel-call inline-src-block
  15774. inlinetask item keyword node-property paragraph
  15775. plain-list planning property-drawer radio-target
  15776. src-block statistics-cookie table table-cell table-row
  15777. timestamp)
  15778. t))
  15779. (radio-list-p (org-at-radio-list-p))
  15780. (type (org-element-type context)))
  15781. ;; For convenience: at the first line of a paragraph on the same
  15782. ;; line as an item, apply function on that item instead.
  15783. (when (eq type 'paragraph)
  15784. (let ((parent (org-element-property :parent context)))
  15785. (when (and (eq (org-element-type parent) 'item)
  15786. (= (line-beginning-position)
  15787. (org-element-property :begin parent)))
  15788. (setq context parent)
  15789. (setq type 'item))))
  15790. ;; Act according to type of element or object at point.
  15791. ;;
  15792. ;; Do nothing on a blank line, except if it is contained in
  15793. ;; a source block. Hence, we first check if point is in such
  15794. ;; a block and then if it is at a blank line.
  15795. (pcase type
  15796. ((or `inline-src-block `src-block)
  15797. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  15798. (org-babel-eval-wipe-error-buffer)
  15799. (org-babel-execute-src-block
  15800. current-prefix-arg (org-babel-get-src-block-info nil context))))
  15801. ((guard (org-match-line "[ \t]*$"))
  15802. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  15803. (user-error
  15804. (substitute-command-keys
  15805. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  15806. ((or `babel-call `inline-babel-call)
  15807. (let ((info (org-babel-lob-get-info context)))
  15808. (when info (org-babel-execute-src-block nil info))))
  15809. (`clock (org-clock-update-time-maybe))
  15810. (`dynamic-block
  15811. (save-excursion
  15812. (goto-char (org-element-property :post-affiliated context))
  15813. (org-update-dblock)))
  15814. (`footnote-definition
  15815. (goto-char (org-element-property :post-affiliated context))
  15816. (call-interactively 'org-footnote-action))
  15817. (`footnote-reference (call-interactively #'org-footnote-action))
  15818. ((or `headline `inlinetask)
  15819. (save-excursion (goto-char (org-element-property :begin context))
  15820. (call-interactively #'org-set-tags-command)))
  15821. (`item
  15822. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  15823. ;; unconditionally, whereas `C-u' will toggle its presence.
  15824. ;; Without a universal argument, if the item has a checkbox,
  15825. ;; toggle it. Otherwise repair the list.
  15826. (if (or radio-list-p
  15827. (and (boundp org-list-checkbox-radio-mode)
  15828. org-list-checkbox-radio-mode))
  15829. (org-toggle-radio-button arg)
  15830. (let* ((box (org-element-property :checkbox context))
  15831. (struct (org-element-property :structure context))
  15832. (old-struct (copy-tree struct))
  15833. (parents (org-list-parents-alist struct))
  15834. (prevs (org-list-prevs-alist struct))
  15835. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  15836. (org-list-set-checkbox
  15837. (org-element-property :begin context) struct
  15838. (cond ((equal arg '(16)) "[-]")
  15839. ((and (not box) (equal arg '(4))) "[ ]")
  15840. ((or (not box) (equal arg '(4))) nil)
  15841. ((eq box 'on) "[ ]")
  15842. (t "[X]")))
  15843. ;; Mimic `org-list-write-struct' but with grabbing a return
  15844. ;; value from `org-list-struct-fix-box'.
  15845. (org-list-struct-fix-ind struct parents 2)
  15846. (org-list-struct-fix-item-end struct)
  15847. (org-list-struct-fix-bul struct prevs)
  15848. (org-list-struct-fix-ind struct parents)
  15849. (let ((block-item
  15850. (org-list-struct-fix-box struct parents prevs orderedp)))
  15851. (if (and box (equal struct old-struct))
  15852. (if (equal arg '(16))
  15853. (message "Checkboxes already reset")
  15854. (user-error "Cannot toggle this checkbox: %s"
  15855. (if (eq box 'on)
  15856. "all subitems checked"
  15857. "unchecked subitems")))
  15858. (org-list-struct-apply-struct struct old-struct)
  15859. (org-update-checkbox-count-maybe))
  15860. (when block-item
  15861. (message "Checkboxes were removed due to empty box at line %d"
  15862. (org-current-line block-item)))))))
  15863. (`plain-list
  15864. ;; At a plain list, with a double C-u argument, set
  15865. ;; checkboxes of each item to "[-]", whereas a single one
  15866. ;; will toggle their presence according to the state of the
  15867. ;; first item in the list. Without an argument, repair the
  15868. ;; list.
  15869. (if (or radio-list-p
  15870. (and (boundp org-list-checkbox-radio-mode)
  15871. org-list-checkbox-radio-mode))
  15872. (org-toggle-radio-button arg)
  15873. (let* ((begin (org-element-property :contents-begin context))
  15874. (struct (org-element-property :structure context))
  15875. (old-struct (copy-tree struct))
  15876. (first-box (save-excursion
  15877. (goto-char begin)
  15878. (looking-at org-list-full-item-re)
  15879. (match-string-no-properties 3)))
  15880. (new-box (cond ((equal arg '(16)) "[-]")
  15881. ((equal arg '(4)) (unless first-box "[ ]"))
  15882. ((equal first-box "[X]") "[ ]")
  15883. (t "[X]"))))
  15884. (cond
  15885. (arg
  15886. (dolist (pos
  15887. (org-list-get-all-items
  15888. begin struct (org-list-prevs-alist struct)))
  15889. (org-list-set-checkbox pos struct new-box)))
  15890. ((and first-box (eq (point) begin))
  15891. ;; For convenience, when point is at bol on the first
  15892. ;; item of the list and no argument is provided, simply
  15893. ;; toggle checkbox of that item, if any.
  15894. (org-list-set-checkbox begin struct new-box)))
  15895. (when (equal
  15896. (org-list-write-struct
  15897. struct (org-list-parents-alist struct) old-struct)
  15898. old-struct)
  15899. (message "Cannot update this checkbox"))
  15900. (org-update-checkbox-count-maybe))))
  15901. (`keyword
  15902. (let ((org-inhibit-startup-visibility-stuff t)
  15903. (org-startup-align-all-tables nil))
  15904. (when (boundp 'org-table-coordinate-overlays)
  15905. (mapc #'delete-overlay org-table-coordinate-overlays)
  15906. (setq org-table-coordinate-overlays nil))
  15907. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  15908. (message "Local setup has been refreshed"))
  15909. ((or `property-drawer `node-property)
  15910. (call-interactively #'org-property-action))
  15911. (`radio-target
  15912. (call-interactively #'org-update-radio-target-regexp))
  15913. (`statistics-cookie
  15914. (call-interactively #'org-update-statistics-cookies))
  15915. ((or `table `table-cell `table-row)
  15916. ;; At a table, generate a plot if on the #+plot line,
  15917. ;; recalculate every field and align it otherwise. Also
  15918. ;; send the table if necessary.
  15919. (cond
  15920. ((and (org-match-line "[ \t]*#\\+plot:")
  15921. (< (point) (org-element-property :post-affiliated context)))
  15922. (org-plot/gnuplot))
  15923. ;; If the table has a `table.el' type, just give up.
  15924. ((eq (org-element-property :type context) 'table.el)
  15925. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  15926. Use `\\[org-edit-special]' to edit table.el tables")))
  15927. ;; At a table row or cell, maybe recalculate line but always
  15928. ;; align table.
  15929. ((or (eq type 'table)
  15930. ;; Check if point is at a TBLFM line.
  15931. (and (eq type 'table-row)
  15932. (= (point) (org-element-property :end context))))
  15933. (save-excursion
  15934. (if (org-at-TBLFM-p)
  15935. (progn (require 'org-table)
  15936. (org-table-calc-current-TBLFM))
  15937. (goto-char (org-element-property :contents-begin context))
  15938. (org-call-with-arg 'org-table-recalculate (or arg t))
  15939. (orgtbl-send-table 'maybe))))
  15940. (t
  15941. (org-table-maybe-eval-formula)
  15942. (cond (arg (call-interactively #'org-table-recalculate))
  15943. ((org-table-maybe-recalculate-line))
  15944. (t (org-table-align))))))
  15945. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  15946. (org-timestamp-change 0 'day))
  15947. ((and `nil (guard (org-at-heading-p)))
  15948. ;; When point is on an unsupported object type, we can miss
  15949. ;; the fact that it also is at a heading. Handle it here.
  15950. (call-interactively #'org-set-tags-command))
  15951. ((guard
  15952. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  15953. (_
  15954. (user-error
  15955. (substitute-command-keys
  15956. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  15957. (defun org-mode-restart ()
  15958. "Restart `org-mode'."
  15959. (interactive)
  15960. (let ((indent-status (bound-and-true-p org-indent-mode)))
  15961. (funcall major-mode)
  15962. (hack-local-variables)
  15963. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  15964. (org-indent-mode -1))
  15965. (org-reset-file-cache))
  15966. (message "%s restarted" major-mode))
  15967. (defun org-kill-note-or-show-branches ()
  15968. "Abort storing current note, or show just branches."
  15969. (interactive)
  15970. (cond (org-finish-function
  15971. (let ((org-note-abort t)) (funcall org-finish-function)))
  15972. ((org-before-first-heading-p)
  15973. (org-fold-show-branches-buffer)
  15974. (org-fold-hide-archived-subtrees (point-min) (point-max)))
  15975. (t
  15976. (let ((beg (progn (org-back-to-heading) (point)))
  15977. (end (save-excursion (org-end-of-subtree t t) (point))))
  15978. (org-fold-hide-subtree)
  15979. (org-fold-show-branches)
  15980. (org-fold-hide-archived-subtrees beg end)))))
  15981. (defun org-delete-indentation (&optional arg)
  15982. "Join current line to previous and fix whitespace at join.
  15983. If previous line is a headline add to headline title. Otherwise
  15984. the function calls `delete-indentation'.
  15985. I.e. with a non-nil optional argument, join the line with the
  15986. following one. If there is a region then join the lines in that
  15987. region."
  15988. (interactive "*P")
  15989. (if (save-excursion
  15990. (beginning-of-line (if arg 1 0))
  15991. (let ((case-fold-search nil))
  15992. (looking-at org-complex-heading-regexp)))
  15993. ;; At headline.
  15994. (let ((tags-column (when (match-beginning 5)
  15995. (save-excursion (goto-char (match-beginning 5))
  15996. (current-column))))
  15997. (string (concat " " (progn (when arg (forward-line 1))
  15998. (org-trim (delete-and-extract-region
  15999. (line-beginning-position)
  16000. (line-end-position)))))))
  16001. (unless (bobp) (delete-region (point) (1- (point))))
  16002. (goto-char (or (match-end 4)
  16003. (match-beginning 5)
  16004. (match-end 0)))
  16005. (skip-chars-backward " \t")
  16006. (save-excursion (insert string))
  16007. ;; Adjust alignment of tags.
  16008. (cond
  16009. ((not tags-column)) ;no tags
  16010. (org-auto-align-tags (org-align-tags))
  16011. (t (org--align-tags-here tags-column)))) ;preserve tags column
  16012. (let ((current-prefix-arg arg))
  16013. (call-interactively #'delete-indentation))))
  16014. (defun org-open-line (n)
  16015. "Insert a new row in tables, call `open-line' elsewhere.
  16016. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  16017. As a special case, when a document starts with a table, allow to
  16018. call `open-line' on the very first character."
  16019. (interactive "*p")
  16020. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  16021. (org-table-insert-row)
  16022. (open-line n)))
  16023. (defun org--newline (indent arg interactive)
  16024. "Call `newline-and-indent' or just `newline'.
  16025. If INDENT is non-nil, call `newline-and-indent' with ARG to
  16026. indent unconditionally; otherwise, call `newline' with ARG and
  16027. INTERACTIVE, which can trigger indentation if
  16028. `electric-indent-mode' is enabled."
  16029. (if indent
  16030. (org-newline-and-indent arg)
  16031. (newline arg interactive)))
  16032. (defun org-return (&optional indent arg interactive)
  16033. "Goto next table row or insert a newline.
  16034. Calls `org-table-next-row' or `newline', depending on context.
  16035. When optional INDENT argument is non-nil, call
  16036. `newline-and-indent' with ARG, otherwise call `newline' with ARG
  16037. and INTERACTIVE.
  16038. When `org-return-follows-link' is non-nil and point is on
  16039. a timestamp or a link, call `org-open-at-point'. However, it
  16040. will not happen if point is in a table or on a \"dead\"
  16041. object (e.g., within a comment). In these case, you need to use
  16042. `org-open-at-point' directly."
  16043. (interactive "i\nP\np")
  16044. (let* ((context (if org-return-follows-link (org-element-context)
  16045. (org-element-at-point)))
  16046. (element-type (org-element-type context)))
  16047. (cond
  16048. ;; In a table, call `org-table-next-row'. However, before first
  16049. ;; column or after last one, split the table.
  16050. ((or (and (eq 'table element-type)
  16051. (not (eq 'table.el (org-element-property :type context)))
  16052. (>= (point) (org-element-property :contents-begin context))
  16053. (< (point) (org-element-property :contents-end context)))
  16054. (org-element-lineage context '(table-row table-cell) t))
  16055. (if (or (looking-at-p "[ \t]*$")
  16056. (save-excursion (skip-chars-backward " \t") (bolp)))
  16057. (insert "\n")
  16058. (org-table-justify-field-maybe)
  16059. (call-interactively #'org-table-next-row)))
  16060. ;; On a link or a timestamp, call `org-open-at-point' if
  16061. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  16062. ;; locations, e.g., in a comment, as `org-open-at-point'.
  16063. ((and org-return-follows-link
  16064. (or (and (eq 'link element-type)
  16065. ;; Ensure point is not on the white spaces after
  16066. ;; the link.
  16067. (let ((origin (point)))
  16068. (org-with-point-at (org-element-property :end context)
  16069. (skip-chars-backward " \t")
  16070. (> (point) origin))))
  16071. (org-in-regexp org-ts-regexp-both nil t)
  16072. (org-in-regexp org-tsr-regexp-both nil t)
  16073. (org-in-regexp org-link-any-re nil t)))
  16074. (call-interactively #'org-open-at-point))
  16075. ;; Insert newline in heading, but preserve tags.
  16076. ((and (not (bolp))
  16077. (let ((case-fold-search nil))
  16078. (org-match-line org-complex-heading-regexp)))
  16079. ;; At headline. Split line. However, if point is on keyword,
  16080. ;; priority cookie or tags, do not break any of them: add
  16081. ;; a newline after the headline instead.
  16082. (let ((tags-column (and (match-beginning 5)
  16083. (save-excursion (goto-char (match-beginning 5))
  16084. (current-column))))
  16085. (string
  16086. (when (and (match-end 4) (org-point-in-group (point) 4))
  16087. (delete-and-extract-region (point) (match-end 4)))))
  16088. ;; Adjust tag alignment.
  16089. (cond
  16090. ((not (and tags-column string)))
  16091. (org-auto-align-tags (org-align-tags))
  16092. (t (org--align-tags-here tags-column))) ;preserve tags column
  16093. (end-of-line)
  16094. (org-fold-show-entry 'hide-drawers)
  16095. (org--newline indent arg interactive)
  16096. (when string (save-excursion (insert (org-trim string))))))
  16097. ;; In a list, make sure indenting keeps trailing text within.
  16098. ((and (not (eolp))
  16099. (org-element-lineage context '(item)))
  16100. (let ((trailing-data
  16101. (delete-and-extract-region (point) (line-end-position))))
  16102. (org--newline indent arg interactive)
  16103. (save-excursion (insert trailing-data))))
  16104. (t
  16105. ;; Do not auto-fill when point is in an Org property drawer.
  16106. (let ((auto-fill-function (and (not (org-at-property-p))
  16107. auto-fill-function)))
  16108. (org--newline indent arg interactive))))))
  16109. (defun org-return-and-maybe-indent ()
  16110. "Goto next table row, or insert a newline, maybe indented.
  16111. Call `org-table-next-row' or `org-return', depending on context.
  16112. See the individual commands for more information.
  16113. When inserting a newline, if `org-adapt-indentation' is t:
  16114. indent the line if `electric-indent-mode' is disabled, don't
  16115. indent it if it is enabled."
  16116. (interactive)
  16117. (org-return (not electric-indent-mode)))
  16118. (defun org-ctrl-c-tab (&optional arg)
  16119. "Toggle columns width in a table, or show children.
  16120. Call `org-table-toggle-column-width' if point is in a table.
  16121. Otherwise provide a compact view of the children. ARG is the
  16122. level to hide."
  16123. (interactive "p")
  16124. (cond
  16125. ((org-at-table-p)
  16126. (call-interactively #'org-table-toggle-column-width))
  16127. ((org-before-first-heading-p)
  16128. (save-excursion
  16129. (org-fold-flag-above-first-heading)
  16130. (org-fold-hide-sublevels (or arg 1))))
  16131. (t
  16132. (org-fold-hide-subtree)
  16133. (org-fold-show-children arg))))
  16134. (defun org-ctrl-c-star ()
  16135. "Compute table, or change heading status of lines.
  16136. Calls `org-table-recalculate' or `org-toggle-heading',
  16137. depending on context."
  16138. (interactive)
  16139. (cond
  16140. ((org-at-table-p)
  16141. (call-interactively 'org-table-recalculate))
  16142. (t
  16143. ;; Convert all lines in region to list items
  16144. (call-interactively 'org-toggle-heading))))
  16145. (defun org-ctrl-c-minus ()
  16146. "Insert separator line in table or modify bullet status of line.
  16147. Also turns a plain line or a region of lines into list items.
  16148. Calls `org-table-insert-hline', `org-toggle-item', or
  16149. `org-cycle-list-bullet', depending on context."
  16150. (interactive)
  16151. (cond
  16152. ((org-at-table-p)
  16153. (call-interactively 'org-table-insert-hline))
  16154. ((org-region-active-p)
  16155. (call-interactively 'org-toggle-item))
  16156. ((org-in-item-p)
  16157. (call-interactively 'org-cycle-list-bullet))
  16158. (t
  16159. (call-interactively 'org-toggle-item))))
  16160. (defun org-toggle-heading (&optional nstars)
  16161. "Convert headings to normal text, or items or text to headings.
  16162. If there is no active region, only convert the current line.
  16163. With a `\\[universal-argument]' prefix, convert the whole list at
  16164. point into heading.
  16165. In a region:
  16166. - If the first non blank line is a headline, remove the stars
  16167. from all headlines in the region.
  16168. - If it is a normal line, turn each and every normal line (i.e.,
  16169. not an heading or an item) in the region into headings. If you
  16170. want to convert only the first line of this region, use one
  16171. universal prefix argument.
  16172. - If it is a plain list item, turn all plain list items into headings.
  16173. When converting a line into a heading, the number of stars is chosen
  16174. such that the lines become children of the current entry. However,
  16175. when a numeric prefix argument is given, its value determines the
  16176. number of stars to add."
  16177. (interactive "P")
  16178. (let ((skip-blanks
  16179. ;; Return beginning of first non-blank line, starting from
  16180. ;; line at POS.
  16181. (lambda (pos)
  16182. (save-excursion
  16183. (goto-char pos)
  16184. (while (org-at-comment-p) (forward-line))
  16185. (skip-chars-forward " \r\t\n")
  16186. (line-beginning-position))))
  16187. beg end toggled)
  16188. ;; Determine boundaries of changes. If a universal prefix has
  16189. ;; been given, put the list in a region. If region ends at a bol,
  16190. ;; do not consider the last line to be in the region.
  16191. (when (and current-prefix-arg (org-at-item-p))
  16192. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16193. (org-mark-element))
  16194. (if (org-region-active-p)
  16195. (setq beg (funcall skip-blanks (region-beginning))
  16196. end (copy-marker (save-excursion
  16197. (goto-char (region-end))
  16198. (if (bolp) (point) (line-end-position)))))
  16199. (setq beg (funcall skip-blanks (line-beginning-position))
  16200. end (copy-marker (line-end-position))))
  16201. ;; Ensure inline tasks don't count as headings.
  16202. (org-with-limited-levels
  16203. (save-excursion
  16204. (goto-char beg)
  16205. (cond
  16206. ;; Case 1. Started at an heading: de-star headings.
  16207. ((org-at-heading-p)
  16208. (while (< (point) end)
  16209. (when (org-at-heading-p)
  16210. (looking-at org-outline-regexp) (replace-match "")
  16211. (setq toggled t))
  16212. (forward-line)))
  16213. ;; Case 2. Started at an item: change items into headlines.
  16214. ;; One star will be added by `org-list-to-subtree'.
  16215. ((org-at-item-p)
  16216. (while (< (point) end)
  16217. (when (org-at-item-p)
  16218. ;; Pay attention to cases when region ends before list.
  16219. (let* ((struct (org-list-struct))
  16220. (list-end
  16221. (min (org-list-get-bottom-point struct) (1+ end))))
  16222. (save-restriction
  16223. (narrow-to-region (point) list-end)
  16224. (insert (org-list-to-subtree
  16225. (org-list-to-lisp t)
  16226. (pcase (org-current-level)
  16227. (`nil 1)
  16228. (l (1+ (org-reduced-level l)))))
  16229. "\n")))
  16230. (setq toggled t))
  16231. (forward-line)))
  16232. ;; Case 3. Started at normal text: make every line an heading,
  16233. ;; skipping headlines and items.
  16234. (t (let* ((stars
  16235. (make-string
  16236. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16237. (add-stars
  16238. (cond (nstars "") ; stars from prefix only
  16239. ((equal stars "") "*") ; before first heading
  16240. (org-odd-levels-only "**") ; inside heading, odd
  16241. (t "*"))) ; inside heading, oddeven
  16242. (rpl (concat stars add-stars " "))
  16243. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16244. (while (< (point) (if (equal nstars '(4)) lend end))
  16245. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16246. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16247. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16248. (forward-line)))))))
  16249. (unless toggled (message "Cannot toggle heading from here"))))
  16250. (defun org-meta-return (&optional arg)
  16251. "Insert a new heading or wrap a region in a table.
  16252. Calls `org-insert-heading', `org-insert-item' or
  16253. `org-table-wrap-region', depending on context. When called with
  16254. an argument, unconditionally call `org-insert-heading'."
  16255. (interactive "P")
  16256. (org-fold-check-before-invisible-edit 'insert)
  16257. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16258. (call-interactively (cond (arg #'org-insert-heading)
  16259. ((org-at-table-p) #'org-table-wrap-region)
  16260. ((org-in-item-p) #'org-insert-item)
  16261. (t #'org-insert-heading)))))
  16262. ;;; Menu entries
  16263. (defsubst org-in-subtree-not-table-p ()
  16264. "Are we in a subtree and not in a table?"
  16265. (and (not (org-before-first-heading-p))
  16266. (not (org-at-table-p))))
  16267. ;; Define the Org mode menus
  16268. (easy-menu-define org-org-menu org-mode-map "Org menu."
  16269. `("Org"
  16270. ("Show/Hide"
  16271. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16272. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16273. ["Sparse Tree..." org-sparse-tree t]
  16274. ["Reveal Context" org-fold-reveal t]
  16275. ["Show All" org-fold-show-all t]
  16276. "--"
  16277. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16278. "--"
  16279. ["New Heading" org-insert-heading t]
  16280. ("Navigate Headings"
  16281. ["Up" outline-up-heading t]
  16282. ["Next" outline-next-visible-heading t]
  16283. ["Previous" outline-previous-visible-heading t]
  16284. ["Next Same Level" outline-forward-same-level t]
  16285. ["Previous Same Level" outline-backward-same-level t]
  16286. "--"
  16287. ["Jump" org-goto t])
  16288. ("Edit Structure"
  16289. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16290. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16291. "--"
  16292. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16293. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16294. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16295. "--"
  16296. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16297. "--"
  16298. ["Copy visible text" org-copy-visible t]
  16299. "--"
  16300. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16301. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16302. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16303. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16304. "--"
  16305. ["Sort Region/Children" org-sort t]
  16306. "--"
  16307. ["Convert to odd levels" org-convert-to-odd-levels t]
  16308. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16309. ("Editing"
  16310. ["Emphasis..." org-emphasize t]
  16311. ["Add block structure" org-insert-structure-template t]
  16312. ["Edit Source Example" org-edit-special t]
  16313. "--"
  16314. ["Footnote new/jump" org-footnote-action t]
  16315. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16316. ("Archive"
  16317. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16318. "--"
  16319. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16320. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16321. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)])
  16322. "--"
  16323. ("Hyperlinks"
  16324. ["Store Link (Global)" org-store-link t]
  16325. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16326. ["Insert Link" org-insert-link t]
  16327. ["Follow Link" org-open-at-point t]
  16328. "--"
  16329. ["Next link" org-next-link t]
  16330. ["Previous link" org-previous-link t]
  16331. "--"
  16332. ["Descriptive Links"
  16333. org-toggle-link-display
  16334. :style radio
  16335. :selected org-descriptive-links
  16336. ]
  16337. ["Literal Links"
  16338. org-toggle-link-display
  16339. :style radio
  16340. :selected (not org-descriptive-links)])
  16341. "--"
  16342. ("TODO Lists"
  16343. ["TODO/DONE/-" org-todo t]
  16344. ("Select keyword"
  16345. ["Next keyword" org-shiftright (org-at-heading-p)]
  16346. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16347. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16348. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16349. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16350. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16351. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16352. "--"
  16353. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16354. :selected org-enforce-todo-dependencies :style toggle :active t]
  16355. "Settings for tree at point"
  16356. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16357. :selected (org-entry-get nil "ORDERED")
  16358. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16359. ["Do Children parallel" org-toggle-ordered-property :style radio
  16360. :selected (not (org-entry-get nil "ORDERED"))
  16361. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16362. "--"
  16363. ["Set Priority" org-priority t]
  16364. ["Priority Up" org-shiftup t]
  16365. ["Priority Down" org-shiftdown t]
  16366. "--"
  16367. ["Get news from all feeds" org-feed-update-all t]
  16368. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16369. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16370. ("TAGS and Properties"
  16371. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16372. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16373. "--"
  16374. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16375. ["Column view of properties" org-columns t]
  16376. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16377. ("Dates and Scheduling"
  16378. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16379. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16380. ("Change Date"
  16381. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16382. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16383. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16384. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16385. ["Compute Time Range" org-evaluate-time-range t]
  16386. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16387. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16388. "--"
  16389. ["Custom time format" org-toggle-time-stamp-overlays
  16390. :style radio :selected org-display-custom-times]
  16391. "--"
  16392. ["Goto Calendar" org-goto-calendar t]
  16393. ["Date from Calendar" org-date-from-calendar t]
  16394. "--"
  16395. ["Start/Restart Timer" org-timer-start t]
  16396. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16397. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16398. ["Insert Timer String" org-timer t]
  16399. ["Insert Timer Item" org-timer-item t])
  16400. ("Logging work"
  16401. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16402. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16403. ["Clock out" org-clock-out t]
  16404. ["Clock cancel" org-clock-cancel t]
  16405. "--"
  16406. ["Mark as default task" org-clock-mark-default-task t]
  16407. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16408. ["Goto running clock" org-clock-goto t]
  16409. "--"
  16410. ["Display times" org-clock-display t]
  16411. ["Create clock table" org-clock-report t]
  16412. "--"
  16413. ["Record DONE time"
  16414. (progn (setq org-log-done (not org-log-done))
  16415. (message "Switching to %s will %s record a timestamp"
  16416. (car org-done-keywords)
  16417. (if org-log-done "automatically" "not")))
  16418. :style toggle :selected org-log-done])
  16419. "--"
  16420. ["Agenda Command..." org-agenda t]
  16421. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16422. ("File List for Agenda")
  16423. ("Special views current file"
  16424. ["TODO Tree" org-show-todo-tree t]
  16425. ["Check Deadlines" org-check-deadlines t]
  16426. ["Tags/Property tree" org-match-sparse-tree t])
  16427. "--"
  16428. ["Export/Publish..." org-export-dispatch t]
  16429. ("LaTeX"
  16430. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16431. :style toggle :selected org-cdlatex-mode]
  16432. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16433. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16434. ["Modify math symbol" org-cdlatex-math-modify
  16435. (org-inside-LaTeX-fragment-p)]
  16436. ["Insert citation" org-reftex-citation t])
  16437. "--"
  16438. ("Documentation"
  16439. ["Show Version" org-version t]
  16440. ["Info Documentation" org-info t]
  16441. ["Browse Org News" org-browse-news t])
  16442. ("Customize"
  16443. ["Browse Org Group" org-customize t]
  16444. "--"
  16445. ["Expand This Menu" org-create-customize-menu t])
  16446. ["Send bug report" org-submit-bug-report t]
  16447. "--"
  16448. ("Refresh/Reload"
  16449. ["Refresh setup current buffer" org-mode-restart t]
  16450. ["Reload Org (after update)" org-reload t]
  16451. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16452. (easy-menu-define org-tbl-menu org-mode-map "Org Table menu."
  16453. '("Table"
  16454. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16455. ["Next Field" org-cycle (org-at-table-p)]
  16456. ["Previous Field" org-shifttab (org-at-table-p)]
  16457. ["Next Row" org-return (org-at-table-p)]
  16458. "--"
  16459. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16460. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16461. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16462. "--"
  16463. ("Column"
  16464. ["Move Column Left" org-metaleft (org-at-table-p)]
  16465. ["Move Column Right" org-metaright (org-at-table-p)]
  16466. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16467. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16468. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16469. ("Row"
  16470. ["Move Row Up" org-metaup (org-at-table-p)]
  16471. ["Move Row Down" org-metadown (org-at-table-p)]
  16472. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16473. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16474. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16475. "--"
  16476. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16477. ("Rectangle"
  16478. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16479. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16480. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16481. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16482. "--"
  16483. ("Calculate"
  16484. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16485. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16486. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16487. "--"
  16488. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16489. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16490. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16491. "--"
  16492. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16493. "--"
  16494. ["Sum Column/Rectangle" org-table-sum
  16495. (or (org-at-table-p) (org-region-active-p))]
  16496. ["Which Column?" org-table-current-column (org-at-table-p)])
  16497. ["Debug Formulas"
  16498. org-table-toggle-formula-debugger
  16499. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16500. ["Show Col/Row Numbers"
  16501. org-table-toggle-coordinate-overlays
  16502. :style toggle
  16503. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16504. "--"
  16505. ["Create" org-table-create (not (org-at-table-p))]
  16506. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16507. ["Import from File" org-table-import (not (org-at-table-p))]
  16508. ["Export to File" org-table-export (org-at-table-p)]
  16509. "--"
  16510. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16511. "--"
  16512. ("Plot"
  16513. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16514. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16515. (defun org-info (&optional node)
  16516. "Read documentation for Org in the info system.
  16517. With optional NODE, go directly to that node."
  16518. (interactive)
  16519. (info (format "(org)%s" (or node ""))))
  16520. (defun org-browse-news ()
  16521. "Browse the news for the latest major release."
  16522. (interactive)
  16523. (browse-url "https://orgmode.org/Changes.html"))
  16524. ;;;###autoload
  16525. (defun org-submit-bug-report ()
  16526. "Submit a bug report on Org via mail.
  16527. Don't hesitate to report any problems or inaccurate documentation.
  16528. If you don't have setup sending mail from (X)Emacs, please copy the
  16529. output buffer into your mail program, as it gives us important
  16530. information about your Org version and configuration."
  16531. (interactive)
  16532. (require 'reporter)
  16533. (defvar reporter-prompt-for-summary-p)
  16534. (org-load-modules-maybe)
  16535. (org-require-autoloaded-modules)
  16536. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  16537. (reporter-submit-bug-report
  16538. "emacs-orgmode@gnu.org"
  16539. (org-version nil 'full)
  16540. (let (list)
  16541. (save-window-excursion
  16542. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  16543. (delete-other-windows)
  16544. (erase-buffer)
  16545. (insert "You are about to submit a bug report to the Org mailing list.
  16546. If your report is about Org installation, please read this section:
  16547. https://orgmode.org/org.html#Installation
  16548. Please read https://orgmode.org/org.html#Feedback on how to make
  16549. a good report, it will help Org contributors fixing your problem.
  16550. Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  16551. if the issue you are about to raise has already been dealt with.
  16552. We also would like to add your full Org and Outline configuration
  16553. to the bug report. It will help us debugging the issue.
  16554. *HOWEVER*, some variables you have customized may contain private
  16555. information. The names of customers, colleagues, or friends, might
  16556. appear in the form of file names, tags, todo states or search strings.
  16557. If you answer \"yes\" to the prompt, you might want to check and remove
  16558. such private information before sending the email.")
  16559. (add-text-properties (point-min) (point-max) '(face org-warning))
  16560. (when (yes-or-no-p "Include your Org configuration ")
  16561. (mapatoms
  16562. (lambda (v)
  16563. (and (boundp v)
  16564. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  16565. (or (and (symbol-value v)
  16566. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  16567. (and
  16568. (get v 'custom-type) (get v 'standard-value)
  16569. (not (equal (symbol-value v)
  16570. (eval (car (get v 'standard-value)) t)))))
  16571. (push v list)))))
  16572. (kill-buffer (get-buffer "*Warn about privacy*"))
  16573. list))
  16574. nil nil
  16575. "Remember to cover the basics, that is, what you expected to happen and
  16576. what in fact did happen. You don't know how to make a good report? See
  16577. https://orgmode.org/manual/Feedback.html#Feedback
  16578. Your bug report will be posted to the Org mailing list.
  16579. ------------------------------------------------------------------------")
  16580. (save-excursion
  16581. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  16582. (replace-match "\\1[BUG] \\3 [\\2]")))))
  16583. (defvar org-agenda-file-menu-enabled t
  16584. "When non-nil, refresh Agenda files in Org menu when loading Org.")
  16585. (defun org-install-agenda-files-menu ()
  16586. "Install agenda file menu."
  16587. (let ((bl (buffer-list)))
  16588. (save-excursion
  16589. (while bl
  16590. (set-buffer (pop bl))
  16591. (when (derived-mode-p 'org-mode) (setq bl nil)))
  16592. (when (derived-mode-p 'org-mode)
  16593. (easy-menu-change
  16594. '("Org") "File List for Agenda"
  16595. (append
  16596. (list
  16597. ["Edit File List" (org-edit-agenda-file-list) t]
  16598. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  16599. ["Remove Current File from List" org-remove-file t]
  16600. ["Cycle through agenda files" org-cycle-agenda-files t]
  16601. ["Occur in all agenda files" org-occur-in-agenda-files t]
  16602. "--")
  16603. (mapcar 'org-file-menu-entry
  16604. ;; Prevent initialization from failing.
  16605. (ignore-errors (org-agenda-files t)))))))))
  16606. ;;;; Documentation
  16607. (defun org-require-autoloaded-modules ()
  16608. (interactive)
  16609. (mapc #'require
  16610. '(org-agenda org-archive org-attach org-clock org-colview org-id
  16611. org-table org-timer)))
  16612. ;;;###autoload
  16613. (defun org-reload (&optional uncompiled)
  16614. "Reload all Org Lisp files.
  16615. With prefix arg UNCOMPILED, load the uncompiled versions."
  16616. (interactive "P")
  16617. (require 'loadhist)
  16618. (let* ((org-dir (org-find-library-dir "org"))
  16619. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  16620. (feature-re "^\\(org\\|ob\\|ox\\|ol\\|oc\\)\\(-.*\\)?")
  16621. (remove-re (format "\\`%s\\'"
  16622. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  16623. (feats (delete-dups
  16624. (mapcar 'file-name-sans-extension
  16625. (mapcar 'file-name-nondirectory
  16626. (delq nil
  16627. (mapcar 'feature-file
  16628. features))))))
  16629. (lfeat (append
  16630. (sort
  16631. (setq feats
  16632. (delq nil (mapcar
  16633. (lambda (f)
  16634. (if (and (string-match feature-re f)
  16635. (not (string-match remove-re f)))
  16636. f nil))
  16637. feats)))
  16638. 'string-lessp)
  16639. (list "org-version" "org")))
  16640. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  16641. load-uncore load-misses)
  16642. (setq load-misses
  16643. (delq t
  16644. (mapcar (lambda (f)
  16645. (or (org-load-noerror-mustsuffix (concat org-dir f))
  16646. (and (string= org-dir contrib-dir)
  16647. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  16648. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  16649. (push f load-uncore)
  16650. t)
  16651. f))
  16652. lfeat)))
  16653. (when load-uncore
  16654. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  16655. (if (> (length load-uncore) 1) "s were" " was")
  16656. (reverse load-uncore)))
  16657. (if load-misses
  16658. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  16659. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  16660. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  16661. ;;;###autoload
  16662. (defun org-customize ()
  16663. "Call the customize function with org as argument."
  16664. (interactive)
  16665. (org-load-modules-maybe)
  16666. (org-require-autoloaded-modules)
  16667. (customize-browse 'org))
  16668. (defun org-create-customize-menu ()
  16669. "Create a full customization menu for Org mode, insert it into the menu."
  16670. (interactive)
  16671. (org-load-modules-maybe)
  16672. (org-require-autoloaded-modules)
  16673. (easy-menu-change
  16674. '("Org") "Customize"
  16675. `(["Browse Org group" org-customize t]
  16676. "--"
  16677. ,(customize-menu-create 'org)
  16678. ["Set" Custom-set t]
  16679. ["Save" Custom-save t]
  16680. ["Reset to Current" Custom-reset-current t]
  16681. ["Reset to Saved" Custom-reset-saved t]
  16682. ["Reset to Standard Settings" Custom-reset-standard t]))
  16683. (message "\"Org\"-menu now contains full customization menu"))
  16684. ;;;; Miscellaneous stuff
  16685. ;;; Generally useful functions
  16686. (defun org-in-clocktable-p ()
  16687. "Check if the cursor is in a clocktable."
  16688. (let ((pos (point)) start)
  16689. (save-excursion
  16690. (end-of-line 1)
  16691. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  16692. (setq start (match-beginning 0))
  16693. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  16694. (>= (match-end 0) pos)
  16695. start))))
  16696. (defun org-in-verbatim-emphasis ()
  16697. (save-match-data
  16698. (and (org-in-regexp org-verbatim-re 2)
  16699. (>= (point) (match-beginning 3))
  16700. (<= (point) (match-end 4)))))
  16701. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  16702. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  16703. (if (and marker (marker-buffer marker)
  16704. (buffer-live-p (marker-buffer marker)))
  16705. (progn
  16706. (pop-to-buffer-same-window (marker-buffer marker))
  16707. (when (or (> marker (point-max)) (< marker (point-min)))
  16708. (widen))
  16709. (goto-char marker)
  16710. (org-fold-show-context 'org-goto))
  16711. (if bookmark
  16712. (bookmark-jump bookmark)
  16713. (error "Cannot find location"))))
  16714. (defun org-quote-csv-field (s)
  16715. "Quote field for inclusion in CSV material."
  16716. (if (string-match "[\",]" s)
  16717. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  16718. s))
  16719. (defun org-force-self-insert (N)
  16720. "Needed to enforce self-insert under remapping."
  16721. (interactive "p")
  16722. (self-insert-command N))
  16723. (defun org-quote-vert (s)
  16724. "Replace \"|\" with \"\\vert\"."
  16725. (while (string-match "|" s)
  16726. (setq s (replace-match "\\vert" t t s)))
  16727. s)
  16728. (defun org-uuidgen-p (s)
  16729. "Is S an ID created by UUIDGEN?"
  16730. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  16731. (defun org-in-src-block-p (&optional inside element)
  16732. "Whether point is in a code source block.
  16733. When INSIDE is non-nil, don't consider we are within a source
  16734. block when point is at #+BEGIN_SRC or #+END_SRC.
  16735. When ELEMENT is provided, it is considered to be element at point."
  16736. (save-match-data (setq element (or element (org-element-at-point))))
  16737. (when (eq 'src-block (org-element-type element))
  16738. (or (not inside)
  16739. (not (or (= (line-beginning-position)
  16740. (org-element-property :post-affiliated element))
  16741. (= (1+ (line-end-position))
  16742. (- (org-element-property :end element)
  16743. (org-element-property :post-blank element))))))))
  16744. (defun org-context ()
  16745. "Return a list of contexts of the current cursor position.
  16746. If several contexts apply, all are returned.
  16747. Each context entry is a list with a symbol naming the context, and
  16748. two positions indicating start and end of the context. Possible
  16749. contexts are:
  16750. :headline anywhere in a headline
  16751. :headline-stars on the leading stars in a headline
  16752. :todo-keyword on a TODO keyword (including DONE) in a headline
  16753. :tags on the TAGS in a headline
  16754. :priority on the priority cookie in a headline
  16755. :item on the first line of a plain list item
  16756. :item-bullet on the bullet/number of a plain list item
  16757. :checkbox on the checkbox in a plain list item
  16758. :table in an Org table
  16759. :table-special on a special filed in a table
  16760. :table-table in a table.el table
  16761. :clocktable in a clocktable
  16762. :src-block in a source block
  16763. :link on a hyperlink
  16764. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  16765. :latex-fragment on a LaTeX fragment
  16766. :latex-preview on a LaTeX fragment with overlaid preview image
  16767. This function expects the position to be visible because it uses font-lock
  16768. faces as a help to recognize the following contexts: :table-special, :link,
  16769. and :keyword."
  16770. (let* ((f (get-text-property (point) 'face))
  16771. (faces (if (listp f) f (list f)))
  16772. (case-fold-search t)
  16773. (p (point)) clist o)
  16774. ;; First the large context
  16775. (cond
  16776. ((org-at-heading-p)
  16777. (push (list :headline (line-beginning-position) (line-end-position)) clist)
  16778. (when (progn
  16779. (beginning-of-line 1)
  16780. (looking-at org-todo-line-tags-regexp))
  16781. (push (org-point-in-group p 1 :headline-stars) clist)
  16782. (push (org-point-in-group p 2 :todo-keyword) clist)
  16783. (push (org-point-in-group p 4 :tags) clist))
  16784. (goto-char p)
  16785. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  16786. (when (looking-at "\\[#[A-Z0-9]\\]")
  16787. (push (org-point-in-group p 0 :priority) clist)))
  16788. ((org-at-item-p)
  16789. (push (org-point-in-group p 2 :item-bullet) clist)
  16790. (push (list :item (line-beginning-position)
  16791. (save-excursion (org-end-of-item) (point)))
  16792. clist)
  16793. (and (org-at-item-checkbox-p)
  16794. (push (org-point-in-group p 0 :checkbox) clist)))
  16795. ((org-at-table-p)
  16796. (push (list :table (org-table-begin) (org-table-end)) clist)
  16797. (when (memq 'org-formula faces)
  16798. (push (list :table-special
  16799. (previous-single-property-change p 'face)
  16800. (next-single-property-change p 'face))
  16801. clist)))
  16802. ((org-at-table-p 'any)
  16803. (push (list :table-table) clist)))
  16804. (goto-char p)
  16805. (let ((case-fold-search t))
  16806. ;; New the "medium" contexts: clocktables, source blocks
  16807. (cond ((org-in-clocktable-p)
  16808. (push (list :clocktable
  16809. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  16810. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  16811. (match-beginning 1))
  16812. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  16813. (match-end 0)))
  16814. clist))
  16815. ((org-in-src-block-p)
  16816. (push (list :src-block
  16817. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  16818. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  16819. (match-beginning 1))
  16820. (and (search-forward "#+END_SRC" nil t)
  16821. (match-beginning 0)))
  16822. clist))))
  16823. (goto-char p)
  16824. ;; Now the small context
  16825. (cond
  16826. ((org-at-timestamp-p)
  16827. (push (org-point-in-group p 0 :timestamp) clist))
  16828. ((memq 'org-link faces)
  16829. (push (list :link
  16830. (previous-single-property-change p 'face)
  16831. (next-single-property-change p 'face))
  16832. clist))
  16833. ((memq 'org-special-keyword faces)
  16834. (push (list :keyword
  16835. (previous-single-property-change p 'face)
  16836. (next-single-property-change p 'face))
  16837. clist))
  16838. ((setq o (cl-some
  16839. (lambda (o)
  16840. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  16841. o))
  16842. (overlays-at (point))))
  16843. (push (list :latex-fragment
  16844. (overlay-start o) (overlay-end o))
  16845. clist)
  16846. (push (list :latex-preview
  16847. (overlay-start o) (overlay-end o))
  16848. clist))
  16849. ((org-inside-LaTeX-fragment-p)
  16850. ;; FIXME: positions wrong.
  16851. (push (list :latex-fragment (point) (point)) clist)))
  16852. (setq clist (nreverse (delq nil clist)))
  16853. clist))
  16854. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  16855. "Non-nil when point is between matches of START-RE and END-RE.
  16856. Also return a non-nil value when point is on one of the matches.
  16857. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  16858. buffer positions. Default values are the positions of headlines
  16859. surrounding the point.
  16860. The functions returns a cons cell whose car (resp. cdr) is the
  16861. position before START-RE (resp. after END-RE)."
  16862. (save-match-data
  16863. (let ((pos (point))
  16864. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  16865. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  16866. beg end)
  16867. (save-excursion
  16868. ;; Point is on a block when on START-RE or if START-RE can be
  16869. ;; found before it...
  16870. (and (or (org-in-regexp start-re)
  16871. (re-search-backward start-re limit-up t))
  16872. (setq beg (match-beginning 0))
  16873. ;; ... and END-RE after it...
  16874. (goto-char (match-end 0))
  16875. (re-search-forward end-re limit-down t)
  16876. (> (setq end (match-end 0)) pos)
  16877. ;; ... without another START-RE in-between.
  16878. (goto-char (match-beginning 0))
  16879. (not (re-search-backward start-re (1+ beg) t))
  16880. ;; Return value.
  16881. (cons beg end))))))
  16882. (defun org-in-block-p (names)
  16883. "Non-nil when point belongs to a block whose name belongs to NAMES.
  16884. NAMES is a list of strings containing names of blocks.
  16885. Return first block name matched, or nil. Beware that in case of
  16886. nested blocks, the returned name may not belong to the closest
  16887. block from point."
  16888. (save-match-data
  16889. (catch 'exit
  16890. (let ((case-fold-search t)
  16891. (lim-up (save-excursion (outline-previous-heading)))
  16892. (lim-down (save-excursion (outline-next-heading))))
  16893. (dolist (name names)
  16894. (let ((n (regexp-quote name)))
  16895. (when (org-between-regexps-p
  16896. (concat "^[ \t]*#\\+begin_" n)
  16897. (concat "^[ \t]*#\\+end_" n)
  16898. lim-up lim-down)
  16899. (throw 'exit n)))))
  16900. nil)))
  16901. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  16902. "Call `multi-occur' with buffers for all agenda files."
  16903. (interactive "sOrg-files matching: ")
  16904. (let* ((files (org-agenda-files))
  16905. (tnames (mapcar #'file-truename files))
  16906. (extra org-agenda-text-search-extra-files))
  16907. (when (eq (car extra) 'agenda-archives)
  16908. (setq extra (cdr extra))
  16909. (setq files (org-add-archive-files files)))
  16910. (dolist (f extra)
  16911. (unless (member (file-truename f) tnames)
  16912. (unless (member f files) (setq files (append files (list f))))
  16913. (setq tnames (append tnames (list (file-truename f))))))
  16914. (multi-occur
  16915. (mapcar (lambda (x)
  16916. (with-current-buffer
  16917. ;; FIXME: Why not just (find-file-noselect x)?
  16918. ;; Is it to avoid the "revert buffer" prompt?
  16919. (or (get-file-buffer x) (find-file-noselect x))
  16920. (widen)
  16921. (current-buffer)))
  16922. files)
  16923. regexp)))
  16924. (add-hook 'occur-mode-find-occurrence-hook
  16925. (lambda () (when (derived-mode-p 'org-mode) (org-fold-reveal))))
  16926. (defun org-occur-link-in-agenda-files ()
  16927. "Create a link and search for it in the agendas.
  16928. The link is not stored in `org-stored-links', it is just created
  16929. for the search purpose."
  16930. (interactive)
  16931. (let ((link (condition-case nil
  16932. (org-store-link nil)
  16933. (error "Unable to create a link to here"))))
  16934. (org-occur-in-agenda-files (regexp-quote link))))
  16935. (defun org-back-over-empty-lines ()
  16936. "Move backwards over whitespace, to the beginning of the first empty line.
  16937. Returns the number of empty lines passed."
  16938. (let ((pos (point)))
  16939. (if (cdr (assq 'heading org-blank-before-new-entry))
  16940. (skip-chars-backward " \t\n\r")
  16941. (unless (eobp)
  16942. (forward-line -1)))
  16943. (beginning-of-line 2)
  16944. (goto-char (min (point) pos))
  16945. (count-lines (point) pos)))
  16946. ;;; TODO: Only called once, from ox-odt which should probably use
  16947. ;;; org-export-inline-image-p or something.
  16948. (defun org-file-image-p (file)
  16949. "Return non-nil if FILE is an image."
  16950. (save-match-data
  16951. (string-match (image-file-name-regexp) file)))
  16952. (defun org-get-cursor-date (&optional with-time)
  16953. "Return the date at cursor in as a time.
  16954. This works in the calendar and in the agenda, anywhere else it just
  16955. returns the current time.
  16956. If WITH-TIME is non-nil, returns the time of the event at point (in
  16957. the agenda) or the current time of the day; otherwise returns the
  16958. earliest time on the cursor date that Org treats as that date
  16959. (bearing in mind `org-extend-today-until')."
  16960. (let (date day defd tp hod mod)
  16961. (when with-time
  16962. (setq tp (get-text-property (point) 'time))
  16963. (when (and tp (string-match "\\([0-2]?[0-9]\\):\\([0-5][0-9]\\)" tp))
  16964. (setq hod (string-to-number (match-string 1 tp))
  16965. mod (string-to-number (match-string 2 tp))))
  16966. (or tp (let ((now (decode-time)))
  16967. (setq hod (nth 2 now)
  16968. mod (nth 1 now)))))
  16969. (cond
  16970. ((eq major-mode 'calendar-mode)
  16971. (setq date (calendar-cursor-to-date)
  16972. defd (org-encode-time 0 (or mod 0) (or hod org-extend-today-until)
  16973. (nth 1 date) (nth 0 date) (nth 2 date))))
  16974. ((eq major-mode 'org-agenda-mode)
  16975. (setq day (get-text-property (point) 'day))
  16976. (when day
  16977. (setq date (calendar-gregorian-from-absolute day)
  16978. defd (org-encode-time 0 (or mod 0) (or hod org-extend-today-until)
  16979. (nth 1 date) (nth 0 date) (nth 2 date))))))
  16980. (or defd (current-time))))
  16981. (defun org-mark-subtree (&optional up)
  16982. "Mark the current subtree.
  16983. This puts point at the start of the current subtree, and mark at
  16984. the end. If a numeric prefix UP is given, move up into the
  16985. hierarchy of headlines by UP levels before marking the subtree."
  16986. (interactive "P")
  16987. (org-with-limited-levels
  16988. (cond ((org-at-heading-p) (beginning-of-line))
  16989. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  16990. (t (outline-previous-visible-heading 1))))
  16991. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  16992. (if (called-interactively-p 'any)
  16993. (call-interactively 'org-mark-element)
  16994. (org-mark-element)))
  16995. ;;; Indentation
  16996. (defvar org-element-greater-elements)
  16997. (defun org--get-expected-indentation (element contentsp)
  16998. "Expected indentation column for current line, according to ELEMENT.
  16999. ELEMENT is an element containing point. CONTENTSP is non-nil
  17000. when indentation is to be computed according to contents of
  17001. ELEMENT."
  17002. (let ((type (org-element-type element))
  17003. (start (org-element-property :begin element))
  17004. (post-affiliated (org-element-property :post-affiliated element)))
  17005. (org-with-wide-buffer
  17006. (cond
  17007. (contentsp
  17008. (cl-case type
  17009. ((diary-sexp footnote-definition) 0)
  17010. (section
  17011. (org--get-expected-indentation
  17012. (org-element-property :parent element)
  17013. t))
  17014. ((headline inlinetask nil)
  17015. (if (not org-adapt-indentation) 0
  17016. (let ((level (org-current-level)))
  17017. (if level (1+ level) 0))))
  17018. ((item plain-list) (org-list-item-body-column post-affiliated))
  17019. (t
  17020. (goto-char start)
  17021. (current-indentation))))
  17022. ((memq type '(headline inlinetask nil))
  17023. (if (org-match-line "[ \t]*$")
  17024. (org--get-expected-indentation element t)
  17025. 0))
  17026. ((memq type '(diary-sexp footnote-definition)) 0)
  17027. ;; First paragraph of a footnote definition or an item.
  17028. ;; Indent like parent.
  17029. ((< (line-beginning-position) start)
  17030. (org--get-expected-indentation
  17031. (org-element-property :parent element) t))
  17032. ;; At first line: indent according to previous sibling, if any,
  17033. ;; ignoring footnote definitions and inline tasks, or parent's
  17034. ;; contents. If `org-adapt-indentation' is `headline-data', ignore
  17035. ;; previous headline data siblings.
  17036. ((= (line-beginning-position) start)
  17037. (catch 'exit
  17038. (while t
  17039. (if (= (point-min) start) (throw 'exit 0)
  17040. (goto-char (1- start))
  17041. (let* ((previous (org-element-at-point))
  17042. (parent previous))
  17043. (while (and parent (<= (org-element-property :end parent) start))
  17044. (setq previous parent
  17045. parent (org-element-property :parent parent)))
  17046. (cond
  17047. ((not previous) (throw 'exit 0))
  17048. ((> (org-element-property :end previous) start)
  17049. (throw 'exit (org--get-expected-indentation previous t)))
  17050. ((memq (org-element-type previous)
  17051. '(footnote-definition inlinetask))
  17052. (setq start (org-element-property :begin previous)))
  17053. ;; Do not indent like previous when the previous
  17054. ;; element is headline data and `org-adapt-indentation'
  17055. ;; is set to `headline-data'.
  17056. ((save-excursion
  17057. (goto-char start)
  17058. (and
  17059. (eq org-adapt-indentation 'headline-data)
  17060. (not (or (org-at-clock-log-p)
  17061. (org-at-planning-p)))
  17062. (progn
  17063. (beginning-of-line 1)
  17064. (skip-chars-backward "\n")
  17065. (or (org-at-heading-p)
  17066. (looking-back ":END:.*" (line-beginning-position))))))
  17067. (throw 'exit 0))
  17068. (t (goto-char (org-element-property :begin previous))
  17069. (throw 'exit
  17070. (if (bolp) (current-indentation)
  17071. ;; At first paragraph in an item or
  17072. ;; a footnote definition.
  17073. (org--get-expected-indentation
  17074. (org-element-property :parent previous) t))))))))))
  17075. ;; Otherwise, move to the first non-blank line above.
  17076. (t
  17077. (beginning-of-line)
  17078. (let ((pos (point)))
  17079. (skip-chars-backward " \r\t\n")
  17080. (cond
  17081. ;; Two blank lines end a footnote definition or a plain
  17082. ;; list. When we indent an empty line after them, the
  17083. ;; containing list or footnote definition is over, so it
  17084. ;; qualifies as a previous sibling. Therefore, we indent
  17085. ;; like its first line.
  17086. ((and (memq type '(footnote-definition plain-list))
  17087. (> (count-lines (point) pos) 2))
  17088. (goto-char start)
  17089. (current-indentation))
  17090. ;; Line above is the first one of a paragraph at the
  17091. ;; beginning of an item or a footnote definition. Indent
  17092. ;; like parent.
  17093. ((< (line-beginning-position) start)
  17094. (org--get-expected-indentation
  17095. (org-element-property :parent element) t))
  17096. ;; Line above is the beginning of an element, i.e., point
  17097. ;; was originally on the blank lines between element's start
  17098. ;; and contents.
  17099. ((= (line-beginning-position) post-affiliated)
  17100. (org--get-expected-indentation element t))
  17101. ;; POS is after contents in a greater element. Indent like
  17102. ;; the beginning of the element.
  17103. ((and (memq type org-element-greater-elements)
  17104. (let ((cend (org-element-property :contents-end element)))
  17105. (and cend (<= cend pos))))
  17106. ;; As a special case, if point is at the end of a footnote
  17107. ;; definition or an item, indent like the very last element
  17108. ;; within. If that last element is an item, indent like
  17109. ;; its contents.
  17110. (if (memq type '(footnote-definition item plain-list))
  17111. (let ((last (org-element-at-point)))
  17112. (goto-char pos)
  17113. (org--get-expected-indentation
  17114. last (eq (org-element-type last) 'item)))
  17115. (goto-char start)
  17116. (current-indentation)))
  17117. ;; In any other case, indent like the current line.
  17118. (t (current-indentation)))))
  17119. ;; Finally, no indentation is needed, fall back to 0.
  17120. (t (current-indentation))))))
  17121. (defun org--align-node-property ()
  17122. "Align node property at point.
  17123. Alignment is done according to `org-property-format', which see."
  17124. (when (save-excursion
  17125. (beginning-of-line)
  17126. (looking-at org-property-re))
  17127. (combine-change-calls (match-beginning 0) (match-end 0)
  17128. (let ((newtext (concat (match-string 4)
  17129. (org-trim
  17130. (format org-property-format (match-string 1) (match-string 3))))))
  17131. ;; Do not use `replace-match' here as we want to inherit folding
  17132. ;; properties if inside fold.
  17133. (delete-region (match-beginning 0) (match-end 0))
  17134. (insert-and-inherit newtext)))))
  17135. (defun org-indent-line ()
  17136. "Indent line depending on context.
  17137. Indentation is done according to the following rules:
  17138. - Footnote definitions, diary sexps, headlines and inline tasks
  17139. have to start at column 0.
  17140. - On the very first line of an element, consider, in order, the
  17141. next rules until one matches:
  17142. 1. If there's a sibling element before, ignoring footnote
  17143. definitions and inline tasks, indent like its first line.
  17144. 2. If element has a parent, indent like its contents. More
  17145. precisely, if parent is an item, indent after the bullet.
  17146. Else, indent like parent's first line.
  17147. 3. Otherwise, indent relatively to current level, if
  17148. `org-adapt-indentation' is t, or to left margin.
  17149. - On a blank line at the end of an element, indent according to
  17150. the type of the element. More precisely
  17151. 1. If element is a plain list, an item, or a footnote
  17152. definition, indent like the very last element within.
  17153. 2. If element is a paragraph, indent like its last non blank
  17154. line.
  17155. 3. Otherwise, indent like its very first line.
  17156. - In the code part of a source block, use language major mode
  17157. to indent current line if `org-src-tab-acts-natively' is
  17158. non-nil. If it is nil, do nothing.
  17159. - Otherwise, indent like the first non-blank line above.
  17160. The function doesn't indent an item as it could break the whole
  17161. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17162. `\\[org-shiftmetaright]'.
  17163. Also align node properties according to `org-property-format'."
  17164. (interactive)
  17165. (unless (or (org-at-heading-p)
  17166. (and (eq org-adapt-indentation 'headline-data)
  17167. (not (or (org-at-clock-log-p)
  17168. (org-at-planning-p)))
  17169. (save-excursion
  17170. (beginning-of-line 1)
  17171. (skip-chars-backward "\n")
  17172. (or (org-at-heading-p)
  17173. (looking-back ":END:.*" (line-beginning-position))))))
  17174. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point-no-context)))
  17175. (type (org-element-type element)))
  17176. (cond ((and (memq type '(plain-list item))
  17177. (= (line-beginning-position)
  17178. (org-element-property :post-affiliated element)))
  17179. nil)
  17180. ((and (eq type 'latex-environment)
  17181. (>= (point) (org-element-property :post-affiliated element))
  17182. (< (point)
  17183. (org-with-point-at (org-element-property :end element)
  17184. (skip-chars-backward " \t\n")
  17185. (line-beginning-position 2))))
  17186. nil)
  17187. ((and (eq type 'src-block)
  17188. org-src-tab-acts-natively
  17189. (> (line-beginning-position)
  17190. (org-element-property :post-affiliated element))
  17191. (< (line-beginning-position)
  17192. (org-with-point-at (org-element-property :end element)
  17193. (skip-chars-backward " \t\n")
  17194. (line-beginning-position))))
  17195. ;; At the beginning of a blank line, do some preindentation. This
  17196. ;; signals org-src--edit-element to preserve the indentation on exit
  17197. (when (and (looking-at-p "^[[:space:]]*$")
  17198. (not org-src-preserve-indentation))
  17199. (let ((element (org-element-at-point))
  17200. block-content-ind some-ind)
  17201. (org-with-point-at (org-element-property :begin element)
  17202. (setq block-content-ind (+ (current-indentation)
  17203. org-edit-src-content-indentation))
  17204. (forward-line)
  17205. (save-match-data (re-search-forward "^[ \t]*\\S-" nil t))
  17206. (backward-char)
  17207. (setq some-ind (if (looking-at-p "#\\+end_src")
  17208. block-content-ind (current-indentation))))
  17209. (indent-line-to (min block-content-ind some-ind))))
  17210. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17211. (t
  17212. (let ((column (org--get-expected-indentation element nil)))
  17213. ;; Preserve current column.
  17214. (if (<= (current-column) (current-indentation))
  17215. (indent-line-to column)
  17216. (save-excursion (indent-line-to column))))
  17217. ;; Align node property. Also preserve current column.
  17218. (when (eq type 'node-property)
  17219. (let ((column (current-column)))
  17220. (org--align-node-property)
  17221. (org-move-to-column column))))))))
  17222. (defun org-indent-region (start end)
  17223. "Indent each non-blank line in the region.
  17224. Called from a program, START and END specify the region to
  17225. indent. The function will not indent contents of example blocks,
  17226. verse blocks and export blocks as leading white spaces are
  17227. assumed to be significant there."
  17228. (interactive "r")
  17229. (save-excursion
  17230. (goto-char start)
  17231. (skip-chars-forward " \r\t\n")
  17232. (unless (eobp) (beginning-of-line))
  17233. (let ((indent-to
  17234. (lambda (ind pos)
  17235. ;; Set IND as indentation for all lines between point and
  17236. ;; POS. Blank lines are ignored. Leave point after POS
  17237. ;; once done.
  17238. (let ((limit (copy-marker pos)))
  17239. (while (< (point) limit)
  17240. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17241. (forward-line))
  17242. (set-marker limit nil))))
  17243. (end (copy-marker end)))
  17244. (while (< (point) end)
  17245. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17246. (let* ((element (org-element-at-point))
  17247. (type (org-element-type element))
  17248. (element-end (copy-marker (org-element-property :end element)))
  17249. (ind (org--get-expected-indentation element nil)))
  17250. (cond
  17251. ;; Element indented as a single block. Example blocks
  17252. ;; preserving indentation are a special case since the
  17253. ;; "contents" must not be indented whereas the block
  17254. ;; boundaries can.
  17255. ((or (memq type '(export-block latex-environment))
  17256. (and (eq type 'example-block)
  17257. (not
  17258. (or org-src-preserve-indentation
  17259. (org-element-property :preserve-indent element)))))
  17260. (let ((offset (- ind (current-indentation))))
  17261. (unless (zerop offset)
  17262. (indent-rigidly (org-element-property :begin element)
  17263. (org-element-property :end element)
  17264. offset)))
  17265. (goto-char element-end))
  17266. ;; Elements indented line wise. Be sure to exclude
  17267. ;; example blocks (preserving indentation) and source
  17268. ;; blocks from this category as they are treated
  17269. ;; specially later.
  17270. ((or (memq type '(paragraph table table-row))
  17271. (not (or (org-element-property :contents-begin element)
  17272. (memq type '(example-block src-block)))))
  17273. (when (eq type 'node-property)
  17274. (org--align-node-property)
  17275. (beginning-of-line))
  17276. (funcall indent-to ind (min element-end end)))
  17277. ;; Elements consisting of three parts: before the
  17278. ;; contents, the contents, and after the contents. The
  17279. ;; contents are treated specially, according to the
  17280. ;; element type, or not indented at all. Other parts are
  17281. ;; indented as a single block.
  17282. (t
  17283. (let* ((post (copy-marker
  17284. (org-element-property :post-affiliated element)))
  17285. (cbeg
  17286. (copy-marker
  17287. (cond
  17288. ((not (org-element-property :contents-begin element))
  17289. ;; Fake contents for source blocks.
  17290. (org-with-wide-buffer
  17291. (goto-char post)
  17292. (line-beginning-position 2)))
  17293. ((memq type '(footnote-definition item plain-list))
  17294. ;; Contents in these elements could start on
  17295. ;; the same line as the beginning of the
  17296. ;; element. Make sure we start indenting
  17297. ;; from the second line.
  17298. (org-with-wide-buffer
  17299. (goto-char post)
  17300. (end-of-line)
  17301. (skip-chars-forward " \r\t\n")
  17302. (if (eobp) (point) (line-beginning-position))))
  17303. (t (org-element-property :contents-begin element)))))
  17304. (cend (copy-marker
  17305. (or (org-element-property :contents-end element)
  17306. ;; Fake contents for source blocks.
  17307. (org-with-wide-buffer
  17308. (goto-char element-end)
  17309. (skip-chars-backward " \r\t\n")
  17310. (line-beginning-position)))
  17311. t)))
  17312. ;; Do not change items indentation individually as it
  17313. ;; might break the list as a whole. On the other
  17314. ;; hand, when at a plain list, indent it as a whole.
  17315. (cond ((eq type 'plain-list)
  17316. (let ((offset (- ind (current-indentation))))
  17317. (unless (zerop offset)
  17318. (indent-rigidly (org-element-property :begin element)
  17319. (org-element-property :end element)
  17320. offset))
  17321. (goto-char cbeg)))
  17322. ((eq type 'item) (goto-char cbeg))
  17323. (t (funcall indent-to ind (min cbeg end))))
  17324. (when (< (point) end)
  17325. (cl-case type
  17326. ((example-block verse-block))
  17327. (src-block
  17328. ;; In a source block, indent source code
  17329. ;; according to language major mode, but only if
  17330. ;; `org-src-tab-acts-natively' is non-nil.
  17331. (when (and (< (point) end) org-src-tab-acts-natively)
  17332. (ignore-errors
  17333. (org-babel-do-in-edit-buffer
  17334. (indent-region (point-min) (point-max))))))
  17335. (t (org-indent-region (point) (min cend end))))
  17336. (goto-char (min cend end))
  17337. (when (< (point) end)
  17338. (funcall indent-to ind (min element-end end))))
  17339. (set-marker post nil)
  17340. (set-marker cbeg nil)
  17341. (set-marker cend nil))))
  17342. (set-marker element-end nil))))
  17343. (set-marker end nil))))
  17344. (defun org-indent-drawer ()
  17345. "Indent the drawer at point."
  17346. (interactive)
  17347. (unless (save-excursion
  17348. (beginning-of-line)
  17349. (looking-at-p org-drawer-regexp))
  17350. (user-error "Not at a drawer"))
  17351. (let ((element (org-element-at-point-no-context)))
  17352. (unless (memq (org-element-type element) '(drawer property-drawer))
  17353. (user-error "Not at a drawer"))
  17354. (org-with-wide-buffer
  17355. (org-indent-region (org-element-property :begin element)
  17356. (org-element-property :end element))))
  17357. (message "Drawer at point indented"))
  17358. (defun org-indent-block ()
  17359. "Indent the block at point."
  17360. (interactive)
  17361. (unless (save-excursion
  17362. (beginning-of-line)
  17363. (let ((case-fold-search t))
  17364. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17365. (user-error "Not at a block"))
  17366. (let ((element (org-element-at-point-no-context)))
  17367. (unless (memq (org-element-type element)
  17368. '(comment-block center-block dynamic-block example-block
  17369. export-block quote-block special-block
  17370. src-block verse-block))
  17371. (user-error "Not at a block"))
  17372. (org-with-wide-buffer
  17373. (org-indent-region (org-element-property :begin element)
  17374. (org-element-property :end element))))
  17375. (message "Block at point indented"))
  17376. ;;; Filling
  17377. ;; We use our own fill-paragraph and auto-fill functions.
  17378. ;; `org-fill-paragraph' relies on adaptive filling and context
  17379. ;; checking. Appropriate `fill-prefix' is computed with
  17380. ;; `org-adaptive-fill-function'.
  17381. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17382. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17383. ;; `org-adaptive-fill-function' value. Internally,
  17384. ;; `org-comment-line-break-function' breaks the line.
  17385. ;; `org-setup-filling' installs filling and auto-filling related
  17386. ;; variables during `org-mode' initialization.
  17387. (defvar org--single-lines-list-is-paragraph) ; defined later
  17388. (defun org-setup-filling ()
  17389. (require 'org-element)
  17390. ;; Prevent auto-fill from inserting unwanted new items.
  17391. (setq-local fill-nobreak-predicate
  17392. (org-uniquify
  17393. (append fill-nobreak-predicate
  17394. '(org-fill-line-break-nobreak-p
  17395. org-fill-n-macro-as-item-nobreak-p
  17396. org-fill-paragraph-with-timestamp-nobreak-p))))
  17397. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17398. (setq-local paragraph-start paragraph-ending)
  17399. (setq-local paragraph-separate paragraph-ending))
  17400. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17401. (setq-local fill-forward-paragraph-function
  17402. (lambda (&optional arg)
  17403. (let ((org--single-lines-list-is-paragraph nil))
  17404. (org-forward-paragraph arg))))
  17405. (setq-local auto-fill-inhibit-regexp nil)
  17406. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17407. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17408. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17409. (defun org-fill-line-break-nobreak-p ()
  17410. "Non-nil when a new line at point would create an Org line break."
  17411. (save-excursion
  17412. (skip-chars-backward " \t")
  17413. (skip-chars-backward "\\\\")
  17414. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17415. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17416. "Non-nil when a new line at point would split a timestamp."
  17417. (and (org-at-timestamp-p 'lax)
  17418. (not (looking-at org-ts-regexp-both))))
  17419. (defun org-fill-n-macro-as-item-nobreak-p ()
  17420. "Non-nil when a new line at point would create a new list."
  17421. ;; During export, a "n" macro followed by a dot or a closing
  17422. ;; parenthesis can end up being parsed as a new list item.
  17423. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17424. (defun org-adaptive-fill-function ()
  17425. "Compute a fill prefix for the current line.
  17426. Return fill prefix, as a string, or nil if current line isn't
  17427. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17428. matches in paragraphs or comments, use it."
  17429. (org-with-wide-buffer
  17430. (unless (org-at-heading-p)
  17431. (let* ((p (line-beginning-position))
  17432. (element (save-excursion
  17433. (beginning-of-line)
  17434. (org-element-at-point)))
  17435. (type (org-element-type element))
  17436. (post-affiliated (org-element-property :post-affiliated element)))
  17437. (unless (< p post-affiliated)
  17438. (cl-case type
  17439. (comment
  17440. (save-excursion
  17441. (beginning-of-line)
  17442. (looking-at "[ \t]*")
  17443. (concat (match-string 0) "# ")))
  17444. (footnote-definition "")
  17445. ((item plain-list)
  17446. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17447. (paragraph
  17448. ;; Fill prefix is usually the same as the current line,
  17449. ;; unless the paragraph is at the beginning of an item.
  17450. (let ((parent (org-element-property :parent element)))
  17451. (save-excursion
  17452. (beginning-of-line)
  17453. (cond ((eq (org-element-type parent) 'item)
  17454. (make-string (org-list-item-body-column
  17455. (org-element-property :begin parent))
  17456. ?\s))
  17457. ((and adaptive-fill-regexp
  17458. ;; Locally disable
  17459. ;; `adaptive-fill-function' to let
  17460. ;; `fill-context-prefix' handle
  17461. ;; `adaptive-fill-regexp' variable.
  17462. (let (adaptive-fill-function)
  17463. (fill-context-prefix
  17464. post-affiliated
  17465. (org-element-property :end element)))))
  17466. ((looking-at "[ \t]+") (match-string 0))
  17467. (t "")))))
  17468. (comment-block
  17469. ;; Only fill contents if P is within block boundaries.
  17470. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17471. (forward-line)
  17472. (point)))
  17473. (cend (save-excursion
  17474. (goto-char (org-element-property :end element))
  17475. (skip-chars-backward " \r\t\n")
  17476. (line-beginning-position))))
  17477. (when (and (>= p cbeg) (< p cend))
  17478. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17479. (match-string 0)
  17480. ""))))))))))
  17481. (defun org-fill-element (&optional justify)
  17482. "Fill element at point, when applicable.
  17483. This function only applies to comment blocks, comments, example
  17484. blocks and paragraphs. Also, as a special case, re-align table
  17485. when point is at one.
  17486. If JUSTIFY is non-nil (interactively, with prefix argument),
  17487. justify as well. If `sentence-end-double-space' is non-nil, then
  17488. period followed by one space does not end a sentence, so don't
  17489. break a line there. The variable `fill-column' controls the
  17490. width for filling.
  17491. For convenience, when point is at a plain list, an item or
  17492. a footnote definition, try to fill the first paragraph within."
  17493. (with-syntax-table org-mode-transpose-word-syntax-table
  17494. ;; Move to end of line in order to get the first paragraph within
  17495. ;; a plain list or a footnote definition.
  17496. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17497. ;; First check if point is in a blank line at the beginning of
  17498. ;; the buffer. In that case, ignore filling.
  17499. (cl-case (org-element-type element)
  17500. ;; Use major mode filling function is source blocks.
  17501. (src-block (org-babel-do-in-edit-buffer
  17502. (push-mark (point-min))
  17503. (goto-char (point-max))
  17504. (setq mark-active t)
  17505. (funcall-interactively #'fill-paragraph justify 'region)))
  17506. ;; Align Org tables, leave table.el tables as-is.
  17507. (table-row (org-table-align) t)
  17508. (table
  17509. (when (eq (org-element-property :type element) 'org)
  17510. (save-excursion
  17511. (goto-char (org-element-property :post-affiliated element))
  17512. (org-table-align)))
  17513. t)
  17514. (paragraph
  17515. ;; Paragraphs may contain `line-break' type objects.
  17516. (let ((beg (max (point-min)
  17517. (org-element-property :contents-begin element)))
  17518. (end (min (point-max)
  17519. (org-element-property :contents-end element))))
  17520. ;; Do nothing if point is at an affiliated keyword.
  17521. (if (< (line-end-position) beg) t
  17522. ;; Fill paragraph, taking line breaks into account.
  17523. (save-excursion
  17524. (goto-char beg)
  17525. (let ((cuts (list beg)))
  17526. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17527. (when (eq 'line-break
  17528. (org-element-type
  17529. (save-excursion (backward-char)
  17530. (org-element-context))))
  17531. (push (point) cuts)))
  17532. (dolist (c (delq end cuts))
  17533. (fill-region-as-paragraph c end justify)
  17534. (setq end c))))
  17535. t)))
  17536. ;; Contents of `comment-block' type elements should be
  17537. ;; filled as plain text, but only if point is within block
  17538. ;; markers.
  17539. (comment-block
  17540. (let* ((case-fold-search t)
  17541. (beg (save-excursion
  17542. (goto-char (org-element-property :begin element))
  17543. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17544. (forward-line)
  17545. (point)))
  17546. (end (save-excursion
  17547. (goto-char (org-element-property :end element))
  17548. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17549. (line-beginning-position))))
  17550. (if (or (< (point) beg) (> (point) end)) t
  17551. (fill-region-as-paragraph
  17552. (save-excursion (end-of-line)
  17553. (re-search-backward "^[ \t]*$" beg 'move)
  17554. (line-beginning-position))
  17555. (save-excursion (beginning-of-line)
  17556. (re-search-forward "^[ \t]*$" end 'move)
  17557. (line-beginning-position))
  17558. justify))))
  17559. ;; Fill comments.
  17560. (comment
  17561. (let ((begin (org-element-property :post-affiliated element))
  17562. (end (org-element-property :end element)))
  17563. (when (and (>= (point) begin) (<= (point) end))
  17564. (let ((begin (save-excursion
  17565. (end-of-line)
  17566. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17567. (progn (forward-line) (point))
  17568. begin)))
  17569. (end (save-excursion
  17570. (end-of-line)
  17571. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17572. (1- (line-beginning-position))
  17573. (skip-chars-backward " \r\t\n")
  17574. (line-end-position)))))
  17575. ;; Do not fill comments when at a blank line.
  17576. (when (> end begin)
  17577. (let ((fill-prefix
  17578. (save-excursion
  17579. (beginning-of-line)
  17580. (looking-at "[ \t]*#")
  17581. (let ((comment-prefix (match-string 0)))
  17582. (goto-char (match-end 0))
  17583. (if (looking-at adaptive-fill-regexp)
  17584. (concat comment-prefix (match-string 0))
  17585. (concat comment-prefix " "))))))
  17586. (save-excursion
  17587. (fill-region-as-paragraph begin end justify))))))
  17588. t))
  17589. ;; Ignore every other element.
  17590. (otherwise t)))))
  17591. (defun org-fill-paragraph (&optional justify region)
  17592. "Fill element at point, when applicable.
  17593. This function only applies to comment blocks, comments, example
  17594. blocks and paragraphs. Also, as a special case, re-align table
  17595. when point is at one.
  17596. For convenience, when point is at a plain list, an item or
  17597. a footnote definition, try to fill the first paragraph within.
  17598. If JUSTIFY is non-nil (interactively, with prefix argument),
  17599. justify as well. If `sentence-end-double-space' is non-nil, then
  17600. period followed by one space does not end a sentence, so don't
  17601. break a line there. The variable `fill-column' controls the
  17602. width for filling.
  17603. The REGION argument is non-nil if called interactively; in that
  17604. case, if Transient Mark mode is enabled and the mark is active,
  17605. fill each of the elements in the active region, instead of just
  17606. filling the current element."
  17607. (interactive (progn
  17608. (barf-if-buffer-read-only)
  17609. (list (when current-prefix-arg 'full) t)))
  17610. (let ((hash (and (not (buffer-modified-p))
  17611. (org-buffer-hash))))
  17612. (cond
  17613. ((and region transient-mark-mode mark-active
  17614. (not (eq (region-beginning) (region-end))))
  17615. (let ((origin (point-marker))
  17616. (start (region-beginning)))
  17617. (unwind-protect
  17618. (progn
  17619. (goto-char (region-end))
  17620. (skip-chars-backward " \t\n")
  17621. (let ((org--single-lines-list-is-paragraph nil))
  17622. (while (> (point) start)
  17623. (org-fill-element justify)
  17624. (org-backward-paragraph)
  17625. (skip-chars-backward " \t\n"))))
  17626. (goto-char origin)
  17627. (set-marker origin nil))))
  17628. (t
  17629. (save-excursion
  17630. (when (org-match-line "[ \t]*$")
  17631. (skip-chars-forward " \t\n"))
  17632. (org-fill-element justify))))
  17633. ;; If we didn't change anything in the buffer (and the buffer was
  17634. ;; previously unmodified), then flip the modification status back
  17635. ;; to "unchanged".
  17636. (when (and hash (equal hash (org-buffer-hash)))
  17637. (set-buffer-modified-p nil))
  17638. ;; Return non-nil.
  17639. t))
  17640. (defun org-auto-fill-function ()
  17641. "Auto-fill function."
  17642. ;; Check if auto-filling is meaningful.
  17643. (let ((fc (current-fill-column)))
  17644. (when (and fc (> (current-column) fc))
  17645. (let* ((fill-prefix (org-adaptive-fill-function))
  17646. ;; Enforce empty fill prefix, if required. Otherwise, it
  17647. ;; will be computed again.
  17648. (adaptive-fill-mode (not (equal fill-prefix ""))))
  17649. (when fill-prefix (do-auto-fill))))))
  17650. (defun org-comment-line-break-function (&optional soft)
  17651. "Break line at point and indent, continuing comment if within one.
  17652. The inserted newline is marked hard if variable
  17653. `use-hard-newlines' is true, unless optional argument SOFT is
  17654. non-nil."
  17655. (if soft (insert-and-inherit ?\n) (newline 1))
  17656. (save-excursion (forward-char -1) (delete-horizontal-space))
  17657. (delete-horizontal-space)
  17658. (indent-to-left-margin)
  17659. (insert-before-markers-and-inherit fill-prefix))
  17660. ;;; Fixed Width Areas
  17661. (defun org-toggle-fixed-width ()
  17662. "Toggle fixed-width markup.
  17663. Add or remove fixed-width markup on current line, whenever it
  17664. makes sense. Return an error otherwise.
  17665. If a region is active and if it contains only fixed-width areas
  17666. or blank lines, remove all fixed-width markup in it. If the
  17667. region contains anything else, convert all non-fixed-width lines
  17668. to fixed-width ones.
  17669. Blank lines at the end of the region are ignored unless the
  17670. region only contains such lines."
  17671. (interactive)
  17672. (if (not (org-region-active-p))
  17673. ;; No region:
  17674. ;;
  17675. ;; Remove fixed width marker only in a fixed-with element.
  17676. ;;
  17677. ;; Add fixed width maker in paragraphs, in blank lines after
  17678. ;; elements or at the beginning of a headline or an inlinetask,
  17679. ;; and before any one-line elements (e.g., a clock).
  17680. (progn
  17681. (beginning-of-line)
  17682. (let* ((element (org-element-at-point))
  17683. (type (org-element-type element)))
  17684. (cond
  17685. ((and (eq type 'fixed-width)
  17686. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  17687. (replace-match
  17688. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  17689. ((and (memq type '(babel-call clock comment diary-sexp headline
  17690. horizontal-rule keyword paragraph
  17691. planning))
  17692. (<= (org-element-property :post-affiliated element) (point)))
  17693. (skip-chars-forward " \t")
  17694. (insert ": "))
  17695. ((and (looking-at-p "[ \t]*$")
  17696. (or (eq type 'inlinetask)
  17697. (save-excursion
  17698. (skip-chars-forward " \r\t\n")
  17699. (<= (org-element-property :end element) (point)))))
  17700. (delete-region (point) (line-end-position))
  17701. (org-indent-line)
  17702. (insert ": "))
  17703. (t (user-error "Cannot insert a fixed-width line here")))))
  17704. ;; Region active.
  17705. (let* ((begin (save-excursion
  17706. (goto-char (region-beginning))
  17707. (line-beginning-position)))
  17708. (end (copy-marker
  17709. (save-excursion
  17710. (goto-char (region-end))
  17711. (unless (eolp) (beginning-of-line))
  17712. (if (save-excursion (re-search-backward "\\S-" begin t))
  17713. (progn (skip-chars-backward " \r\t\n") (point))
  17714. (point)))))
  17715. (all-fixed-width-p
  17716. (catch 'not-all-p
  17717. (save-excursion
  17718. (goto-char begin)
  17719. (skip-chars-forward " \r\t\n")
  17720. (when (eobp) (throw 'not-all-p nil))
  17721. (while (< (point) end)
  17722. (let ((element (org-element-at-point)))
  17723. (if (eq (org-element-type element) 'fixed-width)
  17724. (goto-char (org-element-property :end element))
  17725. (throw 'not-all-p nil))))
  17726. t))))
  17727. (if all-fixed-width-p
  17728. (save-excursion
  17729. (goto-char begin)
  17730. (while (< (point) end)
  17731. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  17732. (replace-match
  17733. "" nil nil nil
  17734. (if (= (line-end-position) (match-end 0)) 0 1)))
  17735. (forward-line)))
  17736. (let ((min-ind (point-max)))
  17737. ;; Find minimum indentation across all lines.
  17738. (save-excursion
  17739. (goto-char begin)
  17740. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  17741. (setq min-ind 0)
  17742. (catch 'zerop
  17743. (while (< (point) end)
  17744. (unless (looking-at-p "[ \t]*$")
  17745. (let ((ind (current-indentation)))
  17746. (setq min-ind (min min-ind ind))
  17747. (when (zerop ind) (throw 'zerop t))))
  17748. (forward-line)))))
  17749. ;; Loop over all lines and add fixed-width markup everywhere
  17750. ;; but in fixed-width lines.
  17751. (save-excursion
  17752. (goto-char begin)
  17753. (while (< (point) end)
  17754. (cond
  17755. ((org-at-heading-p)
  17756. (insert ": ")
  17757. (forward-line)
  17758. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  17759. (insert ":")
  17760. (forward-line)))
  17761. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  17762. (let* ((element (org-element-at-point))
  17763. (element-end (org-element-property :end element)))
  17764. (if (eq (org-element-type element) 'fixed-width)
  17765. (progn (goto-char element-end)
  17766. (skip-chars-backward " \r\t\n")
  17767. (forward-line))
  17768. (let ((limit (min end element-end)))
  17769. (while (< (point) limit)
  17770. (org-move-to-column min-ind t)
  17771. (insert ": ")
  17772. (forward-line))))))
  17773. (t
  17774. (org-move-to-column min-ind t)
  17775. (insert ": ")
  17776. (forward-line)))))))
  17777. (set-marker end nil))))
  17778. ;;; Blocks
  17779. (defun org-block-map (function &optional start end)
  17780. "Call FUNCTION at the head of all source blocks in the current buffer.
  17781. Optional arguments START and END can be used to limit the range."
  17782. (let ((start (or start (point-min)))
  17783. (end (or end (point-max))))
  17784. (save-excursion
  17785. (goto-char start)
  17786. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  17787. (save-excursion
  17788. (save-match-data
  17789. (goto-char (match-beginning 0))
  17790. (funcall function)))))))
  17791. (defun org-next-block (arg &optional backward block-regexp)
  17792. "Jump to the next block.
  17793. With a prefix argument ARG, jump forward ARG many blocks.
  17794. When BACKWARD is non-nil, jump to the previous block.
  17795. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  17796. Match data is set according to this regexp when the function
  17797. returns.
  17798. Return point at beginning of the opening line of found block.
  17799. Throw an error if no block is found."
  17800. (interactive "p")
  17801. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  17802. (case-fold-search t)
  17803. (search-fn (if backward #'re-search-backward #'re-search-forward))
  17804. (count (or arg 1))
  17805. (origin (point))
  17806. last-element)
  17807. (if backward (beginning-of-line) (end-of-line))
  17808. (while (and (> count 0) (funcall search-fn re nil t))
  17809. (let ((element (save-excursion
  17810. (goto-char (match-beginning 0))
  17811. (save-match-data (org-element-at-point)))))
  17812. (when (and (memq (org-element-type element)
  17813. '(center-block comment-block dynamic-block
  17814. example-block export-block quote-block
  17815. special-block src-block verse-block))
  17816. (<= (match-beginning 0)
  17817. (org-element-property :post-affiliated element)))
  17818. (setq last-element element)
  17819. (cl-decf count))))
  17820. (if (= count 0)
  17821. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  17822. (save-match-data (org-fold-show-context)))
  17823. (goto-char origin)
  17824. (user-error "No %s code blocks" (if backward "previous" "further")))))
  17825. (defun org-previous-block (arg &optional block-regexp)
  17826. "Jump to the previous block.
  17827. With a prefix argument ARG, jump backward ARG many source blocks.
  17828. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  17829. (interactive "p")
  17830. (org-next-block arg t block-regexp))
  17831. ;;; Comments
  17832. ;; Org comments syntax is quite complex. It requires the entire line
  17833. ;; to be just a comment. Also, even with the right syntax at the
  17834. ;; beginning of line, some elements (e.g., verse-block or
  17835. ;; example-block) don't accept comments. Usual Emacs comment commands
  17836. ;; cannot cope with those requirements. Therefore, Org replaces them.
  17837. ;; Org still relies on 'comment-dwim', but cannot trust
  17838. ;; 'comment-only-p'. So, 'comment-region-function' and
  17839. ;; 'uncomment-region-function' both point
  17840. ;; to 'org-comment-or-uncomment-region'. Eventually,
  17841. ;; 'org-insert-comment' takes care of insertion of comments at the
  17842. ;; beginning of line.
  17843. ;; 'org-setup-comments-handling' install comments related variables
  17844. ;; during 'org-mode' initialization.
  17845. (defun org-setup-comments-handling ()
  17846. (interactive)
  17847. (setq-local comment-use-syntax nil)
  17848. (setq-local comment-start "# ")
  17849. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  17850. (setq-local comment-insert-comment-function 'org-insert-comment)
  17851. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  17852. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  17853. (defun org-insert-comment ()
  17854. "Insert an empty comment above current line.
  17855. If the line is empty, insert comment at its beginning. When
  17856. point is within a source block, comment according to the related
  17857. major mode."
  17858. (if (let ((element (org-element-at-point)))
  17859. (and (eq (org-element-type element) 'src-block)
  17860. (< (save-excursion
  17861. (goto-char (org-element-property :post-affiliated element))
  17862. (line-end-position))
  17863. (point))
  17864. (> (save-excursion
  17865. (goto-char (org-element-property :end element))
  17866. (skip-chars-backward " \r\t\n")
  17867. (line-beginning-position))
  17868. (point))))
  17869. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  17870. (beginning-of-line)
  17871. (if (looking-at "\\s-*$") (delete-region (point) (line-end-position))
  17872. (open-line 1))
  17873. (org-indent-line)
  17874. (insert "# ")))
  17875. (defvar comment-empty-lines) ; From newcomment.el.
  17876. (defun org-comment-or-uncomment-region (beg end &rest _)
  17877. "Comment or uncomment each non-blank line in the region.
  17878. Uncomment each non-blank line between BEG and END if it only
  17879. contains commented lines. Otherwise, comment them. If region is
  17880. strictly within a source block, use appropriate comment syntax."
  17881. (if (let ((element (org-element-at-point)))
  17882. (and (eq (org-element-type element) 'src-block)
  17883. (< (save-excursion
  17884. (goto-char (org-element-property :post-affiliated element))
  17885. (line-end-position))
  17886. beg)
  17887. (>= (save-excursion
  17888. (goto-char (org-element-property :end element))
  17889. (skip-chars-backward " \r\t\n")
  17890. (line-beginning-position))
  17891. end)))
  17892. ;; Translate region boundaries for the Org buffer to the source
  17893. ;; buffer.
  17894. (let ((offset (- end beg)))
  17895. (save-excursion
  17896. (goto-char beg)
  17897. (org-babel-do-in-edit-buffer
  17898. (comment-or-uncomment-region (point) (+ offset (point))))))
  17899. (save-restriction
  17900. ;; Restrict region
  17901. (narrow-to-region (save-excursion (goto-char beg)
  17902. (skip-chars-forward " \r\t\n" end)
  17903. (line-beginning-position))
  17904. (save-excursion (goto-char end)
  17905. (skip-chars-backward " \r\t\n" beg)
  17906. (line-end-position)))
  17907. (let ((uncommentp
  17908. ;; UNCOMMENTP is non-nil when every non blank line between
  17909. ;; BEG and END is a comment.
  17910. (save-excursion
  17911. (goto-char (point-min))
  17912. (while (and (not (eobp))
  17913. (let ((element (org-element-at-point)))
  17914. (and (eq (org-element-type element) 'comment)
  17915. (goto-char (min (point-max)
  17916. (org-element-property
  17917. :end element)))))))
  17918. (eobp))))
  17919. (if uncommentp
  17920. ;; Only blank lines and comments in region: uncomment it.
  17921. (save-excursion
  17922. (goto-char (point-min))
  17923. (while (not (eobp))
  17924. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  17925. (replace-match "" nil nil nil 1))
  17926. (forward-line)))
  17927. ;; Comment each line in region.
  17928. (let ((min-indent (point-max)))
  17929. ;; First find the minimum indentation across all lines.
  17930. (save-excursion
  17931. (goto-char (point-min))
  17932. (while (and (not (eobp)) (not (zerop min-indent)))
  17933. (unless (looking-at "[ \t]*$")
  17934. (setq min-indent (min min-indent (current-indentation))))
  17935. (forward-line)))
  17936. ;; Then loop over all lines.
  17937. (save-excursion
  17938. (goto-char (point-min))
  17939. (while (not (eobp))
  17940. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  17941. ;; Don't get fooled by invisible text (e.g. link path)
  17942. ;; when moving to column MIN-INDENT.
  17943. (let ((buffer-invisibility-spec nil))
  17944. (org-move-to-column min-indent t))
  17945. (insert comment-start))
  17946. (forward-line)))))))))
  17947. (defun org-comment-dwim (_arg)
  17948. "Call the comment command you mean.
  17949. Call `org-toggle-comment' if on a heading, otherwise call
  17950. `comment-dwim', within a source edit buffer if needed."
  17951. (interactive "*P")
  17952. (cond ((org-at-heading-p)
  17953. (call-interactively #'org-toggle-comment))
  17954. ((org-in-src-block-p)
  17955. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  17956. (t (call-interactively #'comment-dwim))))
  17957. ;;; Timestamps API
  17958. ;; This section contains tools to operate on, or create, timestamp
  17959. ;; objects, as returned by, e.g. `org-element-context'.
  17960. (defun org-timestamp-from-string (s)
  17961. "Convert Org timestamp S, as a string, into a timestamp object.
  17962. Return nil if S is not a valid timestamp string."
  17963. (when (org-string-nw-p s)
  17964. (with-temp-buffer
  17965. (save-excursion (insert s))
  17966. (org-element-timestamp-parser))))
  17967. (defun org-timestamp-from-time (time &optional with-time inactive)
  17968. "Convert a time value into a timestamp object.
  17969. TIME is an Emacs internal time representation, as returned, e.g.,
  17970. by `current-time'.
  17971. When optional argument WITH-TIME is non-nil, return a timestamp
  17972. object with a time part, i.e., with hours and minutes.
  17973. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  17974. return an active timestamp."
  17975. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  17976. (org-element-create 'timestamp
  17977. (list :type (if inactive 'inactive 'active)
  17978. :year-start year
  17979. :month-start month
  17980. :day-start day
  17981. :hour-start (and with-time hour)
  17982. :minute-start (and with-time minute)))))
  17983. (defun org-timestamp-to-time (timestamp &optional end)
  17984. "Convert TIMESTAMP object into an Emacs internal time value.
  17985. Use end of date range or time range when END is non-nil.
  17986. Otherwise, use its start."
  17987. (org-encode-time
  17988. (append '(0)
  17989. (mapcar
  17990. (lambda (prop) (or (org-element-property prop timestamp) 0))
  17991. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  17992. '(:minute-start :hour-start :day-start :month-start
  17993. :year-start)))
  17994. '(nil -1 nil))))
  17995. (defun org-timestamp-has-time-p (timestamp)
  17996. "Non-nil when TIMESTAMP has a time specified."
  17997. (org-element-property :hour-start timestamp))
  17998. (defun org-timestamp-format (timestamp format &optional end utc)
  17999. "Format a TIMESTAMP object into a string.
  18000. FORMAT is a format specifier to be passed to
  18001. `format-time-string'.
  18002. When optional argument END is non-nil, use end of date-range or
  18003. time-range, if possible.
  18004. When optional argument UTC is non-nil, time is be expressed as
  18005. Universal Time."
  18006. (format-time-string format (org-timestamp-to-time timestamp end)
  18007. (and utc t)))
  18008. (defun org-timestamp-split-range (timestamp &optional end)
  18009. "Extract a TIMESTAMP object from a date or time range.
  18010. END, when non-nil, means extract the end of the range.
  18011. Otherwise, extract its start.
  18012. Return a new timestamp object."
  18013. (let ((type (org-element-property :type timestamp)))
  18014. (if (memq type '(active inactive diary)) timestamp
  18015. (let ((split-ts (org-element-copy timestamp)))
  18016. ;; Set new type.
  18017. (org-element-put-property
  18018. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  18019. ;; Copy start properties over end properties if END is
  18020. ;; non-nil. Otherwise, copy end properties over `start' ones.
  18021. (let ((p-alist '((:minute-start . :minute-end)
  18022. (:hour-start . :hour-end)
  18023. (:day-start . :day-end)
  18024. (:month-start . :month-end)
  18025. (:year-start . :year-end))))
  18026. (dolist (p-cell p-alist)
  18027. (org-element-put-property
  18028. split-ts
  18029. (funcall (if end #'car #'cdr) p-cell)
  18030. (org-element-property
  18031. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  18032. ;; Eventually refresh `:raw-value'.
  18033. (org-element-put-property split-ts :raw-value nil)
  18034. (org-element-put-property
  18035. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  18036. (defun org-timestamp-translate (timestamp &optional boundary)
  18037. "Translate TIMESTAMP object to custom format.
  18038. Format string is defined in `org-time-stamp-custom-formats',
  18039. which see.
  18040. When optional argument BOUNDARY is non-nil, it is either the
  18041. symbol `start' or `end'. In this case, only translate the
  18042. starting or ending part of TIMESTAMP if it is a date or time
  18043. range. Otherwise, translate both parts.
  18044. Return timestamp as-is if `org-display-custom-times' is nil or if
  18045. it has a `diary' type."
  18046. (let ((type (org-element-property :type timestamp)))
  18047. (if (or (not org-display-custom-times) (eq type 'diary))
  18048. (org-element-interpret-data timestamp)
  18049. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  18050. org-time-stamp-custom-formats)))
  18051. (if (and (not boundary) (memq type '(active-range inactive-range)))
  18052. (concat (org-timestamp-format timestamp fmt)
  18053. "--"
  18054. (org-timestamp-format timestamp fmt t))
  18055. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  18056. ;;; Other stuff
  18057. (defvar reftex-docstruct-symbol)
  18058. (defvar org--rds)
  18059. (defun org-reftex-citation ()
  18060. "Use `reftex-citation' to insert a citation into the buffer.
  18061. This looks for a line like
  18062. #+BIBLIOGRAPHY: foo plain option:-d
  18063. and derives from it that foo.bib is the bibliography file relevant
  18064. for this document. It then installs the necessary environment for RefTeX
  18065. to work in this buffer and calls `reftex-citation' to insert a citation
  18066. into the buffer.
  18067. Export of such citations to both LaTeX and HTML is handled by the contributed
  18068. package ox-bibtex by Taru Karttunen."
  18069. (interactive)
  18070. (let ((reftex-docstruct-symbol 'org--rds)
  18071. org--rds bib)
  18072. (org-with-wide-buffer
  18073. (let ((case-fold-search t)
  18074. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  18075. (if (not (save-excursion
  18076. (or (re-search-forward re nil t)
  18077. (re-search-backward re nil t))))
  18078. (user-error "No bibliography defined in file")
  18079. (setq bib (concat (match-string 1) ".bib")
  18080. org--rds (list (list 'bib bib))))))
  18081. (call-interactively 'reftex-citation)))
  18082. ;;;; Functions extending outline functionality
  18083. (defun org-beginning-of-line (&optional n)
  18084. "Go to the beginning of the current visible line.
  18085. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18086. symbol `reversed', on the first attempt move to where the
  18087. headline text starts, and only move to beginning of line when the
  18088. cursor is already before the start of the text of the headline.
  18089. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  18090. start of the text on the second attempt.
  18091. With argument N not nil or 1, move forward N - 1 lines first."
  18092. (interactive "^p")
  18093. (let ((origin (point))
  18094. (special (pcase org-special-ctrl-a/e
  18095. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  18096. deactivate-mark)
  18097. ;; First move to a visible line.
  18098. (if (bound-and-true-p visual-line-mode)
  18099. (beginning-of-visual-line n)
  18100. (move-beginning-of-line n)
  18101. ;; `move-beginning-of-line' may leave point after invisible
  18102. ;; characters if line starts with such of these (e.g., with
  18103. ;; a link at column 0). Really move to the beginning of the
  18104. ;; current visible line.
  18105. (beginning-of-line))
  18106. (cond
  18107. ;; No special behavior. Point is already at the beginning of
  18108. ;; a line, logical or visual.
  18109. ((not special))
  18110. ;; `beginning-of-visual-line' left point before logical beginning
  18111. ;; of line: point is at the beginning of a visual line. Bail
  18112. ;; out.
  18113. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  18114. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  18115. ;; At a headline, special position is before the title, but
  18116. ;; after any TODO keyword or priority cookie.
  18117. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  18118. (line-end-position)))
  18119. (bol (point)))
  18120. (if (eq special 'reversed)
  18121. (when (and (= origin bol) (eq last-command this-command))
  18122. (goto-char refpos))
  18123. (when (or (> origin refpos) (= origin bol))
  18124. (goto-char refpos)))))
  18125. ((and (looking-at org-list-full-item-re)
  18126. (memq (org-element-type (save-match-data (org-element-at-point)))
  18127. '(item plain-list)))
  18128. ;; Set special position at first white space character after
  18129. ;; bullet, and check-box, if any.
  18130. (let ((after-bullet
  18131. (let ((box (match-end 3)))
  18132. (cond ((not box) (match-end 1))
  18133. ((eq (char-after box) ?\s) (1+ box))
  18134. (t box)))))
  18135. (if (eq special 'reversed)
  18136. (when (and (= (point) origin) (eq last-command this-command))
  18137. (goto-char after-bullet))
  18138. (when (or (> origin after-bullet) (= (point) origin))
  18139. (goto-char after-bullet)))))
  18140. ;; No special context. Point is already at beginning of line.
  18141. (t nil))))
  18142. (defun org-end-of-line (&optional n)
  18143. "Go to the end of the line, but before ellipsis, if any.
  18144. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18145. symbol `reversed', ignore tags on the first attempt, and only
  18146. move to after the tags when the cursor is already beyond the end
  18147. of the headline.
  18148. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  18149. on the second attempt.
  18150. With argument N not nil or 1, move forward N - 1 lines first."
  18151. (interactive "^p")
  18152. (let ((origin (point))
  18153. (special (pcase org-special-ctrl-a/e
  18154. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  18155. deactivate-mark)
  18156. ;; First move to a visible line.
  18157. (if (bound-and-true-p visual-line-mode)
  18158. (beginning-of-visual-line n)
  18159. (move-beginning-of-line n))
  18160. (cond
  18161. ;; At a headline, with tags.
  18162. ((and special
  18163. (save-excursion
  18164. (beginning-of-line)
  18165. (let ((case-fold-search nil))
  18166. (looking-at org-complex-heading-regexp)))
  18167. (match-end 5))
  18168. (let ((tags (save-excursion
  18169. (goto-char (match-beginning 5))
  18170. (skip-chars-backward " \t")
  18171. (point)))
  18172. (visual-end (and (bound-and-true-p visual-line-mode)
  18173. (save-excursion
  18174. (end-of-visual-line)
  18175. (point)))))
  18176. ;; If `end-of-visual-line' brings us before end of line or
  18177. ;; even tags, i.e., the headline spans over multiple visual
  18178. ;; lines, move there.
  18179. (cond ((and visual-end
  18180. (< visual-end tags)
  18181. (<= origin visual-end))
  18182. (goto-char visual-end))
  18183. ((eq special 'reversed)
  18184. (if (and (= origin (line-end-position))
  18185. (eq this-command last-command))
  18186. (goto-char tags)
  18187. (end-of-line)))
  18188. (t
  18189. (if (or (< origin tags) (= origin (line-end-position)))
  18190. (goto-char tags)
  18191. (end-of-line))))))
  18192. ((bound-and-true-p visual-line-mode)
  18193. (let ((bol (line-beginning-position)))
  18194. (end-of-visual-line)
  18195. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18196. ;; end of a line, backtrack and use `end-of-line' instead.
  18197. (when (/= bol (line-beginning-position))
  18198. (goto-char bol)
  18199. (end-of-line))))
  18200. (t (end-of-line)))))
  18201. (defun org-backward-sentence (&optional _arg)
  18202. "Go to beginning of sentence, or beginning of table field.
  18203. This will call `backward-sentence' or `org-table-beginning-of-field',
  18204. depending on context."
  18205. (interactive)
  18206. (let* ((element (org-element-at-point))
  18207. (contents-begin (org-element-property :contents-begin element))
  18208. (table (org-element-lineage element '(table) t)))
  18209. (if (and table
  18210. (> (point) contents-begin)
  18211. (<= (point) (org-element-property :contents-end table)))
  18212. (call-interactively #'org-table-beginning-of-field)
  18213. (save-restriction
  18214. (when (and contents-begin
  18215. (< (point-min) contents-begin)
  18216. (> (point) contents-begin))
  18217. (narrow-to-region contents-begin
  18218. (org-element-property :contents-end element)))
  18219. (call-interactively #'backward-sentence)))))
  18220. (defun org-forward-sentence (&optional _arg)
  18221. "Go to end of sentence, or end of table field.
  18222. This will call `forward-sentence' or `org-table-end-of-field',
  18223. depending on context."
  18224. (interactive)
  18225. (if (and (org-at-heading-p)
  18226. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18227. (save-restriction
  18228. (narrow-to-region (line-beginning-position) (line-end-position))
  18229. (call-interactively #'forward-sentence))
  18230. (let* ((element (org-element-at-point))
  18231. (contents-end (org-element-property :contents-end element))
  18232. (table (org-element-lineage element '(table) t)))
  18233. (if (and table
  18234. (>= (point) (org-element-property :contents-begin table))
  18235. (< (point) contents-end))
  18236. (call-interactively #'org-table-end-of-field)
  18237. (save-restriction
  18238. (when (and contents-end
  18239. (> (point-max) contents-end)
  18240. ;; Skip blank lines between elements.
  18241. (< (org-element-property :end element)
  18242. (save-excursion (goto-char contents-end)
  18243. (skip-chars-forward " \r\t\n"))))
  18244. (narrow-to-region (org-element-property :contents-begin element)
  18245. contents-end))
  18246. ;; End of heading is considered as the end of a sentence.
  18247. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18248. (call-interactively #'forward-sentence)))))))
  18249. (defun org-kill-line (&optional _arg)
  18250. "Kill line, to tags or end of line."
  18251. (interactive)
  18252. (cond
  18253. ((or (not org-special-ctrl-k)
  18254. (bolp)
  18255. (not (org-at-heading-p)))
  18256. (when (and (org-invisible-p (line-end-position))
  18257. org-ctrl-k-protect-subtree
  18258. (or (eq org-ctrl-k-protect-subtree 'error)
  18259. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18260. (user-error
  18261. (substitute-command-keys
  18262. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18263. (call-interactively
  18264. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18265. ((org-match-line org-tag-line-re)
  18266. (let ((end (save-excursion
  18267. (goto-char (match-beginning 1))
  18268. (skip-chars-backward " \t")
  18269. (point))))
  18270. (if (<= end (point)) ;on tags part
  18271. (kill-region (point) (line-end-position))
  18272. (kill-region (point) end)))
  18273. ;; Only align tags when we are still on a heading:
  18274. (if (org-at-heading-p) (org-align-tags)))
  18275. (t (kill-region (point) (line-end-position)))))
  18276. (defun org-yank (&optional arg)
  18277. "Yank. If the kill is a subtree, treat it specially.
  18278. This command will look at the current kill and check if is a single
  18279. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18280. cursor is at the beginning of a line or after the stars of a currently
  18281. empty headline, then the yank is handled specially. How exactly depends
  18282. on the value of the following variables.
  18283. `org-yank-folded-subtrees'
  18284. By default, this variable is non-nil, which results in
  18285. subtree(s) being folded after insertion, except if doing so
  18286. would swallow text after the yanked text.
  18287. `org-yank-adjusted-subtrees'
  18288. When non-nil (the default value is nil), the subtree will be
  18289. promoted or demoted in order to fit into the local outline tree
  18290. structure, which means that the level will be adjusted so that it
  18291. becomes the smaller one of the two *visible* surrounding headings.
  18292. Any prefix to this command will cause `yank' to be called directly with
  18293. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18294. will just
  18295. plainly yank the text as it is.
  18296. \[1] The test checks if the first non-white line is a heading
  18297. and if there are no other headings with fewer stars."
  18298. (interactive "P")
  18299. (org-yank-generic 'yank arg))
  18300. (defun org-yank-generic (command arg)
  18301. "Perform some yank-like command.
  18302. This function implements the behavior described in the `org-yank'
  18303. documentation. However, it has been generalized to work for any
  18304. interactive command with similar behavior."
  18305. ;; pretend to be command COMMAND
  18306. (setq this-command command)
  18307. (if arg
  18308. (call-interactively command)
  18309. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18310. (and (org-kill-is-subtree-p)
  18311. (or (bolp)
  18312. (and (looking-at "[ \t]*$")
  18313. (string-match
  18314. "\\`\\*+\\'"
  18315. (buffer-substring (line-beginning-position) (point)))))))
  18316. swallowp)
  18317. (cond
  18318. ((and subtreep org-yank-folded-subtrees)
  18319. (let ((beg (point))
  18320. end)
  18321. (if (and subtreep org-yank-adjusted-subtrees)
  18322. (org-paste-subtree nil nil 'for-yank)
  18323. (call-interactively command))
  18324. (setq end (point))
  18325. (goto-char beg)
  18326. (when (and (bolp) subtreep
  18327. (not (setq swallowp
  18328. (org-yank-folding-would-swallow-text beg end))))
  18329. (org-with-limited-levels
  18330. (or (looking-at org-outline-regexp)
  18331. (re-search-forward org-outline-regexp-bol end t))
  18332. (while (and (< (point) end) (looking-at org-outline-regexp))
  18333. (org-fold-subtree t)
  18334. (org-cycle-show-empty-lines 'folded)
  18335. (condition-case nil
  18336. (outline-forward-same-level 1)
  18337. (error (goto-char end))))))
  18338. (when swallowp
  18339. (message
  18340. "Inserted text not folded because that would swallow text"))
  18341. (goto-char end)
  18342. (skip-chars-forward " \t\n\r")
  18343. (beginning-of-line 1)
  18344. (push-mark beg 'nomsg)))
  18345. ((and subtreep org-yank-adjusted-subtrees)
  18346. (let ((beg (line-beginning-position)))
  18347. (org-paste-subtree nil nil 'for-yank)
  18348. (push-mark beg 'nomsg)))
  18349. (t
  18350. (call-interactively command))))))
  18351. (defun org-yank-folding-would-swallow-text (beg end)
  18352. "Would `hide-subtree' at BEG swallow any text after END?"
  18353. (let (level)
  18354. (org-with-limited-levels
  18355. (save-excursion
  18356. (goto-char beg)
  18357. (when (or (looking-at org-outline-regexp)
  18358. (re-search-forward org-outline-regexp-bol end t))
  18359. (setq level (org-outline-level)))
  18360. (goto-char end)
  18361. (skip-chars-forward " \t\r\n\v\f")
  18362. (not (or (eobp)
  18363. (and (bolp) (looking-at-p org-outline-regexp)
  18364. (<= (org-outline-level) level))))))))
  18365. (defun org-back-to-heading (&optional invisible-ok)
  18366. "Go back to beginning of heading."
  18367. (beginning-of-line)
  18368. (or (org-at-heading-p (not invisible-ok))
  18369. (if (org-element--cache-active-p)
  18370. (let ((heading (org-element-lineage (org-element-at-point)
  18371. '(headline inlinetask)
  18372. 'include-self)))
  18373. (when heading
  18374. (goto-char (org-element-property :begin heading)))
  18375. (while (and (not invisible-ok)
  18376. heading
  18377. (org-fold-folded-p))
  18378. (goto-char (org-fold-core-previous-visibility-change))
  18379. (setq heading (org-element-lineage (org-element-at-point)
  18380. '(headline inlinetask)
  18381. 'include-self))
  18382. (when heading
  18383. (goto-char (org-element-property :begin heading))))
  18384. (unless heading
  18385. (user-error "Before first headline at position %d in buffer %s"
  18386. (point) (current-buffer)))
  18387. (point))
  18388. (let (found)
  18389. (save-excursion
  18390. ;; At inlinetask end. Move to bol, so that the following
  18391. ;; search goes to the beginning of the inlinetask.
  18392. (when (and (featurep 'org-inlinetask)
  18393. (fboundp 'org-inlinetask-end-p)
  18394. (org-inlinetask-end-p))
  18395. (goto-char (line-beginning-position)))
  18396. (while (not found)
  18397. (or (re-search-backward (concat "^\\(?:" outline-regexp "\\)")
  18398. nil t)
  18399. (user-error "Before first headline at position %d in buffer %s"
  18400. (point) (current-buffer)))
  18401. ;; Skip inlinetask end.
  18402. (if (and (featurep 'org-inlinetask)
  18403. (fboundp 'org-inlinetask-end-p)
  18404. (org-inlinetask-end-p))
  18405. (org-inlinetask-goto-beginning)
  18406. (setq found (and (or invisible-ok (not (org-fold-folded-p)))
  18407. (point))))))
  18408. (goto-char found)
  18409. found))))
  18410. (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  18411. "Go back to heading or first point in buffer.
  18412. If point is before first heading go to first point in buffer
  18413. instead of back to heading."
  18414. (if (org-before-first-heading-p)
  18415. (goto-char (point-min))
  18416. (org-back-to-heading invisible-ok)))
  18417. (defun org-before-first-heading-p ()
  18418. "Before first heading?
  18419. Respect narrowing."
  18420. (let ((cached (org-element-at-point nil 'cached)))
  18421. (if cached
  18422. (let ((cached-headline (org-element-lineage cached '(headline) t)))
  18423. (or (not cached-headline)
  18424. (< (org-element-property :begin cached-headline) (point-min))))
  18425. (org-with-limited-levels
  18426. (save-excursion
  18427. (end-of-line)
  18428. (null (re-search-backward org-outline-regexp-bol nil t)))))))
  18429. (defun org-at-heading-p (&optional invisible-not-ok)
  18430. "Return t if point is on a (possibly invisible) heading line.
  18431. If INVISIBLE-NOT-OK is non-nil, an invisible heading line is not ok."
  18432. (save-excursion
  18433. (beginning-of-line)
  18434. (and (bolp) (or (not invisible-not-ok) (not (org-fold-folded-p)))
  18435. (looking-at outline-regexp))))
  18436. (defun org-in-commented-heading-p (&optional no-inheritance element)
  18437. "Non-nil if point is under a commented heading.
  18438. This function also checks ancestors of the current headline,
  18439. unless optional argument NO-INHERITANCE is non-nil.
  18440. Optional argument ELEMENT contains element at point."
  18441. (save-match-data
  18442. (let ((el (or element
  18443. (org-element-at-point nil 'cached)
  18444. (org-with-wide-buffer
  18445. (org-back-to-heading-or-point-min t)
  18446. (org-element-at-point)))))
  18447. (catch :found
  18448. (setq el (org-element-lineage el '(headline inlinetask) 'include-self))
  18449. (if no-inheritance
  18450. (org-element-property :commentedp el)
  18451. (while el
  18452. (when (org-element-property :commentedp el)
  18453. (throw :found t))
  18454. (setq el (org-element-property :parent el))))))))
  18455. (defun org-in-archived-heading-p (&optional no-inheritance element)
  18456. "Non-nil if point is under an archived heading.
  18457. This function also checks ancestors of the current headline,
  18458. unless optional argument NO-INHERITANCE is non-nil.
  18459. Optional argument ELEMENT contains element at point."
  18460. (cond
  18461. ((and (not element) (org-before-first-heading-p)) nil)
  18462. ((if element
  18463. (org-element-property :archivedp element)
  18464. (let ((tags (org-get-tags element 'local)))
  18465. (and tags
  18466. (cl-some (apply-partially #'string= org-archive-tag) tags)))))
  18467. (no-inheritance nil)
  18468. (t
  18469. (if (or element (org-element--cache-active-p))
  18470. (catch :archived
  18471. (unless element (setq element (org-element-at-point)))
  18472. (while element
  18473. (when (org-element-property :archivedp element)
  18474. (throw :archived t))
  18475. (setq element (org-element-property :parent element))))
  18476. (save-excursion (and (org-up-heading-safe) (org-in-archived-heading-p)))))))
  18477. (defun org-at-comment-p nil
  18478. "Return t if cursor is in a commented line."
  18479. (save-excursion
  18480. (save-match-data
  18481. (beginning-of-line)
  18482. (looking-at org-comment-regexp))))
  18483. (defun org-at-keyword-p nil
  18484. "Return t if cursor is at a keyword-line."
  18485. (save-excursion
  18486. (move-beginning-of-line 1)
  18487. (looking-at org-keyword-regexp)))
  18488. (defun org-at-drawer-p nil
  18489. "Return t if cursor is at a drawer keyword."
  18490. (save-excursion
  18491. (move-beginning-of-line 1)
  18492. (looking-at org-drawer-regexp)))
  18493. (defun org-at-block-p nil
  18494. "Return t if cursor is at a block keyword."
  18495. (save-excursion
  18496. (move-beginning-of-line 1)
  18497. (looking-at org-block-regexp)))
  18498. (defun org-point-at-end-of-empty-headline ()
  18499. "If point is at the end of an empty headline, return t, else nil.
  18500. If the heading only contains a TODO keyword, it is still considered
  18501. empty."
  18502. (let ((case-fold-search nil))
  18503. (and (looking-at "[ \t]*$")
  18504. org-todo-line-regexp
  18505. (save-excursion
  18506. (beginning-of-line)
  18507. (looking-at org-todo-line-regexp)
  18508. (string= (match-string 3) "")))))
  18509. (defun org-at-heading-or-item-p ()
  18510. (or (org-at-heading-p) (org-at-item-p)))
  18511. (defun org-up-heading-all (arg)
  18512. "Move to the heading line of which the present line is a subheading.
  18513. This function considers both visible and invisible heading lines.
  18514. With argument, move up ARG levels."
  18515. (outline-up-heading arg t))
  18516. (defvar-local org--up-heading-cache nil
  18517. "Buffer-local `org-up-heading-safe' cache.")
  18518. (defvar-local org--up-heading-cache-tick nil
  18519. "Buffer `buffer-chars-modified-tick' in `org--up-heading-cache'.")
  18520. (defun org-up-heading-safe ()
  18521. "Move to the heading line of which the present line is a subheading.
  18522. This version will not throw an error. It will return the level of the
  18523. headline found, or nil if no higher level is found.
  18524. Also, this function will be a lot faster than `outline-up-heading',
  18525. because it relies on stars being the outline starters. This can really
  18526. make a significant difference in outlines with very many siblings."
  18527. (let ((element (and (org-element--cache-active-p)
  18528. (org-element-at-point nil t))))
  18529. (if element
  18530. (let* ((current-heading (org-element-lineage element '(headline inlinetask) 'with-self))
  18531. (parent (org-element-lineage current-heading '(headline))))
  18532. (if (and parent
  18533. (<= (point-min) (org-element-property :begin parent)))
  18534. (progn
  18535. (goto-char (org-element-property :begin parent))
  18536. (org-element-property :level parent))
  18537. (when (and current-heading
  18538. (<= (point-min) (org-element-property :begin current-heading)))
  18539. (goto-char (org-element-property :begin current-heading))
  18540. nil)))
  18541. (when (ignore-errors (org-back-to-heading t))
  18542. (let (level-cache)
  18543. (unless org--up-heading-cache
  18544. (setq org--up-heading-cache (make-hash-table)))
  18545. (if (and (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  18546. (setq level-cache (gethash (point) org--up-heading-cache)))
  18547. (when (<= (point-min) (car level-cache) (point-max))
  18548. ;; Parent is inside accessible part of the buffer.
  18549. (progn (goto-char (car level-cache))
  18550. (cdr level-cache)))
  18551. ;; Buffer modified. Invalidate cache.
  18552. (unless (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  18553. (setq-local org--up-heading-cache-tick
  18554. (buffer-chars-modified-tick))
  18555. (clrhash org--up-heading-cache))
  18556. (let* ((level-up (1- (funcall outline-level)))
  18557. (pos (point))
  18558. (result (and (> level-up 0)
  18559. (re-search-backward
  18560. (format "^\\*\\{1,%d\\} " level-up) nil t)
  18561. (funcall outline-level))))
  18562. (when result (puthash pos (cons (point) result) org--up-heading-cache))
  18563. result)))))))
  18564. (defun org-up-heading-or-point-min ()
  18565. "Move to the heading line of which the present is a subheading, or point-min.
  18566. This version is needed to make point-min behave like a virtual
  18567. heading of level 0 for property-inheritance. It will return the
  18568. level of the headline found (down to 0) or nil if already at a
  18569. point before the first headline or at point-min."
  18570. (when (ignore-errors (org-back-to-heading t))
  18571. (if (< 1 (funcall outline-level))
  18572. (or (org-up-heading-safe)
  18573. ;; The first heading may not be level 1 heading.
  18574. (goto-char (point-min)))
  18575. (unless (= (point) (point-min)) (goto-char (point-min))))))
  18576. (defun org-first-sibling-p ()
  18577. "Is this heading the first child of its parents?"
  18578. (interactive)
  18579. (let ((re org-outline-regexp-bol)
  18580. level l)
  18581. (unless (org-at-heading-p t)
  18582. (user-error "Not at a heading"))
  18583. (setq level (funcall outline-level))
  18584. (save-excursion
  18585. (if (not (re-search-backward re nil t))
  18586. t
  18587. (setq l (funcall outline-level))
  18588. (< l level)))))
  18589. (defun org-goto-sibling (&optional previous)
  18590. "Goto the next sibling, even if it is invisible.
  18591. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18592. when a sibling was found. When none is found, return nil and don't
  18593. move point."
  18594. (let ((fun (if previous 're-search-backward 're-search-forward))
  18595. (pos (point))
  18596. (re org-outline-regexp-bol)
  18597. level l)
  18598. (when (ignore-errors (org-back-to-heading t))
  18599. (setq level (funcall outline-level))
  18600. (catch 'exit
  18601. (or previous (forward-char 1))
  18602. (while (funcall fun re nil t)
  18603. (setq l (funcall outline-level))
  18604. (when (< l level) (goto-char pos) (throw 'exit nil))
  18605. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18606. (goto-char pos)
  18607. nil))))
  18608. (defun org-goto-first-child (&optional element)
  18609. "Goto the first child, even if it is invisible.
  18610. Return t when a child was found. Otherwise don't move point and
  18611. return nil."
  18612. (if (org-element--cache-active-p)
  18613. (let ((heading (org-element-lineage
  18614. (or element (org-element-at-point))
  18615. '(headline inlinetask org-data)
  18616. t)))
  18617. (when heading
  18618. (unless (or (eq 'inlinetask (org-element-type heading))
  18619. (not (org-element-property :contents-begin heading)))
  18620. (let ((pos (point)))
  18621. (goto-char (org-element-property :contents-begin heading))
  18622. (if (re-search-forward
  18623. org-outline-regexp-bol
  18624. (org-element-property :end heading)
  18625. t)
  18626. (progn (goto-char (match-beginning 0)) t)
  18627. (goto-char pos) nil)))))
  18628. (let (level (pos (point)) (re org-outline-regexp-bol))
  18629. (when (org-back-to-heading-or-point-min t)
  18630. (setq level (org-outline-level))
  18631. (forward-char 1)
  18632. (if (and (re-search-forward re nil t) (> (org-outline-level) level))
  18633. (progn (goto-char (match-beginning 0)) t)
  18634. (goto-char pos) nil)))))
  18635. (defun org-get-next-sibling ()
  18636. "Move to next heading of the same level, and return point.
  18637. If there is no such heading, return nil.
  18638. This is like outline-next-sibling, but invisible headings are ok."
  18639. (let ((level (funcall outline-level)))
  18640. (outline-next-heading)
  18641. (while (and (not (eobp)) (> (funcall outline-level) level))
  18642. (outline-next-heading))
  18643. (unless (or (eobp) (< (funcall outline-level) level))
  18644. (point))))
  18645. (defun org-get-previous-sibling ()
  18646. "Move to previous heading of the same level, and return point.
  18647. If there is no such heading, return nil."
  18648. (let ((opoint (point))
  18649. (level (funcall outline-level)))
  18650. (outline-previous-heading)
  18651. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18652. (while (and (> (funcall outline-level) level)
  18653. (not (bobp)))
  18654. (outline-previous-heading))
  18655. (unless (< (funcall outline-level) level)
  18656. (point)))))
  18657. (defun org-end-of-subtree (&optional invisible-ok to-heading element)
  18658. "Goto to the end of a subtree at point or for ELEMENT heading."
  18659. ;; This contains an exact copy of the original function, but it uses
  18660. ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  18661. ;; trees and before first headline. And is uses an invisible-ok argument.
  18662. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18663. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18664. ;; with many children and grandchildren etc, this can be much faster
  18665. ;; than the outline version.
  18666. (if element
  18667. (setq element (org-element-lineage element '(headline inlinetask) 'include-self))
  18668. (org-back-to-heading-or-point-min invisible-ok))
  18669. (unless (and (org-element--cache-active-p)
  18670. (let ((cached (or element (org-element-at-point nil t))))
  18671. (and cached
  18672. (eq 'headline (org-element-type cached))
  18673. (goto-char (org-element-property
  18674. :end cached)))))
  18675. (let ((first t)
  18676. (level (funcall outline-level)))
  18677. (cond ((= level 0)
  18678. (goto-char (point-max)))
  18679. ((and (derived-mode-p 'org-mode) (< level 1000))
  18680. ;; A true heading (not a plain list item), in Org
  18681. ;; This means we can easily find the end by looking
  18682. ;; only for the right number of stars. Using a regexp to do
  18683. ;; this is so much faster than using a Lisp loop.
  18684. (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  18685. (forward-char 1)
  18686. (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  18687. (t
  18688. ;; something else, do it the slow way
  18689. (while (and (not (eobp))
  18690. (or first (> (funcall outline-level) level)))
  18691. (setq first nil)
  18692. (outline-next-heading))))))
  18693. (unless to-heading
  18694. (when (memq (preceding-char) '(?\n ?\^M))
  18695. ;; Go to end of line before heading
  18696. (forward-char -1)
  18697. (when (memq (preceding-char) '(?\n ?\^M))
  18698. ;; leave blank line before heading
  18699. (forward-char -1))))
  18700. (point))
  18701. (defun org-end-of-meta-data (&optional full)
  18702. "Skip planning line and properties drawer in current entry.
  18703. When optional argument FULL is t, also skip planning information,
  18704. clocking lines and any kind of drawer.
  18705. When FULL is non-nil but not t, skip planning information,
  18706. properties, clocking lines and logbook drawers."
  18707. (org-back-to-heading t)
  18708. (forward-line)
  18709. ;; Skip planning information.
  18710. (when (looking-at-p org-planning-line-re) (forward-line))
  18711. ;; Skip property drawer.
  18712. (when (looking-at org-property-drawer-re)
  18713. (goto-char (match-end 0))
  18714. (forward-line))
  18715. ;; When FULL is not nil, skip more.
  18716. (when (and full (not (org-at-heading-p)))
  18717. (catch 'exit
  18718. (let ((end (save-excursion (outline-next-heading) (point)))
  18719. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  18720. (while (not (eobp))
  18721. (cond ;; Skip clock lines.
  18722. ((looking-at-p re) (forward-line))
  18723. ;; Skip logbook drawer.
  18724. ((looking-at-p org-logbook-drawer-re)
  18725. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18726. (forward-line)
  18727. (throw 'exit t)))
  18728. ;; When FULL is t, skip regular drawer too.
  18729. ((and (eq full t) (looking-at-p org-drawer-regexp))
  18730. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18731. (forward-line)
  18732. (throw 'exit t)))
  18733. (t (throw 'exit t))))))))
  18734. (defun org--line-fully-invisible-p ()
  18735. "Return non-nil if the current line is fully invisible."
  18736. (let ((line-beg (line-beginning-position))
  18737. (line-pos (1- (line-end-position)))
  18738. (is-invisible t))
  18739. (while (and (< line-beg line-pos) is-invisible)
  18740. (setq is-invisible (org-invisible-p line-pos))
  18741. (setq line-pos (1- line-pos)))
  18742. is-invisible))
  18743. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  18744. "Move forward to the ARG'th subheading at same level as this one.
  18745. Stop at the first and last subheadings of a superior heading.
  18746. Normally this only looks at visible headings, but when INVISIBLE-OK is
  18747. non-nil it will also look at invisible ones."
  18748. (interactive "p")
  18749. (let ((backward? (and arg (< arg 0))))
  18750. (if (org-before-first-heading-p)
  18751. (if backward? (goto-char (point-min)) (outline-next-heading))
  18752. (org-back-to-heading invisible-ok)
  18753. (unless backward? (end-of-line)) ;do not match current headline
  18754. (let ((level (- (match-end 0) (match-beginning 0) 1))
  18755. (f (if backward? #'re-search-backward #'re-search-forward))
  18756. (count (if arg (abs arg) 1))
  18757. (result (point)))
  18758. (while (and (> count 0)
  18759. (funcall f org-outline-regexp-bol nil 'move))
  18760. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  18761. (cond ((< l level) (setq count 0))
  18762. ((and (= l level)
  18763. (or invisible-ok
  18764. ;; FIXME: See commit a700fadd72 and the
  18765. ;; related discussion on why using
  18766. ;; `org--line-fully-invisible-p' is needed
  18767. ;; here, which is to serve the needs of an
  18768. ;; external package. If the change is
  18769. ;; wrong regarding Org itself, it should
  18770. ;; be removed.
  18771. (not (org--line-fully-invisible-p))))
  18772. (cl-decf count)
  18773. (when (= l level) (setq result (point)))))))
  18774. (goto-char result))
  18775. (beginning-of-line))))
  18776. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  18777. "Move backward to the ARG'th subheading at same level as this one.
  18778. Stop at the first and last subheadings of a superior heading."
  18779. (interactive "p")
  18780. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  18781. (defun org-next-visible-heading (arg)
  18782. "Move to the next visible heading line.
  18783. With ARG, repeats or can move backward if negative."
  18784. (interactive "p")
  18785. (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  18786. (if (< arg 0)
  18787. (beginning-of-line)
  18788. (end-of-line))
  18789. (while (and (< arg 0) (re-search-backward regexp nil :move))
  18790. (unless (bobp)
  18791. (when (org-fold-folded-p)
  18792. (goto-char (org-fold-previous-visibility-change))
  18793. (unless (looking-at-p regexp)
  18794. (re-search-backward regexp nil :mode))))
  18795. (cl-incf arg))
  18796. (while (and (> arg 0) (re-search-forward regexp nil :move))
  18797. (when (org-fold-folded-p)
  18798. (goto-char (org-fold-next-visibility-change))
  18799. (skip-chars-forward " \t\n")
  18800. (end-of-line))
  18801. (cl-decf arg))
  18802. (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
  18803. (defun org-previous-visible-heading (arg)
  18804. "Move to the previous visible heading.
  18805. With ARG, repeats or can move forward if negative."
  18806. (interactive "p")
  18807. (org-next-visible-heading (- arg)))
  18808. (defun org-forward-paragraph (&optional arg)
  18809. "Move forward by a paragraph, or equivalent, unit.
  18810. With argument ARG, do it ARG times;
  18811. a negative argument ARG = -N means move backward N paragraphs.
  18812. The function moves point between two structural
  18813. elements (paragraphs, tables, lists, etc.).
  18814. It also provides the following special moves for convenience:
  18815. - on a table or a property drawer, move to its beginning;
  18816. - on comment, example, export, source and verse blocks, stop
  18817. at blank lines;
  18818. - skip consecutive clocks, diary S-exps, and keywords."
  18819. (interactive "^p")
  18820. (unless arg (setq arg 1))
  18821. (if (< arg 0) (org-backward-paragraph (- arg))
  18822. (while (and (> arg 0) (not (eobp)))
  18823. (org--forward-paragraph-once)
  18824. (cl-decf arg))
  18825. ;; Return moves left.
  18826. arg))
  18827. (defun org-backward-paragraph (&optional arg)
  18828. "Move backward by a paragraph, or equivalent, unit.
  18829. With argument ARG, do it ARG times;
  18830. a negative argument ARG = -N means move forward N paragraphs.
  18831. The function moves point between two structural
  18832. elements (paragraphs, tables, lists, etc.).
  18833. It also provides the following special moves for convenience:
  18834. - on a table or a property drawer, move to its beginning;
  18835. - on comment, example, export, source and verse blocks, stop
  18836. at blank lines;
  18837. - skip consecutive clocks, diary S-exps, and keywords."
  18838. (interactive "^p")
  18839. (unless arg (setq arg 1))
  18840. (if (< arg 0) (org-forward-paragraph (- arg))
  18841. (while (and (> arg 0) (not (bobp)))
  18842. (org--backward-paragraph-once)
  18843. (cl-decf arg))
  18844. ;; Return moves left.
  18845. arg))
  18846. (defvar org--single-lines-list-is-paragraph t
  18847. "Treat plain lists with single line items as a whole paragraph")
  18848. (defun org--paragraph-at-point ()
  18849. "Return paragraph, or equivalent, element at point.
  18850. Paragraph element at point is the element at point, with the
  18851. following special cases:
  18852. - treat table rows (resp. node properties) as the table
  18853. \(resp. property drawer) containing them.
  18854. - treat plain lists with an item every line as a whole.
  18855. - treat consecutive keywords, clocks, and diary-sexps as a single
  18856. block.
  18857. Function may return a real element, or a pseudo-element with type
  18858. `pseudo-paragraph'."
  18859. (let* ((e (org-element-at-point))
  18860. (type (org-element-type e))
  18861. ;; If we need to fake a new pseudo-element, triplet is
  18862. ;;
  18863. ;; (BEG END PARENT)
  18864. ;;
  18865. ;; where BEG and END are element boundaries, and PARENT the
  18866. ;; element containing it, or nil.
  18867. (triplet
  18868. (cond
  18869. ((memq type '(table property-drawer))
  18870. (list (org-element-property :begin e)
  18871. (org-element-property :end e)
  18872. (org-element-property :parent e)))
  18873. ((memq type '(node-property table-row))
  18874. (let ((e (org-element-property :parent e)))
  18875. (list (org-element-property :begin e)
  18876. (org-element-property :end e)
  18877. (org-element-property :parent e))))
  18878. ((memq type '(clock diary-sexp keyword))
  18879. (let* ((regexp (pcase type
  18880. (`clock org-clock-line-re)
  18881. (`diary-sexp "%%(")
  18882. (_ org-keyword-regexp)))
  18883. (end (if (< 0 (org-element-property :post-blank e))
  18884. (org-element-property :end e)
  18885. (org-with-wide-buffer
  18886. (forward-line)
  18887. (while (looking-at regexp) (forward-line))
  18888. (skip-chars-forward " \t\n")
  18889. (line-beginning-position))))
  18890. (begin (org-with-point-at (org-element-property :begin e)
  18891. (while (and (not (bobp)) (looking-at regexp))
  18892. (forward-line -1))
  18893. ;; We may have gotten one line too far.
  18894. (if (looking-at regexp)
  18895. (point)
  18896. (line-beginning-position 2)))))
  18897. (list begin end (org-element-property :parent e))))
  18898. ;; Find the full plain list containing point, the check it
  18899. ;; contains exactly one line per item.
  18900. ((let ((l (org-element-lineage e '(plain-list) t)))
  18901. (while (memq (org-element-type (org-element-property :parent l))
  18902. '(item plain-list))
  18903. (setq l (org-element-property :parent l)))
  18904. (and l org--single-lines-list-is-paragraph
  18905. (org-with-point-at (org-element-property :post-affiliated l)
  18906. (forward-line (length (org-element-property :structure l)))
  18907. (= (point) (org-element-property :contents-end l)))
  18908. ;; Return value.
  18909. (list (org-element-property :begin l)
  18910. (org-element-property :end l)
  18911. (org-element-property :parent l)))))
  18912. (t nil)))) ;no triplet: return element
  18913. (pcase triplet
  18914. (`(,b ,e ,p)
  18915. (org-element-create
  18916. 'pseudo-paragraph
  18917. (list :begin b :end e :parent p :post-blank 0 :post-affiliated b)))
  18918. (_ e))))
  18919. (defun org--forward-paragraph-once ()
  18920. "Move forward to end of paragraph or equivalent, once.
  18921. See `org-forward-paragraph'."
  18922. (interactive)
  18923. (save-restriction
  18924. (widen)
  18925. (skip-chars-forward " \t\n")
  18926. (cond
  18927. ((eobp) nil)
  18928. ;; When inside a folded part, move out of it.
  18929. ((when (org-invisible-p nil t)
  18930. (goto-char (cdr (org-fold-get-region-at-point)))
  18931. (forward-line)
  18932. t))
  18933. (t
  18934. (let* ((element (org--paragraph-at-point))
  18935. (type (org-element-type element))
  18936. (contents-begin (org-element-property :contents-begin element))
  18937. (end (org-element-property :end element))
  18938. (post-affiliated (org-element-property :post-affiliated element)))
  18939. (cond
  18940. ((eq type 'plain-list)
  18941. (forward-char)
  18942. (org--forward-paragraph-once))
  18943. ;; If the element is folded, skip it altogether.
  18944. ((when (org-with-point-at post-affiliated (org-invisible-p (line-end-position) t))
  18945. (goto-char (cdr (org-fold-get-region-at-point
  18946. nil
  18947. (org-with-point-at post-affiliated
  18948. (line-end-position)))))
  18949. (forward-line)
  18950. t))
  18951. ;; At a greater element, move inside.
  18952. ((and contents-begin
  18953. (> contents-begin (point))
  18954. (not (eq type 'paragraph)))
  18955. (goto-char contents-begin)
  18956. ;; Items and footnote definitions contents may not start at
  18957. ;; the beginning of the line. In this case, skip until the
  18958. ;; next paragraph.
  18959. (cond
  18960. ((not (bolp)) (org--forward-paragraph-once))
  18961. ((org-previous-line-empty-p) (forward-line -1))
  18962. (t nil)))
  18963. ;; Move between empty lines in some blocks.
  18964. ((memq type '(comment-block example-block export-block src-block
  18965. verse-block))
  18966. (let ((contents-start
  18967. (org-with-point-at post-affiliated
  18968. (line-beginning-position 2))))
  18969. (if (< (point) contents-start)
  18970. (goto-char contents-start)
  18971. (let ((contents-end
  18972. (org-with-point-at end
  18973. (skip-chars-backward " \t\n")
  18974. (line-beginning-position))))
  18975. (cond
  18976. ((>= (point) contents-end)
  18977. (goto-char end)
  18978. (skip-chars-backward " \t\n")
  18979. (forward-line))
  18980. ((re-search-forward "^[ \t]*\n" contents-end :move)
  18981. (forward-line -1))
  18982. (t nil))))))
  18983. (t
  18984. ;; Move to element's end.
  18985. (goto-char end)
  18986. (skip-chars-backward " \t\n")
  18987. (forward-line))))))))
  18988. (defun org--backward-paragraph-once ()
  18989. "Move backward to start of paragraph or equivalent, once.
  18990. See `org-backward-paragraph'."
  18991. (interactive)
  18992. (save-restriction
  18993. (widen)
  18994. (cond
  18995. ((bobp) nil)
  18996. ;; Blank lines at the beginning of the buffer.
  18997. ((and (org-match-line "^[ \t]*$")
  18998. (save-excursion (skip-chars-backward " \t\n") (bobp)))
  18999. (goto-char (point-min)))
  19000. ;; When inside a folded part, move out of it.
  19001. ((when (org-invisible-p (1- (point)) t)
  19002. (goto-char (1- (car (org-fold-get-region-at-point nil (1- (point))))))
  19003. (org--backward-paragraph-once)
  19004. t))
  19005. (t
  19006. (let* ((element (org--paragraph-at-point))
  19007. (type (org-element-type element))
  19008. (begin (org-element-property :begin element))
  19009. (post-affiliated (org-element-property :post-affiliated element))
  19010. (contents-end (org-element-property :contents-end element))
  19011. (end (org-element-property :end element))
  19012. (parent (org-element-property :parent element))
  19013. (reach
  19014. ;; Move to the visible empty line above position P, or
  19015. ;; to position P. Return t.
  19016. (lambda (p)
  19017. (goto-char p)
  19018. (when (and (org-previous-line-empty-p)
  19019. (let ((end (line-end-position 0)))
  19020. (or (= end (point-min))
  19021. (not (org-invisible-p (1- end))))))
  19022. (forward-line -1))
  19023. t)))
  19024. (cond
  19025. ;; Already at the beginning of an element.
  19026. ((= begin (point))
  19027. (cond
  19028. ;; There is a blank line above. Move there.
  19029. ((and (org-previous-line-empty-p)
  19030. (not (org-invisible-p (1- (line-end-position 0)))))
  19031. (forward-line -1))
  19032. ;; At the beginning of the first element within a greater
  19033. ;; element. Move to the beginning of the greater element.
  19034. ((and parent
  19035. (not (eq 'section (org-element-type parent)))
  19036. (= begin (org-element-property :contents-begin parent)))
  19037. (funcall reach (org-element-property :begin parent)))
  19038. ;; Since we have to move anyway, find the beginning
  19039. ;; position of the element above.
  19040. (t
  19041. (forward-char -1)
  19042. (org--backward-paragraph-once))))
  19043. ;; Skip paragraphs at the very beginning of footnote
  19044. ;; definitions or items.
  19045. ((and (eq type 'paragraph)
  19046. (org-with-point-at begin (not (bolp))))
  19047. (funcall reach (progn (goto-char begin) (line-beginning-position))))
  19048. ;; If the element is folded, skip it altogether.
  19049. ((org-with-point-at post-affiliated (org-invisible-p (line-end-position) t))
  19050. (funcall reach begin))
  19051. ;; At the end of a greater element, move inside.
  19052. ((and contents-end
  19053. (<= contents-end (point))
  19054. (not (eq type 'paragraph)))
  19055. (cond
  19056. ((memq type '(footnote-definition plain-list))
  19057. (skip-chars-backward " \t\n")
  19058. (org--backward-paragraph-once))
  19059. ((= contents-end (point))
  19060. (forward-char -1)
  19061. (org--backward-paragraph-once))
  19062. (t
  19063. (goto-char contents-end))))
  19064. ;; Move between empty lines in some blocks.
  19065. ((and (memq type '(comment-block example-block export-block src-block
  19066. verse-block))
  19067. (let ((contents-start
  19068. (org-with-point-at post-affiliated
  19069. (line-beginning-position 2))))
  19070. (when (> (point) contents-start)
  19071. (let ((contents-end
  19072. (org-with-point-at end
  19073. (skip-chars-backward " \t\n")
  19074. (line-beginning-position))))
  19075. (if (> (point) contents-end)
  19076. (progn (goto-char contents-end) t)
  19077. (skip-chars-backward " \t\n" begin)
  19078. (re-search-backward "^[ \t]*\n" contents-start :move)
  19079. t))))))
  19080. ;; Move to element's start.
  19081. (t
  19082. (funcall reach begin))))))))
  19083. (defun org-forward-element ()
  19084. "Move forward by one element.
  19085. Move to the next element at the same level, when possible."
  19086. (interactive)
  19087. (cond ((eobp) (user-error "Cannot move further down"))
  19088. ((org-with-limited-levels (org-at-heading-p))
  19089. (let ((origin (point)))
  19090. (goto-char (org-end-of-subtree nil t))
  19091. (unless (org-with-limited-levels (org-at-heading-p))
  19092. (goto-char origin)
  19093. (user-error "Cannot move further down"))))
  19094. (t
  19095. (let* ((elem (org-element-at-point))
  19096. (end (org-element-property :end elem))
  19097. (parent (org-element-property :parent elem)))
  19098. (cond ((and parent (= (org-element-property :contents-end parent) end))
  19099. (goto-char (org-element-property :end parent)))
  19100. ((integer-or-marker-p end) (goto-char end))
  19101. (t (message "No element at point")))))))
  19102. (defun org-backward-element ()
  19103. "Move backward by one element.
  19104. Move to the previous element at the same level, when possible."
  19105. (interactive)
  19106. (cond ((bobp) (user-error "Cannot move further up"))
  19107. ((org-with-limited-levels (org-at-heading-p))
  19108. ;; At a headline, move to the previous one, if any, or stay
  19109. ;; here.
  19110. (let ((origin (point)))
  19111. (org-with-limited-levels (org-backward-heading-same-level 1))
  19112. ;; When current headline has no sibling above, move to its
  19113. ;; parent.
  19114. (when (= (point) origin)
  19115. (or (org-with-limited-levels (org-up-heading-safe))
  19116. (progn (goto-char origin)
  19117. (user-error "Cannot move further up"))))))
  19118. (t
  19119. (let* ((elem (org-element-at-point))
  19120. (beg (org-element-property :begin elem)))
  19121. (cond
  19122. ;; Move to beginning of current element if point isn't
  19123. ;; there already.
  19124. ((null beg) (message "No element at point"))
  19125. ((/= (point) beg) (goto-char beg))
  19126. (t (goto-char beg)
  19127. (skip-chars-backward " \r\t\n")
  19128. (unless (bobp)
  19129. (let ((prev (org-element-at-point)))
  19130. (goto-char (org-element-property :begin prev))
  19131. (while (and (setq prev (org-element-property :parent prev))
  19132. (<= (org-element-property :end prev) beg))
  19133. (goto-char (org-element-property :begin prev)))))))))))
  19134. (defun org-up-element ()
  19135. "Move to upper element."
  19136. (interactive)
  19137. (if (org-with-limited-levels (org-at-heading-p))
  19138. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19139. (let* ((elem (org-element-at-point))
  19140. (parent (org-element-property :parent elem)))
  19141. (if (and parent
  19142. (not (memq (org-element-type parent) '(section org-data))))
  19143. (goto-char (org-element-property :begin parent))
  19144. (if (org-with-limited-levels (org-before-first-heading-p))
  19145. (user-error "No surrounding element")
  19146. (org-with-limited-levels (org-back-to-heading)))))))
  19147. (defun org-down-element ()
  19148. "Move to inner element."
  19149. (interactive)
  19150. (let ((element (org-element-at-point)))
  19151. (cond
  19152. ((memq (org-element-type element) '(plain-list table))
  19153. (goto-char (org-element-property :contents-begin element))
  19154. (forward-char))
  19155. ((memq (org-element-type element) org-element-greater-elements)
  19156. ;; If contents are hidden, first disclose them.
  19157. (when (org-invisible-p (line-end-position)) (org-cycle))
  19158. (goto-char (or (org-element-property :contents-begin element)
  19159. (user-error "No content for this element"))))
  19160. (t (user-error "No inner element")))))
  19161. (defun org-drag-element-backward ()
  19162. "Move backward element at point."
  19163. (interactive)
  19164. (let ((elem (or (org-element-at-point)
  19165. (user-error "No element at point"))))
  19166. (if (eq (org-element-type elem) 'headline)
  19167. ;; Preserve point when moving a whole tree, even if point was
  19168. ;; on blank lines below the headline.
  19169. (let ((offset (skip-chars-backward " \t\n")))
  19170. (unwind-protect (org-move-subtree-up)
  19171. (forward-char (- offset))))
  19172. (let ((prev-elem
  19173. (save-excursion
  19174. (goto-char (org-element-property :begin elem))
  19175. (skip-chars-backward " \r\t\n")
  19176. (unless (bobp)
  19177. (let* ((beg (org-element-property :begin elem))
  19178. (prev (org-element-at-point))
  19179. (up prev))
  19180. (while (and (setq up (org-element-property :parent up))
  19181. (<= (org-element-property :end up) beg))
  19182. (setq prev up))
  19183. prev)))))
  19184. ;; Error out if no previous element or previous element is
  19185. ;; a parent of the current one.
  19186. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19187. (user-error "Cannot drag element backward")
  19188. (let ((pos (point)))
  19189. (org-element-swap-A-B prev-elem elem)
  19190. (goto-char (+ (org-element-property :begin prev-elem)
  19191. (- pos (org-element-property :begin elem))))))))))
  19192. (defun org-drag-element-forward ()
  19193. "Move forward element at point."
  19194. (interactive)
  19195. (let* ((pos (point))
  19196. (elem (or (org-element-at-point)
  19197. (user-error "No element at point"))))
  19198. (when (= (point-max) (org-element-property :end elem))
  19199. (user-error "Cannot drag element forward"))
  19200. (goto-char (org-element-property :end elem))
  19201. (let ((next-elem (org-element-at-point)))
  19202. (when (or (org-element-nested-p elem next-elem)
  19203. (and (eq (org-element-type next-elem) 'headline)
  19204. (not (eq (org-element-type elem) 'headline))))
  19205. (goto-char pos)
  19206. (user-error "Cannot drag element forward"))
  19207. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19208. ;; body's length (without final blanks) and by the length of
  19209. ;; blanks between ELEM and NEXT-ELEM.
  19210. (let ((size-next (- (save-excursion
  19211. (goto-char (org-element-property :end next-elem))
  19212. (skip-chars-backward " \r\t\n")
  19213. (forward-line)
  19214. ;; Small correction if buffer doesn't end
  19215. ;; with a newline character.
  19216. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19217. (org-element-property :begin next-elem)))
  19218. (size-blank (- (org-element-property :end elem)
  19219. (save-excursion
  19220. (goto-char (org-element-property :end elem))
  19221. (skip-chars-backward " \r\t\n")
  19222. (forward-line)
  19223. (point)))))
  19224. (org-element-swap-A-B elem next-elem)
  19225. (goto-char (+ pos size-next size-blank))))))
  19226. (defun org-drag-line-forward (arg)
  19227. "Drag the line at point ARG lines forward."
  19228. (interactive "p")
  19229. (dotimes (_ (abs arg))
  19230. (let ((c (current-column)))
  19231. (if (< 0 arg)
  19232. (progn
  19233. (beginning-of-line 2)
  19234. (transpose-lines 1)
  19235. (beginning-of-line 0))
  19236. (transpose-lines 1)
  19237. (beginning-of-line -1))
  19238. (org-move-to-column c))))
  19239. (defun org-drag-line-backward (arg)
  19240. "Drag the line at point ARG lines backward."
  19241. (interactive "p")
  19242. (org-drag-line-forward (- arg)))
  19243. (defun org-mark-element ()
  19244. "Put point at beginning of this element, mark at end.
  19245. Interactively, if this command is repeated or (in Transient Mark
  19246. mode) if the mark is active, it marks the next element after the
  19247. ones already marked."
  19248. (interactive)
  19249. (let (deactivate-mark)
  19250. (if (and (called-interactively-p 'any)
  19251. (or (and (eq last-command this-command) (mark t))
  19252. (and transient-mark-mode mark-active)))
  19253. (set-mark
  19254. (save-excursion
  19255. (goto-char (mark))
  19256. (goto-char (org-element-property :end (org-element-at-point)))
  19257. (point)))
  19258. (let ((element (org-element-at-point)))
  19259. (end-of-line)
  19260. (push-mark (min (point-max) (org-element-property :end element)) t t)
  19261. (goto-char (org-element-property :begin element))))))
  19262. (defun org-narrow-to-element ()
  19263. "Narrow buffer to current element."
  19264. (interactive)
  19265. (let ((elem (org-element-at-point)))
  19266. (cond
  19267. ((eq (car elem) 'headline)
  19268. (narrow-to-region
  19269. (org-element-property :begin elem)
  19270. (org-element-property :end elem)))
  19271. ((memq (car elem) org-element-greater-elements)
  19272. (narrow-to-region
  19273. (org-element-property :contents-begin elem)
  19274. (org-element-property :contents-end elem)))
  19275. (t
  19276. (narrow-to-region
  19277. (org-element-property :begin elem)
  19278. (org-element-property :end elem))))))
  19279. (defun org-transpose-element ()
  19280. "Transpose current and previous elements, keeping blank lines between.
  19281. Point is moved after both elements."
  19282. (interactive)
  19283. (org-skip-whitespace)
  19284. (let ((end (org-element-property :end (org-element-at-point))))
  19285. (org-drag-element-backward)
  19286. (goto-char end)))
  19287. (defun org-unindent-buffer ()
  19288. "Un-indent the visible part of the buffer.
  19289. Relative indentation (between items, inside blocks, etc.) isn't
  19290. modified."
  19291. (interactive)
  19292. (unless (eq major-mode 'org-mode)
  19293. (user-error "Cannot un-indent a buffer not in Org mode"))
  19294. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19295. (unindent-tree
  19296. (lambda (contents)
  19297. (dolist (element (reverse contents))
  19298. (if (memq (org-element-type element) '(headline section))
  19299. (funcall unindent-tree (org-element-contents element))
  19300. (save-excursion
  19301. (save-restriction
  19302. (narrow-to-region
  19303. (org-element-property :begin element)
  19304. (org-element-property :end element))
  19305. (org-do-remove-indentation))))))))
  19306. (funcall unindent-tree (org-element-contents parse-tree))))
  19307. (defun org-make-options-regexp (kwds &optional extra)
  19308. "Make a regular expression for keyword lines.
  19309. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19310. when non-nil, is a regexp matching keywords names."
  19311. (concat "^[ \t]*#\\+\\("
  19312. (regexp-opt kwds)
  19313. (and extra (concat (and kwds "\\|") extra))
  19314. "\\):[ \t]*\\(.*\\)"))
  19315. ;;; Conveniently switch to Info nodes
  19316. (defun org-info-find-node (&optional nodename)
  19317. "Find Info documentation NODENAME or Org documentation according context.
  19318. Started from `gnus-info-find-node'."
  19319. (interactive)
  19320. (Info-goto-node
  19321. (or nodename
  19322. (let ((default-org-info-node "(org) Top"))
  19323. (cond
  19324. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19325. ((eq 'org-mode major-mode)
  19326. (let* ((context (org-element-at-point))
  19327. (element-info-nodes ; compare to `org-element-all-elements'.
  19328. `((babel-call . "(org) Evaluating Code Blocks")
  19329. (center-block . "(org) Paragraphs")
  19330. (clock . ,default-org-info-node)
  19331. (comment . "(org) Comment Lines")
  19332. (comment-block . "(org) Comment Lines")
  19333. (diary-sexp . ,default-org-info-node)
  19334. (drawer . "(org) Drawers")
  19335. (dynamic-block . "(org) Dynamic Blocks")
  19336. (example-block . "(org) Literal Examples")
  19337. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19338. (fixed-width . ,default-org-info-node)
  19339. (footnote-definition . "(org) Creating Footnotes")
  19340. (headline . "(org) Document Structure")
  19341. (horizontal-rule . "(org) Built-in Table Editor")
  19342. (inlinetask . ,default-org-info-node)
  19343. (item . "(org) Plain Lists")
  19344. (keyword . "(org) Per-file keywords")
  19345. (latex-environment . "(org) LaTeX Export")
  19346. (node-property . "(org) Properties and Columns")
  19347. (paragraph . "(org) Paragraphs")
  19348. (plain-list . "(org) Plain Lists")
  19349. (planning . "(org) Deadlines and Scheduling")
  19350. (property-drawer . "(org) Properties and Columns")
  19351. (quote-block . "(org) Paragraphs")
  19352. (section . ,default-org-info-node)
  19353. (special-block . ,default-org-info-node)
  19354. (src-block . "(org) Working with Source Code")
  19355. (table . "(org) Tables")
  19356. (table-row . "(org) Tables")
  19357. (verse-block . "(org) Paragraphs"))))
  19358. (or (cdr (assoc (car context) element-info-nodes))
  19359. default-org-info-node)))
  19360. (t default-org-info-node))))))
  19361. ;;; Finish up
  19362. (add-hook 'org-mode-hook ;remove folds when changing major mode
  19363. (lambda () (add-hook 'change-major-mode-hook
  19364. 'org-fold-show-all 'append 'local)))
  19365. (provide 'org)
  19366. (run-hooks 'org-load-hook)
  19367. ;;; org.el ends here