org.el 873 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080
  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-2018 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: https://orgmode.org
  9. ;; Version: 9.3
  10. ;;
  11. ;; This file is part of GNU Emacs.
  12. ;;
  13. ;; GNU Emacs is free software: you can redistribute it and/or modify
  14. ;; it under the terms of the GNU General Public License as published by
  15. ;; the Free Software Foundation, either version 3 of the License, or
  16. ;; (at your option) any later version.
  17. ;; GNU Emacs is distributed in the hope that it will be useful,
  18. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. ;; GNU General Public License for more details.
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  23. ;;
  24. ;;; Commentary:
  25. ;;
  26. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  27. ;; project planning with a fast and effective plain-text system.
  28. ;;
  29. ;; Org mode develops organizational tasks around NOTES files that
  30. ;; contain information about projects as plain text. Org mode is
  31. ;; implemented on top of outline-mode, which makes it possible to keep
  32. ;; the content of large files well structured. Visibility cycling and
  33. ;; structure editing help to work with the tree. Tables are easily
  34. ;; created with a built-in table editor. Org mode supports ToDo
  35. ;; items, deadlines, time stamps, and scheduling. It dynamically
  36. ;; compiles entries into an agenda that utilizes and smoothly
  37. ;; integrates much of the Emacs calendar and diary. Plain text
  38. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  39. ;; entries, and any files related to the projects. For printing and
  40. ;; sharing of notes, an Org file can be exported as a structured ASCII
  41. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  42. ;; file. It can also serve as a publishing tool for a set of linked
  43. ;; webpages.
  44. ;;
  45. ;; Installation and Activation
  46. ;; ---------------------------
  47. ;; See the corresponding sections in the manual at
  48. ;;
  49. ;; https://orgmode.org/org.html#Installation
  50. ;;
  51. ;; Documentation
  52. ;; -------------
  53. ;; The documentation of Org mode can be found in the TeXInfo file. The
  54. ;; distribution also contains a PDF version of it. At the homepage of
  55. ;; Org mode, you can read the same text online as HTML. There is also an
  56. ;; excellent reference card made by Philip Rooke. This card can be found
  57. ;; in the doc/ directory.
  58. ;;
  59. ;; A list of recent changes can be found at
  60. ;; https://orgmode.org/Changes.html
  61. ;;
  62. ;;; Code:
  63. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  64. (defvar-local org-table-formula-constants-local nil
  65. "Local version of `org-table-formula-constants'.")
  66. (defvar org-inlinetask-min-level)
  67. ;;;; Require other packages
  68. (require 'cl-lib)
  69. (eval-when-compile (require 'gnus-sum))
  70. (require 'calendar)
  71. (require 'find-func)
  72. (require 'format-spec)
  73. (or (eq this-command 'eval-buffer)
  74. (condition-case nil
  75. (load (concat (file-name-directory load-file-name)
  76. "org-loaddefs.el")
  77. nil t t t)
  78. (error
  79. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  80. (sit-for 3)
  81. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  82. (sit-for 3))))
  83. (eval-and-compile (require 'org-macs))
  84. (require 'org-compat)
  85. (require 'org-keys)
  86. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  87. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  88. (defvar org-outline-regexp "\\*+ "
  89. "Regexp to match Org headlines.")
  90. (defvar org-outline-regexp-bol "^\\*+ "
  91. "Regexp to match Org headlines.
  92. This is similar to `org-outline-regexp' but additionally makes
  93. sure that we are at the beginning of the line.")
  94. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  95. "Matches a headline, putting stars and text into groups.
  96. Stars are put in group 1 and the trimmed body in group 2.")
  97. (declare-function calendar-check-holidays "holidays" (date))
  98. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  99. (declare-function cdlatex-math-symbol "ext:cdlatex")
  100. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  101. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  102. (declare-function org-add-archive-files "org-archive" (files))
  103. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  104. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  105. (declare-function org-agenda-redo "org-agenda" (&optional all))
  106. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  107. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  108. (declare-function org-archive-subtree-default "org-archive" ())
  109. (declare-function org-archive-to-archive-sibling "org-archive" ())
  110. (declare-function org-attach "org-attach" ())
  111. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  112. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  113. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  114. (declare-function org-clock-cancel "org-clock" ())
  115. (declare-function org-clock-display "org-clock" (&optional arg))
  116. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  117. (declare-function org-clock-goto "org-clock" (&optional select))
  118. (declare-function org-clock-in "org-clock" (&optional select start-time))
  119. (declare-function org-clock-in-last "org-clock" (&optional arg))
  120. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  121. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  122. (declare-function org-clock-report "org-clock" (&optional arg))
  123. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  124. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  125. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  126. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  127. (declare-function org-clock-update-time-maybe "org-clock" ())
  128. (declare-function org-clocking-buffer "org-clock" ())
  129. (declare-function org-clocktable-shift "org-clock" (dir n))
  130. (declare-function org-columns-insert-dblock "org-colview" ())
  131. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  132. (declare-function org-element-at-point "org-element" ())
  133. (declare-function org-element-cache-refresh "org-element" (pos))
  134. (declare-function org-element-cache-reset "org-element" (&optional all))
  135. (declare-function org-element-contents "org-element" (element))
  136. (declare-function org-element-context "org-element" (&optional element))
  137. (declare-function org-element-copy "org-element" (datum))
  138. (declare-function org-element-create "org-element" (type &optional props &rest children))
  139. (declare-function org-element-interpret-data "org-element" (data))
  140. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  141. (declare-function org-element-link-parser "org-element" ())
  142. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  143. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  144. (declare-function org-element-property "org-element" (property element))
  145. (declare-function org-element-put-property "org-element" (element property value))
  146. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  147. (declare-function org-element-timestamp-parser "org-element" ())
  148. (declare-function org-element-type "org-element" (element))
  149. (declare-function org-element-update-syntax "org-element" ())
  150. (declare-function org-export-dispatch "ox" (&optional arg))
  151. (declare-function org-export-get-backend "ox" (name))
  152. (declare-function org-export-get-backend "ox" (name))
  153. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  154. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  155. (declare-function org-feed-goto-inbox "org-feed" (feed))
  156. (declare-function org-feed-update-all "org-feed" ())
  157. (declare-function org-goto "org-goto" (&optional alternative-interface))
  158. (declare-function org-goto "org-goto" (&optional alternative-interface))
  159. (declare-function org-id-find-id-file "org-id" (id))
  160. (declare-function org-id-get-create "org-id" (&optional force))
  161. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  162. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  163. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  164. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  165. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  166. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  167. (declare-function org-table--shrunk-field "org-table" ()) ;; For `org-table-with-shrunk-field'.
  168. (declare-function org-table-align "org-table" ())
  169. (declare-function org-table-begin "org-table" (&optional table-type))
  170. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  171. (declare-function org-table-blank-field "org-table" ())
  172. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  173. (declare-function org-table-copy-down "org-table" (N))
  174. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  175. (declare-function org-table-create-or-convert-from-region "org-table" (arg))
  176. (declare-function org-table-create-with-table.el "org-table" ())
  177. (declare-function org-table-cut-region "org-table" (beg end))
  178. (declare-function org-table-edit-field "org-table" (arg))
  179. (declare-function org-table-end "org-table" (&optional table-type))
  180. (declare-function org-table-end-of-field "org-table" (&optional n))
  181. (declare-function org-table-eval-formula "org-table" (&optional arg equation suppress-align suppress-const suppress-store suppress-analysis))
  182. (declare-function org-table-field-info "org-table" (arg))
  183. (declare-function org-table-insert-row "org-table" (&optional arg))
  184. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  185. (declare-function org-table-maybe-eval-formula "org-table" ())
  186. (declare-function org-table-maybe-recalculate-line "org-table" ())
  187. (declare-function org-table-next-row "org-table" ())
  188. (declare-function org-table-paste-rectangle "org-table" ())
  189. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  190. (declare-function org-table-rotate-recalc-marks "org-table" (&optional newchar))
  191. (declare-function org-table-shrink "org-table" (&optional begin end))
  192. (declare-function org-table-sort-lines "org-table" (&optional with-case sorting-type getkey-func compare-func interactive?))
  193. (declare-function org-table-sum "org-table" (&optional beg end nlast))
  194. (declare-function org-table-toggle-column-width "org-table" (&optional arg))
  195. (declare-function org-table-toggle-coordinate-overlays "org-table" ())
  196. (declare-function org-table-toggle-formula-debugger "org-table" ())
  197. (declare-function org-table-wrap-region "org-table" (arg))
  198. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  199. (declare-function org-timer "org-timer" (&optional restart no-insert))
  200. (declare-function org-timer-item "org-timer" (&optional arg))
  201. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  202. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  203. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  204. (declare-function org-timer-start "org-timer" (&optional offset))
  205. (declare-function org-timer-stop "org-timer" ())
  206. (declare-function org-timer-stop "org-timer" ())
  207. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  208. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  209. (declare-function orgtbl-mode "org-table" (&optional arg))
  210. (defvar ffap-url-regexp)
  211. (defvar org-element-paragraph-separate)
  212. (defvar org-indent-indentation-per-level)
  213. (defvar org-table-auto-blank-field)
  214. ;; load languages based on value of `org-babel-load-languages'
  215. (defvar org-babel-load-languages)
  216. ;;;###autoload
  217. (defun org-babel-do-load-languages (sym value)
  218. "Load the languages defined in `org-babel-load-languages'."
  219. (set-default sym value)
  220. (dolist (pair org-babel-load-languages)
  221. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  222. (if active
  223. (require (intern (concat "ob-" lang)))
  224. (fmakunbound
  225. (intern (concat "org-babel-execute:" lang)))
  226. (fmakunbound
  227. (intern (concat "org-babel-expand-body:" lang)))))))
  228. ;;;###autoload
  229. (defun org-babel-load-file (file &optional compile)
  230. "Load Emacs Lisp source code blocks in the Org FILE.
  231. This function exports the source code using `org-babel-tangle'
  232. and then loads the resulting file using `load-file'. With
  233. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  234. byte-compiled before it is loaded."
  235. (interactive "fFile to load: \nP")
  236. (let* ((tangled-file (concat (file-name-sans-extension file) ".el")))
  237. ;; Tangle only if the Org file is newer than the Elisp file.
  238. (unless (org-file-newer-than-p tangled-file (nth 5 (file-attributes file)))
  239. (org-babel-tangle-file file tangled-file "emacs-lisp"))
  240. (if compile
  241. (progn
  242. (byte-compile-file tangled-file 'load)
  243. (message "Compiled and loaded %s" tangled-file))
  244. (load-file tangled-file)
  245. (message "Loaded %s" tangled-file))))
  246. (defcustom org-babel-load-languages '((emacs-lisp . t))
  247. "Languages which can be evaluated in Org buffers.
  248. \\<org-mode-map>
  249. This list can be used to load support for any of the languages
  250. below. Each language will depend on a different set of system
  251. executables and/or Emacs modes.
  252. When a language is \"loaded\", code blocks in that language can
  253. be evaluated with `org-babel-execute-src-block', which is bound
  254. by default to \\[org-ctrl-c-ctrl-c].
  255. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  256. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  257. default, only Emacs Lisp is loaded, since it has no specific
  258. requirement."
  259. :group 'org-babel
  260. :set 'org-babel-do-load-languages
  261. :version "24.1"
  262. :type '(alist :tag "Babel Languages"
  263. :key-type
  264. (choice
  265. (const :tag "Awk" awk)
  266. (const :tag "C" C)
  267. (const :tag "R" R)
  268. (const :tag "Asymptote" asymptote)
  269. (const :tag "Calc" calc)
  270. (const :tag "Clojure" clojure)
  271. (const :tag "CSS" css)
  272. (const :tag "Ditaa" ditaa)
  273. (const :tag "Dot" dot)
  274. (const :tag "Ebnf2ps" ebnf2ps)
  275. (const :tag "Emacs Lisp" emacs-lisp)
  276. (const :tag "Forth" forth)
  277. (const :tag "Fortran" fortran)
  278. (const :tag "Gnuplot" gnuplot)
  279. (const :tag "Haskell" haskell)
  280. (const :tag "hledger" hledger)
  281. (const :tag "IO" io)
  282. (const :tag "J" J)
  283. (const :tag "Java" java)
  284. (const :tag "Javascript" js)
  285. (const :tag "LaTeX" latex)
  286. (const :tag "Ledger" ledger)
  287. (const :tag "Lilypond" lilypond)
  288. (const :tag "Lisp" lisp)
  289. (const :tag "Makefile" makefile)
  290. (const :tag "Maxima" maxima)
  291. (const :tag "Matlab" matlab)
  292. (const :tag "Mscgen" mscgen)
  293. (const :tag "Ocaml" ocaml)
  294. (const :tag "Octave" octave)
  295. (const :tag "Org" org)
  296. (const :tag "Perl" perl)
  297. (const :tag "Pico Lisp" picolisp)
  298. (const :tag "PlantUML" plantuml)
  299. (const :tag "Python" python)
  300. (const :tag "Ruby" ruby)
  301. (const :tag "Sass" sass)
  302. (const :tag "Scala" scala)
  303. (const :tag "Scheme" scheme)
  304. (const :tag "Screen" screen)
  305. (const :tag "Shell Script" shell)
  306. (const :tag "Shen" shen)
  307. (const :tag "Sql" sql)
  308. (const :tag "Sqlite" sqlite)
  309. (const :tag "Stan" stan)
  310. (const :tag "Vala" vala))
  311. :value-type (boolean :tag "Activate" :value t)))
  312. ;;;; Customization variables
  313. (defcustom org-clone-delete-id nil
  314. "Remove ID property of clones of a subtree.
  315. When non-nil, clones of a subtree don't inherit the ID property.
  316. Otherwise they inherit the ID property with a new unique
  317. identifier."
  318. :type 'boolean
  319. :version "24.1"
  320. :group 'org-id)
  321. ;;; Version
  322. (org-check-version)
  323. ;;;###autoload
  324. (defun org-version (&optional here full message)
  325. "Show the Org version.
  326. Interactively, or when MESSAGE is non-nil, show it in echo area.
  327. With prefix argument, or when HERE is non-nil, insert it at point.
  328. In non-interactive uses, a reduced version string is output unless
  329. FULL is given."
  330. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  331. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  332. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  333. (load-suffixes (list ".el"))
  334. (org-install-dir
  335. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  336. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  337. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  338. (let* ((load-suffixes save-load-suffixes)
  339. (release (org-release))
  340. (git-version (org-git-version))
  341. (version (format "Org mode version %s (%s @ %s)"
  342. release
  343. git-version
  344. (if org-install-dir
  345. (if (string= org-dir org-install-dir)
  346. org-install-dir
  347. (concat "mixed installation! "
  348. org-install-dir
  349. " and "
  350. org-dir))
  351. "org-loaddefs.el can not be found!")))
  352. (version1 (if full version release)))
  353. (when here (insert version1))
  354. (when message (message "%s" version1))
  355. version1)))
  356. (defconst org-version (org-version))
  357. ;;; Syntax Constants
  358. ;;;; Block
  359. (defconst org-block-regexp
  360. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  361. "Regular expression for hiding blocks.")
  362. (defconst org-dblock-start-re
  363. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  364. "Matches the start line of a dynamic block, with parameters.")
  365. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  366. "Matches the end of a dynamic block.")
  367. ;;;; Clock and Planning
  368. (defconst org-clock-string "CLOCK:"
  369. "String used as prefix for timestamps clocking work hours on an item.")
  370. (defvar org-closed-string "CLOSED:"
  371. "String used as the prefix for timestamps logging closing a TODO entry.")
  372. (defvar org-deadline-string "DEADLINE:"
  373. "String to mark deadline entries.
  374. \\<org-mode-map>
  375. A deadline is this string, followed by a time stamp. It must be
  376. a word, terminated by a colon. You can insert a schedule keyword
  377. and a timestamp with `\\[org-deadline]'.")
  378. (defvar org-scheduled-string "SCHEDULED:"
  379. "String to mark scheduled TODO entries.
  380. \\<org-mode-map>
  381. A schedule is this string, followed by a time stamp. It must be
  382. a word, terminated by a colon. You can insert a schedule keyword
  383. and a timestamp with `\\[org-schedule]'.")
  384. (defconst org-ds-keyword-length
  385. (+ 2
  386. (apply #'max
  387. (mapcar #'length
  388. (list org-deadline-string org-scheduled-string
  389. org-clock-string org-closed-string))))
  390. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  391. (defconst org-planning-line-re
  392. (concat "^[ \t]*"
  393. (regexp-opt
  394. (list org-closed-string org-deadline-string org-scheduled-string)
  395. t))
  396. "Matches a line with planning info.
  397. Matched keyword is in group 1.")
  398. (defconst org-clock-line-re
  399. (concat "^[ \t]*" org-clock-string)
  400. "Matches a line with clock info.")
  401. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  402. "Matches the DEADLINE keyword.")
  403. (defconst org-deadline-time-regexp
  404. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  405. "Matches the DEADLINE keyword together with a time stamp.")
  406. (defconst org-deadline-time-hour-regexp
  407. (concat "\\<" org-deadline-string
  408. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  409. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  410. (defconst org-deadline-line-regexp
  411. (concat "\\<\\(" org-deadline-string "\\).*")
  412. "Matches the DEADLINE keyword and the rest of the line.")
  413. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  414. "Matches the SCHEDULED keyword.")
  415. (defconst org-scheduled-time-regexp
  416. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  417. "Matches the SCHEDULED keyword together with a time stamp.")
  418. (defconst org-scheduled-time-hour-regexp
  419. (concat "\\<" org-scheduled-string
  420. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  421. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  422. (defconst org-closed-time-regexp
  423. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  424. "Matches the CLOSED keyword together with a time stamp.")
  425. (defconst org-keyword-time-regexp
  426. (concat "\\<"
  427. (regexp-opt
  428. (list org-scheduled-string org-deadline-string org-closed-string
  429. org-clock-string)
  430. t)
  431. " *[[<]\\([^]>]+\\)[]>]")
  432. "Matches any of the 4 keywords, together with the time stamp.")
  433. (defconst org-keyword-time-not-clock-regexp
  434. (concat
  435. "\\<"
  436. (regexp-opt
  437. (list org-scheduled-string org-deadline-string org-closed-string) t)
  438. " *[[<]\\([^]>]+\\)[]>]")
  439. "Matches any of the 3 keywords, together with the time stamp.")
  440. (defconst org-maybe-keyword-time-regexp
  441. (concat "\\(\\<"
  442. (regexp-opt
  443. (list org-scheduled-string org-deadline-string org-closed-string
  444. org-clock-string)
  445. t)
  446. "\\)?"
  447. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  448. "\\|"
  449. "<%%([^\r\n>]*>\\)")
  450. "Matches a timestamp, possibly preceded by a keyword.")
  451. (defconst org-all-time-keywords
  452. (mapcar (lambda (w) (substring w 0 -1))
  453. (list org-scheduled-string org-deadline-string
  454. org-clock-string org-closed-string))
  455. "List of time keywords.")
  456. ;;;; Drawer
  457. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  458. "Matches first or last line of a hidden block.
  459. Group 1 contains drawer's name or \"END\".")
  460. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  461. "Regular expression matching the first line of a property drawer.")
  462. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  463. "Regular expression matching the last line of a property drawer.")
  464. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  465. "Regular expression matching the first line of a clock drawer.")
  466. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  467. "Regular expression matching the last line of a clock drawer.")
  468. (defconst org-property-drawer-re
  469. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  470. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  471. "[ \t]*:END:[ \t]*$")
  472. "Matches an entire property drawer.")
  473. (defconst org-clock-drawer-re
  474. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  475. org-clock-drawer-end-re "\\)\n?")
  476. "Matches an entire clock drawer.")
  477. ;;;; Headline
  478. (defconst org-heading-keyword-regexp-format
  479. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  480. "Printf format for a regexp matching a headline with some keyword.
  481. This regexp will match the headline of any node which has the
  482. exact keyword that is put into the format. The keyword isn't in
  483. any group by default, but the stars and the body are.")
  484. (defconst org-heading-keyword-maybe-regexp-format
  485. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  486. "Printf format for a regexp matching a headline, possibly with some keyword.
  487. This regexp can match any headline with the specified keyword, or
  488. without a keyword. The keyword isn't in any group by default,
  489. but the stars and the body are.")
  490. (defconst org-archive-tag "ARCHIVE"
  491. "The tag that marks a subtree as archived.
  492. An archived subtree does not open during visibility cycling, and does
  493. not contribute to the agenda listings.")
  494. (defconst org-tag-re "[[:alnum:]_@#%]+"
  495. "Regexp matching a single tag.")
  496. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  497. "Regexp matching the tag group at the end of a line, with leading spaces.
  498. Tags are stored in match group 1. Match group 2 stores the tags
  499. without the enclosing colons.")
  500. (defconst org-tag-line-re
  501. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  502. "Regexp matching tags in a headline.
  503. Tags are stored in match group 1. Match group 2 stores the tags
  504. without the enclosing colons.")
  505. (eval-and-compile
  506. (defconst org-comment-string "COMMENT"
  507. "Entries starting with this keyword will never be exported.
  508. \\<org-mode-map>
  509. An entry can be toggled between COMMENT and normal with
  510. `\\[org-toggle-comment]'."))
  511. ;;;; LaTeX Environments and Fragments
  512. (defconst org-latex-regexps
  513. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  514. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  515. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  516. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  517. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  518. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  519. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  520. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  521. "Regular expressions for matching embedded LaTeX.")
  522. ;;;; Node Property
  523. (defconst org-effort-property "Effort"
  524. "The property that is being used to keep track of effort estimates.
  525. Effort estimates given in this property need to have the format H:MM.")
  526. ;;;; Table
  527. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  528. "Detect an org-type or table-type table.")
  529. (defconst org-table-line-regexp "^[ \t]*|"
  530. "Detect an org-type table line.")
  531. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  532. "Detect an org-type table line.")
  533. (defconst org-table-hline-regexp "^[ \t]*|-"
  534. "Detect an org-type table hline.")
  535. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  536. "Detect a table-type table hline.")
  537. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  538. "Detect the first line outside a table when searching from within it.
  539. This works for both table types.")
  540. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  541. "Detect a #+TBLFM line.")
  542. ;;;; Timestamp
  543. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  544. "Regular expression for fast time stamp matching.")
  545. (defconst org-ts-regexp-inactive
  546. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  547. "Regular expression for fast inactive time stamp matching.")
  548. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  549. "Regular expression for fast time stamp matching.")
  550. (defconst org-ts-regexp0
  551. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  552. "Regular expression matching time strings for analysis.
  553. This one does not require the space after the date, so it can be used
  554. on a string that terminates immediately after the date.")
  555. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  556. "Regular expression matching time strings for analysis.")
  557. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  558. "Regular expression matching time stamps, with groups.")
  559. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  560. "Regular expression matching time stamps (also [..]), with groups.")
  561. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  562. "Regular expression matching a time stamp range.")
  563. (defconst org-tr-regexp-both
  564. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  565. "Regular expression matching a time stamp range.")
  566. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  567. org-ts-regexp "\\)?")
  568. "Regular expression matching a time stamp or time stamp range.")
  569. (defconst org-tsr-regexp-both
  570. (concat org-ts-regexp-both "\\(--?-?"
  571. org-ts-regexp-both "\\)?")
  572. "Regular expression matching a time stamp or time stamp range.
  573. The time stamps may be either active or inactive.")
  574. (defconst org-repeat-re
  575. "[[<][0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^]>\n]*?\
  576. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  577. "Regular expression for specifying repeated events.
  578. After a match, group 1 contains the repeat expression.")
  579. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  580. "Formats for `format-time-string' which are used for time stamps.")
  581. ;;; The custom variables
  582. (defgroup org nil
  583. "Outline-based notes management and organizer."
  584. :tag "Org"
  585. :group 'outlines
  586. :group 'calendar)
  587. (defcustom org-mode-hook nil
  588. "Mode hook for Org mode, run after the mode was turned on."
  589. :group 'org
  590. :type 'hook)
  591. (defcustom org-load-hook nil
  592. "Hook that is run after org.el has been loaded."
  593. :group 'org
  594. :type 'hook)
  595. (defcustom org-log-buffer-setup-hook nil
  596. "Hook that is run after an Org log buffer is created."
  597. :group 'org
  598. :version "24.1"
  599. :type 'hook)
  600. (defvar org-modules) ; defined below
  601. (defvar org-modules-loaded nil
  602. "Have the modules been loaded already?")
  603. (defun org-load-modules-maybe (&optional force)
  604. "Load all extensions listed in `org-modules'."
  605. (when (or force (not org-modules-loaded))
  606. (dolist (ext org-modules)
  607. (condition-case nil (require ext)
  608. (error (message "Problems while trying to load feature `%s'" ext))))
  609. (setq org-modules-loaded t)))
  610. (defun org-set-modules (var value)
  611. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  612. (set var value)
  613. (when (featurep 'org)
  614. (org-load-modules-maybe 'force)
  615. (org-element-cache-reset 'all)))
  616. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail org-eww)
  617. "Modules that should always be loaded together with org.el.
  618. If a description starts with <C>, the file is not part of Emacs
  619. and loading it will require that you have downloaded and properly
  620. installed the Org mode distribution.
  621. You can also use this system to load external packages (i.e. neither Org
  622. core modules, nor modules from the CONTRIB directory). Just add symbols
  623. to the end of the list. If the package is called org-xyz.el, then you need
  624. to add the symbol `xyz', and the package must have a call to:
  625. (provide \\='org-xyz)
  626. For export specific modules, see also `org-export-backends'."
  627. :group 'org
  628. :set 'org-set-modules
  629. :version "26.1"
  630. :package-version '(Org . "9.2")
  631. :type
  632. '(set :greedy t
  633. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  634. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  635. (const :tag " crypt: Encryption of subtrees" org-crypt)
  636. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  637. (const :tag " docview: Links to doc-view buffers" org-docview)
  638. (const :tag " eww: Store link to url of eww" org-eww)
  639. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  640. (const :tag " habit: Track your consistency with habits" org-habit)
  641. (const :tag " id: Global IDs for identifying entries" org-id)
  642. (const :tag " info: Links to Info nodes" org-info)
  643. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  644. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  645. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  646. (const :tag " mouse: Additional mouse support" org-mouse)
  647. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  648. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  649. (const :tag " tempo: Fast completion for structures" org-tempo)
  650. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  651. (const :tag " eshell: Support for links to working directories in eshell" org-eshell)
  652. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  653. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  654. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  655. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  656. (const :tag "C collector: Collect properties into tables" org-collector)
  657. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  658. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  659. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  660. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  661. (const :tag "C eval: Include command output as text" org-eval)
  662. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  663. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  664. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  665. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  666. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  667. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  668. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  669. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  670. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  671. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  672. (const :tag "C notify: Notifications for Org-mode" org-notify)
  673. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  674. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  675. (const :tag "C registry: A registry for Org links" org-registry)
  676. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  677. (const :tag "C screenshot: Take and manage screenshots in Org-mode files" org-screenshot)
  678. (const :tag "C secretary: Team management with Org" org-secretary)
  679. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  680. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  681. (const :tag "C track: Keep up with Org mode development" org-track)
  682. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  683. (const :tag "C vm: Links to VM folders/messages" org-vm)
  684. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  685. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  686. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  687. (defvar org-export-registered-backends) ; From ox.el.
  688. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  689. (declare-function org-export-backend-name "ox" (backend) t)
  690. (defcustom org-export-backends '(ascii html icalendar latex odt)
  691. "List of export back-ends that should be always available.
  692. If a description starts with <C>, the file is not part of Emacs
  693. and loading it will require that you have downloaded and properly
  694. installed the Org mode distribution.
  695. Unlike to `org-modules', libraries in this list will not be
  696. loaded along with Org, but only once the export framework is
  697. needed.
  698. This variable needs to be set before org.el is loaded. If you
  699. need to make a change while Emacs is running, use the customize
  700. interface or run the following code, where VAL stands for the new
  701. value of the variable, after updating it:
  702. (progn
  703. (setq org-export-registered-backends
  704. (cl-remove-if-not
  705. (lambda (backend)
  706. (let ((name (org-export-backend-name backend)))
  707. (or (memq name val)
  708. (catch \\='parentp
  709. (dolist (b val)
  710. (and (org-export-derived-backend-p b name)
  711. (throw \\='parentp t)))))))
  712. org-export-registered-backends))
  713. (let ((new-list (mapcar #\\='org-export-backend-name
  714. org-export-registered-backends)))
  715. (dolist (backend val)
  716. (cond
  717. ((not (load (format \"ox-%s\" backend) t t))
  718. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  719. backend))
  720. ((not (memq backend new-list)) (push backend new-list))))
  721. (set-default \\='org-export-backends new-list)))
  722. Adding a back-end to this list will also pull the back-end it
  723. depends on, if any."
  724. :group 'org
  725. :group 'org-export
  726. :version "26.1"
  727. :package-version '(Org . "9.0")
  728. :initialize 'custom-initialize-set
  729. :set (lambda (var val)
  730. (if (not (featurep 'ox)) (set-default var val)
  731. ;; Any back-end not required anymore (not present in VAL and not
  732. ;; a parent of any back-end in the new value) is removed from the
  733. ;; list of registered back-ends.
  734. (setq org-export-registered-backends
  735. (cl-remove-if-not
  736. (lambda (backend)
  737. (let ((name (org-export-backend-name backend)))
  738. (or (memq name val)
  739. (catch 'parentp
  740. (dolist (b val)
  741. (and (org-export-derived-backend-p b name)
  742. (throw 'parentp t)))))))
  743. org-export-registered-backends))
  744. ;; Now build NEW-LIST of both new back-ends and required
  745. ;; parents.
  746. (let ((new-list (mapcar #'org-export-backend-name
  747. org-export-registered-backends)))
  748. (dolist (backend val)
  749. (cond
  750. ((not (load (format "ox-%s" backend) t t))
  751. (message "Problems while trying to load export back-end `%s'"
  752. backend))
  753. ((not (memq backend new-list)) (push backend new-list))))
  754. ;; Set VAR to that list with fixed dependencies.
  755. (set-default var new-list))))
  756. :type '(set :greedy t
  757. (const :tag " ascii Export buffer to ASCII format" ascii)
  758. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  759. (const :tag " html Export buffer to HTML format" html)
  760. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  761. (const :tag " latex Export buffer to LaTeX format" latex)
  762. (const :tag " man Export buffer to MAN format" man)
  763. (const :tag " md Export buffer to Markdown format" md)
  764. (const :tag " odt Export buffer to ODT format" odt)
  765. (const :tag " org Export buffer to Org format" org)
  766. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  767. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  768. (const :tag "C deck Export buffer to deck.js presentations" deck)
  769. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  770. (const :tag "C groff Export buffer to Groff format" groff)
  771. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  772. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  773. (const :tag "C s5 Export buffer to s5 presentations" s5)
  774. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  775. (eval-after-load 'ox
  776. '(dolist (backend org-export-backends)
  777. (condition-case nil (require (intern (format "ox-%s" backend)))
  778. (error (message "Problems while trying to load export back-end `%s'"
  779. backend)))))
  780. (defcustom org-support-shift-select nil
  781. "Non-nil means make shift-cursor commands select text when possible.
  782. \\<org-mode-map>\
  783. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  784. start selecting a region, or enlarge regions started in this way.
  785. In Org mode, in special contexts, these same keys are used for
  786. other purposes, important enough to compete with shift selection.
  787. Org tries to balance these needs by supporting `shift-select-mode'
  788. outside these special contexts, under control of this variable.
  789. The default of this variable is nil, to avoid confusing behavior. Shifted
  790. cursor keys will then execute Org commands in the following contexts:
  791. - on a headline, changing TODO state (left/right) and priority (up/down)
  792. - on a time stamp, changing the time
  793. - in a plain list item, changing the bullet type
  794. - in a property definition line, switching between allowed values
  795. - in the BEGIN line of a clock table (changing the time block).
  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, and item lines,
  804. to make shift selection work there as well. If this is what you
  805. 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 nil
  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-archive-subtree', `org-archive-set-tag' and
  831. `org-archive-to-archive-sibling'. The archiving commands skip
  832. already archived entries."
  833. :type '(choice (const :tag "Don't loop" nil)
  834. (const :tag "All headlines in active region" t)
  835. (const :tag "In active region, headlines at the same level than the first one" start-level)
  836. (string :tag "Tags/Property/Todo matcher"))
  837. :version "24.1"
  838. :group 'org-todo
  839. :group 'org-archive)
  840. (defcustom org-startup-folded t
  841. "Non-nil means entering Org mode will switch to OVERVIEW.
  842. This can also be configured on a per-file basis by adding one of
  843. the following lines anywhere in the buffer:
  844. #+STARTUP: fold (or `overview', this is equivalent)
  845. #+STARTUP: nofold (or `showall', this is equivalent)
  846. #+STARTUP: content
  847. #+STARTUP: showeverything
  848. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  849. to ignore this option when Org opens agenda files for the first
  850. time."
  851. :group 'org-startup
  852. :type '(choice
  853. (const :tag "nofold: show all" nil)
  854. (const :tag "fold: overview" t)
  855. (const :tag "content: all headlines" content)
  856. (const :tag "show everything, even drawers" showeverything)))
  857. (defcustom org-startup-truncated t
  858. "Non-nil means entering Org mode will set `truncate-lines'.
  859. This is useful since some lines containing links can be very long and
  860. uninteresting. Also tables look terrible when wrapped.
  861. The variable `org-startup-truncated' allows to configure
  862. truncation for Org mode different to the other modes that use the
  863. variable `truncate-lines' and as a shortcut instead of putting
  864. the variable `truncate-lines' into the `org-mode-hook'. If one
  865. wants to configure truncation for Org mode not statically but
  866. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  867. the variable `truncate-lines' has to be used because in such a
  868. case it is too late to set the variable `org-startup-truncated'."
  869. :group 'org-startup
  870. :type 'boolean)
  871. (defcustom org-startup-indented nil
  872. "Non-nil means turn on `org-indent-mode' on startup.
  873. This can also be configured on a per-file basis by adding one of
  874. the following lines anywhere in the buffer:
  875. #+STARTUP: indent
  876. #+STARTUP: noindent"
  877. :group 'org-structure
  878. :type '(choice
  879. (const :tag "Not" nil)
  880. (const :tag "Globally (slow on startup in large files)" t)))
  881. (defcustom org-use-sub-superscripts t
  882. "Non-nil means interpret \"_\" and \"^\" for display.
  883. If you want to control how Org exports those characters, see
  884. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  885. used to be an alias for `org-export-with-sub-superscripts' in
  886. Org <8.0, it is not anymore.
  887. When this option is turned on, you can use TeX-like syntax for
  888. sub- and superscripts within the buffer. Several characters after
  889. \"_\" or \"^\" will be considered as a single item - so grouping
  890. with {} is normally not needed. For example, the following things
  891. will be parsed as single sub- or superscripts:
  892. 10^24 or 10^tau several digits will be considered 1 item.
  893. 10^-12 or 10^-tau a leading sign with digits or a word
  894. x^2-y^3 will be read as x^2 - y^3, because items are
  895. terminated by almost any nonword/nondigit char.
  896. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  897. Still, ambiguity is possible. So when in doubt, use {} to enclose
  898. the sub/superscript. If you set this variable to the symbol `{}',
  899. the braces are *required* in order to trigger interpretations as
  900. sub/superscript. This can be helpful in documents that need \"_\"
  901. frequently in plain text."
  902. :group 'org-startup
  903. :version "24.4"
  904. :package-version '(Org . "8.0")
  905. :type '(choice
  906. (const :tag "Always interpret" t)
  907. (const :tag "Only with braces" {})
  908. (const :tag "Never interpret" nil)))
  909. (defcustom org-startup-with-beamer-mode nil
  910. "Non-nil means turn on `org-beamer-mode' on startup.
  911. This can also be configured on a per-file basis by adding one of
  912. the following lines anywhere in the buffer:
  913. #+STARTUP: beamer"
  914. :group 'org-startup
  915. :version "24.1"
  916. :type 'boolean)
  917. (defcustom org-startup-align-all-tables nil
  918. "Non-nil means align all tables when visiting a file.
  919. This can also be configured on a per-file basis by adding one of
  920. the following lines anywhere in the buffer:
  921. #+STARTUP: align
  922. #+STARTUP: noalign"
  923. :group 'org-startup
  924. :type 'boolean)
  925. (defcustom org-startup-shrink-all-tables nil
  926. "Non-nil means shrink all table columns with a width cookie.
  927. This can also be configured on a per-file basis by adding one of
  928. the following lines anywhere in the buffer:
  929. #+STARTUP: shrink"
  930. :group 'org-startup
  931. :type 'boolean
  932. :version "27.1"
  933. :package-version '(Org . "9.2")
  934. :safe #'booleanp)
  935. (defcustom org-startup-with-inline-images nil
  936. "Non-nil means show inline images when loading a new Org 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: inlineimages
  940. #+STARTUP: noinlineimages"
  941. :group 'org-startup
  942. :version "24.1"
  943. :type 'boolean)
  944. (defcustom org-startup-with-latex-preview nil
  945. "Non-nil means preview LaTeX fragments when loading a new Org file.
  946. This can also be configured on a per-file basis by adding one of
  947. the following lines anywhere in the buffer:
  948. #+STARTUP: latexpreview
  949. #+STARTUP: nolatexpreview"
  950. :group 'org-startup
  951. :version "24.4"
  952. :package-version '(Org . "8.0")
  953. :type 'boolean)
  954. (defcustom org-insert-mode-line-in-empty-file nil
  955. "Non-nil means insert the first line setting Org mode in empty files.
  956. When the function `org-mode' is called interactively in an empty file, this
  957. normally means that the file name does not automatically trigger Org mode.
  958. To ensure that the file will always be in Org mode in the future, a
  959. line enforcing Org mode will be inserted into the buffer, if this option
  960. has been set."
  961. :group 'org-startup
  962. :type 'boolean)
  963. (defcustom org-ellipsis nil
  964. "The ellipsis to use in the Org mode outline.
  965. When nil, just use the standard three dots. When a non-empty string,
  966. use that string instead.
  967. The change affects only Org mode (which will then use its own display table).
  968. Changing this requires executing `\\[org-mode]' in a buffer to become
  969. effective."
  970. :group 'org-startup
  971. :type '(choice (const :tag "Default" nil)
  972. (string :tag "String" :value "...#"))
  973. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  974. (defvar org-display-table nil
  975. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  976. (defgroup org-keywords nil
  977. "Keywords in Org mode."
  978. :tag "Org Keywords"
  979. :group 'org)
  980. (defcustom org-closed-keep-when-no-todo nil
  981. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  982. :group 'org-todo
  983. :group 'org-keywords
  984. :version "24.4"
  985. :package-version '(Org . "8.0")
  986. :type 'boolean)
  987. (defgroup org-structure nil
  988. "Options concerning the general structure of Org files."
  989. :tag "Org Structure"
  990. :group 'org)
  991. (defgroup org-reveal-location nil
  992. "Options about how to make context of a location visible."
  993. :tag "Org Reveal Location"
  994. :group 'org-structure)
  995. (defcustom org-show-context-detail '((agenda . local)
  996. (bookmark-jump . lineage)
  997. (isearch . lineage)
  998. (default . ancestors))
  999. "Alist between context and visibility span when revealing a location.
  1000. \\<org-mode-map>Some actions may move point into invisible
  1001. locations. As a consequence, Org always expose a neighborhood
  1002. around point. How much is shown depends on the initial action,
  1003. or context. Valid contexts are
  1004. agenda when exposing an entry from the agenda
  1005. org-goto when using the command `org-goto' (`\\[org-goto]')
  1006. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1007. tags-tree when constructing a sparse tree based on tags matches
  1008. link-search when exposing search matches associated with a link
  1009. mark-goto when exposing the jump goal of a mark
  1010. bookmark-jump when exposing a bookmark location
  1011. isearch when exiting from an incremental search
  1012. default default for all contexts not set explicitly
  1013. Allowed visibility spans are
  1014. minimal show current headline; if point is not on headline,
  1015. also show entry
  1016. local show current headline, entry and next headline
  1017. ancestors show current headline and its direct ancestors; if
  1018. point is not on headline, also show entry
  1019. lineage show current headline, its direct ancestors and all
  1020. their children; if point is not on headline, also show
  1021. entry and first child
  1022. tree show current headline, its direct ancestors and all
  1023. their children; if point is not on headline, also show
  1024. entry and all children
  1025. canonical show current headline, its direct ancestors along with
  1026. their entries and children; if point is not located on
  1027. the headline, also show current entry and all children
  1028. As special cases, a nil or t value means show all contexts in
  1029. `minimal' or `canonical' view, respectively.
  1030. Some views can make displayed information very compact, but also
  1031. make it harder to edit the location of the match. In such
  1032. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1033. more context."
  1034. :group 'org-reveal-location
  1035. :version "26.1"
  1036. :package-version '(Org . "9.0")
  1037. :type '(choice
  1038. (const :tag "Canonical" t)
  1039. (const :tag "Minimal" nil)
  1040. (repeat :greedy t :tag "Individual contexts"
  1041. (cons
  1042. (choice :tag "Context"
  1043. (const agenda)
  1044. (const org-goto)
  1045. (const occur-tree)
  1046. (const tags-tree)
  1047. (const link-search)
  1048. (const mark-goto)
  1049. (const bookmark-jump)
  1050. (const isearch)
  1051. (const default))
  1052. (choice :tag "Detail level"
  1053. (const minimal)
  1054. (const local)
  1055. (const ancestors)
  1056. (const lineage)
  1057. (const tree)
  1058. (const canonical))))))
  1059. (defcustom org-indirect-buffer-display 'other-window
  1060. "How should indirect tree buffers be displayed?
  1061. This applies to indirect buffers created with the commands
  1062. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1063. Valid values are:
  1064. current-window Display in the current window
  1065. other-window Just display in another window.
  1066. dedicated-frame Create one new frame, and re-use it each time.
  1067. new-frame Make a new frame each time. Note that in this case
  1068. previously-made indirect buffers are kept, and you need to
  1069. kill these buffers yourself."
  1070. :group 'org-structure
  1071. :group 'org-agenda-windows
  1072. :type '(choice
  1073. (const :tag "In current window" current-window)
  1074. (const :tag "In current frame, other window" other-window)
  1075. (const :tag "Each time a new frame" new-frame)
  1076. (const :tag "One dedicated frame" dedicated-frame)))
  1077. (defcustom org-bookmark-names-plist
  1078. '(:last-capture "org-capture-last-stored"
  1079. :last-refile "org-refile-last-stored"
  1080. :last-capture-marker "org-capture-last-stored-marker")
  1081. "Names for bookmarks automatically set by some Org commands.
  1082. This can provide strings as names for a number of bookmarks Org sets
  1083. automatically. The following keys are currently implemented:
  1084. :last-capture
  1085. :last-capture-marker
  1086. :last-refile
  1087. When a key does not show up in the property list, the corresponding bookmark
  1088. is not set."
  1089. :group 'org-structure
  1090. :type 'plist)
  1091. (defgroup org-cycle nil
  1092. "Options concerning visibility cycling in Org mode."
  1093. :tag "Org Cycle"
  1094. :group 'org-structure)
  1095. (defcustom org-cycle-skip-children-state-if-no-children t
  1096. "Non-nil means skip CHILDREN state in entries that don't have any."
  1097. :group 'org-cycle
  1098. :type 'boolean)
  1099. (defcustom org-cycle-max-level nil
  1100. "Maximum level which should still be subject to visibility cycling.
  1101. Levels higher than this will, for cycling, be treated as text, not a headline.
  1102. When `org-odd-levels-only' is set, a value of N in this variable actually
  1103. means 2N-1 stars as the limiting headline.
  1104. When nil, cycle all levels.
  1105. Note that the limiting level of cycling is also influenced by
  1106. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1107. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1108. than its value."
  1109. :group 'org-cycle
  1110. :type '(choice
  1111. (const :tag "No limit" nil)
  1112. (integer :tag "Maximum level")))
  1113. (defcustom org-hide-block-startup nil
  1114. "Non-nil means entering Org mode will fold all blocks.
  1115. This can also be set in on a per-file basis with
  1116. #+STARTUP: hideblocks
  1117. #+STARTUP: showblocks"
  1118. :group 'org-startup
  1119. :group 'org-cycle
  1120. :type 'boolean)
  1121. (defcustom org-cycle-global-at-bob nil
  1122. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1123. This makes it possible to do global cycling without having to use `S-TAB'
  1124. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1125. line of the buffer
  1126. must not be a headline -- it may be empty or some other text.
  1127. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1128. sure the cursor stays at the beginning of the buffer.
  1129. When this option is nil, don't do anything special at the beginning of
  1130. the buffer."
  1131. :group 'org-cycle
  1132. :type 'boolean)
  1133. (defcustom org-cycle-level-after-item/entry-creation t
  1134. "Non-nil means cycle entry level or item indentation in new empty entries.
  1135. When the cursor is at the end of an empty headline, i.e., with only stars
  1136. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1137. and then all possible ancestor states, before returning to the original state.
  1138. This makes data entry extremely fast: M-RET to create a new headline,
  1139. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1140. When the cursor is at the end of an empty plain list item, one TAB will
  1141. make it a subitem, two or more tabs will back up to make this an item
  1142. higher up in the item hierarchy."
  1143. :group 'org-cycle
  1144. :type 'boolean)
  1145. (defcustom org-cycle-emulate-tab t
  1146. "Where should `org-cycle' emulate TAB.
  1147. nil Never
  1148. white Only in completely white lines
  1149. whitestart Only at the beginning of lines, before the first non-white char
  1150. t Everywhere except in headlines
  1151. exc-hl-bol Everywhere except at the start of a headline
  1152. If TAB is used in a place where it does not emulate TAB, the current subtree
  1153. visibility is cycled."
  1154. :group 'org-cycle
  1155. :type '(choice (const :tag "Never" nil)
  1156. (const :tag "Only in completely white lines" white)
  1157. (const :tag "Before first char in a line" whitestart)
  1158. (const :tag "Everywhere except in headlines" t)
  1159. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1160. (defcustom org-cycle-separator-lines 2
  1161. "Number of empty lines needed to keep an empty line between collapsed trees.
  1162. If you leave an empty line between the end of a subtree and the following
  1163. headline, this empty line is hidden when the subtree is folded.
  1164. Org mode will leave (exactly) one empty line visible if the number of
  1165. empty lines is equal or larger to the number given in this variable.
  1166. So the default 2 means at least 2 empty lines after the end of a subtree
  1167. are needed to produce free space between a collapsed subtree and the
  1168. following headline.
  1169. If the number is negative, and the number of empty lines is at least -N,
  1170. all empty lines are shown.
  1171. Special case: when 0, never leave empty lines in collapsed view."
  1172. :group 'org-cycle
  1173. :type 'integer)
  1174. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1175. (defcustom org-pre-cycle-hook nil
  1176. "Hook that is run before visibility cycling is happening.
  1177. The function(s) in this hook must accept a single argument which indicates
  1178. the new state that will be set right after running this hook. The
  1179. argument is a symbol. Before a global state change, it can have the values
  1180. `overview', `content', or `all'. Before a local state change, it can have
  1181. the values `folded', `children', or `subtree'."
  1182. :group 'org-cycle
  1183. :type 'hook)
  1184. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1185. org-cycle-show-empty-lines
  1186. org-optimize-window-after-visibility-change)
  1187. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1188. The function(s) in this hook must accept a single argument which indicates
  1189. the new state that was set by the most recent `org-cycle' command. The
  1190. argument is a symbol. After a global state change, it can have the values
  1191. `overview', `contents', or `all'. After a local state change, it can have
  1192. the values `folded', `children', or `subtree'."
  1193. :group 'org-cycle
  1194. :type 'hook
  1195. :version "26.1"
  1196. :package-version '(Org . "8.3"))
  1197. (defgroup org-edit-structure nil
  1198. "Options concerning structure editing in Org mode."
  1199. :tag "Org Edit Structure"
  1200. :group 'org-structure)
  1201. (defcustom org-odd-levels-only nil
  1202. "Non-nil means skip even levels and only use odd levels for the outline.
  1203. This has the effect that two stars are being added/taken away in
  1204. promotion/demotion commands. It also influences how levels are
  1205. handled by the exporters.
  1206. Changing it requires restart of `font-lock-mode' to become effective
  1207. for fontification also in regions already fontified.
  1208. You may also set this on a per-file basis by adding one of the following
  1209. lines to the buffer:
  1210. #+STARTUP: odd
  1211. #+STARTUP: oddeven"
  1212. :group 'org-edit-structure
  1213. :group 'org-appearance
  1214. :type 'boolean)
  1215. (defcustom org-adapt-indentation t
  1216. "Non-nil means adapt indentation to outline node level.
  1217. When this variable is set, Org assumes that you write outlines by
  1218. indenting text in each node to align with the headline (after the
  1219. stars). The following issues are influenced by this variable:
  1220. - The indentation is increased by one space in a demotion
  1221. command, and decreased by one in a promotion command. However,
  1222. in the latter case, if shifting some line in the entry body
  1223. would alter document structure (e.g., insert a new headline),
  1224. indentation is not changed at all.
  1225. - Property drawers and planning information is inserted indented
  1226. when this variable is set. When nil, they will not be indented.
  1227. - TAB indents a line relative to current level. The lines below
  1228. a headline will be indented when this variable is set.
  1229. Note that this is all about true indentation, by adding and
  1230. removing space characters. See also \"org-indent.el\" which does
  1231. level-dependent indentation in a virtual way, i.e. at display
  1232. time in Emacs."
  1233. :group 'org-edit-structure
  1234. :type 'boolean
  1235. :safe #'booleanp)
  1236. (defcustom org-special-ctrl-a/e nil
  1237. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1238. When t, `C-a' will bring back the cursor to the beginning of the
  1239. headline text, i.e. after the stars and after a possible TODO
  1240. keyword. In an item, this will be the position after bullet and
  1241. check-box, if any. When the cursor is already at that position,
  1242. another `C-a' will bring it to the beginning of the line.
  1243. `C-e' will jump to the end of the headline, ignoring the presence
  1244. of tags in the headline. A second `C-e' will then jump to the
  1245. true end of the line, after any tags. This also means that, when
  1246. this variable is non-nil, `C-e' also will never jump beyond the
  1247. end of the heading of a folded section, i.e. not after the
  1248. ellipses.
  1249. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1250. normally, going to the true line boundary first. Only a directly
  1251. following, identical keypress will bring the cursor to the
  1252. special positions.
  1253. This may also be a cons cell where the behavior for `C-a' and
  1254. `C-e' is set separately."
  1255. :group 'org-edit-structure
  1256. :type '(choice
  1257. (const :tag "off" nil)
  1258. (const :tag "on: after stars/bullet and before tags first" t)
  1259. (const :tag "reversed: true line boundary first" reversed)
  1260. (cons :tag "Set C-a and C-e separately"
  1261. (choice :tag "Special C-a"
  1262. (const :tag "off" nil)
  1263. (const :tag "on: after stars/bullet first" t)
  1264. (const :tag "reversed: before stars/bullet first" reversed))
  1265. (choice :tag "Special C-e"
  1266. (const :tag "off" nil)
  1267. (const :tag "on: before tags first" t)
  1268. (const :tag "reversed: after tags first" reversed)))))
  1269. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1270. (defcustom org-special-ctrl-k nil
  1271. "Non-nil means `C-k' will behave specially in headlines.
  1272. When nil, `C-k' will call the default `kill-line' command.
  1273. When t, the following will happen while the cursor is in the headline:
  1274. - When the cursor is at the beginning of a headline, kill the entire
  1275. line and possible the folded subtree below the line.
  1276. - When in the middle of the headline text, kill the headline up to the tags.
  1277. - When after the headline text, kill the tags."
  1278. :group 'org-edit-structure
  1279. :type 'boolean)
  1280. (defcustom org-ctrl-k-protect-subtree nil
  1281. "Non-nil means, do not delete a hidden subtree with C-k.
  1282. When set to the symbol `error', simply throw an error when C-k is
  1283. used to kill (part-of) a headline that has hidden text behind it.
  1284. Any other non-nil value will result in a query to the user, if it is
  1285. OK to kill that hidden subtree. When nil, kill without remorse."
  1286. :group 'org-edit-structure
  1287. :version "24.1"
  1288. :type '(choice
  1289. (const :tag "Do not protect hidden subtrees" nil)
  1290. (const :tag "Protect hidden subtrees with a security query" t)
  1291. (const :tag "Never kill a hidden subtree with C-k" error)))
  1292. (defcustom org-special-ctrl-o t
  1293. "Non-nil means, make `C-o' insert a row in tables."
  1294. :group 'org-edit-structure
  1295. :type 'boolean)
  1296. (defcustom org-catch-invisible-edits nil
  1297. "Check if in invisible region before inserting or deleting a character.
  1298. Valid values are:
  1299. nil Do not check, so just do invisible edits.
  1300. error Throw an error and do nothing.
  1301. show Make point visible, and do the requested edit.
  1302. show-and-error Make point visible, then throw an error and abort the edit.
  1303. smart Make point visible, and do insertion/deletion if it is
  1304. adjacent to visible text and the change feels predictable.
  1305. Never delete a previously invisible character or add in the
  1306. middle or right after an invisible region. Basically, this
  1307. allows insertion and backward-delete right before ellipses.
  1308. FIXME: maybe in this case we should not even show?"
  1309. :group 'org-edit-structure
  1310. :version "24.1"
  1311. :type '(choice
  1312. (const :tag "Do not check" nil)
  1313. (const :tag "Throw error when trying to edit" error)
  1314. (const :tag "Unhide, but do not do the edit" show-and-error)
  1315. (const :tag "Show invisible part and do the edit" show)
  1316. (const :tag "Be smart and do the right thing" smart)))
  1317. (defcustom org-yank-folded-subtrees t
  1318. "Non-nil means when yanking subtrees, fold them.
  1319. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1320. it starts with a heading and all other headings in it are either children
  1321. or siblings, then fold all the subtrees. However, do this only if no
  1322. text after the yank would be swallowed into a folded tree by this action."
  1323. :group 'org-edit-structure
  1324. :type 'boolean)
  1325. (defcustom org-yank-adjusted-subtrees nil
  1326. "Non-nil means when yanking subtrees, adjust the level.
  1327. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1328. this function for details."
  1329. :group 'org-edit-structure
  1330. :type 'boolean)
  1331. (defcustom org-M-RET-may-split-line '((default . t))
  1332. "Non-nil means M-RET will split the line at the cursor position.
  1333. When nil, it will go to the end of the line before making a
  1334. new line.
  1335. You may also set this option in a different way for different
  1336. contexts. Valid contexts are:
  1337. headline when creating a new headline
  1338. item when creating a new item
  1339. table in a table field
  1340. default the value to be used for all contexts not explicitly
  1341. customized"
  1342. :group 'org-structure
  1343. :group 'org-table
  1344. :type '(choice
  1345. (const :tag "Always" t)
  1346. (const :tag "Never" nil)
  1347. (repeat :greedy t :tag "Individual contexts"
  1348. (cons
  1349. (choice :tag "Context"
  1350. (const headline)
  1351. (const item)
  1352. (const table)
  1353. (const default))
  1354. (boolean)))))
  1355. (defcustom org-insert-heading-respect-content nil
  1356. "Non-nil means insert new headings after the current subtree.
  1357. \\<org-mode-map>
  1358. When nil, the new heading is created directly after the current line.
  1359. The commands `\\[org-insert-heading-respect-content]' and \
  1360. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1361. for the duration of the command."
  1362. :group 'org-structure
  1363. :type 'boolean)
  1364. (defcustom org-blank-before-new-entry '((heading . auto)
  1365. (plain-list-item . auto))
  1366. "Should `org-insert-heading' leave a blank line before new heading/item?
  1367. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1368. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1369. which case Org will look at the surrounding headings/items and try to
  1370. make an intelligent decision whether to insert a blank line or not."
  1371. :group 'org-edit-structure
  1372. :type '(list
  1373. (cons (const heading)
  1374. (choice (const :tag "Never" nil)
  1375. (const :tag "Always" t)
  1376. (const :tag "Auto" auto)))
  1377. (cons (const plain-list-item)
  1378. (choice (const :tag "Never" nil)
  1379. (const :tag "Always" t)
  1380. (const :tag "Auto" auto)))))
  1381. (defcustom org-insert-heading-hook nil
  1382. "Hook being run after inserting a new heading."
  1383. :group 'org-edit-structure
  1384. :type 'hook)
  1385. (defcustom org-enable-fixed-width-editor t
  1386. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1387. This currently only means they are never auto-wrapped.
  1388. When nil, such lines will be treated like ordinary lines."
  1389. :group 'org-edit-structure
  1390. :type 'boolean)
  1391. (defgroup org-sparse-trees nil
  1392. "Options concerning sparse trees in Org mode."
  1393. :tag "Org Sparse Trees"
  1394. :group 'org-structure)
  1395. (defcustom org-highlight-sparse-tree-matches t
  1396. "Non-nil means highlight all matches that define a sparse tree.
  1397. The highlights will automatically disappear the next time the buffer is
  1398. changed by an edit command."
  1399. :group 'org-sparse-trees
  1400. :type 'boolean)
  1401. (defcustom org-remove-highlights-with-change t
  1402. "Non-nil means any change to the buffer will remove temporary highlights.
  1403. \\<org-mode-map>\
  1404. Such highlights are created by `org-occur' and `org-clock-display'.
  1405. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1406. to get rid of the highlights.
  1407. The highlights created by `org-toggle-latex-fragment' always need
  1408. `\\[org-toggle-latex-fragment]' to be removed."
  1409. :group 'org-sparse-trees
  1410. :group 'org-time
  1411. :type 'boolean)
  1412. (defcustom org-occur-case-fold-search t
  1413. "Non-nil means `org-occur' should be case-insensitive.
  1414. If set to `smart' the search will be case-insensitive only if it
  1415. doesn't specify any upper case character."
  1416. :group 'org-sparse-trees
  1417. :version "26.1"
  1418. :type '(choice
  1419. (const :tag "Case-sensitive" nil)
  1420. (const :tag "Case-insensitive" t)
  1421. (const :tag "Case-insensitive for lower case searches only" smart)))
  1422. (defcustom org-occur-hook '(org-first-headline-recenter)
  1423. "Hook that is run after `org-occur' has constructed a sparse tree.
  1424. This can be used to recenter the window to show as much of the structure
  1425. as possible."
  1426. :group 'org-sparse-trees
  1427. :type 'hook)
  1428. (defgroup org-table nil
  1429. "Options concerning tables in Org mode."
  1430. :tag "Org Table"
  1431. :group 'org)
  1432. (defcustom org-self-insert-cluster-for-undo nil
  1433. "Non-nil means cluster self-insert commands for undo when possible.
  1434. If this is set, then, like in the Emacs command loop, 20 consecutive
  1435. characters will be undone together.
  1436. This is configurable, because there is some impact on typing performance."
  1437. :group 'org-table
  1438. :type 'boolean)
  1439. (defcustom org-table-tab-recognizes-table.el t
  1440. "Non-nil means TAB will automatically notice a table.el table.
  1441. When it sees such a table, it moves point into it and - if necessary -
  1442. calls `table-recognize-table'."
  1443. :group 'org-table-editing
  1444. :type 'boolean)
  1445. (defgroup org-link nil
  1446. "Options concerning links in Org mode."
  1447. :tag "Org Link"
  1448. :group 'org)
  1449. (defvar-local org-link-abbrev-alist-local nil
  1450. "Buffer-local version of `org-link-abbrev-alist', which see.
  1451. The value of this is taken from the #+LINK lines.")
  1452. (defcustom org-link-parameters
  1453. '(("doi" :follow org--open-doi-link)
  1454. ("elisp" :follow org--open-elisp-link)
  1455. ("file" :complete org-file-complete-link)
  1456. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1457. ("help" :follow org--open-help-link)
  1458. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1459. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1460. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1461. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1462. ("shell" :follow org--open-shell-link))
  1463. "An alist of properties that defines all the links in Org mode.
  1464. The key in each association is a string of the link type.
  1465. Subsequent optional elements make up a p-list of link properties.
  1466. :follow - A function that takes the link path as an argument.
  1467. :export - A function that takes the link path, description and
  1468. export-backend as arguments.
  1469. :store - A function responsible for storing the link. See the
  1470. function `org-store-link-functions'.
  1471. :complete - A function that inserts a link with completion. The
  1472. function takes one optional prefix arg.
  1473. :face - A face for the link, or a function that returns a face.
  1474. The function takes one argument which is the link path. The
  1475. default face is `org-link'.
  1476. :mouse-face - The mouse-face. The default is `highlight'.
  1477. :display - `full' will not fold the link in descriptive
  1478. display. Default is `org-link'.
  1479. :help-echo - A string or function that takes (window object position)
  1480. as arguments and returns a string.
  1481. :keymap - A keymap that is active on the link. The default is
  1482. `org-mouse-map'.
  1483. :htmlize-link - A function for the htmlize-link. Defaults
  1484. to (list :uri \"type:path\")
  1485. :activate-func - A function to run at the end of font-lock
  1486. activation. The function must accept (link-start link-end path bracketp)
  1487. as arguments."
  1488. :group 'org-link
  1489. :type '(alist :tag "Link display parameters"
  1490. :value-type plist)
  1491. :version "26.1"
  1492. :package-version '(Org . "9.1"))
  1493. (defun org-link-get-parameter (type key)
  1494. "Get TYPE link property for KEY.
  1495. TYPE is a string and KEY is a plist keyword."
  1496. (plist-get
  1497. (cdr (assoc type org-link-parameters))
  1498. key))
  1499. (defun org-link-set-parameters (type &rest parameters)
  1500. "Set link TYPE properties to PARAMETERS.
  1501. PARAMETERS should be :key val pairs."
  1502. (let ((data (assoc type org-link-parameters)))
  1503. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1504. (push (cons type parameters) org-link-parameters)
  1505. (org-make-link-regexps)
  1506. (org-element-update-syntax))))
  1507. (defun org-link-types ()
  1508. "Return a list of known link types."
  1509. (mapcar #'car org-link-parameters))
  1510. (defcustom org-link-abbrev-alist nil
  1511. "Alist of link abbreviations.
  1512. The car of each element is a string, to be replaced at the start of a link.
  1513. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1514. links in Org buffers can have an optional tag after a double colon, e.g.,
  1515. [[linkkey:tag][description]]
  1516. The `linkkey' must be a single word, starting with a letter, followed
  1517. by letters, numbers, `-' or `_'.
  1518. If REPLACE is a string, the tag will simply be appended to create the link.
  1519. If the string contains \"%s\", the tag will be inserted there. If the string
  1520. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1521. at that point (see the function `url-hexify-string'). If the string contains
  1522. the specifier \"%(my-function)\", then the custom function `my-function' will
  1523. be invoked: this function takes the tag as its only argument and must return
  1524. a string.
  1525. REPLACE may also be a function that will be called with the tag as the
  1526. only argument to create the link, which should be returned as a string.
  1527. See the manual for examples."
  1528. :group 'org-link
  1529. :type '(repeat
  1530. (cons
  1531. (string :tag "Protocol")
  1532. (choice
  1533. (string :tag "Format")
  1534. (function)))))
  1535. (defcustom org-descriptive-links t
  1536. "Non-nil means Org will display descriptive links.
  1537. E.g. [[https://orgmode.org][Org website]] will be displayed as
  1538. \"Org Website\", hiding the link itself and just displaying its
  1539. description. When set to nil, Org will display the full links
  1540. literally.
  1541. You can interactively set the value of this variable by calling
  1542. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1543. :group 'org-link
  1544. :type 'boolean)
  1545. (defcustom org-link-file-path-type 'adaptive
  1546. "How the path name in file links should be stored.
  1547. Valid values are:
  1548. relative Relative to the current directory, i.e. the directory of the file
  1549. into which the link is being inserted.
  1550. absolute Absolute path, if possible with ~ for home directory.
  1551. noabbrev Absolute path, no abbreviation of home directory.
  1552. adaptive Use relative path for files in the current directory and sub-
  1553. directories of it. For other files, use an absolute path."
  1554. :group 'org-link
  1555. :type '(choice
  1556. (const relative)
  1557. (const absolute)
  1558. (const noabbrev)
  1559. (const adaptive)))
  1560. (defvaralias 'org-activate-links 'org-highlight-links)
  1561. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1562. "Types of links that should be highlighted in Org files.
  1563. This is a list of symbols, each one of them leading to the
  1564. highlighting of a certain link type.
  1565. You can still open links that are not highlighted.
  1566. In principle, it does not hurt to turn on highlighting for all
  1567. link types. There may be a small gain when turning off unused
  1568. link types. The types are:
  1569. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1570. angle Links in angular brackets that may contain whitespace like
  1571. <bbdb:Carsten Dominik>.
  1572. plain Plain links in normal text, no whitespace, like http://google.com.
  1573. radio Text that is matched by a radio target, see manual for details.
  1574. tag Tag settings in a headline (link to tag search).
  1575. date Time stamps (link to calendar).
  1576. footnote Footnote labels.
  1577. If you set this variable during an Emacs session, use `org-mode-restart'
  1578. in the Org buffer so that the change takes effect."
  1579. :group 'org-link
  1580. :group 'org-appearance
  1581. :type '(set :greedy t
  1582. (const :tag "Double bracket links" bracket)
  1583. (const :tag "Angular bracket links" angle)
  1584. (const :tag "Plain text links" plain)
  1585. (const :tag "Radio target matches" radio)
  1586. (const :tag "Tags" tag)
  1587. (const :tag "Timestamps" date)
  1588. (const :tag "Footnotes" footnote)))
  1589. (defcustom org-make-link-description-function nil
  1590. "Function to use for generating link descriptions from links.
  1591. This function must take two parameters: the first one is the
  1592. link, the second one is the description generated by
  1593. `org-insert-link'. The function should return the description to
  1594. use."
  1595. :group 'org-link
  1596. :type '(choice (const nil) (function)))
  1597. (defgroup org-link-store nil
  1598. "Options concerning storing links in Org mode."
  1599. :tag "Org Store Link"
  1600. :group 'org-link)
  1601. (defcustom org-url-hexify-p t
  1602. "When non-nil, hexify URL when creating a link."
  1603. :type 'boolean
  1604. :version "24.3"
  1605. :group 'org-link-store)
  1606. (defcustom org-email-link-description-format "Email %c: %s"
  1607. "Format of the description part of a link to an email or usenet message.
  1608. The following %-escapes will be replaced by corresponding information:
  1609. %F full \"From\" field
  1610. %f name, taken from \"From\" field, address if no name
  1611. %T full \"To\" field
  1612. %t first name in \"To\" field, address if no name
  1613. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1614. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1615. %s subject
  1616. %d date
  1617. %m message-id.
  1618. You may use normal field width specification between the % and the letter.
  1619. This is for example useful to limit the length of the subject.
  1620. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1621. :group 'org-link-store
  1622. :package-version '(Org . 9.3)
  1623. :type 'string
  1624. :safe #'stringp)
  1625. (defcustom org-from-is-user-regexp
  1626. (let (r1 r2)
  1627. (when (and user-mail-address (not (string= user-mail-address "")))
  1628. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1629. (when (and user-full-name (not (string= user-full-name "")))
  1630. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1631. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1632. "Regexp matched against the \"From:\" header of an email or usenet message.
  1633. It should match if the message is from the user him/herself."
  1634. :group 'org-link-store
  1635. :type 'regexp)
  1636. (defcustom org-context-in-file-links t
  1637. "Non-nil means file links from `org-store-link' contain context.
  1638. \\<org-mode-map>
  1639. A search string will be added to the file name with :: as separator
  1640. and used to find the context when the link is activated by the command
  1641. `org-open-at-point'. When this option is t, the entire active region
  1642. will be placed in the search string of the file link. If set to a
  1643. positive integer, only the first n lines of context will be stored.
  1644. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1645. \\[org-store-link]')
  1646. negates this setting for the duration of the command."
  1647. :group 'org-link-store
  1648. :type '(choice boolean integer))
  1649. (defcustom org-keep-stored-link-after-insertion nil
  1650. "Non-nil means keep link in list for entire session.
  1651. \\<org-mode-map>
  1652. The command `org-store-link' adds a link pointing to the current
  1653. location to an internal list. These links accumulate during a session.
  1654. The command `org-insert-link' can be used to insert links into any
  1655. Org file (offering completion for all stored links).
  1656. When this option is nil, every link which has been inserted once using
  1657. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1658. unused
  1659. links more efficient."
  1660. :group 'org-link-store
  1661. :type 'boolean)
  1662. (defgroup org-link-follow nil
  1663. "Options concerning following links in Org mode."
  1664. :tag "Org Follow Link"
  1665. :group 'org-link)
  1666. (defcustom org-link-translation-function nil
  1667. "Function to translate links with different syntax to Org syntax.
  1668. This can be used to translate links created for example by the Planner
  1669. or emacs-wiki packages to Org syntax.
  1670. The function must accept two parameters, a TYPE containing the link
  1671. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1672. which is everything after the link protocol. It should return a cons
  1673. with possibly modified values of type and path.
  1674. Org contains a function for this, so if you set this variable to
  1675. `org-translate-link-from-planner', you should be able follow many
  1676. links created by planner."
  1677. :group 'org-link-follow
  1678. :type '(choice (const nil) (function)))
  1679. (defcustom org-mark-ring-length 4
  1680. "Number of different positions to be recorded in the ring.
  1681. Changing this requires a restart of Emacs to work correctly."
  1682. :group 'org-link-follow
  1683. :type 'integer)
  1684. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1685. "Non-nil means internal fuzzy links can only match headlines.
  1686. When nil, the a fuzzy link may point to a target or a named
  1687. construct in the document. When set to the special value
  1688. `query-to-create', offer to create a new headline when none
  1689. matched.
  1690. Spaces and statistics cookies are ignored during heading searches."
  1691. :group 'org-link-follow
  1692. :version "24.1"
  1693. :type '(choice
  1694. (const :tag "Use fuzzy text search" nil)
  1695. (const :tag "Match only exact headline" t)
  1696. (const :tag "Match exact headline or query to create it"
  1697. query-to-create))
  1698. :safe #'symbolp)
  1699. (defcustom org-link-frame-setup
  1700. '((vm . vm-visit-folder-other-frame)
  1701. (vm-imap . vm-visit-imap-folder-other-frame)
  1702. (gnus . org-gnus-no-new-news)
  1703. (file . find-file-other-window)
  1704. (wl . wl-other-frame))
  1705. "Setup the frame configuration for following links.
  1706. When following a link with Emacs, it may often be useful to display
  1707. this link in another window or frame. This variable can be used to
  1708. set this up for the different types of links.
  1709. For VM, use any of
  1710. `vm-visit-folder'
  1711. `vm-visit-folder-other-window'
  1712. `vm-visit-folder-other-frame'
  1713. For Gnus, use any of
  1714. `gnus'
  1715. `gnus-other-frame'
  1716. `org-gnus-no-new-news'
  1717. For FILE, use any of
  1718. `find-file'
  1719. `find-file-other-window'
  1720. `find-file-other-frame'
  1721. For Wanderlust use any of
  1722. `wl'
  1723. `wl-other-frame'
  1724. For the calendar, use the variable `calendar-setup'.
  1725. For BBDB, it is currently only possible to display the matches in
  1726. another window."
  1727. :group 'org-link-follow
  1728. :type '(list
  1729. (cons (const vm)
  1730. (choice
  1731. (const vm-visit-folder)
  1732. (const vm-visit-folder-other-window)
  1733. (const vm-visit-folder-other-frame)))
  1734. (cons (const vm-imap)
  1735. (choice
  1736. (const vm-visit-imap-folder)
  1737. (const vm-visit-imap-folder-other-window)
  1738. (const vm-visit-imap-folder-other-frame)))
  1739. (cons (const gnus)
  1740. (choice
  1741. (const gnus)
  1742. (const gnus-other-frame)
  1743. (const org-gnus-no-new-news)))
  1744. (cons (const file)
  1745. (choice
  1746. (const find-file)
  1747. (const find-file-other-window)
  1748. (const find-file-other-frame)))
  1749. (cons (const wl)
  1750. (choice
  1751. (const wl)
  1752. (const wl-other-frame)))))
  1753. (defcustom org-display-internal-link-with-indirect-buffer nil
  1754. "Non-nil means use indirect buffer to display infile links.
  1755. Activating internal links (from one location in a file to another location
  1756. in the same file) normally just jumps to the location. When the link is
  1757. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1758. is displayed in
  1759. another window. When this option is set, the other window actually displays
  1760. an indirect buffer clone of the current buffer, to avoid any visibility
  1761. changes to the current buffer."
  1762. :group 'org-link-follow
  1763. :type 'boolean)
  1764. (defcustom org-open-non-existing-files nil
  1765. "Non-nil means `org-open-file' will open non-existing files.
  1766. When nil, an error will be generated.
  1767. This variable applies only to external applications because they
  1768. might choke on non-existing files. If the link is to a file that
  1769. will be opened in Emacs, the variable is ignored."
  1770. :group 'org-link-follow
  1771. :type 'boolean)
  1772. (defcustom org-open-directory-means-index-dot-org nil
  1773. "Non-nil means a link to a directory really means to index.org.
  1774. When nil, following a directory link will run dired or open a finder/explorer
  1775. window on that directory."
  1776. :group 'org-link-follow
  1777. :type 'boolean)
  1778. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1779. "Non-nil means ask for confirmation before executing shell links.
  1780. Shell links can be dangerous: just think about a link
  1781. [[shell:rm -rf ~/*][Google Search]]
  1782. This link would show up in your Org document as \"Google Search\",
  1783. but really it would remove your entire home directory.
  1784. Therefore we advise against setting this variable to nil.
  1785. Just change it to `y-or-n-p' if you want to confirm with a
  1786. single keystroke rather than having to type \"yes\"."
  1787. :group 'org-link-follow
  1788. :type '(choice
  1789. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1790. (const :tag "with y-or-n (faster)" y-or-n-p)
  1791. (const :tag "no confirmation (dangerous)" nil)))
  1792. (put 'org-confirm-shell-link-function
  1793. 'safe-local-variable
  1794. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1795. (defcustom org-confirm-shell-link-not-regexp ""
  1796. "A regexp to skip confirmation for shell links."
  1797. :group 'org-link-follow
  1798. :version "24.1"
  1799. :type 'regexp)
  1800. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1801. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1802. Elisp links can be dangerous: just think about a link
  1803. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1804. This link would show up in your Org document as \"Google Search\",
  1805. but really it would remove your entire home directory.
  1806. Therefore we advise against setting this variable to nil.
  1807. Just change it to `y-or-n-p' if you want to confirm with a
  1808. single keystroke rather than having to type \"yes\"."
  1809. :group 'org-link-follow
  1810. :type '(choice
  1811. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1812. (const :tag "with y-or-n (faster)" y-or-n-p)
  1813. (const :tag "no confirmation (dangerous)" nil)))
  1814. (put 'org-confirm-shell-link-function
  1815. 'safe-local-variable
  1816. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1817. (defcustom org-confirm-elisp-link-not-regexp ""
  1818. "A regexp to skip confirmation for Elisp links."
  1819. :group 'org-link-follow
  1820. :version "24.1"
  1821. :type 'regexp)
  1822. (defconst org-file-apps-defaults-gnu
  1823. '((remote . emacs)
  1824. (system . mailcap)
  1825. (t . mailcap))
  1826. "Default file applications on a UNIX or GNU/Linux system.
  1827. See `org-file-apps'.")
  1828. (defconst org-file-apps-defaults-macosx
  1829. '((remote . emacs)
  1830. (system . "open %s")
  1831. ("ps.gz" . "gv %s")
  1832. ("eps.gz" . "gv %s")
  1833. ("dvi" . "xdvi %s")
  1834. ("fig" . "xfig %s")
  1835. (t . "open %s"))
  1836. "Default file applications on a macOS system.
  1837. The system \"open\" is known as a default, but we use X11 applications
  1838. for some files for which the OS does not have a good default.
  1839. See `org-file-apps'.")
  1840. (defconst org-file-apps-defaults-windowsnt
  1841. (list '(remote . emacs)
  1842. (cons 'system (lambda (file _path)
  1843. (with-no-warnings (w32-shell-execute "open" file))))
  1844. (cons t (lambda (file _path)
  1845. (with-no-warnings (w32-shell-execute "open" file)))))
  1846. "Default file applications on a Windows NT system.
  1847. The system \"open\" is used for most files.
  1848. See `org-file-apps'.")
  1849. (defcustom org-file-apps
  1850. '((auto-mode . emacs)
  1851. ("\\.mm\\'" . default)
  1852. ("\\.x?html?\\'" . default)
  1853. ("\\.pdf\\'" . default))
  1854. "External applications for opening `file:path' items in a document.
  1855. \\<org-mode-map>\
  1856. Org mode uses system defaults for different file types, but
  1857. you can use this variable to set the application for a given file
  1858. extension. The entries in this list are cons cells where the car identifies
  1859. files and the cdr the corresponding command.
  1860. Possible values for the file identifier are:
  1861. \"string\" A string as a file identifier can be interpreted in different
  1862. ways, depending on its contents:
  1863. - Alphanumeric characters only:
  1864. Match links with this file extension.
  1865. Example: (\"pdf\" . \"evince %s\")
  1866. to open PDFs with evince.
  1867. - Regular expression: Match links where the
  1868. filename matches the regexp. If you want to
  1869. use groups here, use shy groups.
  1870. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1871. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1872. to open *.html and *.xhtml with firefox.
  1873. - Regular expression which contains (non-shy) groups:
  1874. Match links where the whole link, including \"::\", and
  1875. anything after that, matches the regexp.
  1876. In a custom command string, %1, %2, etc. are replaced with
  1877. the parts of the link that were matched by the groups.
  1878. For backwards compatibility, if a command string is given
  1879. that does not use any of the group matches, this case is
  1880. handled identically to the second one (i.e. match against
  1881. file name only).
  1882. In a custom function, you can access the group matches with
  1883. (match-string n link).
  1884. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1885. \"evince -p %1 %s\")
  1886. to open [[file:document.pdf::5]] with evince at page 5.
  1887. `directory' Matches a directory
  1888. `remote' Matches a remote file, accessible through tramp or efs.
  1889. Remote files most likely should be visited through Emacs
  1890. because external applications cannot handle such paths.
  1891. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1892. so all files Emacs knows how to handle. Using this with
  1893. command `emacs' will open most files in Emacs. Beware that this
  1894. will also open html files inside Emacs, unless you add
  1895. (\"html\" . default) to the list as well.
  1896. `system' The system command to open files, like `open' on Windows
  1897. and macOS, and mailcap under GNU/Linux. This is the command
  1898. that will be selected if you call `org-open-at-point' with a
  1899. double prefix argument (`\\[universal-argument] \
  1900. \\[universal-argument] \\[org-open-at-point]').
  1901. t Default for files not matched by any of the other options.
  1902. Possible values for the command are:
  1903. `emacs' The file will be visited by the current Emacs process.
  1904. `default' Use the default application for this file type, which is the
  1905. association for t in the list, most likely in the system-specific
  1906. part. This can be used to overrule an unwanted setting in the
  1907. system-specific variable.
  1908. `system' Use the system command for opening files, like \"open\".
  1909. This command is specified by the entry whose car is `system'.
  1910. Most likely, the system-specific version of this variable
  1911. does define this command, but you can overrule/replace it
  1912. here.
  1913. `mailcap' Use command specified in the mailcaps.
  1914. string A command to be executed by a shell; %s will be replaced
  1915. by the path to the file.
  1916. function A Lisp function, which will be called with two arguments:
  1917. the file path and the original link string, without the
  1918. \"file:\" prefix.
  1919. For more examples, see the system specific constants
  1920. `org-file-apps-defaults-macosx'
  1921. `org-file-apps-defaults-windowsnt'
  1922. `org-file-apps-defaults-gnu'."
  1923. :group 'org-link-follow
  1924. :type '(repeat
  1925. (cons (choice :value ""
  1926. (string :tag "Extension")
  1927. (const :tag "System command to open files" system)
  1928. (const :tag "Default for unrecognized files" t)
  1929. (const :tag "Remote file" remote)
  1930. (const :tag "Links to a directory" directory)
  1931. (const :tag "Any files that have Emacs modes"
  1932. auto-mode))
  1933. (choice :value ""
  1934. (const :tag "Visit with Emacs" emacs)
  1935. (const :tag "Use default" default)
  1936. (const :tag "Use the system command" system)
  1937. (string :tag "Command")
  1938. (function :tag "Function")))))
  1939. (defcustom org-doi-server-url "http://dx.doi.org/"
  1940. "The URL of the DOI server."
  1941. :type 'string
  1942. :version "24.3"
  1943. :group 'org-link-follow)
  1944. (defgroup org-refile nil
  1945. "Options concerning refiling entries in Org mode."
  1946. :tag "Org Refile"
  1947. :group 'org)
  1948. (defcustom org-directory "~/org"
  1949. "Directory with Org files.
  1950. This is just a default location to look for Org files. There is no need
  1951. at all to put your files into this directory. It is used in the
  1952. following situations:
  1953. 1. When a capture template specifies a target file that is not an
  1954. absolute path. The path will then be interpreted relative to
  1955. `org-directory'
  1956. 2. When the value of variable `org-agenda-files' is a single file, any
  1957. relative paths in this file will be taken as relative to
  1958. `org-directory'."
  1959. :group 'org-refile
  1960. :group 'org-capture
  1961. :type 'directory)
  1962. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  1963. "Default target for storing notes.
  1964. Used as a fall back file for org-capture.el, for templates that
  1965. do not specify a target file."
  1966. :group 'org-refile
  1967. :group 'org-capture
  1968. :type 'file)
  1969. (defcustom org-reverse-note-order nil
  1970. "Non-nil means store new notes at the beginning of a file or entry.
  1971. When nil, new notes will be filed to the end of a file or entry.
  1972. This can also be a list with cons cells of regular expressions that
  1973. are matched against file names, and values."
  1974. :group 'org-capture
  1975. :group 'org-refile
  1976. :type '(choice
  1977. (const :tag "Reverse always" t)
  1978. (const :tag "Reverse never" nil)
  1979. (repeat :tag "By file name regexp"
  1980. (cons regexp boolean))))
  1981. (defcustom org-log-refile nil
  1982. "Information to record when a task is refiled.
  1983. Possible values are:
  1984. nil Don't add anything
  1985. time Add a time stamp to the task
  1986. note Prompt for a note and add it with template `org-log-note-headings'
  1987. This option can also be set with on a per-file-basis with
  1988. #+STARTUP: nologrefile
  1989. #+STARTUP: logrefile
  1990. #+STARTUP: lognoterefile
  1991. You can have local logging settings for a subtree by setting the LOGGING
  1992. property to one or more of these keywords.
  1993. When bulk-refiling from the agenda, the value `note' is forbidden and
  1994. will temporarily be changed to `time'."
  1995. :group 'org-refile
  1996. :group 'org-progress
  1997. :version "24.1"
  1998. :type '(choice
  1999. (const :tag "No logging" nil)
  2000. (const :tag "Record timestamp" time)
  2001. (const :tag "Record timestamp with note." note)))
  2002. (defcustom org-refile-targets nil
  2003. "Targets for refiling entries with `\\[org-refile]'.
  2004. This is a list of cons cells. Each cell contains:
  2005. - a specification of the files to be considered, either a list of files,
  2006. or a symbol whose function or variable value will be used to retrieve
  2007. a file name or a list of file names. If you use `org-agenda-files' for
  2008. that, all agenda files will be scanned for targets. Nil means consider
  2009. headings in the current buffer.
  2010. - A specification of how to find candidate refile targets. This may be
  2011. any of:
  2012. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2013. This tag has to be present in all target headlines, inheritance will
  2014. not be considered.
  2015. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2016. todo keyword.
  2017. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2018. headlines that are refiling targets.
  2019. - a cons cell (:level . N). Any headline of level N is considered a target.
  2020. Note that, when `org-odd-levels-only' is set, level corresponds to
  2021. order in hierarchy, not to the number of stars.
  2022. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2023. Note that, when `org-odd-levels-only' is set, level corresponds to
  2024. order in hierarchy, not to the number of stars.
  2025. Each element of this list generates a set of possible targets.
  2026. The union of these sets is presented (with completion) to
  2027. the user by `org-refile'.
  2028. You can set the variable `org-refile-target-verify-function' to a function
  2029. to verify each headline found by the simple criteria above.
  2030. When this variable is nil, all top-level headlines in the current buffer
  2031. are used, equivalent to the value `((nil . (:level . 1))'."
  2032. :group 'org-refile
  2033. :type '(repeat
  2034. (cons
  2035. (choice :value org-agenda-files
  2036. (const :tag "All agenda files" org-agenda-files)
  2037. (const :tag "Current buffer" nil)
  2038. (function) (variable) (file))
  2039. (choice :tag "Identify target headline by"
  2040. (cons :tag "Specific tag" (const :value :tag) (string))
  2041. (cons :tag "TODO keyword" (const :value :todo) (string))
  2042. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2043. (cons :tag "Level number" (const :value :level) (integer))
  2044. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2045. (defcustom org-refile-target-verify-function nil
  2046. "Function to verify if the headline at point should be a refile target.
  2047. The function will be called without arguments, with point at the
  2048. beginning of the headline. It should return t and leave point
  2049. where it is if the headline is a valid target for refiling.
  2050. If the target should not be selected, the function must return nil.
  2051. In addition to this, it may move point to a place from where the search
  2052. should be continued. For example, the function may decide that the entire
  2053. subtree of the current entry should be excluded and move point to the end
  2054. of the subtree."
  2055. :group 'org-refile
  2056. :type '(choice
  2057. (const nil)
  2058. (function)))
  2059. (defcustom org-refile-use-cache nil
  2060. "Non-nil means cache refile targets to speed up the process.
  2061. \\<org-mode-map>\
  2062. The cache for a particular file will be updated automatically when
  2063. the buffer has been killed, or when any of the marker used for flagging
  2064. refile targets no longer points at a live buffer.
  2065. If you have added new entries to a buffer that might themselves be targets,
  2066. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2067. if you find that easier, \
  2068. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2069. \\[org-refile]'."
  2070. :group 'org-refile
  2071. :version "24.1"
  2072. :type 'boolean)
  2073. (defcustom org-refile-use-outline-path nil
  2074. "Non-nil means provide refile targets as paths.
  2075. So a level 3 headline will be available as level1/level2/level3.
  2076. When the value is `file', also include the file name (without directory)
  2077. into the path. In this case, you can also stop the completion after
  2078. the file name, to get entries inserted as top level in the file.
  2079. When `full-file-path', include the full file path.
  2080. When `buffer-name', use the buffer name."
  2081. :group 'org-refile
  2082. :type '(choice
  2083. (const :tag "Not" nil)
  2084. (const :tag "Yes" t)
  2085. (const :tag "Start with file name" file)
  2086. (const :tag "Start with full file path" full-file-path)
  2087. (const :tag "Start with buffer name" buffer-name)))
  2088. (defcustom org-outline-path-complete-in-steps t
  2089. "Non-nil means complete the outline path in hierarchical steps.
  2090. When Org uses the refile interface to select an outline path (see
  2091. `org-refile-use-outline-path'), the completion of the path can be
  2092. done in a single go, or it can be done in steps down the headline
  2093. hierarchy. Going in steps is probably the best if you do not use
  2094. a special completion package like `ido' or `icicles'. However,
  2095. when using these packages, going in one step can be very fast,
  2096. while still showing the whole path to the entry."
  2097. :group 'org-refile
  2098. :type 'boolean)
  2099. (defcustom org-refile-allow-creating-parent-nodes nil
  2100. "Non-nil means allow the creation of new nodes as refile targets.
  2101. New nodes are then created by adding \"/new node name\" to the completion
  2102. of an existing node. When the value of this variable is `confirm',
  2103. new node creation must be confirmed by the user (recommended).
  2104. When nil, the completion must match an existing entry.
  2105. Note that, if the new heading is not seen by the criteria
  2106. listed in `org-refile-targets', multiple instances of the same
  2107. heading would be created by trying again to file under the new
  2108. heading."
  2109. :group 'org-refile
  2110. :type '(choice
  2111. (const :tag "Never" nil)
  2112. (const :tag "Always" t)
  2113. (const :tag "Prompt for confirmation" confirm)))
  2114. (defcustom org-refile-active-region-within-subtree nil
  2115. "Non-nil means also refile active region within a subtree.
  2116. By default `org-refile' doesn't allow refiling regions if they
  2117. don't contain a set of subtrees, but it might be convenient to
  2118. do so sometimes: in that case, the first line of the region is
  2119. converted to a headline before refiling."
  2120. :group 'org-refile
  2121. :version "24.1"
  2122. :type 'boolean)
  2123. (defgroup org-todo nil
  2124. "Options concerning TODO items in Org mode."
  2125. :tag "Org TODO"
  2126. :group 'org)
  2127. (defgroup org-progress nil
  2128. "Options concerning Progress logging in Org mode."
  2129. :tag "Org Progress"
  2130. :group 'org-time)
  2131. (defvar org-todo-interpretation-widgets
  2132. '((:tag "Sequence (cycling hits every state)" sequence)
  2133. (:tag "Type (cycling directly to DONE)" type))
  2134. "The available interpretation symbols for customizing `org-todo-keywords'.
  2135. Interested libraries should add to this list.")
  2136. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2137. "List of TODO entry keyword sequences and their interpretation.
  2138. \\<org-mode-map>This is a list of sequences.
  2139. Each sequence starts with a symbol, either `sequence' or `type',
  2140. indicating if the keywords should be interpreted as a sequence of
  2141. action steps, or as different types of TODO items. The first
  2142. keywords are states requiring action - these states will select a headline
  2143. for inclusion into the global TODO list Org produces. If one of the
  2144. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2145. signify that no further action is necessary. If \"|\" is not found,
  2146. the last keyword is treated as the only DONE state of the sequence.
  2147. The command `\\[org-todo]' cycles an entry through these states, and one
  2148. additional state where no keyword is present. For details about this
  2149. cycling, see the manual.
  2150. TODO keywords and interpretation can also be set on a per-file basis with
  2151. the special #+SEQ_TODO and #+TYP_TODO lines.
  2152. Each keyword can optionally specify a character for fast state selection
  2153. \(in combination with the variable `org-use-fast-todo-selection')
  2154. and specifiers for state change logging, using the same syntax that
  2155. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2156. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2157. indicates to record a time stamp each time this state is selected.
  2158. Each keyword may also specify if a timestamp or a note should be
  2159. recorded when entering or leaving the state, by adding additional
  2160. characters in the parenthesis after the keyword. This looks like this:
  2161. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2162. record only the time of the state change. With X and Y being either
  2163. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2164. Y when leaving the state if and only if the *target* state does not
  2165. define X. You may omit any of the fast-selection key or X or /Y,
  2166. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2167. For backward compatibility, this variable may also be just a list
  2168. of keywords. In this case the interpretation (sequence or type) will be
  2169. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2170. :group 'org-todo
  2171. :group 'org-keywords
  2172. :type '(choice
  2173. (repeat :tag "Old syntax, just keywords"
  2174. (string :tag "Keyword"))
  2175. (repeat :tag "New syntax"
  2176. (cons
  2177. (choice
  2178. :tag "Interpretation"
  2179. ;;Quick and dirty way to see
  2180. ;;`org-todo-interpretations'. This takes the
  2181. ;;place of item arguments
  2182. :convert-widget
  2183. (lambda (widget)
  2184. (widget-put widget
  2185. :args (mapcar
  2186. (lambda (x)
  2187. (widget-convert
  2188. (cons 'const x)))
  2189. org-todo-interpretation-widgets))
  2190. widget))
  2191. (repeat
  2192. (string :tag "Keyword"))))))
  2193. (defvar-local org-todo-keywords-1 nil
  2194. "All TODO and DONE keywords active in a buffer.")
  2195. (defvar org-todo-keywords-for-agenda nil)
  2196. (defvar org-done-keywords-for-agenda nil)
  2197. (defvar org-todo-keyword-alist-for-agenda nil)
  2198. (defvar org-tag-alist-for-agenda nil
  2199. "Alist of all tags from all agenda files.")
  2200. (defvar org-tag-groups-alist-for-agenda nil
  2201. "Alist of all groups tags from all current agenda files.")
  2202. (defvar-local org-tag-groups-alist nil)
  2203. (defvar org-agenda-contributing-files nil)
  2204. (defvar-local org-current-tag-alist nil
  2205. "Alist of all tag groups in current buffer.
  2206. This variable takes into consideration `org-tag-alist',
  2207. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2208. (defvar-local org-not-done-keywords nil)
  2209. (defvar-local org-done-keywords nil)
  2210. (defvar-local org-todo-heads nil)
  2211. (defvar-local org-todo-sets nil)
  2212. (defvar-local org-todo-log-states nil)
  2213. (defvar-local org-todo-kwd-alist nil)
  2214. (defvar-local org-todo-key-alist nil)
  2215. (defvar-local org-todo-key-trigger nil)
  2216. (defcustom org-todo-interpretation 'sequence
  2217. "Controls how TODO keywords are interpreted.
  2218. This variable is in principle obsolete and is only used for
  2219. backward compatibility, if the interpretation of todo keywords is
  2220. not given already in `org-todo-keywords'. See that variable for
  2221. more information."
  2222. :group 'org-todo
  2223. :group 'org-keywords
  2224. :type '(choice (const sequence)
  2225. (const type)))
  2226. (defcustom org-use-fast-todo-selection t
  2227. "\\<org-mode-map>\
  2228. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2229. This variable describes if and under what circumstances the cycling
  2230. mechanism for TODO keywords will be replaced by a single-key, direct
  2231. selection scheme.
  2232. When nil, fast selection is never used.
  2233. When the symbol `prefix', it will be used when `org-todo' is called
  2234. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2235. in an Org buffer, and
  2236. `\\[universal-argument] t' in an agenda buffer.
  2237. When t, fast selection is used by default. In this case, the prefix
  2238. argument forces cycling instead.
  2239. In all cases, the special interface is only used if access keys have
  2240. actually been assigned by the user, i.e. if keywords in the configuration
  2241. are followed by a letter in parenthesis, like TODO(t)."
  2242. :group 'org-todo
  2243. :type '(choice
  2244. (const :tag "Never" nil)
  2245. (const :tag "By default" t)
  2246. (const :tag "Only with C-u C-c C-t" prefix)))
  2247. (defcustom org-provide-todo-statistics t
  2248. "Non-nil means update todo statistics after insert and toggle.
  2249. ALL-HEADLINES means update todo statistics by including headlines
  2250. with no TODO keyword as well, counting them as not done.
  2251. A list of TODO keywords means the same, but skip keywords that are
  2252. not in this list.
  2253. When set to a list of two lists, the first list contains keywords
  2254. to consider as TODO keywords, the second list contains keywords
  2255. to consider as DONE keywords.
  2256. When this is set, todo statistics is updated in the parent of the
  2257. current entry each time a todo state is changed."
  2258. :group 'org-todo
  2259. :type '(choice
  2260. (const :tag "Yes, only for TODO entries" t)
  2261. (const :tag "Yes, including all entries" all-headlines)
  2262. (repeat :tag "Yes, for TODOs in this list"
  2263. (string :tag "TODO keyword"))
  2264. (list :tag "Yes, for TODOs and DONEs in these lists"
  2265. (repeat (string :tag "TODO keyword"))
  2266. (repeat (string :tag "DONE keyword")))
  2267. (other :tag "No TODO statistics" nil)))
  2268. (defcustom org-hierarchical-todo-statistics t
  2269. "Non-nil means TODO statistics covers just direct children.
  2270. When nil, all entries in the subtree are considered.
  2271. This has only an effect if `org-provide-todo-statistics' is set.
  2272. To set this to nil for only a single subtree, use a COOKIE_DATA
  2273. property and include the word \"recursive\" into the value."
  2274. :group 'org-todo
  2275. :type 'boolean)
  2276. (defcustom org-after-todo-state-change-hook nil
  2277. "Hook which is run after the state of a TODO item was changed.
  2278. The new state (a string with a TODO keyword, or nil) is available in the
  2279. Lisp variable `org-state'."
  2280. :group 'org-todo
  2281. :type 'hook)
  2282. (defvar org-blocker-hook nil
  2283. "Hook for functions that are allowed to block a state change.
  2284. Functions in this hook should not modify the buffer.
  2285. Each function gets as its single argument a property list,
  2286. see `org-trigger-hook' for more information about this list.
  2287. If any of the functions in this hook returns nil, the state change
  2288. is blocked.")
  2289. (defvar org-trigger-hook nil
  2290. "Hook for functions that are triggered by a state change.
  2291. Each function gets as its single argument a property list with at
  2292. least the following elements:
  2293. (:type type-of-change :position pos-at-entry-start
  2294. :from old-state :to new-state)
  2295. Depending on the type, more properties may be present.
  2296. This mechanism is currently implemented for:
  2297. TODO state changes
  2298. ------------------
  2299. :type todo-state-change
  2300. :from previous state (keyword as a string), or nil, or a symbol
  2301. `todo' or `done', to indicate the general type of state.
  2302. :to new state, like in :from")
  2303. (defcustom org-enforce-todo-dependencies nil
  2304. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2305. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2306. be blocked if any prior sibling is not yet done.
  2307. Finally, if the parent is blocked because of ordered siblings of its own,
  2308. the child will also be blocked."
  2309. :set (lambda (var val)
  2310. (set var val)
  2311. (if val
  2312. (add-hook 'org-blocker-hook
  2313. 'org-block-todo-from-children-or-siblings-or-parent)
  2314. (remove-hook 'org-blocker-hook
  2315. 'org-block-todo-from-children-or-siblings-or-parent)))
  2316. :group 'org-todo
  2317. :type 'boolean)
  2318. (defcustom org-enforce-todo-checkbox-dependencies nil
  2319. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2320. When this is nil, checkboxes have no influence on switching TODO states.
  2321. When non-nil, you first need to check off all check boxes before the TODO
  2322. entry can be switched to DONE.
  2323. This variable needs to be set before org.el is loaded, and you need to
  2324. restart Emacs after a change to make the change effective. The only way
  2325. to change it while Emacs is running is through the customize interface."
  2326. :set (lambda (var val)
  2327. (set var val)
  2328. (if val
  2329. (add-hook 'org-blocker-hook
  2330. 'org-block-todo-from-checkboxes)
  2331. (remove-hook 'org-blocker-hook
  2332. 'org-block-todo-from-checkboxes)))
  2333. :group 'org-todo
  2334. :type 'boolean)
  2335. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2336. "Non-nil means inserting a TODO heading is treated as state change.
  2337. So when the command `\\[org-insert-todo-heading]' is used, state change
  2338. logging will apply if appropriate. When nil, the new TODO item will
  2339. be inserted directly, and no logging will take place."
  2340. :group 'org-todo
  2341. :type 'boolean)
  2342. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2343. "Non-nil means switching TODO states with S-cursor counts as state change.
  2344. This is the default behavior. However, setting this to nil allows a
  2345. convenient way to select a TODO state and bypass any logging associated
  2346. with that."
  2347. :group 'org-todo
  2348. :type 'boolean)
  2349. (defcustom org-todo-state-tags-triggers nil
  2350. "Tag changes that should be triggered by TODO state changes.
  2351. This is a list. Each entry is
  2352. (state-change (tag . flag) .......)
  2353. State-change can be a string with a state, and empty string to indicate the
  2354. state that has no TODO keyword, or it can be one of the symbols `todo'
  2355. or `done', meaning any not-done or done state, respectively."
  2356. :group 'org-todo
  2357. :group 'org-tags
  2358. :type '(repeat
  2359. (cons (choice :tag "When changing to"
  2360. (const :tag "Not-done state" todo)
  2361. (const :tag "Done state" done)
  2362. (string :tag "State"))
  2363. (repeat
  2364. (cons :tag "Tag action"
  2365. (string :tag "Tag")
  2366. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2367. (defcustom org-log-done nil
  2368. "Information to record when a task moves to the DONE state.
  2369. Possible values are:
  2370. nil Don't add anything, just change the keyword
  2371. time Add a time stamp to the task
  2372. note Prompt for a note and add it with template `org-log-note-headings'
  2373. This option can also be set with on a per-file-basis with
  2374. #+STARTUP: nologdone
  2375. #+STARTUP: logdone
  2376. #+STARTUP: lognotedone
  2377. You can have local logging settings for a subtree by setting the LOGGING
  2378. property to one or more of these keywords."
  2379. :group 'org-todo
  2380. :group 'org-progress
  2381. :type '(choice
  2382. (const :tag "No logging" nil)
  2383. (const :tag "Record CLOSED timestamp" time)
  2384. (const :tag "Record CLOSED timestamp with note." note)))
  2385. ;; Normalize old uses of org-log-done.
  2386. (cond
  2387. ((eq org-log-done t) (setq org-log-done 'time))
  2388. ((and (listp org-log-done) (memq 'done org-log-done))
  2389. (setq org-log-done 'note)))
  2390. (defcustom org-log-reschedule nil
  2391. "Information to record when the scheduling date of a task is modified.
  2392. Possible values are:
  2393. nil Don't add anything, just change the date
  2394. time Add a time stamp to the task
  2395. note Prompt for a note and add it with template `org-log-note-headings'
  2396. This option can also be set with on a per-file-basis with
  2397. #+STARTUP: nologreschedule
  2398. #+STARTUP: logreschedule
  2399. #+STARTUP: lognotereschedule
  2400. You can have local logging settings for a subtree by setting the LOGGING
  2401. property to one or more of these keywords.
  2402. This variable has an effect when calling `org-schedule' or
  2403. `org-agenda-schedule' only."
  2404. :group 'org-todo
  2405. :group 'org-progress
  2406. :type '(choice
  2407. (const :tag "No logging" nil)
  2408. (const :tag "Record timestamp" time)
  2409. (const :tag "Record timestamp with note" note)))
  2410. (defcustom org-log-redeadline nil
  2411. "Information to record when the deadline date of a task is modified.
  2412. Possible values are:
  2413. nil Don't add anything, just change the date
  2414. time Add a time stamp to the task
  2415. note Prompt for a note and add it with template `org-log-note-headings'
  2416. This option can also be set with on a per-file-basis with
  2417. #+STARTUP: nologredeadline
  2418. #+STARTUP: logredeadline
  2419. #+STARTUP: lognoteredeadline
  2420. You can have local logging settings for a subtree by setting the LOGGING
  2421. property to one or more of these keywords.
  2422. This variable has an effect when calling `org-deadline' or
  2423. `org-agenda-deadline' only."
  2424. :group 'org-todo
  2425. :group 'org-progress
  2426. :type '(choice
  2427. (const :tag "No logging" nil)
  2428. (const :tag "Record timestamp" time)
  2429. (const :tag "Record timestamp with note." note)))
  2430. (defcustom org-log-note-clock-out nil
  2431. "Non-nil means record a note when clocking out of an item.
  2432. This can also be configured on a per-file basis by adding one of
  2433. the following lines anywhere in the buffer:
  2434. #+STARTUP: lognoteclock-out
  2435. #+STARTUP: nolognoteclock-out"
  2436. :group 'org-todo
  2437. :group 'org-progress
  2438. :type 'boolean)
  2439. (defcustom org-log-done-with-time t
  2440. "Non-nil means the CLOSED time stamp will contain date and time.
  2441. When nil, only the date will be recorded."
  2442. :group 'org-progress
  2443. :type 'boolean)
  2444. (defcustom org-log-note-headings
  2445. '((done . "CLOSING NOTE %t")
  2446. (state . "State %-12s from %-12S %t")
  2447. (note . "Note taken on %t")
  2448. (reschedule . "Rescheduled from %S on %t")
  2449. (delschedule . "Not scheduled, was %S on %t")
  2450. (redeadline . "New deadline from %S on %t")
  2451. (deldeadline . "Removed deadline, was %S on %t")
  2452. (refile . "Refiled on %t")
  2453. (clock-out . ""))
  2454. "Headings for notes added to entries.
  2455. The value is an alist, with the car being a symbol indicating the
  2456. note context, and the cdr is the heading to be used. The heading
  2457. may also be the empty string. The following placeholders can be
  2458. used:
  2459. %t a time stamp.
  2460. %T an active time stamp instead the default inactive one
  2461. %d a short-format time stamp.
  2462. %D an active short-format time stamp.
  2463. %s the new TODO state or time stamp (inactive), in double quotes.
  2464. %S the old TODO state or time stamp (inactive), in double quotes.
  2465. %u the user name.
  2466. %U full user name.
  2467. In fact, it is not a good idea to change the `state' entry,
  2468. because Agenda Log mode depends on the format of these entries."
  2469. :group 'org-todo
  2470. :group 'org-progress
  2471. :type '(list :greedy t
  2472. (cons (const :tag "Heading when closing an item" done) string)
  2473. (cons (const :tag
  2474. "Heading when changing todo state (todo sequence only)"
  2475. state) string)
  2476. (cons (const :tag "Heading when just taking a note" note) string)
  2477. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2478. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2479. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2480. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2481. (cons (const :tag "Heading when refiling" refile) string)
  2482. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2483. (unless (assq 'note org-log-note-headings)
  2484. (push '(note . "%t") org-log-note-headings))
  2485. (defcustom org-log-into-drawer nil
  2486. "Non-nil means insert state change notes and time stamps into a drawer.
  2487. When nil, state changes notes will be inserted after the headline and
  2488. any scheduling and clock lines, but not inside a drawer.
  2489. The value of this variable should be the name of the drawer to use.
  2490. LOGBOOK is proposed as the default drawer for this purpose, you can
  2491. also set this to a string to define the drawer of your choice.
  2492. A value of t is also allowed, representing \"LOGBOOK\".
  2493. A value of t or nil can also be set with on a per-file-basis with
  2494. #+STARTUP: logdrawer
  2495. #+STARTUP: nologdrawer
  2496. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2497. will be ignored.
  2498. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2499. a subtree.
  2500. Do not check directly this variable in a Lisp program. Call
  2501. function `org-log-into-drawer' instead."
  2502. :group 'org-todo
  2503. :group 'org-progress
  2504. :type '(choice
  2505. (const :tag "Not into a drawer" nil)
  2506. (const :tag "LOGBOOK" t)
  2507. (string :tag "Other")))
  2508. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2509. (defun org-log-into-drawer ()
  2510. "Name of the log drawer, as a string, or nil.
  2511. This is the value of `org-log-into-drawer'. However, if the
  2512. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2513. be used instead of the default value."
  2514. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2515. (cond ((equal p "nil") nil)
  2516. ((equal p "t") "LOGBOOK")
  2517. ((stringp p) p)
  2518. (p "LOGBOOK")
  2519. ((stringp org-log-into-drawer) org-log-into-drawer)
  2520. (org-log-into-drawer "LOGBOOK"))))
  2521. (defcustom org-log-state-notes-insert-after-drawers nil
  2522. "Non-nil means insert state change notes after any drawers in entry.
  2523. Only the drawers that *immediately* follow the headline and the
  2524. deadline/scheduled line are skipped.
  2525. When nil, insert notes right after the heading and perhaps the line
  2526. with deadline/scheduling if present.
  2527. This variable will have no effect if `org-log-into-drawer' is
  2528. set."
  2529. :group 'org-todo
  2530. :group 'org-progress
  2531. :type 'boolean)
  2532. (defcustom org-log-states-order-reversed t
  2533. "Non-nil means the latest state note will be directly after heading.
  2534. When nil, the state change notes will be ordered according to time.
  2535. This option can also be set with on a per-file-basis with
  2536. #+STARTUP: logstatesreversed
  2537. #+STARTUP: nologstatesreversed"
  2538. :group 'org-todo
  2539. :group 'org-progress
  2540. :type 'boolean)
  2541. (defcustom org-todo-repeat-to-state nil
  2542. "The TODO state to which a repeater should return the repeating task.
  2543. By default this is the first task of a TODO sequence or the
  2544. previous state of a TYPE_TODO set. But you can specify to use
  2545. the previous state in a TODO sequence or a string.
  2546. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2547. entry, which has precedence over this option."
  2548. :group 'org-todo
  2549. :version "24.1"
  2550. :type '(choice (const :tag "Use the previous TODO state" t)
  2551. (const :tag "Use the head of the TODO sequence" nil)
  2552. (string :tag "Use a specific TODO state")))
  2553. (defcustom org-log-repeat 'time
  2554. "Non-nil means record moving through the DONE state when triggering repeat.
  2555. An auto-repeating task is immediately switched back to TODO when
  2556. marked DONE. If you are not logging state changes (by adding \"@\"
  2557. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2558. record a closing note, there will be no record of the task moving
  2559. through DONE. This variable forces taking a note anyway.
  2560. nil Don't force a record
  2561. time Record a time stamp
  2562. note Prompt for a note and add it with template `org-log-note-headings'
  2563. This option can also be set with on a per-file-basis with
  2564. #+STARTUP: nologrepeat
  2565. #+STARTUP: logrepeat
  2566. #+STARTUP: lognoterepeat
  2567. You can have local logging settings for a subtree by setting the LOGGING
  2568. property to one or more of these keywords."
  2569. :group 'org-todo
  2570. :group 'org-progress
  2571. :type '(choice
  2572. (const :tag "Don't force a record" nil)
  2573. (const :tag "Force recording the DONE state" time)
  2574. (const :tag "Force recording a note with the DONE state" note)))
  2575. (defgroup org-priorities nil
  2576. "Priorities in Org mode."
  2577. :tag "Org Priorities"
  2578. :group 'org-todo)
  2579. (defcustom org-enable-priority-commands t
  2580. "Non-nil means priority commands are active.
  2581. When nil, these commands will be disabled, so that you never accidentally
  2582. set a priority."
  2583. :group 'org-priorities
  2584. :type 'boolean)
  2585. (defcustom org-highest-priority ?A
  2586. "The highest priority of TODO items. A character like ?A, ?B etc.
  2587. Must have a smaller ASCII number than `org-lowest-priority'."
  2588. :group 'org-priorities
  2589. :type 'character)
  2590. (defcustom org-lowest-priority ?C
  2591. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2592. Must have a larger ASCII number than `org-highest-priority'."
  2593. :group 'org-priorities
  2594. :type 'character)
  2595. (defcustom org-default-priority ?B
  2596. "The default priority of TODO items.
  2597. This is the priority an item gets if no explicit priority is given.
  2598. When starting to cycle on an empty priority the first step in the cycle
  2599. depends on `org-priority-start-cycle-with-default'. The resulting first
  2600. step priority must not exceed the range from `org-highest-priority' to
  2601. `org-lowest-priority' which means that `org-default-priority' has to be
  2602. in this range exclusive or inclusive the range boundaries. Else the
  2603. first step refuses to set the default and the second will fall back
  2604. to (depending on the command used) the highest or lowest priority."
  2605. :group 'org-priorities
  2606. :type 'character)
  2607. (defcustom org-priority-start-cycle-with-default t
  2608. "Non-nil means start with default priority when starting to cycle.
  2609. When this is nil, the first step in the cycle will be (depending on the
  2610. command used) one higher or lower than the default priority.
  2611. See also `org-default-priority'."
  2612. :group 'org-priorities
  2613. :type 'boolean)
  2614. (defcustom org-get-priority-function nil
  2615. "Function to extract the priority from a string.
  2616. The string is normally the headline. If this is nil Org computes the
  2617. priority from the priority cookie like [#A] in the headline. It returns
  2618. an integer, increasing by 1000 for each priority level.
  2619. The user can set a different function here, which should take a string
  2620. as an argument and return the numeric priority."
  2621. :group 'org-priorities
  2622. :version "24.1"
  2623. :type '(choice
  2624. (const nil)
  2625. (function)))
  2626. (defgroup org-time nil
  2627. "Options concerning time stamps and deadlines in Org mode."
  2628. :tag "Org Time"
  2629. :group 'org)
  2630. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2631. "Number of minutes to round time stamps to.
  2632. \\<org-mode-map>\
  2633. These are two values, the first applies when first creating a time stamp.
  2634. The second applies when changing it with the commands `S-up' and `S-down'.
  2635. When changing the time stamp, this means that it will change in steps
  2636. of N minutes, as given by the second value.
  2637. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2638. numbers should be factors of 60, so for example 5, 10, 15.
  2639. When this is larger than 1, you can still force an exact time stamp by using
  2640. a double prefix argument to a time stamp command like \
  2641. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2642. and by using a prefix arg to `S-up/down' to specify the exact number
  2643. of minutes to shift."
  2644. :group 'org-time
  2645. :get (lambda (var) ; Make sure both elements are there
  2646. (if (integerp (default-value var))
  2647. (list (default-value var) 5)
  2648. (default-value var)))
  2649. :type '(list
  2650. (integer :tag "when inserting times")
  2651. (integer :tag "when modifying times")))
  2652. ;; Normalize old customizations of this variable.
  2653. (when (integerp org-time-stamp-rounding-minutes)
  2654. (setq org-time-stamp-rounding-minutes
  2655. (list org-time-stamp-rounding-minutes
  2656. org-time-stamp-rounding-minutes)))
  2657. (defcustom org-display-custom-times nil
  2658. "Non-nil means overlay custom formats over all time stamps.
  2659. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2660. To turn this on on a per-file basis, insert anywhere in the file:
  2661. #+STARTUP: customtime"
  2662. :group 'org-time
  2663. :set 'set-default
  2664. :type 'sexp)
  2665. (make-variable-buffer-local 'org-display-custom-times)
  2666. (defcustom org-time-stamp-custom-formats
  2667. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2668. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2669. These are overlaid over the default ISO format if the variable
  2670. `org-display-custom-times' is set. Time like %H:%M should be at the
  2671. end of the second format. The custom formats are also honored by export
  2672. commands, if custom time display is turned on at the time of export."
  2673. :group 'org-time
  2674. :type 'sexp)
  2675. (defun org-time-stamp-format (&optional long inactive)
  2676. "Get the right format for a time string."
  2677. (let ((f (if long (cdr org-time-stamp-formats)
  2678. (car org-time-stamp-formats))))
  2679. (if inactive
  2680. (concat "[" (substring f 1 -1) "]")
  2681. f)))
  2682. (defcustom org-deadline-warning-days 14
  2683. "Number of days before expiration during which a deadline becomes active.
  2684. This variable governs the display in sparse trees and in the agenda.
  2685. When 0 or negative, it means use this number (the absolute value of it)
  2686. even if a deadline has a different individual lead time specified.
  2687. Custom commands can set this variable in the options section."
  2688. :group 'org-time
  2689. :group 'org-agenda-daily/weekly
  2690. :type 'integer)
  2691. (defcustom org-scheduled-delay-days 0
  2692. "Number of days before a scheduled item becomes active.
  2693. This variable governs the display in sparse trees and in the agenda.
  2694. The default value (i.e. 0) means: don't delay scheduled item.
  2695. When negative, it means use this number (the absolute value of it)
  2696. even if a scheduled item has a different individual delay time
  2697. specified.
  2698. Custom commands can set this variable in the options section."
  2699. :group 'org-time
  2700. :group 'org-agenda-daily/weekly
  2701. :version "24.4"
  2702. :package-version '(Org . "8.0")
  2703. :type 'integer)
  2704. (defcustom org-read-date-prefer-future t
  2705. "Non-nil means assume future for incomplete date input from user.
  2706. This affects the following situations:
  2707. 1. The user gives a month but not a year.
  2708. For example, if it is April and you enter \"feb 2\", this will be read
  2709. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2710. 2. The user gives a day, but no month.
  2711. For example, if today is the 15th, and you enter \"3\", Org will read
  2712. this as the third of *next* month. However, if you enter \"17\",
  2713. it will be considered as *this* month.
  2714. If you set this variable to the symbol `time', then also the following
  2715. will work:
  2716. 3. If the user gives a time.
  2717. If the time is before now, it will be interpreted as tomorrow.
  2718. Currently none of this works for ISO week specifications.
  2719. When this option is nil, the current day, month and year will always be
  2720. used as defaults.
  2721. See also `org-agenda-jump-prefer-future'."
  2722. :group 'org-time
  2723. :type '(choice
  2724. (const :tag "Never" nil)
  2725. (const :tag "Check month and day" t)
  2726. (const :tag "Check month, day, and time" time)))
  2727. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2728. "Should the agenda jump command prefer the future for incomplete dates?
  2729. The default is to do the same as configured in `org-read-date-prefer-future'.
  2730. But you can also set a deviating value here.
  2731. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2732. :group 'org-agenda
  2733. :group 'org-time
  2734. :version "24.1"
  2735. :type '(choice
  2736. (const :tag "Use org-read-date-prefer-future"
  2737. org-read-date-prefer-future)
  2738. (const :tag "Never" nil)
  2739. (const :tag "Always" t)))
  2740. (defcustom org-read-date-force-compatible-dates t
  2741. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2742. Depending on the system Emacs is running on, certain dates cannot
  2743. be represented with the type used internally to represent time.
  2744. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2745. correctly. Some systems allow for earlier dates, some for later,
  2746. some for both. One way to find out it to insert any date into an
  2747. Org buffer, putting the cursor on the year and hitting S-up and
  2748. S-down to test the range.
  2749. When this variable is set to t, the date/time prompt will not let
  2750. you specify dates outside the 1970-2037 range, so it is certain that
  2751. these dates will work in whatever version of Emacs you are
  2752. running, and also that you can move a file from one Emacs implementation
  2753. to another. WHenever Org is forcing the year for you, it will display
  2754. a message and beep.
  2755. When this variable is nil, Org will check if the date is
  2756. representable in the specific Emacs implementation you are using.
  2757. If not, it will force a year, usually the current year, and beep
  2758. to remind you. Currently this setting is not recommended because
  2759. the likelihood that you will open your Org files in an Emacs that
  2760. has limited date range is not negligible.
  2761. A workaround for this problem is to use diary sexp dates for time
  2762. stamps outside of this range."
  2763. :group 'org-time
  2764. :version "24.1"
  2765. :type 'boolean)
  2766. (defcustom org-read-date-display-live t
  2767. "Non-nil means display current interpretation of date prompt live.
  2768. This display will be in an overlay, in the minibuffer."
  2769. :group 'org-time
  2770. :type 'boolean)
  2771. (defcustom org-read-date-popup-calendar t
  2772. "Non-nil means pop up a calendar when prompting for a date.
  2773. In the calendar, the date can be selected with mouse-1. However, the
  2774. minibuffer will also be active, and you can simply enter the date as well.
  2775. When nil, only the minibuffer will be available."
  2776. :group 'org-time
  2777. :type 'boolean)
  2778. (defvaralias 'org-popup-calendar-for-date-prompt
  2779. 'org-read-date-popup-calendar)
  2780. (defcustom org-extend-today-until 0
  2781. "The hour when your day really ends. Must be an integer.
  2782. This has influence for the following applications:
  2783. - When switching the agenda to \"today\". It it is still earlier than
  2784. the time given here, the day recognized as TODAY is actually yesterday.
  2785. - When a date is read from the user and it is still before the time given
  2786. here, the current date and time will be assumed to be yesterday, 23:59.
  2787. Also, timestamps inserted in capture templates follow this rule.
  2788. IMPORTANT: This is a feature whose implementation is and likely will
  2789. remain incomplete. Really, it is only here because past midnight seems to
  2790. be the favorite working time of John Wiegley :-)"
  2791. :group 'org-time
  2792. :type 'integer)
  2793. (defcustom org-use-effective-time nil
  2794. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2795. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2796. \"effective time\" of any timestamps between midnight and 8am will be
  2797. 23:59 of the previous day."
  2798. :group 'org-time
  2799. :version "24.1"
  2800. :type 'boolean)
  2801. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2802. "When non-nil, use the last clock out time for `org-todo'.
  2803. Note that this option has precedence over the combined use of
  2804. `org-use-effective-time' and `org-extend-today-until'."
  2805. :group 'org-time
  2806. :version "24.4"
  2807. :package-version '(Org . "8.0")
  2808. :type 'boolean)
  2809. (defcustom org-edit-timestamp-down-means-later nil
  2810. "Non-nil means S-down will increase the time in a time stamp.
  2811. When nil, S-up will increase."
  2812. :group 'org-time
  2813. :type 'boolean)
  2814. (defcustom org-calendar-follow-timestamp-change t
  2815. "Non-nil means make the calendar window follow timestamp changes.
  2816. When a timestamp is modified and the calendar window is visible, it will be
  2817. moved to the new date."
  2818. :group 'org-time
  2819. :type 'boolean)
  2820. (defgroup org-tags nil
  2821. "Options concerning tags in Org mode."
  2822. :tag "Org Tags"
  2823. :group 'org)
  2824. (defcustom org-tag-alist nil
  2825. "Default tags available in Org files.
  2826. The value of this variable is an alist. Associations either:
  2827. (TAG)
  2828. (TAG . SELECT)
  2829. (SPECIAL)
  2830. where TAG is a tag as a string, SELECT is character, used to
  2831. select that tag through the fast tag selection interface, and
  2832. SPECIAL is one of the following keywords: `:startgroup',
  2833. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2834. `:newline'. These keywords are used to define a hierarchy of
  2835. tags. See manual for details.
  2836. When this variable is nil, Org mode bases tag input on what is
  2837. already in the buffer. The value can be overridden locally by
  2838. using a TAGS keyword, e.g.,
  2839. #+TAGS: tag1 tag2
  2840. See also `org-tag-persistent-alist' to sidestep this behavior."
  2841. :group 'org-tags
  2842. :type '(repeat
  2843. (choice
  2844. (cons :tag "Tag with key"
  2845. (string :tag "Tag name")
  2846. (character :tag "Access char"))
  2847. (list :tag "Tag" (string :tag "Tag name"))
  2848. (const :tag "Start radio group" (:startgroup))
  2849. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2850. (const :tag "Group tags delimiter" (:grouptags))
  2851. (const :tag "End radio group" (:endgroup))
  2852. (const :tag "End tag group, non distinct" (:endgrouptag))
  2853. (const :tag "New line" (:newline)))))
  2854. (defcustom org-tag-persistent-alist nil
  2855. "Tags always available in Org files.
  2856. The value of this variable is an alist. Associations either:
  2857. (TAG)
  2858. (TAG . SELECT)
  2859. (SPECIAL)
  2860. where TAG is a tag as a string, SELECT is a character, used to
  2861. select that tag through the fast tag selection interface, and
  2862. SPECIAL is one of the following keywords: `:startgroup',
  2863. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2864. `:newline'. These keywords are used to define a hierarchy of
  2865. tags. See manual for details.
  2866. Unlike to `org-tag-alist', tags defined in this variable do not
  2867. depend on a local TAGS keyword. Instead, to disable these tags
  2868. on a per-file basis, insert anywhere in the file:
  2869. #+STARTUP: noptag"
  2870. :group 'org-tags
  2871. :type '(repeat
  2872. (choice
  2873. (cons :tag "Tag with key"
  2874. (string :tag "Tag name")
  2875. (character :tag "Access char"))
  2876. (list :tag "Tag" (string :tag "Tag name"))
  2877. (const :tag "Start radio group" (:startgroup))
  2878. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2879. (const :tag "Group tags delimiter" (:grouptags))
  2880. (const :tag "End radio group" (:endgroup))
  2881. (const :tag "End tag group, non distinct" (:endgrouptag))
  2882. (const :tag "New line" (:newline)))))
  2883. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2884. "If non-nil, always offer completion for all tags of all agenda files.
  2885. Setting this variable locally allows for dynamic generation of tag
  2886. completions in capture buffers.
  2887. (add-hook \\='org-capture-mode-hook
  2888. (lambda ()
  2889. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2890. :group 'org-tags
  2891. :version "24.1"
  2892. :type 'boolean)
  2893. (defvar org-file-tags nil
  2894. "List of tags that can be inherited by all entries in the file.
  2895. The tags will be inherited if the variable `org-use-tag-inheritance'
  2896. says they should be.
  2897. This variable is populated from #+FILETAGS lines.")
  2898. (defcustom org-use-fast-tag-selection 'auto
  2899. "Non-nil means use fast tag selection scheme.
  2900. This is a special interface to select and deselect tags with single keys.
  2901. When nil, fast selection is never used.
  2902. When the symbol `auto', fast selection is used if and only if selection
  2903. characters for tags have been configured, either through the variable
  2904. `org-tag-alist' or through a #+TAGS line in the buffer.
  2905. When t, fast selection is always used and selection keys are assigned
  2906. automatically if necessary."
  2907. :group 'org-tags
  2908. :type '(choice
  2909. (const :tag "Always" t)
  2910. (const :tag "Never" nil)
  2911. (const :tag "When selection characters are configured" auto)))
  2912. (defcustom org-fast-tag-selection-single-key nil
  2913. "Non-nil means fast tag selection exits after first change.
  2914. When nil, you have to press RET to exit it.
  2915. During fast tag selection, you can toggle this flag with `C-c'.
  2916. This variable can also have the value `expert'. In this case, the window
  2917. displaying the tags menu is not even shown, until you press C-c again."
  2918. :group 'org-tags
  2919. :type '(choice
  2920. (const :tag "No" nil)
  2921. (const :tag "Yes" t)
  2922. (const :tag "Expert" expert)))
  2923. (defvar org-fast-tag-selection-include-todo nil
  2924. "Non-nil means fast tags selection interface will also offer TODO states.
  2925. This is an undocumented feature, you should not rely on it.")
  2926. (defcustom org-tags-column -77
  2927. "The column to which tags should be indented in a headline.
  2928. If this number is positive, it specifies the column. If it is negative,
  2929. it means that the tags should be flushright to that column. For example,
  2930. -80 works well for a normal 80 character screen.
  2931. When 0, place tags directly after headline text, with only one space in
  2932. between."
  2933. :group 'org-tags
  2934. :type 'integer)
  2935. (defcustom org-auto-align-tags t
  2936. "Non-nil keeps tags aligned when modifying headlines.
  2937. Some operations (i.e. demoting) change the length of a headline and
  2938. therefore shift the tags around. With this option turned on, after
  2939. each such operation the tags are again aligned to `org-tags-column'."
  2940. :group 'org-tags
  2941. :type 'boolean)
  2942. (defcustom org-use-tag-inheritance t
  2943. "Non-nil means tags in levels apply also for sublevels.
  2944. When nil, only the tags directly given in a specific line apply there.
  2945. This may also be a list of tags that should be inherited, or a regexp that
  2946. matches tags that should be inherited. Additional control is possible
  2947. with the variable `org-tags-exclude-from-inheritance' which gives an
  2948. explicit list of tags to be excluded from inheritance, even if the value of
  2949. `org-use-tag-inheritance' would select it for inheritance.
  2950. If this option is t, a match early-on in a tree can lead to a large
  2951. number of matches in the subtree when constructing the agenda or creating
  2952. a sparse tree. If you only want to see the first match in a tree during
  2953. a search, check out the variable `org-tags-match-list-sublevels'."
  2954. :group 'org-tags
  2955. :type '(choice
  2956. (const :tag "Not" nil)
  2957. (const :tag "Always" t)
  2958. (repeat :tag "Specific tags" (string :tag "Tag"))
  2959. (regexp :tag "Tags matched by regexp")))
  2960. (defcustom org-tags-exclude-from-inheritance nil
  2961. "List of tags that should never be inherited.
  2962. This is a way to exclude a few tags from inheritance. For way to do
  2963. the opposite, to actively allow inheritance for selected tags,
  2964. see the variable `org-use-tag-inheritance'."
  2965. :group 'org-tags
  2966. :type '(repeat (string :tag "Tag")))
  2967. (defun org-tag-inherit-p (tag)
  2968. "Check if TAG is one that should be inherited."
  2969. (cond
  2970. ((member tag org-tags-exclude-from-inheritance) nil)
  2971. ((eq org-use-tag-inheritance t) t)
  2972. ((not org-use-tag-inheritance) nil)
  2973. ((stringp org-use-tag-inheritance)
  2974. (string-match org-use-tag-inheritance tag))
  2975. ((listp org-use-tag-inheritance)
  2976. (member tag org-use-tag-inheritance))
  2977. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2978. (defcustom org-tags-match-list-sublevels t
  2979. "Non-nil means list also sublevels of headlines matching a search.
  2980. This variable applies to tags/property searches, and also to stuck
  2981. projects because this search is based on a tags match as well.
  2982. When set to the symbol `indented', sublevels are indented with
  2983. leading dots.
  2984. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2985. the sublevels of a headline matching a tag search often also match
  2986. the same search. Listing all of them can create very long lists.
  2987. Setting this variable to nil causes subtrees of a match to be skipped.
  2988. This variable is semi-obsolete and probably should always be true. It
  2989. is better to limit inheritance to certain tags using the variables
  2990. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2991. :group 'org-tags
  2992. :type '(choice
  2993. (const :tag "No, don't list them" nil)
  2994. (const :tag "Yes, do list them" t)
  2995. (const :tag "List them, indented with leading dots" indented)))
  2996. (defcustom org-tags-sort-function nil
  2997. "When set, tags are sorted using this function as a comparator."
  2998. :group 'org-tags
  2999. :type '(choice
  3000. (const :tag "No sorting" nil)
  3001. (const :tag "Alphabetical" org-string-collate-lessp)
  3002. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  3003. (function :tag "Custom function" nil)))
  3004. (defvar org-tags-history nil
  3005. "History of minibuffer reads for tags.")
  3006. (defvar org-last-tags-completion-table nil
  3007. "The last used completion table for tags.")
  3008. (defvar org-after-tags-change-hook nil
  3009. "Hook that is run after the tags in a line have changed.")
  3010. (defgroup org-properties nil
  3011. "Options concerning properties in Org mode."
  3012. :tag "Org Properties"
  3013. :group 'org)
  3014. (defcustom org-property-format "%-10s %s"
  3015. "How property key/value pairs should be formatted by `indent-line'.
  3016. When `indent-line' hits a property definition, it will format the line
  3017. according to this format, mainly to make sure that the values are
  3018. lined-up with respect to each other."
  3019. :group 'org-properties
  3020. :type 'string)
  3021. (defcustom org-properties-postprocess-alist nil
  3022. "Alist of properties and functions to adjust inserted values.
  3023. Elements of this alist must be of the form
  3024. ([string] [function])
  3025. where [string] must be a property name and [function] must be a
  3026. lambda expression: this lambda expression must take one argument,
  3027. the value to adjust, and return the new value as a string.
  3028. For example, this element will allow the property \"Remaining\"
  3029. to be updated wrt the relation between the \"Effort\" property
  3030. and the clock summary:
  3031. ((\"Remaining\" (lambda(value)
  3032. (let ((clocksum (org-clock-sum-current-item))
  3033. (effort (org-duration-to-minutes
  3034. (org-entry-get (point) \"Effort\"))))
  3035. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3036. :group 'org-properties
  3037. :version "24.1"
  3038. :type '(alist :key-type (string :tag "Property")
  3039. :value-type (function :tag "Function")))
  3040. (defcustom org-use-property-inheritance nil
  3041. "Non-nil means properties apply also for sublevels.
  3042. This setting is chiefly used during property searches. Turning it on can
  3043. cause significant overhead when doing a search, which is why it is not
  3044. on by default.
  3045. When nil, only the properties directly given in the current entry count.
  3046. When t, every property is inherited. The value may also be a list of
  3047. properties that should have inheritance, or a regular expression matching
  3048. properties that should be inherited.
  3049. However, note that some special properties use inheritance under special
  3050. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3051. and the properties ending in \"_ALL\" when they are used as descriptor
  3052. for valid values of a property.
  3053. Note for programmers:
  3054. When querying an entry with `org-entry-get', you can control if inheritance
  3055. should be used. By default, `org-entry-get' looks only at the local
  3056. properties. You can request inheritance by setting the inherit argument
  3057. to t (to force inheritance) or to `selective' (to respect the setting
  3058. in this variable)."
  3059. :group 'org-properties
  3060. :type '(choice
  3061. (const :tag "Not" nil)
  3062. (const :tag "Always" t)
  3063. (repeat :tag "Specific properties" (string :tag "Property"))
  3064. (regexp :tag "Properties matched by regexp")))
  3065. (defun org-property-inherit-p (property)
  3066. "Return a non-nil value if PROPERTY should be inherited."
  3067. (cond
  3068. ((eq org-use-property-inheritance t) t)
  3069. ((not org-use-property-inheritance) nil)
  3070. ((stringp org-use-property-inheritance)
  3071. (string-match org-use-property-inheritance property))
  3072. ((listp org-use-property-inheritance)
  3073. (member-ignore-case property org-use-property-inheritance))
  3074. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3075. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3076. "The default column format, if no other format has been defined.
  3077. This variable can be set on the per-file basis by inserting a line
  3078. #+COLUMNS: %25ITEM ....."
  3079. :group 'org-properties
  3080. :type 'string)
  3081. (defcustom org-columns-ellipses ".."
  3082. "The ellipses to be used when a field in column view is truncated.
  3083. When this is the empty string, as many characters as possible are shown,
  3084. but then there will be no visual indication that the field has been truncated.
  3085. When this is a string of length N, the last N characters of a truncated
  3086. field are replaced by this string. If the column is narrower than the
  3087. ellipses string, only part of the ellipses string will be shown."
  3088. :group 'org-properties
  3089. :type 'string)
  3090. (defconst org-global-properties-fixed
  3091. '(("VISIBILITY_ALL" . "folded children content all")
  3092. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3093. "List of property/value pairs that can be inherited by any entry.
  3094. These are fixed values, for the preset properties. The user variable
  3095. that can be used to add to this list is `org-global-properties'.
  3096. The entries in this list are cons cells where the car is a property
  3097. name and cdr is a string with the value. If the value represents
  3098. multiple items like an \"_ALL\" property, separate the items by
  3099. spaces.")
  3100. (defcustom org-global-properties nil
  3101. "List of property/value pairs that can be inherited by any entry.
  3102. This list will be combined with the constant `org-global-properties-fixed'.
  3103. The entries in this list are cons cells where the car is a property
  3104. name and cdr is a string with the value.
  3105. You can set buffer-local values for the same purpose in the variable
  3106. `org-file-properties' this by adding lines like
  3107. #+PROPERTY: NAME VALUE"
  3108. :group 'org-properties
  3109. :type '(repeat
  3110. (cons (string :tag "Property")
  3111. (string :tag "Value"))))
  3112. (defvar-local org-file-properties nil
  3113. "List of property/value pairs that can be inherited by any entry.
  3114. Valid for the current buffer.
  3115. This variable is populated from #+PROPERTY lines.")
  3116. (defgroup org-agenda nil
  3117. "Options concerning agenda views in Org mode."
  3118. :tag "Org Agenda"
  3119. :group 'org)
  3120. (defvar-local org-category nil
  3121. "Variable used by Org files to set a category for agenda display.
  3122. Such files should use a file variable to set it, for example
  3123. # -*- mode: org; org-category: \"ELisp\"
  3124. or contain a special line
  3125. #+CATEGORY: ELisp
  3126. If the file does not specify a category, then file's base name
  3127. is used instead.")
  3128. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3129. (defcustom org-agenda-files nil
  3130. "The files to be used for agenda display.
  3131. If an entry is a directory, all files in that directory that are matched
  3132. by `org-agenda-file-regexp' will be part of the file list.
  3133. If the value of the variable is not a list but a single file name, then
  3134. the list of agenda files is actually stored and maintained in that file,
  3135. one agenda file per line. In this file paths can be given relative to
  3136. `org-directory'. Tilde expansion and environment variable substitution
  3137. are also made.
  3138. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3139. and removed with `\\[org-remove-file]'."
  3140. :group 'org-agenda
  3141. :type '(choice
  3142. (repeat :tag "List of files and directories" file)
  3143. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3144. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3145. "Regular expression to match files for `org-agenda-files'.
  3146. If any element in the list in that variable contains a directory instead
  3147. of a normal file, all files in that directory that are matched by this
  3148. regular expression will be included."
  3149. :group 'org-agenda
  3150. :type 'regexp)
  3151. (defcustom org-agenda-text-search-extra-files nil
  3152. "List of extra files to be searched by text search commands.
  3153. These files will be searched in addition to the agenda files by the
  3154. commands `org-search-view' (`\\[org-agenda] s') \
  3155. and `org-occur-in-agenda-files'.
  3156. Note that these files will only be searched for text search commands,
  3157. not for the other agenda views like todo lists, tag searches or the weekly
  3158. agenda. This variable is intended to list notes and possibly archive files
  3159. that should also be searched by these two commands.
  3160. In fact, if the first element in the list is the symbol `agenda-archives',
  3161. then all archive files of all agenda files will be added to the search
  3162. scope."
  3163. :group 'org-agenda
  3164. :type '(set :greedy t
  3165. (const :tag "Agenda Archives" agenda-archives)
  3166. (repeat :inline t (file))))
  3167. (defvaralias 'org-agenda-multi-occur-extra-files
  3168. 'org-agenda-text-search-extra-files)
  3169. (defcustom org-agenda-skip-unavailable-files nil
  3170. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3171. A nil value means to remove them, after a query, from the list."
  3172. :group 'org-agenda
  3173. :type 'boolean)
  3174. (defcustom org-agenda-diary-file 'diary-file
  3175. "File to which to add new entries with the `i' key in agenda and calendar.
  3176. When this is the symbol `diary-file', the functionality in the Emacs
  3177. calendar will be used to add entries to the `diary-file'. But when this
  3178. points to a file, `org-agenda-diary-entry' will be used instead."
  3179. :group 'org-agenda
  3180. :type '(choice
  3181. (const :tag "The standard Emacs diary file" diary-file)
  3182. (file :tag "Special Org file diary entries")))
  3183. (defgroup org-latex nil
  3184. "Options for embedding LaTeX code into Org mode."
  3185. :tag "Org LaTeX"
  3186. :group 'org)
  3187. (defcustom org-format-latex-options
  3188. '(:foreground default :background default :scale 1.0
  3189. :html-foreground "Black" :html-background "Transparent"
  3190. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3191. "Options for creating images from LaTeX fragments.
  3192. This is a property list with the following properties:
  3193. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3194. `default' means use the foreground of the default face.
  3195. `auto' means use the foreground from the text face.
  3196. :background the background color, or \"Transparent\".
  3197. `default' means use the background of the default face.
  3198. `auto' means use the background from the text face.
  3199. :scale a scaling factor for the size of the images, to get more pixels
  3200. :html-foreground, :html-background, :html-scale
  3201. the same numbers for HTML export.
  3202. :matchers a list indicating which matchers should be used to
  3203. find LaTeX fragments. Valid members of this list are:
  3204. \"begin\" find environments
  3205. \"$1\" find single characters surrounded by $.$
  3206. \"$\" find math expressions surrounded by $...$
  3207. \"$$\" find math expressions surrounded by $$....$$
  3208. \"\\(\" find math expressions surrounded by \\(...\\)
  3209. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3210. :group 'org-latex
  3211. :type 'plist)
  3212. (defcustom org-format-latex-signal-error t
  3213. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3214. When nil, just push out a message."
  3215. :group 'org-latex
  3216. :version "24.1"
  3217. :type 'boolean)
  3218. (defcustom org-latex-to-mathml-jar-file nil
  3219. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3220. Use this to specify additional executable file say a jar file.
  3221. When using MathToWeb as the converter, specify the full-path to
  3222. your mathtoweb.jar file."
  3223. :group 'org-latex
  3224. :version "24.1"
  3225. :type '(choice
  3226. (const :tag "None" nil)
  3227. (file :tag "JAR file" :must-match t)))
  3228. (defcustom org-latex-to-mathml-convert-command nil
  3229. "Command to convert LaTeX fragments to MathML.
  3230. Replace format-specifiers in the command as noted below and use
  3231. `shell-command' to convert LaTeX to MathML.
  3232. %j: Executable file in fully expanded form as specified by
  3233. `org-latex-to-mathml-jar-file'.
  3234. %I: Input LaTeX file in fully expanded form.
  3235. %i: The latex fragment to be converted.
  3236. %o: Output MathML file.
  3237. This command is used by `org-create-math-formula'.
  3238. When using MathToWeb as the converter, set this option to
  3239. \"java -jar %j -unicode -force -df %o %I\".
  3240. When using LaTeXML set this option to
  3241. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3242. :group 'org-latex
  3243. :version "24.1"
  3244. :type '(choice
  3245. (const :tag "None" nil)
  3246. (string :tag "\nShell command")))
  3247. (defcustom org-preview-latex-default-process 'dvipng
  3248. "The default process to convert LaTeX fragments to image files.
  3249. All available processes and theirs documents can be found in
  3250. `org-preview-latex-process-alist', which see."
  3251. :group 'org-latex
  3252. :version "26.1"
  3253. :package-version '(Org . "9.0")
  3254. :type 'symbol)
  3255. (defcustom org-preview-latex-process-alist
  3256. '((dvipng
  3257. :programs ("latex" "dvipng")
  3258. :description "dvi > png"
  3259. :message "you need to install the programs: latex and dvipng."
  3260. :image-input-type "dvi"
  3261. :image-output-type "png"
  3262. :image-size-adjust (1.0 . 1.0)
  3263. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3264. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3265. (dvisvgm
  3266. :programs ("latex" "dvisvgm")
  3267. :description "dvi > svg"
  3268. :message "you need to install the programs: latex and dvisvgm."
  3269. :use-xcolor t
  3270. :image-input-type "dvi"
  3271. :image-output-type "svg"
  3272. :image-size-adjust (1.7 . 1.5)
  3273. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3274. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3275. (imagemagick
  3276. :programs ("latex" "convert")
  3277. :description "pdf > png"
  3278. :message "you need to install the programs: latex and imagemagick."
  3279. :use-xcolor t
  3280. :image-input-type "pdf"
  3281. :image-output-type "png"
  3282. :image-size-adjust (1.0 . 1.0)
  3283. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3284. :image-converter
  3285. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3286. "Definitions of external processes for LaTeX previewing.
  3287. Org mode can use some external commands to generate TeX snippet's images for
  3288. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3289. `org-create-formula-image' how to call them.
  3290. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3291. PROPERTIES accepts the following attributes:
  3292. :programs list of strings, required programs.
  3293. :description string, describe the process.
  3294. :message string, message it when required programs cannot be found.
  3295. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3296. :image-output-type string, output file type of image converter (e.g., \"png\").
  3297. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3298. deal with background and foreground color of image.
  3299. Otherwise, dvipng style background and foreground color
  3300. format are generated. You may then refer to them in
  3301. command options with \"%F\" and \"%B\".
  3302. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3303. image size showed in buffer and the cdr element is for
  3304. HTML file. This option is only useful for process
  3305. developers, users should use variable
  3306. `org-format-latex-options' instead.
  3307. :post-clean list of strings, files matched are to be cleaned up once
  3308. the image is generated. When nil, the files with \".dvi\",
  3309. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3310. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3311. be cleaned up.
  3312. :latex-header list of strings, the LaTeX header of the snippet file.
  3313. When nil, the fallback value is used instead, which is
  3314. controlled by `org-format-latex-header',
  3315. `org-latex-default-packages-alist' and
  3316. `org-latex-packages-alist', which see.
  3317. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3318. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3319. replaced with values defined below.
  3320. :image-converter list of image converter commands strings. Each of them is
  3321. given to the shell and supports any of the following
  3322. place-holders defined below.
  3323. Place-holders used by `:image-converter' and `:latex-compiler':
  3324. %f input file name
  3325. %b base name of input file
  3326. %o base directory of input file
  3327. %O absolute output file name
  3328. Place-holders only used by `:image-converter':
  3329. %F foreground of image
  3330. %B background of image
  3331. %D dpi, which is used to adjust image size by some processing commands.
  3332. %S the image size scale ratio, which is used to adjust image size by some
  3333. processing commands."
  3334. :group 'org-latex
  3335. :version "26.1"
  3336. :package-version '(Org . "9.0")
  3337. :type '(alist :tag "LaTeX to image backends"
  3338. :value-type (plist)))
  3339. (defcustom org-preview-latex-image-directory "ltximg/"
  3340. "Path to store latex preview images.
  3341. A relative path here creates many directories relative to the
  3342. processed Org files paths. An absolute path puts all preview
  3343. images at the same place."
  3344. :group 'org-latex
  3345. :version "26.1"
  3346. :package-version '(Org . "9.0")
  3347. :type 'string)
  3348. (defun org-format-latex-mathml-available-p ()
  3349. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3350. (save-match-data
  3351. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3352. org-latex-to-mathml-convert-command)
  3353. (let ((executable (car (split-string
  3354. org-latex-to-mathml-convert-command))))
  3355. (when (executable-find executable)
  3356. (if (string-match
  3357. "%j" org-latex-to-mathml-convert-command)
  3358. (file-readable-p org-latex-to-mathml-jar-file)
  3359. t))))))
  3360. (defcustom org-format-latex-header "\\documentclass{article}
  3361. \\usepackage[usenames]{color}
  3362. \[PACKAGES]
  3363. \[DEFAULT-PACKAGES]
  3364. \\pagestyle{empty} % do not remove
  3365. % The settings below are copied from fullpage.sty
  3366. \\setlength{\\textwidth}{\\paperwidth}
  3367. \\addtolength{\\textwidth}{-3cm}
  3368. \\setlength{\\oddsidemargin}{1.5cm}
  3369. \\addtolength{\\oddsidemargin}{-2.54cm}
  3370. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3371. \\setlength{\\textheight}{\\paperheight}
  3372. \\addtolength{\\textheight}{-\\headheight}
  3373. \\addtolength{\\textheight}{-\\headsep}
  3374. \\addtolength{\\textheight}{-\\footskip}
  3375. \\addtolength{\\textheight}{-3cm}
  3376. \\setlength{\\topmargin}{1.5cm}
  3377. \\addtolength{\\topmargin}{-2.54cm}"
  3378. "The document header used for processing LaTeX fragments.
  3379. It is imperative that this header make sure that no page number
  3380. appears on the page. The package defined in the variables
  3381. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3382. will either replace the placeholder \"[PACKAGES]\" in this
  3383. header, or they will be appended."
  3384. :group 'org-latex
  3385. :type 'string)
  3386. (defun org-set-packages-alist (var val)
  3387. "Set the packages alist and make sure it has 3 elements per entry."
  3388. (set var (mapcar (lambda (x)
  3389. (if (and (consp x) (= (length x) 2))
  3390. (list (car x) (nth 1 x) t)
  3391. x))
  3392. val)))
  3393. (defun org-get-packages-alist (var)
  3394. "Get the packages alist and make sure it has 3 elements per entry."
  3395. (mapcar (lambda (x)
  3396. (if (and (consp x) (= (length x) 2))
  3397. (list (car x) (nth 1 x) t)
  3398. x))
  3399. (default-value var)))
  3400. (defcustom org-latex-default-packages-alist
  3401. '(("AUTO" "inputenc" t ("pdflatex"))
  3402. ("T1" "fontenc" t ("pdflatex"))
  3403. ("" "graphicx" t)
  3404. ("" "grffile" t)
  3405. ("" "longtable" nil)
  3406. ("" "wrapfig" nil)
  3407. ("" "rotating" nil)
  3408. ("normalem" "ulem" t)
  3409. ("" "amsmath" t)
  3410. ("" "textcomp" t)
  3411. ("" "amssymb" t)
  3412. ("" "capt-of" nil)
  3413. ("" "hyperref" nil))
  3414. "Alist of default packages to be inserted in the header.
  3415. Change this only if one of the packages here causes an
  3416. incompatibility with another package you are using.
  3417. The packages in this list are needed by one part or another of
  3418. Org mode to function properly:
  3419. - inputenc, fontenc: for basic font and character selection
  3420. - graphicx: for including images
  3421. - grffile: allow periods and spaces in graphics file names
  3422. - longtable: For multipage tables
  3423. - wrapfig: for figure placement
  3424. - rotating: for sideways figures and tables
  3425. - ulem: for underline and strike-through
  3426. - amsmath: for subscript and superscript and math environments
  3427. - textcomp, amssymb: for various symbols used
  3428. for interpreting the entities in `org-entities'. You can skip
  3429. some of these packages if you don't use any of their symbols.
  3430. - capt-of: for captions outside of floats
  3431. - hyperref: for cross references
  3432. Therefore you should not modify this variable unless you know
  3433. what you are doing. The one reason to change it anyway is that
  3434. you might be loading some other package that conflicts with one
  3435. of the default packages. Each element is either a cell or
  3436. a string.
  3437. A cell is of the format
  3438. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3439. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3440. when compiling LaTeX snippets into images for inclusion into
  3441. non-LaTeX output.
  3442. COMPILERS is a list of compilers that should include the package,
  3443. see `org-latex-compiler'. If the document compiler is not in the
  3444. list, and the list is non-nil, the package will not be inserted
  3445. in the final document.
  3446. A string will be inserted as-is in the header of the document."
  3447. :group 'org-latex
  3448. :group 'org-export-latex
  3449. :set 'org-set-packages-alist
  3450. :get 'org-get-packages-alist
  3451. :version "26.1"
  3452. :package-version '(Org . "8.3")
  3453. :type '(repeat
  3454. (choice
  3455. (list :tag "options/package pair"
  3456. (string :tag "options")
  3457. (string :tag "package")
  3458. (boolean :tag "Snippet")
  3459. (choice
  3460. (const :tag "For all compilers" nil)
  3461. (repeat :tag "Allowed compiler" string)))
  3462. (string :tag "A line of LaTeX"))))
  3463. (defcustom org-latex-packages-alist nil
  3464. "Alist of packages to be inserted in every LaTeX header.
  3465. These will be inserted after `org-latex-default-packages-alist'.
  3466. Each element is either a cell or a string.
  3467. A cell is of the format:
  3468. (\"options\" \"package\" SNIPPET-FLAG)
  3469. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3470. needed when turning LaTeX snippets into images for inclusion into
  3471. non-LaTeX output.
  3472. COMPILERS is a list of compilers that should include the package,
  3473. see `org-latex-compiler'. If the document compiler is not in the
  3474. list, and the list is non-nil, the package will not be inserted
  3475. in the final document.
  3476. A string will be inserted as-is in the header of the document.
  3477. Make sure that you only list packages here which:
  3478. - you want in every file;
  3479. - do not conflict with the setup in `org-format-latex-header';
  3480. - do not conflict with the default packages in
  3481. `org-latex-default-packages-alist'."
  3482. :group 'org-latex
  3483. :group 'org-export-latex
  3484. :set 'org-set-packages-alist
  3485. :get 'org-get-packages-alist
  3486. :type '(repeat
  3487. (choice
  3488. (list :tag "options/package pair"
  3489. (string :tag "options")
  3490. (string :tag "package")
  3491. (boolean :tag "Snippet"))
  3492. (string :tag "A line of LaTeX"))))
  3493. (defgroup org-appearance nil
  3494. "Settings for Org mode appearance."
  3495. :tag "Org Appearance"
  3496. :group 'org)
  3497. (defcustom org-level-color-stars-only nil
  3498. "Non-nil means fontify only the stars in each headline.
  3499. When nil, the entire headline is fontified.
  3500. Changing it requires restart of `font-lock-mode' to become effective
  3501. also in regions already fontified."
  3502. :group 'org-appearance
  3503. :type 'boolean)
  3504. (defcustom org-hide-leading-stars nil
  3505. "Non-nil means hide the first N-1 stars in a headline.
  3506. This works by using the face `org-hide' for these stars. This
  3507. face is white for a light background, and black for a dark
  3508. background. You may have to customize the face `org-hide' to
  3509. make this work.
  3510. Changing it requires restart of `font-lock-mode' to become effective
  3511. also in regions already fontified.
  3512. You may also set this on a per-file basis by adding one of the following
  3513. lines to the buffer:
  3514. #+STARTUP: hidestars
  3515. #+STARTUP: showstars"
  3516. :group 'org-appearance
  3517. :type 'boolean)
  3518. (defcustom org-hidden-keywords nil
  3519. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3520. For example, a value \\='(title) for this list makes the document's title
  3521. appear in the buffer without the initial \"#+TITLE:\" part."
  3522. :group 'org-appearance
  3523. :version "24.1"
  3524. :type '(set (const :tag "#+AUTHOR" author)
  3525. (const :tag "#+DATE" date)
  3526. (const :tag "#+EMAIL" email)
  3527. (const :tag "#+TITLE" title)))
  3528. (defcustom org-custom-properties nil
  3529. "List of properties (as strings) with a special meaning.
  3530. The default use of these custom properties is to let the user
  3531. hide them with `org-toggle-custom-properties-visibility'."
  3532. :group 'org-properties
  3533. :group 'org-appearance
  3534. :version "24.3"
  3535. :type '(repeat (string :tag "Property Name")))
  3536. (defcustom org-fontify-done-headline nil
  3537. "Non-nil means change the face of a headline if it is marked DONE.
  3538. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3539. When this is non-nil, the headline after the keyword is set to the
  3540. `org-headline-done' as an additional indication."
  3541. :group 'org-appearance
  3542. :type 'boolean)
  3543. (defcustom org-fontify-emphasized-text t
  3544. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3545. Changing this variable requires a restart of Emacs to take effect."
  3546. :group 'org-appearance
  3547. :type 'boolean)
  3548. (defcustom org-fontify-whole-heading-line nil
  3549. "Non-nil means fontify the whole line for headings.
  3550. This is useful when setting a background color for the
  3551. org-level-* faces."
  3552. :group 'org-appearance
  3553. :type 'boolean)
  3554. (defcustom org-highlight-latex-and-related nil
  3555. "Non-nil means highlight LaTeX related syntax in the buffer.
  3556. When non nil, the value should be a list containing any of the
  3557. following symbols:
  3558. `latex' Highlight LaTeX snippets and environments.
  3559. `script' Highlight subscript and superscript.
  3560. `entities' Highlight entities."
  3561. :group 'org-appearance
  3562. :version "24.4"
  3563. :package-version '(Org . "8.0")
  3564. :type '(choice
  3565. (const :tag "No highlighting" nil)
  3566. (set :greedy t :tag "Highlight"
  3567. (const :tag "LaTeX snippets and environments" latex)
  3568. (const :tag "Subscript and superscript" script)
  3569. (const :tag "Entities" entities))))
  3570. (defcustom org-hide-emphasis-markers nil
  3571. "Non-nil mean font-lock should hide the emphasis marker characters."
  3572. :group 'org-appearance
  3573. :type 'boolean
  3574. :safe #'booleanp)
  3575. (defcustom org-hide-macro-markers nil
  3576. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3577. :group 'org-appearance
  3578. :type 'boolean)
  3579. (defcustom org-pretty-entities nil
  3580. "Non-nil means show entities as UTF8 characters.
  3581. When nil, the \\name form remains in the buffer."
  3582. :group 'org-appearance
  3583. :version "24.1"
  3584. :type 'boolean)
  3585. (defcustom org-pretty-entities-include-sub-superscripts t
  3586. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3587. :group 'org-appearance
  3588. :version "24.1"
  3589. :type 'boolean)
  3590. (defvar org-emph-re nil
  3591. "Regular expression for matching emphasis.
  3592. After a match, the match groups contain these elements:
  3593. 0 The match of the full regular expression, including the characters
  3594. before and after the proper match
  3595. 1 The character before the proper match, or empty at beginning of line
  3596. 2 The proper match, including the leading and trailing markers
  3597. 3 The leading marker like * or /, indicating the type of highlighting
  3598. 4 The text between the emphasis markers, not including the markers
  3599. 5 The character after the match, empty at the end of a line")
  3600. (defvar org-verbatim-re nil
  3601. "Regular expression for matching verbatim text.")
  3602. (defvar org-emphasis-regexp-components) ; defined just below
  3603. (defvar org-emphasis-alist) ; defined just below
  3604. (defun org-set-emph-re (var val)
  3605. "Set variable and compute the emphasis regular expression."
  3606. (set var val)
  3607. (when (and (boundp 'org-emphasis-alist)
  3608. (boundp 'org-emphasis-regexp-components)
  3609. org-emphasis-alist org-emphasis-regexp-components)
  3610. (pcase-let*
  3611. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3612. (body (if (<= nl 0) body
  3613. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3614. (template
  3615. (format (concat "\\([%s]\\|^\\)" ;before markers
  3616. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3617. "\\([%s]\\|$\\)") ;after markers
  3618. pre border border body border post)))
  3619. (setq org-emph-re (format template "*/_+"))
  3620. (setq org-verbatim-re (format template "=~")))))
  3621. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3622. ;; set this option proved cumbersome. See this message/thread:
  3623. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3624. (defvar org-emphasis-regexp-components
  3625. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3626. "Components used to build the regular expression for emphasis.
  3627. This is a list with five entries. Terminology: In an emphasis string
  3628. like \" *strong word* \", we call the initial space PREMATCH, the final
  3629. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3630. and \"trong wor\" is the body. The different components in this variable
  3631. specify what is allowed/forbidden in each part:
  3632. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3633. post Chars allowed as postmatch. End of line will be allowed too.
  3634. border The chars *forbidden* as border characters.
  3635. body-regexp A regexp like \".\" to match a body character. Don't use
  3636. non-shy groups here, and don't allow newline here.
  3637. newline The maximum number of newlines allowed in an emphasis exp.
  3638. You need to reload Org or to restart Emacs after setting this.")
  3639. (defcustom org-emphasis-alist
  3640. '(("*" bold)
  3641. ("/" italic)
  3642. ("_" underline)
  3643. ("=" org-verbatim verbatim)
  3644. ("~" org-code verbatim)
  3645. ("+" (:strike-through t)))
  3646. "Alist of characters and faces to emphasize text.
  3647. Text starting and ending with a special character will be emphasized,
  3648. for example *bold*, _underlined_ and /italic/. This variable sets the
  3649. marker characters and the face to be used by font-lock for highlighting
  3650. in Org buffers.
  3651. You need to reload Org or to restart Emacs after customizing this."
  3652. :group 'org-appearance
  3653. :set 'org-set-emph-re
  3654. :version "24.4"
  3655. :package-version '(Org . "8.0")
  3656. :type '(repeat
  3657. (list
  3658. (string :tag "Marker character")
  3659. (choice
  3660. (face :tag "Font-lock-face")
  3661. (plist :tag "Face property list"))
  3662. (option (const verbatim)))))
  3663. (defvar org-protecting-blocks '("src" "example" "export")
  3664. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3665. This is needed for font-lock setup.")
  3666. ;;; Functions and variables from their packages
  3667. ;; Declared here to avoid compiler warnings
  3668. (defvar mark-active)
  3669. ;; Various packages
  3670. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3671. (declare-function calendar-forward-day "cal-move" (arg))
  3672. (declare-function calendar-goto-date "cal-move" (date))
  3673. (declare-function calendar-goto-today "cal-move" ())
  3674. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3675. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3676. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3677. (declare-function cdlatex-tab "ext:cdlatex" ())
  3678. (declare-function dired-get-filename
  3679. "dired"
  3680. (&optional localp no-error-if-not-filep))
  3681. (declare-function iswitchb-read-buffer
  3682. "iswitchb"
  3683. (prompt &optional
  3684. default require-match _predicate start matches-set))
  3685. (declare-function org-agenda-change-all-lines
  3686. "org-agenda"
  3687. (newhead hdmarker &optional fixface just-this))
  3688. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3689. "org-agenda"
  3690. (&optional end))
  3691. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3692. (declare-function org-agenda-format-item
  3693. "org-agenda"
  3694. (extra txt &optional level category tags dotime
  3695. remove-re habitp))
  3696. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3697. (declare-function org-agenda-save-markers-for-cut-and-paste
  3698. "org-agenda"
  3699. (beg end))
  3700. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3701. (declare-function org-agenda-skip "org-agenda" ())
  3702. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3703. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3704. (declare-function org-indent-mode "org-indent" (&optional arg))
  3705. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3706. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3707. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3708. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3709. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3710. (declare-function parse-time-string "parse-time" (string))
  3711. (defvar align-mode-rules-list)
  3712. (defvar calc-embedded-close-formula)
  3713. (defvar calc-embedded-open-formula)
  3714. (defvar calc-embedded-open-mode)
  3715. (defvar font-lock-unfontify-region-function)
  3716. (defvar iswitchb-temp-buflist)
  3717. (defvar org-agenda-tags-todo-honor-ignore-options)
  3718. (defvar remember-data-file)
  3719. (defvar texmathp-why)
  3720. ;;;###autoload
  3721. (defun turn-on-orgtbl ()
  3722. "Unconditionally turn on `orgtbl-mode'."
  3723. (require 'org-table)
  3724. (orgtbl-mode 1))
  3725. (defun org-at-table-p (&optional table-type)
  3726. "Non-nil if the cursor is inside an Org table.
  3727. If TABLE-TYPE is non-nil, also check for table.el-type tables."
  3728. (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
  3729. (or (not (derived-mode-p 'org-mode))
  3730. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3731. (and e (or table-type
  3732. (eq 'org (org-element-property :type e))))))))
  3733. (defun org-at-table.el-p ()
  3734. "Non-nil when point is at a table.el table."
  3735. (and (org-match-line "[ \t]*[|+]")
  3736. (let ((element (org-element-at-point)))
  3737. (and (eq (org-element-type element) 'table)
  3738. (eq (org-element-property :type element) 'table.el)))))
  3739. (defun org-at-table-hline-p ()
  3740. "Non-nil when point is inside a hline in a table.
  3741. Assume point is already in a table."
  3742. (org-match-line org-table-hline-regexp))
  3743. (defun org-table-map-tables (function &optional quietly)
  3744. "Apply FUNCTION to the start of all tables in the buffer."
  3745. (org-with-wide-buffer
  3746. (goto-char (point-min))
  3747. (while (re-search-forward org-table-any-line-regexp nil t)
  3748. (unless quietly
  3749. (message "Mapping tables: %d%%"
  3750. (floor (* 100.0 (point)) (buffer-size))))
  3751. (beginning-of-line 1)
  3752. (when (and (looking-at org-table-line-regexp)
  3753. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3754. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3755. (save-excursion (funcall function))
  3756. (or (looking-at org-table-line-regexp)
  3757. (forward-char 1)))
  3758. (re-search-forward org-table-any-border-regexp nil 1)))
  3759. (unless quietly (message "Mapping tables: done")))
  3760. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3761. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3762. (declare-function org-resolve-clocks "org-clock"
  3763. (&optional also-non-dangling-p prompt last-valid))
  3764. (defun org-at-TBLFM-p (&optional pos)
  3765. "Non-nil when point (or POS) is in #+TBLFM line."
  3766. (save-excursion
  3767. (goto-char (or pos (point)))
  3768. (beginning-of-line)
  3769. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3770. (eq (org-element-type (org-element-at-point)) 'table))))
  3771. (defvar org-clock-start-time)
  3772. (defvar org-clock-marker (make-marker)
  3773. "Marker recording the last clock-in.")
  3774. (defvar org-clock-hd-marker (make-marker)
  3775. "Marker recording the last clock-in, but the headline position.")
  3776. (defvar org-clock-heading ""
  3777. "The heading of the current clock entry.")
  3778. (defun org-clock-is-active ()
  3779. "Return the buffer where the clock is currently running.
  3780. Return nil if no clock is running."
  3781. (marker-buffer org-clock-marker))
  3782. (defun org-check-running-clock ()
  3783. "Check if the current buffer contains the running clock.
  3784. If yes, offer to stop it and to save the buffer with the changes."
  3785. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3786. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3787. (buffer-name))))
  3788. (org-clock-out)
  3789. (when (y-or-n-p "Save changed buffer?")
  3790. (save-buffer))))
  3791. (defun org-clocktable-try-shift (dir n)
  3792. "Check if this line starts a clock table, if yes, shift the time block."
  3793. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3794. (org-clocktable-shift dir n)))
  3795. ;;;###autoload
  3796. (defun org-clock-persistence-insinuate ()
  3797. "Set up hooks for clock persistence."
  3798. (require 'org-clock)
  3799. (add-hook 'org-mode-hook 'org-clock-load)
  3800. (add-hook 'kill-emacs-hook 'org-clock-save))
  3801. (defgroup org-archive nil
  3802. "Options concerning archiving in Org mode."
  3803. :tag "Org Archive"
  3804. :group 'org-structure)
  3805. (defcustom org-archive-location "%s_archive::"
  3806. "The location where subtrees should be archived.
  3807. The value of this variable is a string, consisting of two parts,
  3808. separated by a double-colon. The first part is a filename and
  3809. the second part is a headline.
  3810. When the filename is omitted, archiving happens in the same file.
  3811. %s in the filename will be replaced by the current file
  3812. name (without the directory part). Archiving to a different file
  3813. is useful to keep archived entries from contributing to the
  3814. Org Agenda.
  3815. The archived entries will be filed as subtrees of the specified
  3816. headline. When the headline is omitted, the subtrees are simply
  3817. filed away at the end of the file, as top-level entries. Also in
  3818. the heading you can use %s to represent the file name, this can be
  3819. useful when using the same archive for a number of different files.
  3820. Here are a few examples:
  3821. \"%s_archive::\"
  3822. If the current file is Projects.org, archive in file
  3823. Projects.org_archive, as top-level trees. This is the default.
  3824. \"::* Archived Tasks\"
  3825. Archive in the current file, under the top-level headline
  3826. \"* Archived Tasks\".
  3827. \"~/org/archive.org::\"
  3828. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3829. \"~/org/archive.org::* From %s\"
  3830. Archive in file ~/org/archive.org (absolute path), under headlines
  3831. \"From FILENAME\" where file name is the current file name.
  3832. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3833. The \"datetree/\" string is special, signifying to archive
  3834. items to the datetree. Items are placed in either the CLOSED
  3835. date of the item, or the current date if there is no CLOSED date.
  3836. The heading will be a subentry to the current date. There doesn't
  3837. need to be a heading, but there always needs to be a slash after
  3838. datetree. For example, to store archived items directly in the
  3839. datetree, use \"~/org/datetree.org::datetree/\".
  3840. \"basement::** Finished Tasks\"
  3841. Archive in file ./basement (relative path), as level 3 trees
  3842. below the level 2 heading \"** Finished Tasks\".
  3843. You may set this option on a per-file basis by adding to the buffer a
  3844. line like
  3845. #+ARCHIVE: basement::** Finished Tasks
  3846. You may also define it locally for a subtree by setting an ARCHIVE property
  3847. in the entry. If such a property is found in an entry, or anywhere up
  3848. the hierarchy, it will be used."
  3849. :group 'org-archive
  3850. :type 'string)
  3851. (defcustom org-agenda-skip-archived-trees t
  3852. "Non-nil means the agenda will skip any items located in archived trees.
  3853. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3854. variable is no longer recommended, you should leave it at the value t.
  3855. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3856. :group 'org-archive
  3857. :group 'org-agenda-skip
  3858. :type 'boolean)
  3859. (defcustom org-columns-skip-archived-trees t
  3860. "Non-nil means ignore archived trees when creating column view."
  3861. :group 'org-archive
  3862. :group 'org-properties
  3863. :type 'boolean)
  3864. (defcustom org-cycle-open-archived-trees nil
  3865. "Non-nil means `org-cycle' will open archived trees.
  3866. An archived tree is a tree marked with the tag ARCHIVE.
  3867. When nil, archived trees will stay folded. You can still open them with
  3868. normal outline commands like `show-all', but not with the cycling commands."
  3869. :group 'org-archive
  3870. :group 'org-cycle
  3871. :type 'boolean)
  3872. (defcustom org-sparse-tree-open-archived-trees nil
  3873. "Non-nil means sparse tree construction shows matches in archived trees.
  3874. When nil, matches in these trees are highlighted, but the trees are kept in
  3875. collapsed state."
  3876. :group 'org-archive
  3877. :group 'org-sparse-trees
  3878. :type 'boolean)
  3879. (defcustom org-sparse-tree-default-date-type nil
  3880. "The default date type when building a sparse tree.
  3881. When this is nil, a date is a scheduled or a deadline timestamp.
  3882. Otherwise, these types are allowed:
  3883. all: all timestamps
  3884. active: only active timestamps (<...>)
  3885. inactive: only inactive timestamps ([...])
  3886. scheduled: only scheduled timestamps
  3887. deadline: only deadline timestamps"
  3888. :type '(choice (const :tag "Scheduled or deadline" nil)
  3889. (const :tag "All timestamps" all)
  3890. (const :tag "Only active timestamps" active)
  3891. (const :tag "Only inactive timestamps" inactive)
  3892. (const :tag "Only scheduled timestamps" scheduled)
  3893. (const :tag "Only deadline timestamps" deadline)
  3894. (const :tag "Only closed timestamps" closed))
  3895. :version "26.1"
  3896. :package-version '(Org . "8.3")
  3897. :group 'org-sparse-trees)
  3898. (defun org-cycle-hide-archived-subtrees (state)
  3899. "Re-hide all archived subtrees after a visibility state change.
  3900. STATE should be one of the symbols listed in the docstring of
  3901. `org-cycle-hook'."
  3902. (when (and (not org-cycle-open-archived-trees)
  3903. (not (memq state '(overview folded))))
  3904. (save-excursion
  3905. (let* ((globalp (memq state '(contents all)))
  3906. (beg (if globalp (point-min) (point)))
  3907. (end (if globalp (point-max) (org-end-of-subtree t))))
  3908. (org-hide-archived-subtrees beg end)
  3909. (goto-char beg)
  3910. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3911. (message "%s" (substitute-command-keys
  3912. "Subtree is archived and stays closed. Use \
  3913. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3914. (defun org-force-cycle-archived ()
  3915. "Cycle subtree even if it is archived."
  3916. (interactive)
  3917. (setq this-command 'org-cycle)
  3918. (let ((org-cycle-open-archived-trees t))
  3919. (call-interactively 'org-cycle)))
  3920. (defun org-hide-archived-subtrees (beg end)
  3921. "Re-hide all archived subtrees after a visibility state change."
  3922. (org-with-wide-buffer
  3923. (let ((case-fold-search nil)
  3924. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3925. (goto-char beg)
  3926. ;; Include headline point is currently on.
  3927. (beginning-of-line)
  3928. (while (and (< (point) end) (re-search-forward re end t))
  3929. (when (member org-archive-tag (org-get-tags nil t))
  3930. (org-flag-subtree t)
  3931. (org-end-of-subtree t))))))
  3932. (defun org-flag-subtree (flag)
  3933. (save-excursion
  3934. (org-back-to-heading t)
  3935. (org-flag-region (line-end-position)
  3936. (progn (org-end-of-subtree t) (point))
  3937. flag
  3938. 'outline)))
  3939. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3940. ;; Declare Column View Code
  3941. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3942. (declare-function org-columns-compute "org-colview" (property))
  3943. ;; Declare ID code
  3944. (declare-function org-id-store-link "org-id")
  3945. (declare-function org-id-locations-load "org-id")
  3946. (declare-function org-id-locations-save "org-id")
  3947. (defvar org-id-track-globally)
  3948. ;;; Variables for pre-computed regular expressions, all buffer local
  3949. (defvar-local org-todo-regexp nil
  3950. "Matches any of the TODO state keywords.
  3951. Since TODO keywords are case-sensitive, `case-fold-search' is
  3952. expected to be bound to nil when matching against this regexp.")
  3953. (defvar-local org-not-done-regexp nil
  3954. "Matches any of the TODO state keywords except the last one.
  3955. Since TODO keywords are case-sensitive, `case-fold-search' is
  3956. expected to be bound to nil when matching against this regexp.")
  3957. (defvar-local org-not-done-heading-regexp nil
  3958. "Matches a TODO headline that is not done.
  3959. Since TODO keywords are case-sensitive, `case-fold-search' is
  3960. expected to be bound to nil when matching against this regexp.")
  3961. (defvar-local org-todo-line-regexp nil
  3962. "Matches a headline and puts TODO state into group 2 if present.
  3963. Since TODO keywords are case-sensitive, `case-fold-search' is
  3964. expected to be bound to nil when matching against this regexp.")
  3965. (defvar-local org-complex-heading-regexp nil
  3966. "Matches a headline and puts everything into groups:
  3967. group 1: Stars
  3968. group 2: The TODO keyword, maybe
  3969. group 3: Priority cookie
  3970. group 4: True headline
  3971. group 5: Tags
  3972. Since TODO keywords are case-sensitive, `case-fold-search' is
  3973. expected to be bound to nil when matching against this regexp.")
  3974. (defvar-local org-complex-heading-regexp-format nil
  3975. "Printf format to make regexp to match an exact headline.
  3976. This regexp will match the headline of any node which has the
  3977. exact headline text that is put into the format, but may have any
  3978. TODO state, priority and tags.")
  3979. (defvar-local org-todo-line-tags-regexp nil
  3980. "Matches a headline and puts TODO state into group 2 if present.
  3981. Also put tags into group 4 if tags are present.")
  3982. (defconst org-plain-time-of-day-regexp
  3983. (concat
  3984. "\\(\\<[012]?[0-9]"
  3985. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3986. "\\(--?"
  3987. "\\(\\<[012]?[0-9]"
  3988. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3989. "\\)?")
  3990. "Regular expression to match a plain time or time range.
  3991. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3992. groups carry important information:
  3993. 0 the full match
  3994. 1 the first time, range or not
  3995. 8 the second time, if it is a range.")
  3996. (defconst org-plain-time-extension-regexp
  3997. (concat
  3998. "\\(\\<[012]?[0-9]"
  3999. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4000. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4001. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4002. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4003. groups carry important information:
  4004. 0 the full match
  4005. 7 hours of duration
  4006. 9 minutes of duration")
  4007. (defconst org-stamp-time-of-day-regexp
  4008. (concat
  4009. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4010. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4011. "\\(--?"
  4012. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4013. "Regular expression to match a timestamp time or time range.
  4014. After a match, the following groups carry important information:
  4015. 0 the full match
  4016. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4017. 2 the first time, range or not
  4018. 4 the second time, if it is a range.")
  4019. (defconst org-startup-options
  4020. '(("fold" org-startup-folded t)
  4021. ("overview" org-startup-folded t)
  4022. ("nofold" org-startup-folded nil)
  4023. ("showall" org-startup-folded nil)
  4024. ("showeverything" org-startup-folded showeverything)
  4025. ("content" org-startup-folded content)
  4026. ("indent" org-startup-indented t)
  4027. ("noindent" org-startup-indented nil)
  4028. ("hidestars" org-hide-leading-stars t)
  4029. ("showstars" org-hide-leading-stars nil)
  4030. ("odd" org-odd-levels-only t)
  4031. ("oddeven" org-odd-levels-only nil)
  4032. ("align" org-startup-align-all-tables t)
  4033. ("noalign" org-startup-align-all-tables nil)
  4034. ("shrink" org-startup-shrink-all-tables t)
  4035. ("inlineimages" org-startup-with-inline-images t)
  4036. ("noinlineimages" org-startup-with-inline-images nil)
  4037. ("latexpreview" org-startup-with-latex-preview t)
  4038. ("nolatexpreview" org-startup-with-latex-preview nil)
  4039. ("customtime" org-display-custom-times t)
  4040. ("logdone" org-log-done time)
  4041. ("lognotedone" org-log-done note)
  4042. ("nologdone" org-log-done nil)
  4043. ("lognoteclock-out" org-log-note-clock-out t)
  4044. ("nolognoteclock-out" org-log-note-clock-out nil)
  4045. ("logrepeat" org-log-repeat state)
  4046. ("lognoterepeat" org-log-repeat note)
  4047. ("logdrawer" org-log-into-drawer t)
  4048. ("nologdrawer" org-log-into-drawer nil)
  4049. ("logstatesreversed" org-log-states-order-reversed t)
  4050. ("nologstatesreversed" org-log-states-order-reversed nil)
  4051. ("nologrepeat" org-log-repeat nil)
  4052. ("logreschedule" org-log-reschedule time)
  4053. ("lognotereschedule" org-log-reschedule note)
  4054. ("nologreschedule" org-log-reschedule nil)
  4055. ("logredeadline" org-log-redeadline time)
  4056. ("lognoteredeadline" org-log-redeadline note)
  4057. ("nologredeadline" org-log-redeadline nil)
  4058. ("logrefile" org-log-refile time)
  4059. ("lognoterefile" org-log-refile note)
  4060. ("nologrefile" org-log-refile nil)
  4061. ("fninline" org-footnote-define-inline t)
  4062. ("nofninline" org-footnote-define-inline nil)
  4063. ("fnlocal" org-footnote-section nil)
  4064. ("fnauto" org-footnote-auto-label t)
  4065. ("fnprompt" org-footnote-auto-label nil)
  4066. ("fnconfirm" org-footnote-auto-label confirm)
  4067. ("fnplain" org-footnote-auto-label plain)
  4068. ("fnadjust" org-footnote-auto-adjust t)
  4069. ("nofnadjust" org-footnote-auto-adjust nil)
  4070. ("constcgs" constants-unit-system cgs)
  4071. ("constSI" constants-unit-system SI)
  4072. ("noptag" org-tag-persistent-alist nil)
  4073. ("hideblocks" org-hide-block-startup t)
  4074. ("nohideblocks" org-hide-block-startup nil)
  4075. ("beamer" org-startup-with-beamer-mode t)
  4076. ("entitiespretty" org-pretty-entities t)
  4077. ("entitiesplain" org-pretty-entities nil))
  4078. "Variable associated with STARTUP options for Org.
  4079. Each element is a list of three items: the startup options (as written
  4080. in the #+STARTUP line), the corresponding variable, and the value to set
  4081. this variable to if the option is found. An optional forth element PUSH
  4082. means to push this value onto the list in the variable.")
  4083. (defcustom org-group-tags t
  4084. "When non-nil (the default), use group tags.
  4085. This can be turned on/off through `org-toggle-tags-groups'."
  4086. :group 'org-tags
  4087. :group 'org-startup
  4088. :type 'boolean)
  4089. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4090. (defun org-toggle-tags-groups ()
  4091. "Toggle support for group tags.
  4092. Support for group tags is controlled by the option
  4093. `org-group-tags', which is non-nil by default."
  4094. (interactive)
  4095. (setq org-group-tags (not org-group-tags))
  4096. (cond ((and (derived-mode-p 'org-agenda-mode)
  4097. org-group-tags)
  4098. (org-agenda-redo))
  4099. ((derived-mode-p 'org-mode)
  4100. (let ((org-inhibit-startup t)) (org-mode))))
  4101. (message "Groups tags support has been turned %s"
  4102. (if org-group-tags "on" "off")))
  4103. (defun org--tag-add-to-alist (alist1 alist2)
  4104. "Merge tags from ALIST1 into ALIST2.
  4105. Duplicates tags outside a group are removed. Keywords and order
  4106. are preserved.
  4107. The function assumes ALIST1 and ALIST2 are proper tag alists.
  4108. See `org-tag-alist' for their structure."
  4109. (cond
  4110. ((null alist2) alist1)
  4111. ((null alist1) alist2)
  4112. (t
  4113. (let ((to-add nil)
  4114. (group-flag nil))
  4115. (dolist (tag-pair alist1)
  4116. (pcase tag-pair
  4117. (`(,(or :startgrouptag :startgroup))
  4118. (setq group-flag t)
  4119. (push tag-pair to-add))
  4120. (`(,(or :endgrouptag :endgroup))
  4121. (setq group-flag nil)
  4122. (push tag-pair to-add))
  4123. (`(,(or :grouptags :newline))
  4124. (push tag-pair to-add))
  4125. (`(,tag . ,_)
  4126. ;; Remove duplicates from ALIST1, unless they are in
  4127. ;; a group. Indeed, it makes sense to have a tag appear in
  4128. ;; multiple groups.
  4129. (when (or group-flag (not (assoc tag alist2)))
  4130. (push tag-pair to-add)))
  4131. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  4132. ;; Preserve order of ALIST1.
  4133. (append (nreverse to-add) alist2)))))
  4134. (defun org-set-regexps-and-options (&optional tags-only)
  4135. "Precompute regular expressions used in the current buffer.
  4136. When optional argument TAGS-ONLY is non-nil, only compute tags
  4137. related expressions."
  4138. (when (derived-mode-p 'org-mode)
  4139. (let ((alist (org--setup-collect-keywords
  4140. (org-make-options-regexp
  4141. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4142. (and (not tags-only)
  4143. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4144. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4145. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4146. ;; Startup options. Get this early since it does change
  4147. ;; behavior for other options (e.g., tags).
  4148. (let ((startup (cdr (assq 'startup alist))))
  4149. (dolist (option startup)
  4150. (let ((entry (assoc-string option org-startup-options t)))
  4151. (when entry
  4152. (let ((var (nth 1 entry))
  4153. (val (nth 2 entry)))
  4154. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4155. (unless (listp (symbol-value var))
  4156. (set (make-local-variable var) nil))
  4157. (add-to-list var val)))))))
  4158. (setq-local org-file-tags
  4159. (mapcar #'org-add-prop-inherited
  4160. (cdr (assq 'filetags alist))))
  4161. (setq org-current-tag-alist
  4162. (org--tag-add-to-alist
  4163. org-tag-persistent-alist
  4164. (let ((tags (cdr (assq 'tags alist))))
  4165. (if tags (org-tag-string-to-alist tags)
  4166. org-tag-alist))))
  4167. (setq org-tag-groups-alist
  4168. (org-tag-alist-to-groups org-current-tag-alist))
  4169. (unless tags-only
  4170. ;; File properties.
  4171. (setq-local org-file-properties (cdr (assq 'property alist)))
  4172. ;; Archive location.
  4173. (let ((archive (cdr (assq 'archive alist))))
  4174. (when archive (setq-local org-archive-location archive)))
  4175. ;; Category.
  4176. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4177. (when cat
  4178. (setq-local org-category (intern cat))
  4179. (setq-local org-file-properties
  4180. (org--update-property-plist
  4181. "CATEGORY" cat org-file-properties))))
  4182. ;; Columns.
  4183. (let ((column (cdr (assq 'columns alist))))
  4184. (when column (setq-local org-columns-default-format column)))
  4185. ;; Constants.
  4186. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4187. ;; Link abbreviations.
  4188. (let ((links (cdr (assq 'link alist))))
  4189. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4190. ;; Priorities.
  4191. (let ((priorities (cdr (assq 'priorities alist))))
  4192. (when priorities
  4193. (setq-local org-highest-priority (nth 0 priorities))
  4194. (setq-local org-lowest-priority (nth 1 priorities))
  4195. (setq-local org-default-priority (nth 2 priorities))))
  4196. ;; Scripts.
  4197. (let ((scripts (assq 'scripts alist)))
  4198. (when scripts
  4199. (setq-local org-use-sub-superscripts (cdr scripts))))
  4200. ;; TODO keywords.
  4201. (setq-local org-todo-kwd-alist nil)
  4202. (setq-local org-todo-key-alist nil)
  4203. (setq-local org-todo-key-trigger nil)
  4204. (setq-local org-todo-keywords-1 nil)
  4205. (setq-local org-done-keywords nil)
  4206. (setq-local org-todo-heads nil)
  4207. (setq-local org-todo-sets nil)
  4208. (setq-local org-todo-log-states nil)
  4209. (let ((todo-sequences
  4210. (or (nreverse (cdr (assq 'todo alist)))
  4211. (let ((d (default-value 'org-todo-keywords)))
  4212. (if (not (stringp (car d))) d
  4213. ;; XXX: Backward compatibility code.
  4214. (list (cons org-todo-interpretation d)))))))
  4215. (dolist (sequence todo-sequences)
  4216. (let* ((sequence (or (run-hook-with-args-until-success
  4217. 'org-todo-setup-filter-hook sequence)
  4218. sequence))
  4219. (sequence-type (car sequence))
  4220. (keywords (cdr sequence))
  4221. (sep (member "|" keywords))
  4222. names alist)
  4223. (dolist (k (remove "|" keywords))
  4224. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4225. k)
  4226. (error "Invalid TODO keyword %s" k))
  4227. (let ((name (match-string 1 k))
  4228. (key (match-string 2 k))
  4229. (log (org-extract-log-state-settings k)))
  4230. (push name names)
  4231. (push (cons name (and key (string-to-char key))) alist)
  4232. (when log (push log org-todo-log-states))))
  4233. (let* ((names (nreverse names))
  4234. (done (if sep (org-remove-keyword-keys (cdr sep))
  4235. (last names)))
  4236. (head (car names))
  4237. (tail (list sequence-type head (car done) (org-last done))))
  4238. (add-to-list 'org-todo-heads head 'append)
  4239. (push names org-todo-sets)
  4240. (setq org-done-keywords (append org-done-keywords done nil))
  4241. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4242. (setq org-todo-key-alist
  4243. (append org-todo-key-alist
  4244. (and alist
  4245. (append '((:startgroup))
  4246. (nreverse alist)
  4247. '((:endgroup))))))
  4248. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4249. (setq org-todo-sets (nreverse org-todo-sets)
  4250. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4251. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4252. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4253. ;; Compute the regular expressions and other local variables.
  4254. ;; Using `org-outline-regexp-bol' would complicate them much,
  4255. ;; because of the fixed white space at the end of that string.
  4256. (unless org-done-keywords
  4257. (setq org-done-keywords
  4258. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4259. (setq org-not-done-keywords
  4260. (org-delete-all org-done-keywords
  4261. (copy-sequence org-todo-keywords-1))
  4262. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4263. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4264. org-not-done-heading-regexp
  4265. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4266. org-todo-line-regexp
  4267. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4268. org-complex-heading-regexp
  4269. (concat "^\\(\\*+\\)"
  4270. "\\(?: +" org-todo-regexp "\\)?"
  4271. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4272. "\\(?: +\\(.*?\\)\\)??"
  4273. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4274. "[ \t]*$")
  4275. org-complex-heading-regexp-format
  4276. (concat "^\\(\\*+\\)"
  4277. "\\(?: +" org-todo-regexp "\\)?"
  4278. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4279. "\\(?: +"
  4280. ;; Stats cookies can be stuck to body.
  4281. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4282. "\\(%s\\)"
  4283. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4284. "\\)"
  4285. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4286. "[ \t]*$")
  4287. org-todo-line-tags-regexp
  4288. (concat "^\\(\\*+\\)"
  4289. "\\(?: +" org-todo-regexp "\\)?"
  4290. "\\(?: +\\(.*?\\)\\)??"
  4291. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4292. "[ \t]*$"))
  4293. (org-compute-latex-and-related-regexp)))))
  4294. (defun org--setup-collect-keywords (regexp &optional files alist)
  4295. "Return setup keywords values as an alist.
  4296. REGEXP matches a subset of setup keywords. FILES is a list of
  4297. file names already visited. It is used to avoid circular setup
  4298. files. ALIST, when non-nil, is the alist computed so far.
  4299. Return value contains the following keys: `archive', `category',
  4300. `columns', `constants', `filetags', `link', `priorities',
  4301. `property', `scripts', `startup', `tags' and `todo'."
  4302. (org-with-wide-buffer
  4303. (goto-char (point-min))
  4304. (let ((case-fold-search t))
  4305. (while (re-search-forward regexp nil t)
  4306. (let ((element (org-element-at-point)))
  4307. (when (eq (org-element-type element) 'keyword)
  4308. (let ((key (org-element-property :key element))
  4309. (value (org-element-property :value element)))
  4310. (cond
  4311. ((equal key "ARCHIVE")
  4312. (when (org-string-nw-p value)
  4313. (push (cons 'archive value) alist)))
  4314. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4315. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4316. ((equal key "CONSTANTS")
  4317. (let* ((constants (assq 'constants alist))
  4318. (store (cdr constants)))
  4319. (dolist (pair (split-string value))
  4320. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4321. pair)
  4322. (let* ((name (match-string 1 pair))
  4323. (value (match-string 2 pair))
  4324. (old (assoc name store)))
  4325. (if old (setcdr old value)
  4326. (push (cons name value) store)))))
  4327. (if constants (setcdr constants store)
  4328. (push (cons 'constants store) alist))))
  4329. ((equal key "FILETAGS")
  4330. (when (org-string-nw-p value)
  4331. (let ((old (assq 'filetags alist))
  4332. (new (apply #'nconc
  4333. (mapcar (lambda (x) (org-split-string x ":"))
  4334. (split-string value)))))
  4335. (if old (setcdr old (append new (cdr old)))
  4336. (push (cons 'filetags new) alist)))))
  4337. ((equal key "LINK")
  4338. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4339. (let ((links (assq 'link alist))
  4340. (pair (cons (match-string-no-properties 1 value)
  4341. (match-string-no-properties 2 value))))
  4342. (if links (push pair (cdr links))
  4343. (push (list 'link pair) alist)))))
  4344. ((equal key "OPTIONS")
  4345. (when (and (org-string-nw-p value)
  4346. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4347. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4348. ((equal key "PRIORITIES")
  4349. (push (cons 'priorities
  4350. (let ((prio (split-string value)))
  4351. (if (< (length prio) 3) '(?A ?C ?B)
  4352. (mapcar #'string-to-char prio))))
  4353. alist))
  4354. ((equal key "PROPERTY")
  4355. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4356. (let* ((property (assq 'property alist))
  4357. (value (org--update-property-plist
  4358. (match-string-no-properties 1 value)
  4359. (match-string-no-properties 2 value)
  4360. (cdr property))))
  4361. (if property (setcdr property value)
  4362. (push (cons 'property value) alist)))))
  4363. ((equal key "STARTUP")
  4364. (let ((startup (assq 'startup alist)))
  4365. (if startup
  4366. (setcdr startup
  4367. (append (cdr startup) (split-string value)))
  4368. (push (cons 'startup (split-string value)) alist))))
  4369. ((equal key "TAGS")
  4370. (let ((tag-cell (assq 'tags alist)))
  4371. (if tag-cell
  4372. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4373. (push (cons 'tags value) alist))))
  4374. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4375. (let ((todo (assq 'todo alist))
  4376. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4377. (split-string value))))
  4378. (if todo (push value (cdr todo))
  4379. (push (list 'todo value) alist))))
  4380. ((equal key "SETUPFILE")
  4381. (unless buffer-read-only ; Do not check in Gnus messages.
  4382. (let ((f (and (org-string-nw-p value)
  4383. (expand-file-name (org-strip-quotes value)))))
  4384. (when (and f (file-readable-p f) (not (member f files)))
  4385. (with-temp-buffer
  4386. (setq default-directory (file-name-directory f))
  4387. (insert-file-contents f)
  4388. (setq alist
  4389. ;; Fake Org mode to benefit from cache
  4390. ;; without recurring needlessly.
  4391. (let ((major-mode 'org-mode))
  4392. (org--setup-collect-keywords
  4393. regexp (cons f files) alist)))))))))))))))
  4394. alist)
  4395. (defun org-tag-string-to-alist (s)
  4396. "Return tag alist associated to string S.
  4397. S is a value for TAGS keyword or produced with
  4398. `org-tag-alist-to-string'. Return value is an alist suitable for
  4399. `org-tag-alist' or `org-tag-persistent-alist'."
  4400. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4401. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  4402. "\\(?:(\\(.\\))\\)?\\'"))
  4403. alist group-flag)
  4404. (dolist (tokens lines (cdr (nreverse alist)))
  4405. (push '(:newline) alist)
  4406. (while tokens
  4407. (let ((token (pop tokens)))
  4408. (pcase token
  4409. ("{"
  4410. (push '(:startgroup) alist)
  4411. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4412. ("}"
  4413. (push '(:endgroup) alist)
  4414. (setq group-flag nil))
  4415. ("["
  4416. (push '(:startgrouptag) alist)
  4417. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4418. ("]"
  4419. (push '(:endgrouptag) alist)
  4420. (setq group-flag nil))
  4421. (":"
  4422. (push '(:grouptags) alist))
  4423. ((guard (string-match tag-re token))
  4424. (let ((tag (match-string 1 token))
  4425. (key (and (match-beginning 2)
  4426. (string-to-char (match-string 2 token)))))
  4427. ;; Push all tags in groups, no matter if they already
  4428. ;; appear somewhere else in the list.
  4429. (when (or group-flag (not (assoc tag alist)))
  4430. (push (cons tag key) alist))))))))))
  4431. (defun org-tag-alist-to-string (alist &optional skip-key)
  4432. "Return tag string associated to ALIST.
  4433. ALIST is an alist, as defined in `org-tag-alist' or
  4434. `org-tag-persistent-alist', or produced with
  4435. `org-tag-string-to-alist'.
  4436. Return value is a string suitable as a value for \"TAGS\"
  4437. keyword.
  4438. When optional argument SKIP-KEY is non-nil, skip selection keys
  4439. next to tags."
  4440. (mapconcat (lambda (token)
  4441. (pcase token
  4442. (`(:startgroup) "{")
  4443. (`(:endgroup) "}")
  4444. (`(:startgrouptag) "[")
  4445. (`(:endgrouptag) "]")
  4446. (`(:grouptags) ":")
  4447. (`(:newline) "\\n")
  4448. ((and
  4449. (guard (not skip-key))
  4450. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4451. (format "%s(%c)" tag key))
  4452. (`(,(and tag (pred stringp)) . ,_) tag)
  4453. (_ (user-error "Invalid tag token: %S" token))))
  4454. alist
  4455. " "))
  4456. (defun org-tag-alist-to-groups (alist)
  4457. "Return group alist from tag ALIST.
  4458. ALIST is an alist, as defined in `org-tag-alist' or
  4459. `org-tag-persistent-alist', or produced with
  4460. `org-tag-string-to-alist'. Return value is an alist following
  4461. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4462. a string, summarizing TAGS, as a list of strings."
  4463. (let (groups group-status current-group)
  4464. (dolist (token alist (nreverse groups))
  4465. (pcase token
  4466. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4467. (`(,(or :endgroup :endgrouptag))
  4468. (when (eq group-status 'append)
  4469. (push (nreverse current-group) groups))
  4470. (setq group-status nil current-group nil))
  4471. (`(:grouptags) (setq group-status 'append))
  4472. ((and `(,tag . ,_) (guard group-status))
  4473. (if (eq group-status 'append) (push tag current-group)
  4474. (setq current-group (list tag))))
  4475. (_ nil)))))
  4476. (defvar org--file-cache (make-hash-table :test #'equal)
  4477. "Hash table to store contents of files referenced via a URL.
  4478. This is the cache of file URLs read using `org-file-contents'.")
  4479. (defun org-reset-file-cache ()
  4480. "Reset the cache of files downloaded by `org-file-contents'."
  4481. (clrhash org--file-cache))
  4482. (defun org-file-url-p (file)
  4483. "Non-nil if FILE is a URL."
  4484. (require 'ffap)
  4485. (string-match-p ffap-url-regexp file))
  4486. (defun org-file-contents (file &optional noerror nocache)
  4487. "Return the contents of FILE, as a string.
  4488. FILE can be a file name or URL.
  4489. If FILE is a URL, download the contents. If the URL contents are
  4490. already cached in the `org--file-cache' hash table, the download step
  4491. is skipped.
  4492. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4493. from file or URL.
  4494. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4495. is available. This option applies only if FILE is a URL."
  4496. (let* ((is-url (org-file-url-p file))
  4497. (cache (and is-url
  4498. (not nocache)
  4499. (gethash file org--file-cache))))
  4500. (cond
  4501. (cache)
  4502. (is-url
  4503. (with-current-buffer (url-retrieve-synchronously file)
  4504. (goto-char (point-min))
  4505. ;; Move point to after the url-retrieve header.
  4506. (search-forward "\n\n" nil :move)
  4507. ;; Search for the success code only in the url-retrieve header.
  4508. (if (save-excursion
  4509. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4510. ;; Update the cache `org--file-cache' and return contents.
  4511. (puthash file
  4512. (buffer-substring-no-properties (point) (point-max))
  4513. org--file-cache)
  4514. (funcall (if noerror #'message #'user-error)
  4515. "Unable to fetch file from %S"
  4516. file))))
  4517. (t
  4518. (with-temp-buffer
  4519. (condition-case nil
  4520. (progn
  4521. (insert-file-contents file)
  4522. (buffer-string))
  4523. (file-error
  4524. (funcall (if noerror #'message #'user-error)
  4525. "Unable to read file %S"
  4526. file))))))))
  4527. (defun org-extract-log-state-settings (x)
  4528. "Extract the log state setting from a TODO keyword string.
  4529. This will extract info from a string like \"WAIT(w@/!)\"."
  4530. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4531. (let ((kw (match-string 1 x))
  4532. (log1 (and (match-end 3) (match-string 3 x)))
  4533. (log2 (and (match-end 4) (match-string 4 x))))
  4534. (and (or log1 log2)
  4535. (list kw
  4536. (and log1 (if (equal log1 "!") 'time 'note))
  4537. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4538. (defun org-remove-keyword-keys (list)
  4539. "Remove a pair of parenthesis at the end of each string in LIST."
  4540. (mapcar (lambda (x)
  4541. (if (string-match "(.*)$" x)
  4542. (substring x 0 (match-beginning 0))
  4543. x))
  4544. list))
  4545. (defun org-assign-fast-keys (alist)
  4546. "Assign fast keys to a keyword-key alist.
  4547. Respect keys that are already there."
  4548. (let (new e (alt ?0))
  4549. (while (setq e (pop alist))
  4550. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4551. (cdr e)) ;; Key already assigned.
  4552. (push e new)
  4553. (let ((clist (string-to-list (downcase (car e))))
  4554. (used (append new alist)))
  4555. (when (= (car clist) ?@)
  4556. (pop clist))
  4557. (while (and clist (rassoc (car clist) used))
  4558. (pop clist))
  4559. (unless clist
  4560. (while (rassoc alt used)
  4561. (cl-incf alt)))
  4562. (push (cons (car e) (or (car clist) alt)) new))))
  4563. (nreverse new)))
  4564. ;;; Some variables used in various places
  4565. (defvar org-window-configuration nil
  4566. "Used in various places to store a window configuration.")
  4567. (defvar org-selected-window nil
  4568. "Used in various places to store a window configuration.")
  4569. (defvar org-finish-function nil
  4570. "Function to be called when `C-c C-c' is used.
  4571. This is for getting out of special buffers like capture.")
  4572. (defvar org-last-state)
  4573. ;; Defined somewhere in this file, but used before definition.
  4574. (defvar org-entities) ;; defined in org-entities.el
  4575. (defvar org-struct-menu)
  4576. (defvar org-org-menu)
  4577. (defvar org-tbl-menu)
  4578. ;;;; Define the Org mode
  4579. ;; We use a before-change function to check if a table might need
  4580. ;; an update.
  4581. (defvar org-table-may-need-update t
  4582. "Indicates that a table might need an update.
  4583. This variable is set by `org-before-change-function'.
  4584. `org-table-align' sets it back to nil.")
  4585. (defun org-before-change-function (_beg _end)
  4586. "Every change indicates that a table might need an update."
  4587. (setq org-table-may-need-update t))
  4588. (defvar org-mode-map)
  4589. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4590. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4591. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4592. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4593. (defvar org-table-buffer-is-an nil)
  4594. (defvar bidi-paragraph-direction)
  4595. (defvar buffer-face-mode-face)
  4596. (require 'outline)
  4597. ;; Other stuff we need.
  4598. (require 'time-date)
  4599. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4600. (require 'easymenu)
  4601. (autoload 'easy-menu-add "easymenu")
  4602. (require 'overlay)
  4603. ;; (require 'org-macs) moved higher up in the file before it is first used
  4604. (require 'org-entities)
  4605. ;; (require 'org-compat) moved higher up in the file before it is first used
  4606. (require 'org-faces)
  4607. (require 'org-list)
  4608. (require 'org-pcomplete)
  4609. (require 'org-src)
  4610. (require 'org-footnote)
  4611. (require 'org-macro)
  4612. ;; babel
  4613. (require 'ob)
  4614. ;;;###autoload
  4615. (define-derived-mode org-mode outline-mode "Org"
  4616. "Outline-based notes management and organizer, alias
  4617. \"Carsten's outline-mode for keeping track of everything.\"
  4618. Org mode develops organizational tasks around a NOTES file which
  4619. contains information about projects as plain text. Org mode is
  4620. implemented on top of Outline mode, which is ideal to keep the content
  4621. of large files well structured. It supports ToDo items, deadlines and
  4622. time stamps, which magically appear in the diary listing of the Emacs
  4623. calendar. Tables are easily created with a built-in table editor.
  4624. Plain text URL-like links connect to websites, emails (VM), Usenet
  4625. messages (Gnus), BBDB entries, and any files related to the project.
  4626. For printing and sharing of notes, an Org file (or a part of it)
  4627. can be exported as a structured ASCII or HTML file.
  4628. The following commands are available:
  4629. \\{org-mode-map}"
  4630. (org-load-modules-maybe)
  4631. (org-install-agenda-files-menu)
  4632. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4633. (add-to-invisibility-spec '(org-hide-block . t))
  4634. (add-to-invisibility-spec '(org-hide-drawer . t))
  4635. (setq-local outline-regexp org-outline-regexp)
  4636. (setq-local outline-level 'org-outline-level)
  4637. (setq bidi-paragraph-direction 'left-to-right)
  4638. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4639. (unless org-display-table
  4640. (setq org-display-table (make-display-table)))
  4641. (set-display-table-slot
  4642. org-display-table 4
  4643. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4644. org-ellipsis)))
  4645. (setq buffer-display-table org-display-table))
  4646. (org-set-regexps-and-options)
  4647. (org-set-font-lock-defaults)
  4648. (when (and org-tag-faces (not org-tags-special-faces-re))
  4649. ;; tag faces set outside customize.... force initialization.
  4650. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4651. ;; Calc embedded
  4652. (setq-local calc-embedded-open-mode "# ")
  4653. ;; Modify a few syntax entries
  4654. (modify-syntax-entry ?\" "\"")
  4655. (modify-syntax-entry ?\\ "_")
  4656. (modify-syntax-entry ?~ "_")
  4657. (modify-syntax-entry ?< "(>")
  4658. (modify-syntax-entry ?> ")<")
  4659. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4660. ;; Activate before-change-function
  4661. (setq-local org-table-may-need-update t)
  4662. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4663. ;; Check for running clock before killing a buffer
  4664. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4665. ;; Initialize macros templates.
  4666. (org-macro-initialize-templates)
  4667. ;; Initialize radio targets.
  4668. (org-update-radio-target-regexp)
  4669. ;; Indentation.
  4670. (setq-local indent-line-function 'org-indent-line)
  4671. (setq-local indent-region-function 'org-indent-region)
  4672. ;; Filling and auto-filling.
  4673. (org-setup-filling)
  4674. ;; Comments.
  4675. (org-setup-comments-handling)
  4676. ;; Initialize cache.
  4677. (org-element-cache-reset)
  4678. ;; Beginning/end of defun
  4679. (setq-local beginning-of-defun-function 'org-backward-element)
  4680. (setq-local end-of-defun-function
  4681. (lambda ()
  4682. (if (not (org-at-heading-p))
  4683. (org-forward-element)
  4684. (org-forward-element)
  4685. (forward-char -1))))
  4686. ;; Next error for sparse trees
  4687. (setq-local next-error-function 'org-occur-next-match)
  4688. ;; Make commit log messages from Org documents easier.
  4689. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4690. ;; Make sure dependence stuff works reliably, even for users who set it
  4691. ;; too late :-(
  4692. (if org-enforce-todo-dependencies
  4693. (add-hook 'org-blocker-hook
  4694. 'org-block-todo-from-children-or-siblings-or-parent)
  4695. (remove-hook 'org-blocker-hook
  4696. 'org-block-todo-from-children-or-siblings-or-parent))
  4697. (if org-enforce-todo-checkbox-dependencies
  4698. (add-hook 'org-blocker-hook
  4699. 'org-block-todo-from-checkboxes)
  4700. (remove-hook 'org-blocker-hook
  4701. 'org-block-todo-from-checkboxes))
  4702. ;; Align options lines
  4703. (setq-local
  4704. align-mode-rules-list
  4705. '((org-in-buffer-settings
  4706. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4707. (modes . '(org-mode)))))
  4708. ;; Make isearch reveal context
  4709. (setq-local outline-isearch-open-invisible-function
  4710. (lambda (&rest _) (org-show-context 'isearch)))
  4711. ;; Setup the pcomplete hooks
  4712. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4713. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4714. (setq-local pcomplete-default-completion-function 'ignore)
  4715. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4716. (setq-local pcomplete-termination-string "")
  4717. (setq-local buffer-face-mode-face 'org-default)
  4718. ;; If empty file that did not turn on Org mode automatically, make
  4719. ;; it to.
  4720. (when (and org-insert-mode-line-in-empty-file
  4721. (called-interactively-p 'any)
  4722. (= (point-min) (point-max)))
  4723. (insert "# -*- mode: org -*-\n\n"))
  4724. (unless org-inhibit-startup
  4725. (org-unmodified
  4726. (when org-startup-with-beamer-mode (org-beamer-mode))
  4727. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4728. (org-table-map-tables
  4729. (cond ((and org-startup-align-all-tables
  4730. org-startup-shrink-all-tables)
  4731. (lambda () (org-table-align) (org-table-shrink)))
  4732. (org-startup-align-all-tables #'org-table-align)
  4733. (t #'org-table-shrink))
  4734. t))
  4735. (when org-startup-with-inline-images (org-display-inline-images))
  4736. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4737. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4738. (when org-startup-truncated (setq truncate-lines t))
  4739. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4740. ;; Try to set `org-hide' face correctly.
  4741. (let ((foreground (org-find-invisible-foreground)))
  4742. (when foreground
  4743. (set-face-foreground 'org-hide foreground))))
  4744. ;; Update `customize-package-emacs-version-alist'
  4745. (add-to-list 'customize-package-emacs-version-alist
  4746. '(Org ("8.0" . "24.4")
  4747. ("8.1" . "24.4")
  4748. ("8.2" . "24.4")
  4749. ("8.2.7" . "24.4")
  4750. ("8.3" . "26.1")
  4751. ("9.0" . "26.1")
  4752. ("9.1" . "26.1")
  4753. ("9.2" . "27.1")))
  4754. (defvar org-mode-transpose-word-syntax-table
  4755. (let ((st (make-syntax-table text-mode-syntax-table)))
  4756. (dolist (c org-emphasis-alist st)
  4757. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4758. (when (fboundp 'abbrev-table-put)
  4759. (abbrev-table-put org-mode-abbrev-table
  4760. :parents (list text-mode-abbrev-table)))
  4761. (defun org-find-invisible-foreground ()
  4762. (let ((candidates (remove
  4763. "unspecified-bg"
  4764. (nconc
  4765. (list (face-background 'default)
  4766. (face-background 'org-default))
  4767. (mapcar
  4768. (lambda (alist)
  4769. (when (boundp alist)
  4770. (cdr (assq 'background-color (symbol-value alist)))))
  4771. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4772. (list (face-foreground 'org-hide))))))
  4773. (car (remove nil candidates))))
  4774. (defun org-current-time (&optional rounding-minutes past)
  4775. "Current time, possibly rounded to ROUNDING-MINUTES.
  4776. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4777. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4778. the rounding returns a past time."
  4779. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4780. (car org-time-stamp-rounding-minutes)))
  4781. (time (decode-time)) res)
  4782. (if (< r 1)
  4783. (current-time)
  4784. (setq res
  4785. (apply 'encode-time
  4786. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4787. (nthcdr 2 time))))
  4788. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4789. (seconds-to-time (- (float-time res) (* r 60)))
  4790. res))))
  4791. (defun org-today ()
  4792. "Return today date, considering `org-extend-today-until'."
  4793. (time-to-days
  4794. (time-subtract (current-time)
  4795. (list 0 (* 3600 org-extend-today-until) 0))))
  4796. ;;;; Font-Lock stuff, including the activators
  4797. (require 'font-lock)
  4798. (defconst org-non-link-chars "]\t\n\r<>")
  4799. (defvar org-link-types-re nil
  4800. "Matches a link that has a url-like prefix like \"http:\"")
  4801. (defvar org-link-re-with-space nil
  4802. "Matches a link with spaces, optional angular brackets around it.")
  4803. (defvar org-link-re-with-space2 nil
  4804. "Matches a link with spaces, optional angular brackets around it.")
  4805. (defvar org-link-re-with-space3 nil
  4806. "Matches a link with spaces, only for internal part in bracket links.")
  4807. (defvar org-angle-link-re nil
  4808. "Matches link with angular brackets, spaces are allowed.")
  4809. (defvar org-plain-link-re nil
  4810. "Matches plain link, without spaces.")
  4811. (defvar org-bracket-link-regexp nil
  4812. "Matches a link in double brackets.")
  4813. (defvar org-bracket-link-analytic-regexp nil
  4814. "Regular expression used to analyze links.
  4815. Here is what the match groups contain after a match:
  4816. 1: http:
  4817. 2: http
  4818. 3: path
  4819. 4: [desc]
  4820. 5: desc")
  4821. (defvar org-bracket-link-analytic-regexp++ nil
  4822. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4823. (defvar org-any-link-re nil
  4824. "Regular expression matching any link.")
  4825. (defconst org-match-sexp-depth 3
  4826. "Number of stacked braces for sub/superscript matching.")
  4827. (defun org-create-multibrace-regexp (left right n)
  4828. "Create a regular expression which will match a balanced sexp.
  4829. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4830. as single character strings.
  4831. The regexp returned will match the entire expression including the
  4832. delimiters. It will also define a single group which contains the
  4833. match except for the outermost delimiters. The maximum depth of
  4834. stacked delimiters is N. Escaping delimiters is not possible."
  4835. (let* ((nothing (concat "[^" left right "]*?"))
  4836. (or "\\|")
  4837. (re nothing)
  4838. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4839. (while (> n 1)
  4840. (setq n (1- n)
  4841. re (concat re or next)
  4842. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4843. (concat left "\\(" re "\\)" right)))
  4844. (defconst org-match-substring-regexp
  4845. (concat
  4846. "\\(\\S-\\)\\([_^]\\)\\("
  4847. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4848. "\\|"
  4849. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4850. "\\|"
  4851. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4852. "The regular expression matching a sub- or superscript.")
  4853. (defconst org-match-substring-with-braces-regexp
  4854. (concat
  4855. "\\(\\S-\\)\\([_^]\\)"
  4856. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4857. "The regular expression matching a sub- or superscript, forcing braces.")
  4858. (defun org-make-link-regexps ()
  4859. "Update the link regular expressions.
  4860. This should be called after the variable `org-link-parameters' has changed."
  4861. (let ((types-re (regexp-opt (org-link-types) t)))
  4862. (setq org-link-types-re
  4863. (concat "\\`" types-re ":")
  4864. org-link-re-with-space
  4865. (concat "<?" types-re ":"
  4866. "\\([^" org-non-link-chars " ]"
  4867. "[^" org-non-link-chars "]*"
  4868. "[^" org-non-link-chars " ]\\)>?")
  4869. org-link-re-with-space2
  4870. (concat "<?" types-re ":"
  4871. "\\([^" org-non-link-chars " ]"
  4872. "[^\t\n\r]*"
  4873. "[^" org-non-link-chars " ]\\)>?")
  4874. org-link-re-with-space3
  4875. (concat "<?" types-re ":"
  4876. "\\([^" org-non-link-chars " ]"
  4877. "[^\t\n\r]*\\)")
  4878. org-angle-link-re
  4879. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  4880. types-re)
  4881. org-plain-link-re
  4882. (concat
  4883. "\\<" types-re ":"
  4884. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  4885. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  4886. org-bracket-link-regexp
  4887. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  4888. org-bracket-link-analytic-regexp
  4889. (concat
  4890. "\\[\\["
  4891. "\\(" types-re ":\\)?"
  4892. "\\([^]]+\\)"
  4893. "\\]"
  4894. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4895. "\\]")
  4896. org-bracket-link-analytic-regexp++
  4897. (concat
  4898. "\\[\\["
  4899. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  4900. "\\([^]]+\\)"
  4901. "\\]"
  4902. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4903. "\\]")
  4904. org-any-link-re
  4905. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  4906. org-angle-link-re "\\)\\|\\("
  4907. org-plain-link-re "\\)"))))
  4908. (org-make-link-regexps)
  4909. (defvar org-emph-face nil)
  4910. (defun org-do-emphasis-faces (limit)
  4911. "Run through the buffer and emphasize strings."
  4912. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4913. (car org-emphasis-regexp-components))))
  4914. (catch :exit
  4915. (while (re-search-forward quick-re limit t)
  4916. (let* ((marker (match-string 2))
  4917. (verbatim? (member marker '("~" "="))))
  4918. (when (save-excursion
  4919. (goto-char (match-beginning 0))
  4920. (and
  4921. ;; Do not match table hlines.
  4922. (not (and (equal marker "+")
  4923. (org-match-line
  4924. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4925. ;; Do not match headline stars. Do not consider
  4926. ;; stars of a headline as closing marker for bold
  4927. ;; markup either.
  4928. (not (and (equal marker "*")
  4929. (save-excursion
  4930. (forward-char)
  4931. (skip-chars-backward "*")
  4932. (looking-at-p org-outline-regexp-bol))))
  4933. ;; Match full emphasis markup regexp.
  4934. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4935. ;; Do not span over paragraph boundaries.
  4936. (not (string-match-p org-element-paragraph-separate
  4937. (match-string 2)))
  4938. ;; Do not span over cells in table rows.
  4939. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4940. (string-match-p "|" (match-string 4))))))
  4941. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  4942. (font-lock-prepend-text-property
  4943. (match-beginning 2) (match-end 2) 'face face)
  4944. (when verbatim?
  4945. (org-remove-flyspell-overlays-in
  4946. (match-beginning 0) (match-end 0))
  4947. (remove-text-properties (match-beginning 2) (match-end 2)
  4948. '(display t invisible t intangible t)))
  4949. (add-text-properties (match-beginning 2) (match-end 2)
  4950. '(font-lock-multiline t org-emphasis t))
  4951. (when org-hide-emphasis-markers
  4952. (add-text-properties (match-end 4) (match-beginning 5)
  4953. '(invisible org-link))
  4954. (add-text-properties (match-beginning 3) (match-end 3)
  4955. '(invisible org-link)))
  4956. (throw :exit t))))))))
  4957. (defun org-emphasize (&optional char)
  4958. "Insert or change an emphasis, i.e. a font like bold or italic.
  4959. If there is an active region, change that region to a new emphasis.
  4960. If there is no region, just insert the marker characters and position
  4961. the cursor between them.
  4962. CHAR should be the marker character. If it is a space, it means to
  4963. remove the emphasis of the selected region.
  4964. If CHAR is not given (for example in an interactive call) it will be
  4965. prompted for."
  4966. (interactive)
  4967. (let ((erc org-emphasis-regexp-components)
  4968. (string "") beg end move s)
  4969. (if (org-region-active-p)
  4970. (setq beg (region-beginning)
  4971. end (region-end)
  4972. string (buffer-substring beg end))
  4973. (setq move t))
  4974. (unless char
  4975. (message "Emphasis marker or tag: [%s]"
  4976. (mapconcat #'car org-emphasis-alist ""))
  4977. (setq char (read-char-exclusive)))
  4978. (if (equal char ?\s)
  4979. (setq s ""
  4980. move nil)
  4981. (unless (assoc (char-to-string char) org-emphasis-alist)
  4982. (user-error "No such emphasis marker: \"%c\"" char))
  4983. (setq s (char-to-string char)))
  4984. (while (and (> (length string) 1)
  4985. (equal (substring string 0 1) (substring string -1))
  4986. (assoc (substring string 0 1) org-emphasis-alist))
  4987. (setq string (substring string 1 -1)))
  4988. (setq string (concat s string s))
  4989. (when beg (delete-region beg end))
  4990. (unless (or (bolp)
  4991. (string-match (concat "[" (nth 0 erc) "\n]")
  4992. (char-to-string (char-before (point)))))
  4993. (insert " "))
  4994. (unless (or (eobp)
  4995. (string-match (concat "[" (nth 1 erc) "\n]")
  4996. (char-to-string (char-after (point)))))
  4997. (insert " ") (backward-char 1))
  4998. (insert string)
  4999. (and move (backward-char 1))))
  5000. (defconst org-nonsticky-props
  5001. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5002. (defsubst org-rear-nonsticky-at (pos)
  5003. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5004. (defun org-activate-links (limit)
  5005. "Add link properties to links.
  5006. This includes angle, plain, and bracket links."
  5007. (catch :exit
  5008. (while (re-search-forward org-any-link-re limit t)
  5009. (let* ((start (match-beginning 0))
  5010. (end (match-end 0))
  5011. (style (cond ((eq ?< (char-after start)) 'angle)
  5012. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5013. (t 'plain))))
  5014. (when (and (memq style org-highlight-links)
  5015. ;; Do not confuse plain links with tags.
  5016. (not (and (eq style 'plain)
  5017. (let ((face (get-text-property
  5018. (max (1- start) (point-min)) 'face)))
  5019. (if (consp face) (memq 'org-tag face)
  5020. (eq 'org-tag face))))))
  5021. (let* ((link-object (save-excursion
  5022. (goto-char start)
  5023. (save-match-data (org-element-link-parser))))
  5024. (link (org-element-property :raw-link link-object))
  5025. (type (org-element-property :type link-object))
  5026. (path (org-element-property :path link-object))
  5027. (properties ;for link's visible part
  5028. (list
  5029. 'face (pcase (org-link-get-parameter type :face)
  5030. ((and (pred functionp) face) (funcall face path))
  5031. ((and (pred facep) face) face)
  5032. ((and (pred consp) face) face) ;anonymous
  5033. (_ 'org-link))
  5034. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5035. 'highlight)
  5036. 'keymap (or (org-link-get-parameter type :keymap)
  5037. org-mouse-map)
  5038. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5039. ((and (pred stringp) echo) echo)
  5040. ((and (pred functionp) echo) echo)
  5041. (_ (concat "LINK: " link)))
  5042. 'htmlize-link (pcase (org-link-get-parameter type
  5043. :htmlize-link)
  5044. ((and (pred functionp) f) (funcall f))
  5045. (_ `(:uri ,link)))
  5046. 'font-lock-multiline t)))
  5047. (org-remove-flyspell-overlays-in start end)
  5048. (org-rear-nonsticky-at end)
  5049. (if (not (eq 'bracket style))
  5050. (add-text-properties start end properties)
  5051. ;; Handle invisible parts in bracket links.
  5052. (remove-text-properties start end '(invisible nil))
  5053. (let ((hidden
  5054. (append `(invisible
  5055. ,(or (org-link-get-parameter type :display)
  5056. 'org-link))
  5057. properties))
  5058. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5059. (visible-end (or (match-end 4) (match-end 2))))
  5060. (add-text-properties start visible-start hidden)
  5061. (add-text-properties visible-start visible-end properties)
  5062. (add-text-properties visible-end end hidden)
  5063. (org-rear-nonsticky-at visible-start)
  5064. (org-rear-nonsticky-at visible-end)))
  5065. (let ((f (org-link-get-parameter type :activate-func)))
  5066. (when (functionp f)
  5067. (funcall f start end path (eq style 'bracket))))
  5068. (throw :exit t))))) ;signal success
  5069. nil))
  5070. (defun org-activate-code (limit)
  5071. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5072. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5073. (remove-text-properties (match-beginning 0) (match-end 0)
  5074. '(display t invisible t intangible t))
  5075. t))
  5076. (defcustom org-src-fontify-natively t
  5077. "When non-nil, fontify code in code blocks.
  5078. See also the `org-block' face."
  5079. :type 'boolean
  5080. :version "26.1"
  5081. :package-version '(Org . "8.3")
  5082. :group 'org-appearance
  5083. :group 'org-babel)
  5084. (defcustom org-allow-promoting-top-level-subtree nil
  5085. "When non-nil, allow promoting a top level subtree.
  5086. The leading star of the top level headline will be replaced
  5087. by a #."
  5088. :type 'boolean
  5089. :version "24.1"
  5090. :group 'org-appearance)
  5091. (defun org-fontify-meta-lines-and-blocks (limit)
  5092. (condition-case nil
  5093. (org-fontify-meta-lines-and-blocks-1 limit)
  5094. (error (message "Org mode fontification error in %S at %d"
  5095. (current-buffer)
  5096. (line-number-at-pos)))))
  5097. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5098. "Fontify #+ lines and blocks."
  5099. (let ((case-fold-search t))
  5100. (when (re-search-forward
  5101. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5102. limit t)
  5103. (let ((beg (match-beginning 0))
  5104. (block-start (match-end 0))
  5105. (block-end nil)
  5106. (lang (match-string 7))
  5107. (beg1 (line-beginning-position 2))
  5108. (dc1 (downcase (match-string 2)))
  5109. (dc3 (downcase (match-string 3)))
  5110. end end1 quoting block-type)
  5111. (cond
  5112. ((and (match-end 4) (equal dc3 "+begin"))
  5113. ;; Truly a block
  5114. (setq block-type (downcase (match-string 5))
  5115. quoting (member block-type org-protecting-blocks))
  5116. (when (re-search-forward
  5117. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5118. nil t) ;; on purpose, we look further than LIMIT
  5119. (setq end (min (point-max) (match-end 0))
  5120. end1 (min (point-max) (1- (match-beginning 0))))
  5121. (setq block-end (match-beginning 0))
  5122. (when quoting
  5123. (org-remove-flyspell-overlays-in beg1 end1)
  5124. (remove-text-properties beg end
  5125. '(display t invisible t intangible t)))
  5126. (add-text-properties
  5127. beg end '(font-lock-fontified t font-lock-multiline t))
  5128. (add-text-properties beg beg1 '(face org-meta-line))
  5129. (org-remove-flyspell-overlays-in beg beg1)
  5130. (add-text-properties ; For end_src
  5131. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5132. (org-remove-flyspell-overlays-in end1 end)
  5133. (cond
  5134. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5135. (org-src-font-lock-fontify-block lang block-start block-end)
  5136. (add-text-properties beg1 block-end '(src-block t)))
  5137. (quoting
  5138. (add-text-properties beg1 (min (point-max) (1+ end1))
  5139. (list 'face
  5140. (list :inherit
  5141. (let ((face-name
  5142. (intern (format "org-block-%s" lang))))
  5143. (append (and (facep face-name) (list face-name))
  5144. '(org-block))))))) ; end of source block
  5145. ((not org-fontify-quote-and-verse-blocks))
  5146. ((string= block-type "quote")
  5147. (add-face-text-property
  5148. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5149. ((string= block-type "verse")
  5150. (add-face-text-property
  5151. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5152. (add-text-properties beg beg1 '(face org-block-begin-line))
  5153. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5154. '(face org-block-end-line))
  5155. t))
  5156. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5157. (org-remove-flyspell-overlays-in
  5158. (match-beginning 0)
  5159. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5160. (add-text-properties
  5161. beg (match-end 3)
  5162. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5163. '(font-lock-fontified t invisible t)
  5164. '(font-lock-fontified t face org-document-info-keyword)))
  5165. (add-text-properties
  5166. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5167. (if (string-equal dc1 "+title:")
  5168. '(font-lock-fontified t face org-document-title)
  5169. '(font-lock-fontified t face org-document-info))))
  5170. ((string-prefix-p "+caption" dc1)
  5171. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5172. (remove-text-properties (match-beginning 0) (match-end 0)
  5173. '(display t invisible t intangible t))
  5174. ;; Handle short captions.
  5175. (save-excursion
  5176. (beginning-of-line)
  5177. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5178. (add-text-properties (line-beginning-position) (match-end 1)
  5179. '(font-lock-fontified t face org-meta-line))
  5180. (add-text-properties (match-end 0) (line-end-position)
  5181. '(font-lock-fontified t face org-block))
  5182. t)
  5183. ((member dc3 '(" " ""))
  5184. (org-remove-flyspell-overlays-in beg (match-end 0))
  5185. (add-text-properties
  5186. beg (match-end 0)
  5187. '(font-lock-fontified t face font-lock-comment-face)))
  5188. (t ;; just any other in-buffer setting, but not indented
  5189. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5190. (remove-text-properties (match-beginning 0) (match-end 0)
  5191. '(display t invisible t intangible t))
  5192. (add-text-properties beg (match-end 0)
  5193. '(font-lock-fontified t face org-meta-line))
  5194. t))))))
  5195. (defun org-fontify-drawers (limit)
  5196. "Fontify drawers."
  5197. (when (re-search-forward org-drawer-regexp limit t)
  5198. (add-text-properties
  5199. (match-beginning 0) (match-end 0)
  5200. '(font-lock-fontified t face org-special-keyword))
  5201. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5202. t))
  5203. (defun org-fontify-macros (limit)
  5204. "Fontify macros."
  5205. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  5206. (let ((begin (match-beginning 0))
  5207. (opening-end (match-beginning 1)))
  5208. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  5209. (match-string 1))
  5210. (let ((end (match-end 1))
  5211. (closing-start (match-beginning 1)))
  5212. (add-text-properties
  5213. begin end
  5214. '(font-lock-multiline t font-lock-fontified t face org-macro))
  5215. (org-remove-flyspell-overlays-in begin end)
  5216. (when org-hide-macro-markers
  5217. (add-text-properties begin opening-end '(invisible t))
  5218. (add-text-properties closing-start end '(invisible t)))
  5219. t)))))
  5220. (defun org-activate-footnote-links (limit)
  5221. "Add text properties for footnotes."
  5222. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5223. (when fn
  5224. (let* ((beg (nth 1 fn))
  5225. (end (nth 2 fn))
  5226. (label (car fn))
  5227. (referencep (/= (line-beginning-position) beg)))
  5228. (when (and referencep (nth 3 fn))
  5229. (save-excursion
  5230. (goto-char beg)
  5231. (search-forward (or label "fn:"))
  5232. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5233. (add-text-properties beg end
  5234. (list 'mouse-face 'highlight
  5235. 'keymap org-mouse-map
  5236. 'help-echo
  5237. (if referencep "Footnote reference"
  5238. "Footnote definition")
  5239. 'font-lock-fontified t
  5240. 'font-lock-multiline t
  5241. 'face 'org-footnote))))))
  5242. (defun org-activate-dates (limit)
  5243. "Add text properties for dates."
  5244. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5245. (not (equal (char-before (match-beginning 0)) 91)))
  5246. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5247. (add-text-properties (match-beginning 0) (match-end 0)
  5248. (list 'mouse-face 'highlight
  5249. 'keymap org-mouse-map))
  5250. (org-rear-nonsticky-at (match-end 0))
  5251. (when org-display-custom-times
  5252. ;; If it's a date range, activate custom time for second date.
  5253. (when (match-end 3)
  5254. (org-display-custom-time (match-beginning 3) (match-end 3)))
  5255. (org-display-custom-time (match-beginning 1) (match-end 1)))
  5256. t))
  5257. (defvar-local org-target-link-regexp nil
  5258. "Regular expression matching radio targets in plain text.")
  5259. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5260. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5261. border border border))
  5262. "Regular expression matching a link target.")
  5263. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5264. "Regular expression matching a radio target.")
  5265. (defconst org-any-target-regexp
  5266. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5267. "Regular expression matching any target.")
  5268. (defun org-activate-target-links (limit)
  5269. "Add text properties for target matches."
  5270. (when org-target-link-regexp
  5271. (let ((case-fold-search t))
  5272. (when (re-search-forward org-target-link-regexp limit t)
  5273. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5274. (add-text-properties (match-beginning 1) (match-end 1)
  5275. (list 'mouse-face 'highlight
  5276. 'keymap org-mouse-map
  5277. 'help-echo "Radio target link"
  5278. 'org-linked-text t))
  5279. (org-rear-nonsticky-at (match-end 1))
  5280. t))))
  5281. (defun org-update-radio-target-regexp ()
  5282. "Find all radio targets in this file and update the regular expression.
  5283. Also refresh fontification if needed."
  5284. (interactive)
  5285. (let ((old-regexp org-target-link-regexp)
  5286. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5287. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5288. (targets
  5289. (org-with-wide-buffer
  5290. (goto-char (point-min))
  5291. (let (rtn)
  5292. (while (re-search-forward org-radio-target-regexp nil t)
  5293. ;; Make sure point is really within the object.
  5294. (backward-char)
  5295. (let ((obj (org-element-context)))
  5296. (when (eq (org-element-type obj) 'radio-target)
  5297. (cl-pushnew (org-element-property :value obj) rtn
  5298. :test #'equal))))
  5299. rtn))))
  5300. (setq org-target-link-regexp
  5301. (and targets
  5302. (concat before-re
  5303. (mapconcat
  5304. (lambda (x)
  5305. (replace-regexp-in-string
  5306. " +" "\\s-+" (regexp-quote x) t t))
  5307. targets
  5308. "\\|")
  5309. after-re)))
  5310. (unless (equal old-regexp org-target-link-regexp)
  5311. ;; Clean-up cache.
  5312. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5313. ((not org-target-link-regexp) old-regexp)
  5314. (t
  5315. (concat before-re
  5316. (mapconcat
  5317. (lambda (re)
  5318. (substring re (length before-re)
  5319. (- (length after-re))))
  5320. (list old-regexp org-target-link-regexp)
  5321. "\\|")
  5322. after-re)))))
  5323. (org-with-wide-buffer
  5324. (goto-char (point-min))
  5325. (while (re-search-forward regexp nil t)
  5326. (org-element-cache-refresh (match-beginning 1)))))
  5327. ;; Re fontify buffer.
  5328. (when (memq 'radio org-highlight-links)
  5329. (org-restart-font-lock)))))
  5330. (defvar org-latex-and-related-regexp nil
  5331. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5332. (defun org-compute-latex-and-related-regexp ()
  5333. "Compute regular expression for LaTeX, entities and sub/superscript.
  5334. Result depends on variable `org-highlight-latex-and-related'."
  5335. (setq-local
  5336. org-latex-and-related-regexp
  5337. (let* ((re-sub
  5338. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5339. ((eq org-use-sub-superscripts '{})
  5340. (list org-match-substring-with-braces-regexp))
  5341. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5342. (re-latex
  5343. (when (memq 'latex org-highlight-latex-and-related)
  5344. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5345. (delq nil
  5346. (mapcar (lambda (x)
  5347. (and (member (car x) matchers) (nth 1 x)))
  5348. org-latex-regexps)))))
  5349. (re-entities
  5350. (when (memq 'entities org-highlight-latex-and-related)
  5351. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5352. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5353. (defun org-do-latex-and-related (limit)
  5354. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5355. LIMIT bounds the search for syntax to highlight. Stop at first
  5356. highlighted object, if any. Return t if some highlighting was
  5357. done, nil otherwise."
  5358. (when (org-string-nw-p org-latex-and-related-regexp)
  5359. (catch 'found
  5360. (while (re-search-forward org-latex-and-related-regexp limit t)
  5361. (unless
  5362. (cl-some
  5363. (lambda (f)
  5364. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5365. (save-excursion
  5366. (goto-char (1+ (match-beginning 0)))
  5367. (face-at-point nil t)))
  5368. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5369. '(?_ ?^))
  5370. 1
  5371. 0)))
  5372. (font-lock-prepend-text-property
  5373. (+ offset (match-beginning 0)) (match-end 0)
  5374. 'face 'org-latex-and-related)
  5375. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5376. '(font-lock-multiline t)))
  5377. (throw 'found t)))
  5378. nil)))
  5379. (defun org-restart-font-lock ()
  5380. "Restart `font-lock-mode', to force refontification."
  5381. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5382. (font-lock-mode -1)
  5383. (font-lock-mode 1)))
  5384. (defun org-activate-tags (limit)
  5385. (when (re-search-forward org-tag-line-re limit t)
  5386. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5387. (add-text-properties (match-beginning 1) (match-end 1)
  5388. (list 'mouse-face 'highlight
  5389. 'keymap org-mouse-map))
  5390. (org-rear-nonsticky-at (match-end 1))
  5391. t))
  5392. (defun org-outline-level ()
  5393. "Compute the outline level of the heading at point.
  5394. If this is called at a normal headline, the level is the number
  5395. of stars. Use `org-reduced-level' to remove the effect of
  5396. `org-odd-levels'. Unlike to `org-current-level', this function
  5397. takes into consideration inlinetasks."
  5398. (org-with-wide-buffer
  5399. (end-of-line)
  5400. (if (re-search-backward org-outline-regexp-bol nil t)
  5401. (1- (- (match-end 0) (match-beginning 0)))
  5402. 0)))
  5403. (defvar org-font-lock-keywords nil)
  5404. (defsubst org-re-property (property &optional literal allow-null value)
  5405. "Return a regexp matching a PROPERTY line.
  5406. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5407. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5408. non-nil, match properties even without a value.
  5409. Match group 3 is set to the value when it exists. If there is no
  5410. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5411. With optional argument VALUE, match only property lines with
  5412. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5413. unless LITERAL is non-nil."
  5414. (concat
  5415. "^\\(?4:[ \t]*\\)"
  5416. (format "\\(?1::\\(?2:%s\\):\\)"
  5417. (if literal property (regexp-quote property)))
  5418. (cond (value
  5419. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5420. (if literal value (regexp-quote value))))
  5421. (allow-null
  5422. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5423. (t
  5424. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5425. (defconst org-property-re
  5426. (org-re-property "\\S-+" 'literal t)
  5427. "Regular expression matching a property line.
  5428. There are four matching groups:
  5429. 1: :PROPKEY: including the leading and trailing colon,
  5430. 2: PROPKEY without the leading and trailing colon,
  5431. 3: PROPVAL without leading or trailing spaces,
  5432. 4: the indentation of the current line,
  5433. 5: trailing whitespace.")
  5434. (defvar org-font-lock-hook nil
  5435. "Functions to be called for special font lock stuff.")
  5436. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5437. (defvar org-font-lock-set-keywords-hook nil
  5438. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5439. This is called after `org-font-lock-extra-keywords' is defined, but before
  5440. it is installed to be used by font lock. This can be useful if something
  5441. needs to be inserted at a specific position in the font-lock sequence.")
  5442. (defun org-font-lock-hook (limit)
  5443. "Run `org-font-lock-hook' within LIMIT."
  5444. (run-hook-with-args 'org-font-lock-hook limit))
  5445. (defun org-set-font-lock-defaults ()
  5446. "Set font lock defaults for the current buffer."
  5447. (let* ((em org-fontify-emphasized-text)
  5448. (lk org-highlight-links)
  5449. (org-font-lock-extra-keywords
  5450. (list
  5451. ;; Call the hook
  5452. '(org-font-lock-hook)
  5453. ;; Headlines
  5454. `(,(if org-fontify-whole-heading-line
  5455. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5456. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5457. (1 (org-get-level-face 1))
  5458. (2 (org-get-level-face 2))
  5459. (3 (org-get-level-face 3)))
  5460. ;; Table lines
  5461. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5462. (1 'org-table t))
  5463. ;; Table internals
  5464. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5465. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5466. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5467. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5468. ;; Drawers
  5469. '(org-fontify-drawers)
  5470. ;; Properties
  5471. (list org-property-re
  5472. '(1 'org-special-keyword t)
  5473. '(3 'org-property-value t))
  5474. ;; Link related fontification.
  5475. '(org-activate-links)
  5476. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5477. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5478. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5479. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5480. ;; Targets.
  5481. (list org-any-target-regexp '(0 'org-target t))
  5482. ;; Diary sexps.
  5483. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5484. ;; Macro
  5485. '(org-fontify-macros)
  5486. ;; TODO keyword
  5487. (list (format org-heading-keyword-regexp-format
  5488. org-todo-regexp)
  5489. '(2 (org-get-todo-face 2) t))
  5490. ;; DONE
  5491. (if org-fontify-done-headline
  5492. (list (format org-heading-keyword-regexp-format
  5493. (concat
  5494. "\\(?:"
  5495. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5496. "\\)"))
  5497. '(2 'org-headline-done t))
  5498. nil)
  5499. ;; Priorities
  5500. '(org-font-lock-add-priority-faces)
  5501. ;; Tags
  5502. '(org-font-lock-add-tag-faces)
  5503. ;; Tags groups
  5504. (when (and org-group-tags org-tag-groups-alist)
  5505. (list (concat org-outline-regexp-bol ".+\\(:"
  5506. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5507. ":\\).*$")
  5508. '(1 'org-tag-group prepend)))
  5509. ;; Special keywords
  5510. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5511. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5512. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5513. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5514. ;; Emphasis
  5515. (when em '(org-do-emphasis-faces))
  5516. ;; Checkboxes
  5517. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5518. 1 'org-checkbox prepend)
  5519. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5520. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5521. (0 (org-get-checkbox-statistics-face) t)))
  5522. ;; Description list items
  5523. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5524. 1 'org-list-dt prepend)
  5525. ;; ARCHIVEd headings
  5526. (list (concat
  5527. org-outline-regexp-bol
  5528. "\\(.*:" org-archive-tag ":.*\\)")
  5529. '(1 'org-archived prepend))
  5530. ;; Specials
  5531. '(org-do-latex-and-related)
  5532. '(org-fontify-entities)
  5533. '(org-raise-scripts)
  5534. ;; Code
  5535. '(org-activate-code (1 'org-code t))
  5536. ;; COMMENT
  5537. (list (format
  5538. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5539. org-todo-regexp
  5540. org-comment-string)
  5541. '(9 'org-special-keyword t))
  5542. ;; Blocks and meta lines
  5543. '(org-fontify-meta-lines-and-blocks))))
  5544. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5545. (run-hooks 'org-font-lock-set-keywords-hook)
  5546. ;; Now set the full font-lock-keywords
  5547. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5548. (setq-local font-lock-defaults
  5549. '(org-font-lock-keywords t nil nil backward-paragraph))
  5550. (kill-local-variable 'font-lock-keywords)
  5551. nil))
  5552. (defun org-toggle-pretty-entities ()
  5553. "Toggle the composition display of entities as UTF8 characters."
  5554. (interactive)
  5555. (setq-local org-pretty-entities (not org-pretty-entities))
  5556. (org-restart-font-lock)
  5557. (if org-pretty-entities
  5558. (message "Entities are now displayed as UTF8 characters")
  5559. (save-restriction
  5560. (widen)
  5561. (decompose-region (point-min) (point-max))
  5562. (message "Entities are now displayed as plain text"))))
  5563. (defvar-local org-custom-properties-overlays nil
  5564. "List of overlays used for custom properties.")
  5565. (defun org-toggle-custom-properties-visibility ()
  5566. "Display or hide properties in `org-custom-properties'."
  5567. (interactive)
  5568. (if org-custom-properties-overlays
  5569. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5570. (setq org-custom-properties-overlays nil))
  5571. (when org-custom-properties
  5572. (org-with-wide-buffer
  5573. (goto-char (point-min))
  5574. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5575. (while (re-search-forward regexp nil t)
  5576. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5577. (when (and end (< (point) end))
  5578. ;; Hide first custom property in current drawer.
  5579. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5580. (overlay-put o 'invisible t)
  5581. (overlay-put o 'org-custom-property t)
  5582. (push o org-custom-properties-overlays))
  5583. ;; Hide additional custom properties in the same drawer.
  5584. (while (re-search-forward regexp end t)
  5585. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5586. (overlay-put o 'invisible t)
  5587. (overlay-put o 'org-custom-property t)
  5588. (push o org-custom-properties-overlays)))))
  5589. ;; Each entry is limited to a single property drawer.
  5590. (outline-next-heading)))))))
  5591. (defun org-fontify-entities (limit)
  5592. "Find an entity to fontify."
  5593. (let (ee)
  5594. (when org-pretty-entities
  5595. (catch 'match
  5596. ;; "\_ "-family is left out on purpose. Only the first one,
  5597. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5598. ;; confusing when adding a second white space character.
  5599. (while (re-search-forward
  5600. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5601. limit t)
  5602. (when (and (not (org-at-comment-p))
  5603. (setq ee (org-entity-get (match-string 1)))
  5604. (= (length (nth 6 ee)) 1))
  5605. (let* ((end (if (equal (match-string 2) "{}")
  5606. (match-end 2)
  5607. (match-end 1))))
  5608. (add-text-properties
  5609. (match-beginning 0) end
  5610. (list 'font-lock-fontified t))
  5611. (compose-region (match-beginning 0) end
  5612. (nth 6 ee) nil)
  5613. (backward-char 1)
  5614. (throw 'match t))))
  5615. nil))))
  5616. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5617. "Fontify string S like in Org mode."
  5618. (with-temp-buffer
  5619. (insert s)
  5620. (let ((org-odd-levels-only odd-levels))
  5621. (org-mode)
  5622. (org-font-lock-ensure)
  5623. (buffer-string))))
  5624. (defvar org-m nil)
  5625. (defvar org-l nil)
  5626. (defvar org-f nil)
  5627. (defun org-get-level-face (n)
  5628. "Get the right face for match N in font-lock matching of headlines."
  5629. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5630. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5631. (if org-cycle-level-faces
  5632. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5633. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5634. (cond
  5635. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5636. ((eq n 2) org-f)
  5637. (t (unless org-level-color-stars-only org-f))))
  5638. (defun org-face-from-face-or-color (context inherit face-or-color)
  5639. "Create a face list that inherits INHERIT, but sets the foreground color.
  5640. When FACE-OR-COLOR is not a string, just return it."
  5641. (if (stringp face-or-color)
  5642. (list :inherit inherit
  5643. (cdr (assoc context org-faces-easy-properties))
  5644. face-or-color)
  5645. face-or-color))
  5646. (defun org-get-todo-face (kwd)
  5647. "Get the right face for a TODO keyword KWD.
  5648. If KWD is a number, get the corresponding match group."
  5649. (when (numberp kwd) (setq kwd (match-string kwd)))
  5650. (or (org-face-from-face-or-color
  5651. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5652. (and (member kwd org-done-keywords) 'org-done)
  5653. 'org-todo))
  5654. (defun org-get-priority-face (priority)
  5655. "Get the right face for PRIORITY.
  5656. PRIORITY is a character."
  5657. (or (org-face-from-face-or-color
  5658. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5659. 'org-priority))
  5660. (defun org-get-tag-face (tag)
  5661. "Get the right face for TAG.
  5662. If TAG is a number, get the corresponding match group."
  5663. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5664. (or (org-face-from-face-or-color
  5665. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5666. 'org-tag)))
  5667. (defun org-font-lock-add-priority-faces (limit)
  5668. "Add the special priority faces."
  5669. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5670. (add-text-properties
  5671. (match-beginning 1) (match-end 1)
  5672. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5673. 'font-lock-fontified t))))
  5674. (defun org-font-lock-add-tag-faces (limit)
  5675. "Add the special tag faces."
  5676. (when (and org-tag-faces org-tags-special-faces-re)
  5677. (while (re-search-forward org-tags-special-faces-re limit t)
  5678. (add-text-properties (match-beginning 1) (match-end 1)
  5679. (list 'face (org-get-tag-face 1)
  5680. 'font-lock-fontified t))
  5681. (backward-char 1))))
  5682. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5683. "Remove fontification and activation overlays from links."
  5684. (font-lock-default-unfontify-region beg end)
  5685. (let* ((buffer-undo-list t)
  5686. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5687. (inhibit-modification-hooks t)
  5688. deactivate-mark buffer-file-name buffer-file-truename)
  5689. (decompose-region beg end)
  5690. (remove-text-properties beg end
  5691. '(mouse-face t keymap t org-linked-text t
  5692. invisible t intangible t
  5693. org-emphasis t))
  5694. (org-remove-font-lock-display-properties beg end)))
  5695. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5696. ((raise 0.3) (height 0.7))
  5697. ((raise -0.5))
  5698. ((raise 0.5)))
  5699. "Display properties for showing superscripts and subscripts.")
  5700. (defun org-remove-font-lock-display-properties (beg end)
  5701. "Remove specific display properties that have been added by font lock.
  5702. The will remove the raise properties that are used to show superscripts
  5703. and subscripts."
  5704. (let (next prop)
  5705. (while (< beg end)
  5706. (setq next (next-single-property-change beg 'display nil end)
  5707. prop (get-text-property beg 'display))
  5708. (when (member prop org-script-display)
  5709. (put-text-property beg next 'display nil))
  5710. (setq beg next))))
  5711. (defun org-raise-scripts (limit)
  5712. "Add raise properties to sub/superscripts."
  5713. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5714. (re-search-forward
  5715. (if (eq org-use-sub-superscripts t)
  5716. org-match-substring-regexp
  5717. org-match-substring-with-braces-regexp)
  5718. limit t))
  5719. (let* ((pos (point)) table-p comment-p
  5720. (mpos (match-beginning 3))
  5721. (emph-p (get-text-property mpos 'org-emphasis))
  5722. (link-p (get-text-property mpos 'mouse-face))
  5723. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5724. (goto-char (point-at-bol))
  5725. (setq table-p (looking-at-p org-table-dataline-regexp)
  5726. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5727. (goto-char pos)
  5728. ;; Handle a_b^c
  5729. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5730. (unless (or comment-p emph-p link-p keyw-p)
  5731. (put-text-property (match-beginning 3) (match-end 0)
  5732. 'display
  5733. (if (equal (char-after (match-beginning 2)) ?^)
  5734. (nth (if table-p 3 1) org-script-display)
  5735. (nth (if table-p 2 0) org-script-display)))
  5736. (add-text-properties (match-beginning 2) (match-end 2)
  5737. (list 'invisible t))
  5738. (when (and (eq (char-after (match-beginning 3)) ?{)
  5739. (eq (char-before (match-end 3)) ?}))
  5740. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5741. (list 'invisible t))
  5742. (add-text-properties (1- (match-end 3)) (match-end 3)
  5743. (list 'invisible t))))
  5744. t)))
  5745. (defun org-remove-empty-overlays-at (pos)
  5746. "Remove outline overlays that do not contain non-white stuff."
  5747. (dolist (o (overlays-at pos))
  5748. (and (eq 'outline (overlay-get o 'invisible))
  5749. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5750. (overlay-end o))))
  5751. (delete-overlay o))))
  5752. (defun org-show-empty-lines-in-parent ()
  5753. "Move to the parent and re-show empty lines before visible headlines."
  5754. (save-excursion
  5755. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5756. (org-cycle-show-empty-lines context))))
  5757. (defun org-files-list ()
  5758. "Return `org-agenda-files' list, plus all open Org files.
  5759. This is useful for operations that need to scan all of a user's
  5760. open and agenda-wise Org files."
  5761. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5762. (dolist (buf (buffer-list))
  5763. (with-current-buffer buf
  5764. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5765. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5766. :test #'equal))))
  5767. files))
  5768. (defsubst org-entry-beginning-position ()
  5769. "Return the beginning position of the current entry."
  5770. (save-excursion (org-back-to-heading t) (point)))
  5771. (defsubst org-entry-end-position ()
  5772. "Return the end position of the current entry."
  5773. (save-excursion (outline-next-heading) (point)))
  5774. (defun org-subtree-end-visible-p ()
  5775. "Is the end of the current subtree visible?"
  5776. (pos-visible-in-window-p
  5777. (save-excursion (org-end-of-subtree t) (point))))
  5778. (defun org-first-headline-recenter ()
  5779. "Move cursor to the first headline and recenter the headline."
  5780. (let ((window (get-buffer-window)))
  5781. (when window
  5782. (goto-char (point-min))
  5783. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5784. (set-window-start window (line-beginning-position))))))
  5785. ;;; Visibility (headlines, blocks, drawers)
  5786. ;;;; Headlines visibility
  5787. (defun org-show-entry ()
  5788. "Show the body directly following this heading.
  5789. Show the heading too, if it is currently invisible."
  5790. (interactive)
  5791. (save-excursion
  5792. (ignore-errors
  5793. (org-back-to-heading t)
  5794. (org-flag-region
  5795. (line-end-position 0)
  5796. (save-excursion
  5797. (if (re-search-forward
  5798. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5799. (match-beginning 1)
  5800. (point-max)))
  5801. nil
  5802. 'outline))))
  5803. (defun org-show-children (&optional level)
  5804. "Show all direct subheadings of this heading.
  5805. Prefix arg LEVEL is how many levels below the current level
  5806. should be shown. Default is enough to cause the following
  5807. heading to appear."
  5808. (interactive "p")
  5809. (save-excursion
  5810. (org-back-to-heading t)
  5811. (let* ((current-level (funcall outline-level))
  5812. (max-level (org-get-valid-level
  5813. current-level
  5814. (if level (prefix-numeric-value level) 1)))
  5815. (end (save-excursion (org-end-of-subtree t t)))
  5816. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5817. (past-first-child nil)
  5818. ;; Make sure to skip inlinetasks.
  5819. (re (format regexp-fmt
  5820. current-level
  5821. (cond
  5822. ((not (featurep 'org-inlinetask)) "")
  5823. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5824. 3))
  5825. (t (1- org-inlinetask-min-level))))))
  5826. ;; Display parent heading.
  5827. (org-flag-heading nil)
  5828. (forward-line)
  5829. ;; Display children. First child may be deeper than expected
  5830. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5831. ;; MAX-LEVEL accordingly.
  5832. (while (re-search-forward re end t)
  5833. (unless past-first-child
  5834. (setq re (format regexp-fmt
  5835. current-level
  5836. (max (funcall outline-level) max-level)))
  5837. (setq past-first-child t))
  5838. (org-flag-heading nil)))))
  5839. (defun org-show-subtree ()
  5840. "Show everything after this heading at deeper levels."
  5841. (interactive)
  5842. (org-flag-region
  5843. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5844. ;;;; Blocks visibility
  5845. (defun org-hide-block-toggle-maybe ()
  5846. "Toggle visibility of block at point.
  5847. Unlike to `org-hide-block-toggle', this function does not throw
  5848. an error. Return a non-nil value when toggling is successful."
  5849. (interactive)
  5850. (ignore-errors (org-hide-block-toggle)))
  5851. (defun org-hide-block-toggle (&optional force)
  5852. "Toggle the visibility of the current block.
  5853. When optional argument FORCE is `off', make block visible. If it
  5854. is non-nil, hide it unconditionally. Throw an error when not at
  5855. a block. Return a non-nil value when toggling is successful."
  5856. (interactive)
  5857. (let ((element (org-element-at-point)))
  5858. (unless (memq (org-element-type element)
  5859. '(center-block comment-block dynamic-block example-block
  5860. export-block quote-block special-block
  5861. src-block verse-block))
  5862. (user-error "Not at a block"))
  5863. (let* ((post (org-element-property :post-affiliated element))
  5864. (start (save-excursion
  5865. (goto-char post)
  5866. (line-end-position)))
  5867. (end (save-excursion
  5868. (goto-char (org-element-property :end element))
  5869. (skip-chars-backward " \t\n")
  5870. (line-end-position))))
  5871. ;; Do nothing when not before or at the block opening line or at
  5872. ;; the block closing line.
  5873. (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
  5874. (cond ((eq force 'off)
  5875. (org-flag-region start end nil 'org-hide-block))
  5876. (force
  5877. (org-flag-region start end t 'org-hide-block))
  5878. ((eq (get-char-property start 'invisible) 'org-hide-block)
  5879. (org-flag-region start end nil 'org-hide-block))
  5880. (t
  5881. (org-flag-region start end t 'org-hide-block)))
  5882. ;; When the block is hidden away, make sure point is left in
  5883. ;; a visible part of the buffer.
  5884. (when (invisible-p (max (1- (point)) (point-min)))
  5885. (goto-char post))
  5886. ;; Signal success.
  5887. t))))
  5888. (defun org-hide-block-toggle-all ()
  5889. "Toggle the visibility of all blocks in the current buffer."
  5890. (org-block-map 'org-hide-block-toggle))
  5891. (defun org-hide-block-all ()
  5892. "Fold all blocks in the current buffer."
  5893. (interactive)
  5894. (org-show-all '(blocks))
  5895. (org-block-map 'org-hide-block-toggle-maybe))
  5896. ;;;; Drawers visibility
  5897. (defun org-cycle-hide-drawers (state &optional exceptions)
  5898. "Re-hide all drawers after a visibility state change.
  5899. STATE should be one of the symbols listed in the docstring of
  5900. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  5901. a list of strings specifying which drawers should not be hidden."
  5902. (when (and (derived-mode-p 'org-mode)
  5903. (not (memq state '(overview folded contents))))
  5904. (save-excursion
  5905. (let* ((globalp (eq state 'all))
  5906. (beg (if globalp (point-min) (point)))
  5907. (end (if globalp (point-max)
  5908. (if (eq state 'children)
  5909. (save-excursion (outline-next-heading) (point))
  5910. (org-end-of-subtree t)))))
  5911. (goto-char beg)
  5912. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  5913. (unless (member-ignore-case (match-string 1) exceptions)
  5914. (let ((drawer (org-element-at-point)))
  5915. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5916. (org-flag-drawer t drawer)
  5917. ;; Make sure to skip drawer entirely or we might flag
  5918. ;; it another time when matching its ending line with
  5919. ;; `org-drawer-regexp'.
  5920. (goto-char (org-element-property :end drawer))))))))))
  5921. (defun org-flag-drawer (flag &optional element)
  5922. "When FLAG is non-nil, hide the drawer we are at.
  5923. Otherwise make it visible. When optional argument ELEMENT is
  5924. a parsed drawer, as returned by `org-element-at-point', hide or
  5925. show that drawer instead."
  5926. (let ((drawer (or element
  5927. (and (save-excursion
  5928. (beginning-of-line)
  5929. (looking-at-p org-drawer-regexp))
  5930. (org-element-at-point)))))
  5931. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5932. (let ((post (org-element-property :post-affiliated drawer)))
  5933. (org-flag-region
  5934. (save-excursion (goto-char post) (line-end-position))
  5935. (save-excursion (goto-char (org-element-property :end drawer))
  5936. (skip-chars-backward " \t\n")
  5937. (line-end-position))
  5938. flag 'org-hide-drawer)
  5939. ;; When the drawer is hidden away, make sure point lies in
  5940. ;; a visible part of the buffer.
  5941. (when (invisible-p (max (1- (point)) (point-min)))
  5942. (goto-char post))))))
  5943. ;;;; Visibility cycling
  5944. (defvar-local org-cycle-global-status nil)
  5945. (put 'org-cycle-global-status 'org-state t)
  5946. (defvar-local org-cycle-subtree-status nil)
  5947. (put 'org-cycle-subtree-status 'org-state t)
  5948. (defun org-show-all (&optional types)
  5949. "Show all contents in the visible part of the buffer.
  5950. By default, the function expands headings, blocks and drawers.
  5951. When optional argument TYPE is a list of symbols among `blocks',
  5952. `drawers' and `headings', to only expand one specific type."
  5953. (dolist (type (or types '(blocks drawers headings)))
  5954. (org-flag-region (point-min) (point-max) nil
  5955. (pcase type
  5956. (`blocks 'org-hide-block)
  5957. (`drawers 'org-hide-drawer)
  5958. (`headings 'outline)
  5959. (_ (error "Invalid type: %S" type))))))
  5960. ;;;###autoload
  5961. (defun org-cycle (&optional arg)
  5962. "TAB-action and visibility cycling for Org mode.
  5963. This is the command invoked in Org mode by the `TAB' key. Its main
  5964. purpose is outline visibility cycling, but it also invokes other actions
  5965. in special contexts.
  5966. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5967. the entire
  5968. buffer through 3 states (global cycling)
  5969. 1. OVERVIEW: Show only top-level headlines.
  5970. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5971. 3. SHOW ALL: Show everything.
  5972. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5973. switch to the startup visibility,
  5974. determined by the variable `org-startup-folded', and by any VISIBILITY
  5975. properties in the buffer.
  5976. With a `\\[universal-argument] \\[universal-argument] \
  5977. \\[universal-argument]' prefix argument, show the entire buffer, including
  5978. any drawers.
  5979. When inside a table, re-align the table and move to the next field.
  5980. When point is at the beginning of a headline, rotate the subtree started
  5981. by this line through 3 different states (local cycling)
  5982. 1. FOLDED: Only the main headline is shown.
  5983. 2. CHILDREN: The main headline and the direct children are shown.
  5984. From this state, you can move to one of the children
  5985. and zoom in further.
  5986. 3. SUBTREE: Show the entire subtree, including body text.
  5987. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5988. When point is at the beginning of an empty headline and the variable
  5989. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5990. of the headline by demoting and promoting it to likely levels. This
  5991. speeds up creation document structure by pressing `TAB' once or several
  5992. times right after creating a new headline.
  5993. When there is a numeric prefix, go up to a heading with level ARG, do
  5994. a `show-subtree' and return to the previous cursor position. If ARG
  5995. is negative, go up that many levels.
  5996. When point is not at the beginning of a headline, execute the global
  5997. binding for `TAB', which is re-indenting the line. See the option
  5998. `org-cycle-emulate-tab' for details.
  5999. As a special case, if point is at the beginning of the buffer and there is
  6000. no headline in line 1, this function will act as if called with prefix arg
  6001. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  6002. prefix arg, but only
  6003. if the variable `org-cycle-global-at-bob' is t."
  6004. (interactive "P")
  6005. (org-load-modules-maybe)
  6006. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  6007. (and org-cycle-level-after-item/entry-creation
  6008. (or (org-cycle-level)
  6009. (org-cycle-item-indentation))))
  6010. (let* ((limit-level
  6011. (or org-cycle-max-level
  6012. (and (boundp 'org-inlinetask-min-level)
  6013. org-inlinetask-min-level
  6014. (1- org-inlinetask-min-level))))
  6015. (nstars (and limit-level
  6016. (if org-odd-levels-only
  6017. (and limit-level (1- (* limit-level 2)))
  6018. limit-level)))
  6019. (org-outline-regexp
  6020. (if (not (derived-mode-p 'org-mode))
  6021. outline-regexp
  6022. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  6023. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  6024. (not (looking-at org-outline-regexp))))
  6025. (org-cycle-hook
  6026. (if bob-special
  6027. (delq 'org-optimize-window-after-visibility-change
  6028. (copy-sequence org-cycle-hook))
  6029. org-cycle-hook))
  6030. (pos (point)))
  6031. (cond
  6032. ((equal arg '(16))
  6033. (setq last-command 'dummy)
  6034. (org-set-startup-visibility)
  6035. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  6036. ((equal arg '(64))
  6037. (org-show-all)
  6038. (org-unlogged-message "Entire buffer visible, including drawers"))
  6039. ((equal arg '(4)) (org-cycle-internal-global))
  6040. ;; Try hiding block at point.
  6041. ((org-hide-block-toggle-maybe))
  6042. ;; Try cdlatex TAB completion
  6043. ((org-try-cdlatex-tab))
  6044. ;; Table: enter it or move to the next field.
  6045. ((org-at-table-p 'any)
  6046. (if (org-at-table.el-p)
  6047. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6048. Use `\\[org-edit-special]' to edit table.el tables"))
  6049. (if arg (org-table-edit-field t)
  6050. (org-table-justify-field-maybe)
  6051. (call-interactively 'org-table-next-field))))
  6052. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  6053. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6054. (bob-special (org-cycle-internal-global))
  6055. ;; Drawers: delegate to `org-flag-drawer'.
  6056. ((save-excursion
  6057. (beginning-of-line 1)
  6058. (looking-at org-drawer-regexp))
  6059. (org-flag-drawer ; toggle block visibility
  6060. (not (get-char-property (match-end 0) 'invisible))))
  6061. ;; Show-subtree, ARG levels up from here.
  6062. ((integerp arg)
  6063. (save-excursion
  6064. (org-back-to-heading)
  6065. (outline-up-heading (if (< arg 0) (- arg)
  6066. (- (funcall outline-level) arg)))
  6067. (org-show-subtree)))
  6068. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6069. ((and (featurep 'org-inlinetask)
  6070. (org-inlinetask-at-task-p)
  6071. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6072. (org-inlinetask-toggle-visibility))
  6073. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6074. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6075. (save-excursion (move-beginning-of-line 1)
  6076. (looking-at org-outline-regexp)))
  6077. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6078. (org-cycle-internal-local))
  6079. ;; From there: TAB emulation and template completion.
  6080. (buffer-read-only (org-back-to-heading))
  6081. ((run-hook-with-args-until-success
  6082. 'org-tab-after-check-for-cycling-hook))
  6083. ((run-hook-with-args-until-success
  6084. 'org-tab-before-tab-emulation-hook))
  6085. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6086. (or (not (bolp))
  6087. (not (looking-at org-outline-regexp))))
  6088. (call-interactively (global-key-binding "\t")))
  6089. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6090. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6091. (or (and (eq org-cycle-emulate-tab 'white)
  6092. (= (match-end 0) (point-at-eol)))
  6093. (and (eq org-cycle-emulate-tab 'whitestart)
  6094. (>= (match-end 0) pos))))
  6095. t
  6096. (eq org-cycle-emulate-tab t))
  6097. (call-interactively (global-key-binding "\t")))
  6098. (t (save-excursion
  6099. (org-back-to-heading)
  6100. (org-cycle)))))))
  6101. (defun org-cycle-internal-global ()
  6102. "Do the global cycling action."
  6103. ;; Hack to avoid display of messages for .org attachments in Gnus
  6104. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6105. (cond
  6106. ((and (eq last-command this-command)
  6107. (eq org-cycle-global-status 'overview))
  6108. ;; We just created the overview - now do table of contents
  6109. ;; This can be slow in very large buffers, so indicate action
  6110. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6111. (unless ga (org-unlogged-message "CONTENTS..."))
  6112. (org-content)
  6113. (unless ga (org-unlogged-message "CONTENTS...done"))
  6114. (setq org-cycle-global-status 'contents)
  6115. (run-hook-with-args 'org-cycle-hook 'contents))
  6116. ((and (eq last-command this-command)
  6117. (eq org-cycle-global-status 'contents))
  6118. ;; We just showed the table of contents - now show everything
  6119. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6120. (org-show-all '(headings blocks))
  6121. (unless ga (org-unlogged-message "SHOW ALL"))
  6122. (setq org-cycle-global-status 'all)
  6123. (run-hook-with-args 'org-cycle-hook 'all))
  6124. (t
  6125. ;; Default action: go to overview
  6126. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6127. (org-overview)
  6128. (unless ga (org-unlogged-message "OVERVIEW"))
  6129. (setq org-cycle-global-status 'overview)
  6130. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6131. (defvar org-called-with-limited-levels nil
  6132. "Non-nil when `org-with-limited-levels' is currently active.")
  6133. (defun org-cycle-internal-local ()
  6134. "Do the local cycling action."
  6135. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6136. ;; First, determine end of headline (EOH), end of subtree or item
  6137. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6138. (save-excursion
  6139. (if (org-at-item-p)
  6140. (progn
  6141. (beginning-of-line)
  6142. (setq struct (org-list-struct))
  6143. (setq eoh (point-at-eol))
  6144. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6145. (setq has-children (org-list-has-child-p (point) struct)))
  6146. (org-back-to-heading)
  6147. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6148. (setq eos (save-excursion (org-end-of-subtree t t)
  6149. (when (bolp) (backward-char)) (point)))
  6150. (setq has-children
  6151. (or (save-excursion
  6152. (let ((level (funcall outline-level)))
  6153. (outline-next-heading)
  6154. (and (org-at-heading-p t)
  6155. (> (funcall outline-level) level))))
  6156. (save-excursion
  6157. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6158. ;; Determine end invisible part of buffer (EOL)
  6159. (beginning-of-line 2)
  6160. (while (and (not (eobp)) ;This is like `next-line'.
  6161. (get-char-property (1- (point)) 'invisible))
  6162. (goto-char (next-single-char-property-change (point) 'invisible))
  6163. (and (eolp) (beginning-of-line 2)))
  6164. (setq eol (point)))
  6165. ;; Find out what to do next and set `this-command'
  6166. (cond
  6167. ((= eos eoh)
  6168. ;; Nothing is hidden behind this heading
  6169. (unless (org-before-first-heading-p)
  6170. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6171. (org-unlogged-message "EMPTY ENTRY")
  6172. (setq org-cycle-subtree-status nil)
  6173. (save-excursion
  6174. (goto-char eos)
  6175. (outline-next-heading)
  6176. (when (org-invisible-p) (org-flag-heading nil))))
  6177. ((and (or (>= eol eos)
  6178. (not (string-match "\\S-" (buffer-substring eol eos))))
  6179. (or has-children
  6180. (not (setq children-skipped
  6181. org-cycle-skip-children-state-if-no-children))))
  6182. ;; Entire subtree is hidden in one line: children view
  6183. (unless (org-before-first-heading-p)
  6184. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6185. (if (org-at-item-p)
  6186. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6187. (org-show-entry)
  6188. (org-with-limited-levels (org-show-children))
  6189. (org-show-set-visibility 'canonical)
  6190. ;; Fold every list in subtree to top-level items.
  6191. (when (eq org-cycle-include-plain-lists 'integrate)
  6192. (save-excursion
  6193. (org-back-to-heading)
  6194. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6195. (beginning-of-line 1)
  6196. (let* ((struct (org-list-struct))
  6197. (prevs (org-list-prevs-alist struct))
  6198. (end (org-list-get-bottom-point struct)))
  6199. (dolist (e (org-list-get-all-items (point) struct prevs))
  6200. (org-list-set-item-visibility e struct 'folded))
  6201. (goto-char (if (< end eos) end eos)))))))
  6202. (org-unlogged-message "CHILDREN")
  6203. (save-excursion
  6204. (goto-char eos)
  6205. (outline-next-heading)
  6206. (when (org-invisible-p) (org-flag-heading nil)))
  6207. (setq org-cycle-subtree-status 'children)
  6208. (unless (org-before-first-heading-p)
  6209. (run-hook-with-args 'org-cycle-hook 'children)))
  6210. ((or children-skipped
  6211. (and (eq last-command this-command)
  6212. (eq org-cycle-subtree-status 'children)))
  6213. ;; We just showed the children, or no children are there,
  6214. ;; now show everything.
  6215. (unless (org-before-first-heading-p)
  6216. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6217. (org-flag-region eoh eos nil 'outline)
  6218. (org-unlogged-message
  6219. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6220. (setq org-cycle-subtree-status 'subtree)
  6221. (unless (org-before-first-heading-p)
  6222. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6223. (t
  6224. ;; Default action: hide the subtree.
  6225. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6226. (org-flag-region eoh eos t 'outline)
  6227. (org-unlogged-message "FOLDED")
  6228. (setq org-cycle-subtree-status 'folded)
  6229. (unless (org-before-first-heading-p)
  6230. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6231. ;;;###autoload
  6232. (defun org-global-cycle (&optional arg)
  6233. "Cycle the global visibility. For details see `org-cycle'.
  6234. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6235. With a numeric prefix, show all headlines up to that level."
  6236. (interactive "P")
  6237. (let ((org-cycle-include-plain-lists
  6238. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6239. (cond
  6240. ((integerp arg)
  6241. (org-show-all '(headings blocks))
  6242. (outline-hide-sublevels arg)
  6243. (setq org-cycle-global-status 'contents))
  6244. ((equal arg '(4))
  6245. (org-set-startup-visibility)
  6246. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6247. (t
  6248. (org-cycle '(4))))))
  6249. (defun org-set-startup-visibility ()
  6250. "Set the visibility required by startup options and properties."
  6251. (cond
  6252. ((eq org-startup-folded t)
  6253. (org-overview))
  6254. ((eq org-startup-folded 'content)
  6255. (org-content))
  6256. ((or (eq org-startup-folded 'showeverything)
  6257. (eq org-startup-folded nil))
  6258. (org-show-all)))
  6259. (unless (eq org-startup-folded 'showeverything)
  6260. (when org-hide-block-startup (org-hide-block-all))
  6261. (org-set-visibility-according-to-property)
  6262. (org-cycle-hide-archived-subtrees 'all)
  6263. (org-cycle-hide-drawers 'all)
  6264. (org-cycle-show-empty-lines t)))
  6265. (defun org-set-visibility-according-to-property ()
  6266. "Switch subtree visibilities according to :VISIBILITY: property."
  6267. (interactive)
  6268. (org-with-wide-buffer
  6269. (goto-char (point-min))
  6270. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6271. (if (not (org-at-property-p)) (outline-next-heading)
  6272. (let ((state (match-string 3)))
  6273. (save-excursion
  6274. (org-back-to-heading t)
  6275. (outline-hide-subtree)
  6276. (org-reveal)
  6277. (cond
  6278. ((equal state "folded")
  6279. (outline-hide-subtree))
  6280. ((equal state "children")
  6281. (org-show-hidden-entry)
  6282. (org-show-children))
  6283. ((equal state "content")
  6284. (save-excursion
  6285. (save-restriction
  6286. (org-narrow-to-subtree)
  6287. (org-content))))
  6288. ((member state '("all" "showall"))
  6289. (outline-show-subtree)))))))))
  6290. (defun org-overview ()
  6291. "Switch to overview mode, showing only top-level headlines.
  6292. This shows all headlines with a level equal or greater than the level
  6293. of the first headline in the buffer. This is important, because if the
  6294. first headline is not level one, then (hide-sublevels 1) gives confusing
  6295. results."
  6296. (interactive)
  6297. (save-excursion
  6298. (let ((level
  6299. (save-excursion
  6300. (goto-char (point-min))
  6301. (when (re-search-forward org-outline-regexp-bol nil t)
  6302. (goto-char (match-beginning 0))
  6303. (funcall outline-level)))))
  6304. (and level (outline-hide-sublevels level)))))
  6305. (defun org-content (&optional arg)
  6306. "Show all headlines in the buffer, like a table of contents.
  6307. With numerical argument N, show content up to level N."
  6308. (interactive "P")
  6309. (org-overview)
  6310. (save-excursion
  6311. ;; Visit all headings and show their offspring
  6312. (and (integerp arg) (org-overview))
  6313. (goto-char (point-max))
  6314. (catch 'exit
  6315. (while (and (progn (condition-case nil
  6316. (outline-previous-visible-heading 1)
  6317. (error (goto-char (point-min))))
  6318. t)
  6319. (looking-at org-outline-regexp))
  6320. (if (integerp arg)
  6321. (org-show-children (1- arg))
  6322. (outline-show-branches))
  6323. (when (bobp) (throw 'exit nil))))))
  6324. (defun org-optimize-window-after-visibility-change (state)
  6325. "Adjust the window after a change in outline visibility.
  6326. This function is the default value of the hook `org-cycle-hook'."
  6327. (when (get-buffer-window (current-buffer))
  6328. (cond
  6329. ((eq state 'content) nil)
  6330. ((eq state 'all) nil)
  6331. ((eq state 'folded) nil)
  6332. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6333. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6334. (defun org-clean-visibility-after-subtree-move ()
  6335. "Fix visibility issues after moving a subtree."
  6336. ;; First, find a reasonable region to look at:
  6337. ;; Start two siblings above, end three below
  6338. (let* ((beg (save-excursion
  6339. (and (org-get-last-sibling)
  6340. (org-get-last-sibling))
  6341. (point)))
  6342. (end (save-excursion
  6343. (and (org-get-next-sibling)
  6344. (org-get-next-sibling)
  6345. (org-get-next-sibling))
  6346. (if (org-at-heading-p)
  6347. (point-at-eol)
  6348. (point))))
  6349. (level (looking-at "\\*+"))
  6350. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6351. (save-excursion
  6352. (save-restriction
  6353. (narrow-to-region beg end)
  6354. (when re
  6355. ;; Properly fold already folded siblings
  6356. (goto-char (point-min))
  6357. (while (re-search-forward re nil t)
  6358. (when (and (not (org-invisible-p))
  6359. (org-invisible-p (line-end-position)))
  6360. (outline-hide-entry))))
  6361. (org-cycle-hide-drawers 'all)
  6362. (org-cycle-show-empty-lines 'overview)))))
  6363. (defun org-cycle-show-empty-lines (state)
  6364. "Show empty lines above all visible headlines.
  6365. The region to be covered depends on STATE when called through
  6366. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6367. entire buffer covered. Note that an empty line is only shown if there
  6368. are at least `org-cycle-separator-lines' empty lines before the headline."
  6369. (when (/= org-cycle-separator-lines 0)
  6370. (save-excursion
  6371. (let* ((n (abs org-cycle-separator-lines))
  6372. (re (cond
  6373. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6374. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6375. (t (let ((ns (number-to-string (- n 2))))
  6376. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6377. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6378. beg end)
  6379. (cond
  6380. ((memq state '(overview contents t))
  6381. (setq beg (point-min) end (point-max)))
  6382. ((memq state '(children folded))
  6383. (setq beg (point)
  6384. end (progn (org-end-of-subtree t t)
  6385. (line-beginning-position 2)))))
  6386. (when beg
  6387. (goto-char beg)
  6388. (while (re-search-forward re end t)
  6389. (unless (get-char-property (match-end 1) 'invisible)
  6390. (let ((e (match-end 1))
  6391. (b (if (>= org-cycle-separator-lines 0)
  6392. (match-beginning 1)
  6393. (save-excursion
  6394. (goto-char (match-beginning 0))
  6395. (skip-chars-backward " \t\n")
  6396. (line-end-position)))))
  6397. (org-flag-region b e nil 'outline))))))))
  6398. ;; Never hide empty lines at the end of the file.
  6399. (save-excursion
  6400. (goto-char (point-max))
  6401. (outline-previous-heading)
  6402. (outline-end-of-heading)
  6403. (when (and (looking-at "[ \t\n]+")
  6404. (= (match-end 0) (point-max)))
  6405. (org-flag-region (point) (match-end 0) nil 'outline))))
  6406. ;;;; Reveal point location
  6407. (defun org-show-context (&optional key)
  6408. "Make sure point and context are visible.
  6409. Optional argument KEY, when non-nil, is a symbol. See
  6410. `org-show-context-detail' for allowed values and how much is to
  6411. be shown."
  6412. (org-show-set-visibility
  6413. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  6414. ((cdr (assq key org-show-context-detail)))
  6415. (t (cdr (assq 'default org-show-context-detail))))))
  6416. (defun org-show-set-visibility (detail)
  6417. "Set visibility around point according to DETAIL.
  6418. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  6419. `tree', `canonical' or t. See `org-show-context-detail' for more
  6420. information."
  6421. ;; Show current heading and possibly its entry, following headline
  6422. ;; or all children.
  6423. (if (and (org-at-heading-p) (not (eq detail 'local)))
  6424. (org-flag-heading nil)
  6425. (org-show-entry)
  6426. ;; If point is hidden within a drawer or a block, make sure to
  6427. ;; expose it.
  6428. (dolist (o (overlays-at (point)))
  6429. (when (memq (overlay-get o 'invisible)
  6430. '(org-hide-block org-hide-drawer outline))
  6431. (delete-overlay o)))
  6432. (unless (org-before-first-heading-p)
  6433. (org-with-limited-levels
  6434. (cl-case detail
  6435. ((tree canonical t) (org-show-children))
  6436. ((nil minimal ancestors))
  6437. (t (save-excursion
  6438. (outline-next-heading)
  6439. (org-flag-heading nil)))))))
  6440. ;; Show all siblings.
  6441. (when (eq detail 'lineage) (org-show-siblings))
  6442. ;; Show ancestors, possibly with their children.
  6443. (when (memq detail '(ancestors lineage tree canonical t))
  6444. (save-excursion
  6445. (while (org-up-heading-safe)
  6446. (org-flag-heading nil)
  6447. (when (memq detail '(canonical t)) (org-show-entry))
  6448. (when (memq detail '(tree canonical t)) (org-show-children))))))
  6449. (defvar org-reveal-start-hook nil
  6450. "Hook run before revealing a location.")
  6451. (defun org-reveal (&optional siblings)
  6452. "Show current entry, hierarchy above it, and the following headline.
  6453. This can be used to show a consistent set of context around
  6454. locations exposed with `org-show-context'.
  6455. With optional argument SIBLINGS, on each level of the hierarchy all
  6456. siblings are shown. This repairs the tree structure to what it would
  6457. look like when opened with hierarchical calls to `org-cycle'.
  6458. With a \\[universal-argument] \\[universal-argument] prefix, \
  6459. go to the parent and show the entire tree."
  6460. (interactive "P")
  6461. (run-hooks 'org-reveal-start-hook)
  6462. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6463. ((equal siblings '(16))
  6464. (save-excursion
  6465. (when (org-up-heading-safe)
  6466. (org-show-subtree)
  6467. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6468. (t (org-show-set-visibility 'lineage))))
  6469. ;;; Indirect buffer display of subtrees
  6470. (defvar org-indirect-dedicated-frame nil
  6471. "This is the frame being used for indirect tree display.")
  6472. (defvar org-last-indirect-buffer nil)
  6473. (defun org-tree-to-indirect-buffer (&optional arg)
  6474. "Create indirect buffer and narrow it to current subtree.
  6475. With a numerical prefix ARG, go up to this level and then take that tree.
  6476. If ARG is negative, go up that many levels.
  6477. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6478. indirect buffer previously made with this command, to avoid proliferation of
  6479. indirect buffers. However, when you call the command with a \
  6480. `\\[universal-argument]' prefix, or
  6481. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6482. so that you can work with several indirect buffers at the same time. If
  6483. `org-indirect-buffer-display' is `dedicated-frame', the \
  6484. `\\[universal-argument]' prefix also
  6485. requests that a new frame be made for the new buffer, so that the dedicated
  6486. frame is not changed."
  6487. (interactive "P")
  6488. (let ((cbuf (current-buffer))
  6489. (cwin (selected-window))
  6490. (pos (point))
  6491. beg end level heading ibuf)
  6492. (save-excursion
  6493. (org-back-to-heading t)
  6494. (when (numberp arg)
  6495. (setq level (org-outline-level))
  6496. (when (< arg 0) (setq arg (+ level arg)))
  6497. (while (> (setq level (org-outline-level)) arg)
  6498. (org-up-heading-safe)))
  6499. (setq beg (point)
  6500. heading (org-get-heading 'no-tags))
  6501. (org-end-of-subtree t t)
  6502. (when (org-at-heading-p) (backward-char 1))
  6503. (setq end (point)))
  6504. (when (and (buffer-live-p org-last-indirect-buffer)
  6505. (not (eq org-indirect-buffer-display 'new-frame))
  6506. (not arg))
  6507. (kill-buffer org-last-indirect-buffer))
  6508. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6509. org-last-indirect-buffer ibuf)
  6510. (cond
  6511. ((or (eq org-indirect-buffer-display 'new-frame)
  6512. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6513. (select-frame (make-frame))
  6514. (delete-other-windows)
  6515. (pop-to-buffer-same-window ibuf)
  6516. (org-set-frame-title heading))
  6517. ((eq org-indirect-buffer-display 'dedicated-frame)
  6518. (raise-frame
  6519. (select-frame (or (and org-indirect-dedicated-frame
  6520. (frame-live-p org-indirect-dedicated-frame)
  6521. org-indirect-dedicated-frame)
  6522. (setq org-indirect-dedicated-frame (make-frame)))))
  6523. (delete-other-windows)
  6524. (pop-to-buffer-same-window ibuf)
  6525. (org-set-frame-title (concat "Indirect: " heading)))
  6526. ((eq org-indirect-buffer-display 'current-window)
  6527. (pop-to-buffer-same-window ibuf))
  6528. ((eq org-indirect-buffer-display 'other-window)
  6529. (pop-to-buffer ibuf))
  6530. (t (error "Invalid value")))
  6531. (narrow-to-region beg end)
  6532. (org-show-all '(headings blocks))
  6533. (goto-char pos)
  6534. (run-hook-with-args 'org-cycle-hook 'all)
  6535. (and (window-live-p cwin) (select-window cwin))))
  6536. (defun org-get-indirect-buffer (&optional buffer heading)
  6537. (setq buffer (or buffer (current-buffer)))
  6538. (let ((n 1) (base (buffer-name buffer)) bname)
  6539. (while (buffer-live-p
  6540. (get-buffer
  6541. (setq bname
  6542. (concat base "-"
  6543. (if heading (concat heading "-" (number-to-string n))
  6544. (number-to-string n))))))
  6545. (setq n (1+ n)))
  6546. (condition-case nil
  6547. (make-indirect-buffer buffer bname 'clone)
  6548. (error (make-indirect-buffer buffer bname)))))
  6549. (defun org-set-frame-title (title)
  6550. "Set the title of the current frame to the string TITLE."
  6551. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6552. ;;;; Structure editing
  6553. ;;; Inserting headlines
  6554. (defun org--line-empty-p (n)
  6555. "Is the Nth next line empty?
  6556. Counts the current line as N = 1 and the previous line as N = 0;
  6557. see `beginning-of-line'."
  6558. (save-excursion
  6559. (and (not (bobp))
  6560. (or (beginning-of-line n) t)
  6561. (save-match-data
  6562. (looking-at "[ \t]*$")))))
  6563. (defun org-previous-line-empty-p ()
  6564. "Is the previous line a blank line?
  6565. When NEXT is non-nil, check the next line instead."
  6566. (org--line-empty-p 0))
  6567. (defun org-next-line-empty-p ()
  6568. "Is the previous line a blank line?
  6569. When NEXT is non-nil, check the next line instead."
  6570. (org--line-empty-p 2))
  6571. (defun org--blank-before-heading-p (&optional parent)
  6572. "Non-nil when an empty line should precede a new heading here.
  6573. When optional argument PARENT is non-nil, consider parent
  6574. headline instead of current one."
  6575. (pcase (assq 'heading org-blank-before-new-entry)
  6576. (`(heading . auto)
  6577. (save-excursion
  6578. (org-with-limited-levels
  6579. (unless (and (org-before-first-heading-p)
  6580. (not (outline-next-heading)))
  6581. (org-back-to-heading t)
  6582. (when parent (org-up-heading-safe))
  6583. (cond ((not (bobp))
  6584. (org-previous-line-empty-p))
  6585. ((outline-next-heading)
  6586. (org-previous-line-empty-p))
  6587. ;; Ignore trailing spaces on last buffer line.
  6588. ((progn (skip-chars-backward " \t") (bolp))
  6589. (org-previous-line-empty-p))
  6590. (t nil))))))
  6591. (`(heading . ,value) value)
  6592. (_ nil)))
  6593. (defun org-insert-heading (&optional arg invisible-ok top)
  6594. "Insert a new heading or an item with the same depth at point.
  6595. If point is at the beginning of a heading, insert a new heading
  6596. or a new headline above the current one. When at the beginning
  6597. of a regular line of text, turn it into a heading.
  6598. If point is in the middle of a line, split it and create a new
  6599. headline with the text in the current line after point (see
  6600. `org-M-RET-may-split-line' on how to modify this behavior). As
  6601. a special case, on a headline, splitting can only happen on the
  6602. title itself. E.g., this excludes breaking stars or tags.
  6603. With a `\\[universal-argument]' prefix, set \
  6604. `org-insert-heading-respect-content' to
  6605. a non-nil value for the duration of the command. This forces the
  6606. insertion of a heading after the current subtree, independently
  6607. on the location of point.
  6608. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6609. insert the heading at the end of the tree
  6610. above the current heading. For example, if point is within a
  6611. 2nd-level heading, then it will insert a 2nd-level heading at
  6612. the end of the 1st-level parent subtree.
  6613. When INVISIBLE-OK is set, stop at invisible headlines when going
  6614. back. This is important for non-interactive uses of the
  6615. command.
  6616. When optional argument TOP is non-nil, insert a level 1 heading,
  6617. unconditionally."
  6618. (interactive "P")
  6619. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6620. (level (org-current-level))
  6621. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6622. (cond
  6623. ((or org-insert-heading-respect-content
  6624. (member arg '((4) (16)))
  6625. (and (not invisible-ok)
  6626. (invisible-p (max (1- (point)) (point-min)))))
  6627. ;; Position point at the location of insertion. Make sure we
  6628. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6629. (org-with-limited-levels
  6630. (if (not level) (outline-next-heading) ;before first headline
  6631. (org-back-to-heading invisible-ok)
  6632. (when (equal arg '(16)) (org-up-heading-safe))
  6633. (org-end-of-subtree)))
  6634. (unless (bolp) (insert "\n"))
  6635. (unless (and blank? (org-previous-line-empty-p))
  6636. (org-N-empty-lines-before-current (if blank? 1 0)))
  6637. (insert stars " ")
  6638. (when (eobp) (save-excursion (insert "\n")))
  6639. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6640. ;; is visible.
  6641. (unless invisible-ok
  6642. (pcase (get-char-property-and-overlay (point) 'invisible)
  6643. (`(outline . ,o)
  6644. (move-overlay o (overlay-start o) (line-end-position 0)))
  6645. (_ nil))))
  6646. ;; At a headline...
  6647. ((org-at-heading-p)
  6648. (cond ((bolp)
  6649. (when blank? (save-excursion (insert "\n")))
  6650. (save-excursion (insert stars " \n"))
  6651. (unless (and blank? (org-previous-line-empty-p))
  6652. (org-N-empty-lines-before-current (if blank? 1 0)))
  6653. (end-of-line))
  6654. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6655. (org-match-line org-complex-heading-regexp)
  6656. (org-pos-in-match-range (point) 4))
  6657. ;; Grab the text that should moved to the new headline.
  6658. ;; Preserve tags.
  6659. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6660. (if (looking-at "[ \t]*$") (replace-match "")
  6661. (org-align-tags))
  6662. (end-of-line)
  6663. (when blank? (insert "\n"))
  6664. (insert "\n" stars " ")
  6665. (when (org-string-nw-p split) (insert split))
  6666. (when (eobp) (save-excursion (insert "\n")))))
  6667. (t
  6668. (end-of-line)
  6669. (when blank? (insert "\n"))
  6670. (insert "\n" stars " ")
  6671. (when (eobp) (save-excursion (insert "\n"))))))
  6672. ;; On regular text, turn line into a headline or split, if
  6673. ;; appropriate.
  6674. ((bolp)
  6675. (insert stars " ")
  6676. (unless (and blank? (org-previous-line-empty-p))
  6677. (org-N-empty-lines-before-current (if blank? 1 0))))
  6678. (t
  6679. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6680. (end-of-line))
  6681. (insert "\n" stars " ")
  6682. (unless (and blank? (org-previous-line-empty-p))
  6683. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6684. (run-hooks 'org-insert-heading-hook))
  6685. (defun org-N-empty-lines-before-current (n)
  6686. "Make the number of empty lines before current exactly N.
  6687. So this will delete or add empty lines."
  6688. (let ((column (current-column)))
  6689. (beginning-of-line)
  6690. (unless (bobp)
  6691. (let ((start (save-excursion
  6692. (skip-chars-backward " \r\t\n")
  6693. (line-end-position))))
  6694. (delete-region start (line-end-position 0))))
  6695. (insert (make-string n ?\n))
  6696. (move-to-column column)))
  6697. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6698. "Return the heading of the current entry, without the stars.
  6699. When NO-TAGS is non-nil, don't include tags.
  6700. When NO-TODO is non-nil, don't include TODO keywords.
  6701. When NO-PRIORITY is non-nil, don't include priority cookie.
  6702. When NO-COMMENT is non-nil, don't include COMMENT string.
  6703. Return nil before first heading."
  6704. (unless (org-before-first-heading-p)
  6705. (save-excursion
  6706. (org-back-to-heading t)
  6707. (let ((case-fold-search nil))
  6708. (looking-at org-complex-heading-regexp)
  6709. (let ((todo (and (not no-todo) (match-string 2)))
  6710. (priority (and (not no-priority) (match-string 3)))
  6711. (headline (pcase (match-string 4)
  6712. (`nil "")
  6713. ((and (guard no-comment) h)
  6714. (replace-regexp-in-string
  6715. (eval-when-compile
  6716. (format "\\`%s[ \t]+" org-comment-string))
  6717. "" h))
  6718. (h h)))
  6719. (tags (and (not no-tags) (match-string 5))))
  6720. (mapconcat #'identity
  6721. (delq nil (list todo priority headline tags))
  6722. " "))))))
  6723. (defun org-heading-components ()
  6724. "Return the components of the current heading.
  6725. This is a list with the following elements:
  6726. - the level as an integer
  6727. - the reduced level, different if `org-odd-levels-only' is set.
  6728. - the TODO keyword, or nil
  6729. - the priority character, like ?A, or nil if no priority is given
  6730. - the headline text itself, or the tags string if no headline text
  6731. - the tags string, or nil."
  6732. (save-excursion
  6733. (org-back-to-heading t)
  6734. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6735. (list (length (match-string 1))
  6736. (org-reduced-level (length (match-string 1)))
  6737. (match-string-no-properties 2)
  6738. (and (match-end 3) (aref (match-string 3) 2))
  6739. (match-string-no-properties 4)
  6740. (match-string-no-properties 5)))))
  6741. (defun org-get-entry ()
  6742. "Get the entry text, after heading, entire subtree."
  6743. (save-excursion
  6744. (org-back-to-heading t)
  6745. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6746. (defun org-edit-headline (&optional heading)
  6747. "Edit the current headline.
  6748. Set it to HEADING when provided."
  6749. (interactive)
  6750. (org-with-wide-buffer
  6751. (org-back-to-heading t)
  6752. (let ((case-fold-search nil))
  6753. (when (looking-at org-complex-heading-regexp)
  6754. (let* ((old (match-string-no-properties 4))
  6755. (new (save-match-data
  6756. (org-trim (or heading (read-string "Edit: " old))))))
  6757. (unless (equal old new)
  6758. (if old (replace-match new t t nil 4)
  6759. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6760. (insert " " new))
  6761. (org-align-tags)
  6762. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6763. (defun org-insert-heading-after-current ()
  6764. "Insert a new heading with same level as current, after current subtree."
  6765. (interactive)
  6766. (org-back-to-heading)
  6767. (org-insert-heading)
  6768. (org-move-subtree-down)
  6769. (end-of-line 1))
  6770. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6771. "Insert heading with `org-insert-heading-respect-content' set to t."
  6772. (interactive)
  6773. (org-insert-heading '(4) invisible-ok))
  6774. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6775. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6776. (interactive)
  6777. (org-insert-todo-heading force-state '(4)))
  6778. (defun org-insert-todo-heading (arg &optional force-heading)
  6779. "Insert a new heading with the same level and TODO state as current heading.
  6780. If the heading has no TODO state, or if the state is DONE, use
  6781. the first state (TODO by default). Also with one prefix arg,
  6782. force first state. With two prefix args, force inserting at the
  6783. end of the parent subtree.
  6784. When called at a plain list item, insert a new item with an
  6785. unchecked check box."
  6786. (interactive "P")
  6787. (when (or force-heading (not (org-insert-item 'checkbox)))
  6788. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6789. force-heading))
  6790. (save-excursion
  6791. (org-forward-heading-same-level -1)
  6792. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6793. (let* ((new-mark-x
  6794. (if (or (equal arg '(4))
  6795. (not (match-beginning 2))
  6796. (member (match-string 2) org-done-keywords))
  6797. (car org-todo-keywords-1)
  6798. (match-string 2)))
  6799. (new-mark
  6800. (or
  6801. (run-hook-with-args-until-success
  6802. 'org-todo-get-default-hook new-mark-x nil)
  6803. new-mark-x)))
  6804. (beginning-of-line 1)
  6805. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6806. (if org-treat-insert-todo-heading-as-state-change
  6807. (org-todo new-mark)
  6808. (insert new-mark " "))))
  6809. (when org-provide-todo-statistics
  6810. (org-update-parent-todo-statistics))))
  6811. (defun org-insert-subheading (arg)
  6812. "Insert a new subheading and demote it.
  6813. Works for outline headings and for plain lists alike."
  6814. (interactive "P")
  6815. (org-insert-heading arg)
  6816. (cond
  6817. ((org-at-heading-p) (org-do-demote))
  6818. ((org-at-item-p) (org-indent-item))))
  6819. (defun org-insert-todo-subheading (arg)
  6820. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6821. Works for outline headings and for plain lists alike."
  6822. (interactive "P")
  6823. (org-insert-todo-heading arg)
  6824. (cond
  6825. ((org-at-heading-p) (org-do-demote))
  6826. ((org-at-item-p) (org-indent-item))))
  6827. ;;; Promotion and Demotion
  6828. (defvar org-after-demote-entry-hook nil
  6829. "Hook run after an entry has been demoted.
  6830. The cursor will be at the beginning of the entry.
  6831. When a subtree is being demoted, the hook will be called for each node.")
  6832. (defvar org-after-promote-entry-hook nil
  6833. "Hook run after an entry has been promoted.
  6834. The cursor will be at the beginning of the entry.
  6835. When a subtree is being promoted, the hook will be called for each node.")
  6836. (defun org-promote-subtree ()
  6837. "Promote the entire subtree.
  6838. See also `org-promote'."
  6839. (interactive)
  6840. (save-excursion
  6841. (org-with-limited-levels (org-map-tree 'org-promote)))
  6842. (org-fix-position-after-promote))
  6843. (defun org-demote-subtree ()
  6844. "Demote the entire subtree.
  6845. See `org-demote' and `org-promote'."
  6846. (interactive)
  6847. (save-excursion
  6848. (org-with-limited-levels (org-map-tree 'org-demote)))
  6849. (org-fix-position-after-promote))
  6850. (defun org-do-promote ()
  6851. "Promote the current heading higher up the tree.
  6852. If the region is active in `transient-mark-mode', promote all
  6853. headings in the region."
  6854. (interactive)
  6855. (save-excursion
  6856. (if (org-region-active-p)
  6857. (org-map-region 'org-promote (region-beginning) (region-end))
  6858. (org-promote)))
  6859. (org-fix-position-after-promote))
  6860. (defun org-do-demote ()
  6861. "Demote the current heading lower down the tree.
  6862. If the region is active in `transient-mark-mode', demote all
  6863. headings in the region."
  6864. (interactive)
  6865. (save-excursion
  6866. (if (org-region-active-p)
  6867. (org-map-region 'org-demote (region-beginning) (region-end))
  6868. (org-demote)))
  6869. (org-fix-position-after-promote))
  6870. (defun org-fix-position-after-promote ()
  6871. "Fix cursor position and indentation after demoting/promoting."
  6872. (let ((pos (point)))
  6873. (when (save-excursion
  6874. (beginning-of-line)
  6875. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6876. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6877. (cond ((eobp) (insert " "))
  6878. ((eolp) (insert " "))
  6879. ((equal (char-after) ?\s) (forward-char 1))))))
  6880. (defun org-current-level ()
  6881. "Return the level of the current entry, or nil if before the first headline.
  6882. The level is the number of stars at the beginning of the
  6883. headline. Use `org-reduced-level' to remove the effect of
  6884. `org-odd-levels'. Unlike to `org-outline-level', this function
  6885. ignores inlinetasks."
  6886. (let ((level (org-with-limited-levels (org-outline-level))))
  6887. (and (> level 0) level)))
  6888. (defun org-get-previous-line-level ()
  6889. "Return the outline depth of the last headline before the current line.
  6890. Returns 0 for the first headline in the buffer, and nil if before the
  6891. first headline."
  6892. (and (org-current-level)
  6893. (or (and (/= (line-beginning-position) (point-min))
  6894. (save-excursion (beginning-of-line 0) (org-current-level)))
  6895. 0)))
  6896. (defun org-reduced-level (l)
  6897. "Compute the effective level of a heading.
  6898. This takes into account the setting of `org-odd-levels-only'."
  6899. (cond
  6900. ((zerop l) 0)
  6901. (org-odd-levels-only (1+ (floor (/ l 2))))
  6902. (t l)))
  6903. (defun org-level-increment ()
  6904. "Return the number of stars that will be added or removed at a
  6905. time to headlines when structure editing, based on the value of
  6906. `org-odd-levels-only'."
  6907. (if org-odd-levels-only 2 1))
  6908. (defun org-get-valid-level (level &optional change)
  6909. "Rectify a level change under the influence of `org-odd-levels-only'.
  6910. LEVEL is a current level, CHANGE is by how much the level should
  6911. be modified. Even if CHANGE is nil, LEVEL may be returned
  6912. modified because even level numbers will become the next higher
  6913. odd number. Returns values greater than 0."
  6914. (if org-odd-levels-only
  6915. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6916. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6917. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6918. (max 1 (+ level (or change 0)))))
  6919. (defun org-promote ()
  6920. "Promote the current heading higher up the tree."
  6921. (org-with-wide-buffer
  6922. (org-back-to-heading t)
  6923. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6924. after-change-functions))
  6925. (level (save-match-data (funcall outline-level)))
  6926. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6927. (diff (abs (- level (length up-head) -1))))
  6928. (cond
  6929. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6930. (replace-match "# " nil t))
  6931. ((= level 1)
  6932. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6933. (t (replace-match up-head nil t)))
  6934. (unless (= level 1)
  6935. (when org-auto-align-tags (org-align-tags))
  6936. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6937. (run-hooks 'org-after-promote-entry-hook))))
  6938. (defun org-demote ()
  6939. "Demote the current heading lower down the tree."
  6940. (org-with-wide-buffer
  6941. (org-back-to-heading t)
  6942. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6943. after-change-functions))
  6944. (level (save-match-data (funcall outline-level)))
  6945. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6946. (diff (abs (- level (length down-head) -1))))
  6947. (replace-match down-head nil t)
  6948. (when org-auto-align-tags (org-align-tags))
  6949. (when org-adapt-indentation (org-fixup-indentation diff))
  6950. (run-hooks 'org-after-demote-entry-hook))))
  6951. (defun org-cycle-level ()
  6952. "Cycle the level of an empty headline through possible states.
  6953. This goes first to child, then to parent, level, then up the hierarchy.
  6954. After top level, it switches back to sibling level."
  6955. (interactive)
  6956. (let ((org-adapt-indentation nil))
  6957. (when (org-point-at-end-of-empty-headline)
  6958. (setq this-command 'org-cycle-level) ; Only needed for caching
  6959. (let ((cur-level (org-current-level))
  6960. (prev-level (org-get-previous-line-level)))
  6961. (cond
  6962. ;; If first headline in file, promote to top-level.
  6963. ((= prev-level 0)
  6964. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6965. do (org-do-promote)))
  6966. ;; If same level as prev, demote one.
  6967. ((= prev-level cur-level)
  6968. (org-do-demote))
  6969. ;; If parent is top-level, promote to top level if not already.
  6970. ((= prev-level 1)
  6971. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6972. do (org-do-promote)))
  6973. ;; If top-level, return to prev-level.
  6974. ((= cur-level 1)
  6975. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6976. do (org-do-demote)))
  6977. ;; If less than prev-level, promote one.
  6978. ((< cur-level prev-level)
  6979. (org-do-promote))
  6980. ;; If deeper than prev-level, promote until higher than
  6981. ;; prev-level.
  6982. ((> cur-level prev-level)
  6983. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6984. do (org-do-promote))))
  6985. t))))
  6986. (defun org-map-tree (fun)
  6987. "Call FUN for every heading underneath the current one."
  6988. (org-back-to-heading t)
  6989. (let ((level (funcall outline-level)))
  6990. (save-excursion
  6991. (funcall fun)
  6992. (while (and (progn
  6993. (outline-next-heading)
  6994. (> (funcall outline-level) level))
  6995. (not (eobp)))
  6996. (funcall fun)))))
  6997. (defun org-map-region (fun beg end)
  6998. "Call FUN for every heading between BEG and END."
  6999. (let ((org-ignore-region t))
  7000. (save-excursion
  7001. (setq end (copy-marker end))
  7002. (goto-char beg)
  7003. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7004. (< (point) end))
  7005. (funcall fun))
  7006. (while (and (progn
  7007. (outline-next-heading)
  7008. (< (point) end))
  7009. (not (eobp)))
  7010. (funcall fun)))))
  7011. (defun org-fixup-indentation (diff)
  7012. "Change the indentation in the current entry by DIFF.
  7013. DIFF is an integer. Indentation is done according to the
  7014. following rules:
  7015. - Planning information and property drawers are always indented
  7016. according to the new level of the headline;
  7017. - Footnote definitions and their contents are ignored;
  7018. - Inlinetasks' boundaries are not shifted;
  7019. - Empty lines are ignored;
  7020. - Other lines' indentation are shifted by DIFF columns, unless
  7021. it would introduce a structural change in the document, in
  7022. which case no shifting is done at all.
  7023. Assume point is at a heading or an inlinetask beginning."
  7024. (org-with-wide-buffer
  7025. (narrow-to-region (line-beginning-position)
  7026. (save-excursion
  7027. (if (org-with-limited-levels (org-at-heading-p))
  7028. (org-with-limited-levels (outline-next-heading))
  7029. (org-inlinetask-goto-end))
  7030. (point)))
  7031. (forward-line)
  7032. ;; Indent properly planning info and property drawer.
  7033. (when (looking-at-p org-planning-line-re)
  7034. (org-indent-line)
  7035. (forward-line))
  7036. (when (looking-at org-property-drawer-re)
  7037. (goto-char (match-end 0))
  7038. (forward-line)
  7039. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7040. (catch 'no-shift
  7041. (when (zerop diff) (throw 'no-shift nil))
  7042. ;; If DIFF is negative, first check if a shift is possible at all
  7043. ;; (e.g., it doesn't break structure). This can only happen if
  7044. ;; some contents are not properly indented.
  7045. (let ((case-fold-search t))
  7046. (when (< diff 0)
  7047. (let ((diff (- diff))
  7048. (forbidden-re (concat org-outline-regexp
  7049. "\\|"
  7050. (substring org-footnote-definition-re 1))))
  7051. (save-excursion
  7052. (while (not (eobp))
  7053. (cond
  7054. ((looking-at-p "[ \t]*$") (forward-line))
  7055. ((and (looking-at-p org-footnote-definition-re)
  7056. (let ((e (org-element-at-point)))
  7057. (and (eq (org-element-type e) 'footnote-definition)
  7058. (goto-char (org-element-property :end e))))))
  7059. ((looking-at-p org-outline-regexp) (forward-line))
  7060. ;; Give up if shifting would move before column 0 or
  7061. ;; if it would introduce a headline or a footnote
  7062. ;; definition.
  7063. (t
  7064. (skip-chars-forward " \t")
  7065. (let ((ind (current-column)))
  7066. (when (or (< ind diff)
  7067. (and (= ind diff) (looking-at-p forbidden-re)))
  7068. (throw 'no-shift nil)))
  7069. ;; Ignore contents of example blocks and source
  7070. ;; blocks if their indentation is meant to be
  7071. ;; preserved. Jump to block's closing line.
  7072. (beginning-of-line)
  7073. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7074. (let ((e (org-element-at-point)))
  7075. (and (memq (org-element-type e)
  7076. '(example-block src-block))
  7077. (or org-src-preserve-indentation
  7078. (org-element-property :preserve-indent e))
  7079. (goto-char (org-element-property :end e))
  7080. (progn (skip-chars-backward " \r\t\n")
  7081. (beginning-of-line)
  7082. t))))
  7083. (forward-line))))))))
  7084. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7085. ;; by DIFF. Also skip contents of source or example blocks
  7086. ;; when indentation is meant to be preserved.
  7087. (while (not (eobp))
  7088. (cond
  7089. ((and (looking-at-p org-footnote-definition-re)
  7090. (let ((e (org-element-at-point)))
  7091. (and (eq (org-element-type e) 'footnote-definition)
  7092. (goto-char (org-element-property :end e))))))
  7093. ((looking-at-p org-outline-regexp) (forward-line))
  7094. ((looking-at-p "[ \t]*$") (forward-line))
  7095. (t
  7096. (indent-line-to (+ (current-indentation) diff))
  7097. (beginning-of-line)
  7098. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7099. (let ((e (org-element-at-point)))
  7100. (and (memq (org-element-type e)
  7101. '(example-block src-block))
  7102. (or org-src-preserve-indentation
  7103. (org-element-property :preserve-indent e))
  7104. (goto-char (org-element-property :end e))
  7105. (progn (skip-chars-backward " \r\t\n")
  7106. (beginning-of-line)
  7107. t))))
  7108. (forward-line)))))))))
  7109. (defun org-convert-to-odd-levels ()
  7110. "Convert an Org file with all levels allowed to one with odd levels.
  7111. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7112. level 5 etc."
  7113. (interactive)
  7114. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7115. (let ((outline-level 'org-outline-level)
  7116. (org-odd-levels-only nil) n)
  7117. (save-excursion
  7118. (goto-char (point-min))
  7119. (while (re-search-forward "^\\*\\*+ " nil t)
  7120. (setq n (- (length (match-string 0)) 2))
  7121. (while (>= (setq n (1- n)) 0)
  7122. (org-demote))
  7123. (end-of-line 1))))))
  7124. (defun org-convert-to-oddeven-levels ()
  7125. "Convert an Org file with only odd levels to one with odd/even levels.
  7126. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7127. file contains a section with an even level, conversion would
  7128. destroy the structure of the file. An error is signaled in this
  7129. case."
  7130. (interactive)
  7131. (goto-char (point-min))
  7132. ;; First check if there are no even levels
  7133. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7134. (org-show-set-visibility 'canonical)
  7135. (error "Not all levels are odd in this file. Conversion not possible"))
  7136. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7137. (let ((outline-regexp org-outline-regexp)
  7138. (outline-level 'org-outline-level)
  7139. (org-odd-levels-only nil) n)
  7140. (save-excursion
  7141. (goto-char (point-min))
  7142. (while (re-search-forward "^\\*\\*+ " nil t)
  7143. (setq n (/ (1- (length (match-string 0))) 2))
  7144. (while (>= (setq n (1- n)) 0)
  7145. (org-promote))
  7146. (end-of-line 1))))))
  7147. (defun org-tr-level (n)
  7148. "Make N odd if required."
  7149. (if org-odd-levels-only (1+ (/ n 2)) n))
  7150. ;;; Vertical tree motion, cutting and pasting of subtrees
  7151. (defun org-move-subtree-up (&optional arg)
  7152. "Move the current subtree up past ARG headlines of the same level."
  7153. (interactive "p")
  7154. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7155. (defun org-move-subtree-down (&optional arg)
  7156. "Move the current subtree down past ARG headlines of the same level."
  7157. (interactive "p")
  7158. (setq arg (prefix-numeric-value arg))
  7159. (org-preserve-local-variables
  7160. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7161. 'org-get-last-sibling))
  7162. (ins-point (make-marker))
  7163. (cnt (abs arg))
  7164. (col (current-column))
  7165. beg end txt folded)
  7166. ;; Select the tree
  7167. (org-back-to-heading)
  7168. (setq beg (point))
  7169. (save-match-data
  7170. (save-excursion (outline-end-of-heading)
  7171. (setq folded (org-invisible-p)))
  7172. (progn (org-end-of-subtree nil t)
  7173. (unless (eobp) (backward-char))))
  7174. (outline-next-heading)
  7175. (setq end (point))
  7176. (goto-char beg)
  7177. ;; Find insertion point, with error handling
  7178. (while (> cnt 0)
  7179. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  7180. (goto-char beg)
  7181. (user-error "Cannot move past superior level or buffer limit"))
  7182. (setq cnt (1- cnt)))
  7183. (when (> arg 0)
  7184. ;; Moving forward - still need to move over subtree
  7185. (org-end-of-subtree t t)
  7186. (save-excursion
  7187. (org-back-over-empty-lines)
  7188. (or (bolp) (newline))))
  7189. (move-marker ins-point (point))
  7190. (setq txt (buffer-substring beg end))
  7191. (org-save-markers-in-region beg end)
  7192. (delete-region beg end)
  7193. (org-remove-empty-overlays-at beg)
  7194. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  7195. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  7196. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7197. (let ((bbb (point)))
  7198. (insert-before-markers txt)
  7199. (org-reinstall-markers-in-region bbb)
  7200. (move-marker ins-point bbb))
  7201. (or (bolp) (insert "\n"))
  7202. (goto-char ins-point)
  7203. (org-skip-whitespace)
  7204. (move-marker ins-point nil)
  7205. (if folded
  7206. (outline-hide-subtree)
  7207. (org-show-entry)
  7208. (org-show-children))
  7209. (org-clean-visibility-after-subtree-move)
  7210. ;; move back to the initial column we were at
  7211. (move-to-column col))))
  7212. (defvar org-subtree-clip ""
  7213. "Clipboard for cut and paste of subtrees.
  7214. This is actually only a copy of the kill, because we use the normal kill
  7215. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7216. (defvar org-subtree-clip-folded nil
  7217. "Was the last copied subtree folded?
  7218. This is used to fold the tree back after pasting.")
  7219. (defun org-cut-subtree (&optional n)
  7220. "Cut the current subtree into the clipboard.
  7221. With prefix arg N, cut this many sequential subtrees.
  7222. This is a short-hand for marking the subtree and then cutting it."
  7223. (interactive "p")
  7224. (org-copy-subtree n 'cut))
  7225. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7226. "Copy the current subtree into the clipboard.
  7227. With prefix arg N, copy this many sequential subtrees.
  7228. This is a short-hand for marking the subtree and then copying it.
  7229. If CUT is non-nil, actually cut the subtree.
  7230. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7231. of some markers in the region, even if CUT is non-nil. This is
  7232. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7233. (interactive "p")
  7234. (org-preserve-local-variables
  7235. (let (beg end folded (beg0 (point)))
  7236. (if (called-interactively-p 'any)
  7237. (org-back-to-heading nil) ; take what looks like a subtree
  7238. (org-back-to-heading t)) ; take what is really there
  7239. (setq beg (point))
  7240. (skip-chars-forward " \t\r\n")
  7241. (save-match-data
  7242. (if nosubtrees
  7243. (outline-next-heading)
  7244. (save-excursion (outline-end-of-heading)
  7245. (setq folded (org-invisible-p)))
  7246. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7247. (org-end-of-subtree t t)))
  7248. ;; Include the end of an inlinetask
  7249. (when (and (featurep 'org-inlinetask)
  7250. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7251. "END[ \t]*$")))
  7252. (end-of-line))
  7253. (setq end (point))
  7254. (goto-char beg0)
  7255. (when (> end beg)
  7256. (setq org-subtree-clip-folded folded)
  7257. (when (or cut force-store-markers)
  7258. (org-save-markers-in-region beg end))
  7259. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7260. (setq org-subtree-clip (current-kill 0))
  7261. (message "%s: Subtree(s) with %d characters"
  7262. (if cut "Cut" "Copied")
  7263. (length org-subtree-clip))))))
  7264. (defun org-paste-subtree (&optional level tree for-yank remove)
  7265. "Paste the clipboard as a subtree, with modification of headline level.
  7266. The entire subtree is promoted or demoted in order to match a new headline
  7267. level.
  7268. If the cursor is at the beginning of a headline, the same level as
  7269. that headline is used to paste the tree.
  7270. If not, the new level is derived from the *visible* headings
  7271. before and after the insertion point, and taken to be the inferior headline
  7272. level of the two. So if the previous visible heading is level 3 and the
  7273. next is level 4 (or vice versa), level 4 will be used for insertion.
  7274. This makes sure that the subtree remains an independent subtree and does
  7275. not swallow low level entries.
  7276. You can also force a different level, either by using a numeric prefix
  7277. argument, or by inserting the heading marker by hand. For example, if the
  7278. cursor is after \"*****\", then the tree will be shifted to level 5.
  7279. If optional TREE is given, use this text instead of the kill ring.
  7280. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7281. move back over whitespace before inserting, and move point to the end of
  7282. the inserted text when done.
  7283. When REMOVE is non-nil, remove the subtree from the clipboard."
  7284. (interactive "P")
  7285. (setq tree (or tree (and kill-ring (current-kill 0))))
  7286. (unless (org-kill-is-subtree-p tree)
  7287. (user-error
  7288. (substitute-command-keys
  7289. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  7290. (org-with-limited-levels
  7291. (let* ((visp (not (org-invisible-p)))
  7292. (txt tree)
  7293. (old-level (if (string-match org-outline-regexp-bol txt)
  7294. (- (match-end 0) (match-beginning 0) 1)
  7295. -1))
  7296. (force-level
  7297. (cond
  7298. (level (prefix-numeric-value level))
  7299. ;; When point is after the stars in an otherwise empty
  7300. ;; headline, use the number of stars as the forced level.
  7301. ((and (org-match-line "^\\*+[ \t]*$")
  7302. (not (eq ?* (char-after))))
  7303. (org-outline-level))
  7304. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  7305. (previous-level
  7306. (save-excursion
  7307. (org-previous-visible-heading 1)
  7308. (if (org-at-heading-p) (org-outline-level) 1)))
  7309. (next-level
  7310. (save-excursion
  7311. (if (org-at-heading-p) (org-outline-level)
  7312. (org-next-visible-heading 1)
  7313. (if (org-at-heading-p) (org-outline-level) 1))))
  7314. (new-level (or force-level (max previous-level next-level)))
  7315. (shift (if (or (= old-level -1)
  7316. (= new-level -1)
  7317. (= old-level new-level))
  7318. 0
  7319. (- new-level old-level)))
  7320. (delta (if (> shift 0) -1 1))
  7321. (func (if (> shift 0) #'org-demote #'org-promote))
  7322. (org-odd-levels-only nil)
  7323. beg end newend)
  7324. ;; Remove the forced level indicator.
  7325. (when (and force-level (not level))
  7326. (delete-region (line-beginning-position) (point)))
  7327. ;; Paste before the next visible heading or at end of buffer,
  7328. ;; unless point is at the beginning of a headline.
  7329. (unless (and (bolp) (org-at-heading-p))
  7330. (org-next-visible-heading 1)
  7331. (unless (bolp) (insert "\n")))
  7332. (setq beg (point))
  7333. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7334. (insert-before-markers txt)
  7335. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7336. (setq newend (point))
  7337. (org-reinstall-markers-in-region beg)
  7338. (setq end (point))
  7339. (goto-char beg)
  7340. (skip-chars-forward " \t\n\r")
  7341. (setq beg (point))
  7342. (when (and (org-invisible-p) visp)
  7343. (save-excursion (outline-show-heading)))
  7344. ;; Shift if necessary.
  7345. (unless (= shift 0)
  7346. (save-restriction
  7347. (narrow-to-region beg end)
  7348. (while (not (= shift 0))
  7349. (org-map-region func (point-min) (point-max))
  7350. (setq shift (+ delta shift)))
  7351. (goto-char (point-min))
  7352. (setq newend (point-max))))
  7353. (when (or for-yank (called-interactively-p 'interactive))
  7354. (message "Clipboard pasted as level %d subtree" new-level))
  7355. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7356. kill-ring
  7357. (equal org-subtree-clip (current-kill 0))
  7358. org-subtree-clip-folded)
  7359. ;; The tree was folded before it was killed/copied
  7360. (outline-hide-subtree))
  7361. (when for-yank (goto-char newend))
  7362. (when remove (pop kill-ring)))))
  7363. (defun org-kill-is-subtree-p (&optional txt)
  7364. "Check if the current kill is an outline subtree, or a set of trees.
  7365. Returns nil if kill does not start with a headline, or if the first
  7366. headline level is not the largest headline level in the tree.
  7367. So this will actually accept several entries of equal levels as well,
  7368. which is OK for `org-paste-subtree'.
  7369. If optional TXT is given, check this string instead of the current kill."
  7370. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7371. (re (org-get-limited-outline-regexp))
  7372. (^re (concat "^" re))
  7373. (start-level (and kill
  7374. (string-match
  7375. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7376. kill)
  7377. (- (match-end 2) (match-beginning 2) 1)))
  7378. (start (1+ (or (match-beginning 2) -1))))
  7379. (if (not start-level)
  7380. (progn
  7381. nil) ;; does not even start with a heading
  7382. (catch 'exit
  7383. (while (setq start (string-match ^re kill (1+ start)))
  7384. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7385. (throw 'exit nil)))
  7386. t))))
  7387. (defvar org-markers-to-move nil
  7388. "Markers that should be moved with a cut-and-paste operation.
  7389. Those markers are stored together with their positions relative to
  7390. the start of the region.")
  7391. (defun org-save-markers-in-region (beg end)
  7392. "Check markers in region.
  7393. If these markers are between BEG and END, record their position relative
  7394. to BEG, so that after moving the block of text, we can put the markers back
  7395. into place.
  7396. This function gets called just before an entry or tree gets cut from the
  7397. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7398. called immediately, to move the markers with the entries."
  7399. (setq org-markers-to-move nil)
  7400. (when (featurep 'org-clock)
  7401. (org-clock-save-markers-for-cut-and-paste beg end))
  7402. (when (featurep 'org-agenda)
  7403. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7404. (defun org-check-and-save-marker (marker beg end)
  7405. "Check if MARKER is between BEG and END.
  7406. If yes, remember the marker and the distance to BEG."
  7407. (when (and (marker-buffer marker)
  7408. (equal (marker-buffer marker) (current-buffer))
  7409. (>= marker beg) (< marker end))
  7410. (push (cons marker (- marker beg)) org-markers-to-move)))
  7411. (defun org-reinstall-markers-in-region (beg)
  7412. "Move all remembered markers to their position relative to BEG."
  7413. (dolist (x org-markers-to-move)
  7414. (move-marker (car x) (+ beg (cdr x))))
  7415. (setq org-markers-to-move nil))
  7416. (defun org-narrow-to-subtree ()
  7417. "Narrow buffer to the current subtree."
  7418. (interactive)
  7419. (save-excursion
  7420. (save-match-data
  7421. (org-with-limited-levels
  7422. (narrow-to-region
  7423. (progn (org-back-to-heading t) (point))
  7424. (progn (org-end-of-subtree t t)
  7425. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7426. (point)))))))
  7427. (defun org-toggle-narrow-to-subtree ()
  7428. "Narrow to the subtree at point or widen a narrowed buffer."
  7429. (interactive)
  7430. (if (buffer-narrowed-p)
  7431. (widen)
  7432. (org-narrow-to-subtree)))
  7433. (defun org-narrow-to-block ()
  7434. "Narrow buffer to the current block."
  7435. (interactive)
  7436. (let* ((case-fold-search t)
  7437. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7438. "^[ \t]*#\\+end_.*")))
  7439. (if blockp
  7440. (narrow-to-region (car blockp) (cdr blockp))
  7441. (user-error "Not in a block"))))
  7442. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7443. "Clone the task (subtree) at point N times.
  7444. The clones will be inserted as siblings.
  7445. In interactive use, the user will be prompted for the number of
  7446. clones to be produced. If the entry has a timestamp, the user
  7447. will also be prompted for a time shift, which may be a repeater
  7448. as used in time stamps, for example `+3d'. To disable this,
  7449. you can call the function with a universal prefix argument.
  7450. When a valid repeater is given and the entry contains any time
  7451. stamps, the clones will become a sequence in time, with time
  7452. stamps in the subtree shifted for each clone produced. If SHIFT
  7453. is nil or the empty string, time stamps will be left alone. The
  7454. ID property of the original subtree is removed.
  7455. In each clone, all the CLOCK entries will be removed. This
  7456. prevents Org from considering that the clocked times overlap.
  7457. If the original subtree did contain time stamps with a repeater,
  7458. the following will happen:
  7459. - the repeater will be removed in each clone
  7460. - an additional clone will be produced, with the current, unshifted
  7461. date(s) in the entry.
  7462. - the original entry will be placed *after* all the clones, with
  7463. repeater intact.
  7464. - the start days in the repeater in the original entry will be shifted
  7465. to past the last clone.
  7466. In this way you can spell out a number of instances of a repeating task,
  7467. and still retain the repeater to cover future instances of the task.
  7468. As described above, N+1 clones are produced when the original
  7469. subtree has a repeater. Setting N to 0, then, can be used to
  7470. remove the repeater from a subtree and create a shifted clone
  7471. with the original repeater."
  7472. (interactive "nNumber of clones to produce: ")
  7473. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7474. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7475. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7476. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7477. (shift
  7478. (or shift
  7479. (if (and (not (equal current-prefix-arg '(4)))
  7480. (save-excursion
  7481. (goto-char beg)
  7482. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7483. (read-from-minibuffer
  7484. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7485. ""))) ;No time shift
  7486. (doshift
  7487. (and (org-string-nw-p shift)
  7488. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7489. shift)
  7490. (user-error "Invalid shift specification %s" shift)))))
  7491. (goto-char end-of-tree)
  7492. (unless (bolp) (insert "\n"))
  7493. (let* ((end (point))
  7494. (template (buffer-substring beg end))
  7495. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7496. (shift-what (pcase (and doshift (match-string 2 shift))
  7497. (`nil nil)
  7498. ("d" 'day)
  7499. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7500. ("m" 'month)
  7501. ("y" 'year)
  7502. (_ (error "Unsupported time unit"))))
  7503. (nmin 1)
  7504. (nmax n)
  7505. (n-no-remove -1)
  7506. (idprop (org-entry-get nil "ID")))
  7507. (when (and doshift
  7508. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7509. template))
  7510. (delete-region beg end)
  7511. (setq end beg)
  7512. (setq nmin 0)
  7513. (setq nmax (1+ nmax))
  7514. (setq n-no-remove nmax))
  7515. (goto-char end)
  7516. (cl-loop for n from nmin to nmax do
  7517. (insert
  7518. ;; Prepare clone.
  7519. (with-temp-buffer
  7520. (insert template)
  7521. (org-mode)
  7522. (goto-char (point-min))
  7523. (org-show-subtree)
  7524. (and idprop (if org-clone-delete-id
  7525. (org-entry-delete nil "ID")
  7526. (org-id-get-create t)))
  7527. (unless (= n 0)
  7528. (while (re-search-forward org-clock-line-re nil t)
  7529. (delete-region (line-beginning-position)
  7530. (line-beginning-position 2)))
  7531. (goto-char (point-min))
  7532. (while (re-search-forward org-drawer-regexp nil t)
  7533. (org-remove-empty-drawer-at (point))))
  7534. (goto-char (point-min))
  7535. (when doshift
  7536. (while (re-search-forward org-ts-regexp-both nil t)
  7537. (org-timestamp-change (* n shift-n) shift-what))
  7538. (unless (= n n-no-remove)
  7539. (goto-char (point-min))
  7540. (while (re-search-forward org-ts-regexp nil t)
  7541. (save-excursion
  7542. (goto-char (match-beginning 0))
  7543. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7544. (delete-region (match-beginning 1) (match-end 1)))))))
  7545. (buffer-string)))))
  7546. (goto-char beg)))
  7547. ;;; Outline Sorting
  7548. (defun org-sort (&optional with-case)
  7549. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7550. Optional argument WITH-CASE means sort case-sensitively."
  7551. (interactive "P")
  7552. (org-call-with-arg
  7553. (cond ((org-at-table-p) #'org-table-sort-lines)
  7554. ((org-at-item-p) #'org-sort-list)
  7555. (t #'org-sort-entries))
  7556. with-case))
  7557. (defun org-sort-remove-invisible (s)
  7558. "Remove invisible part of links and emphasis markers from string S."
  7559. (remove-text-properties 0 (length s) org-rm-props s)
  7560. (replace-regexp-in-string
  7561. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7562. (replace-regexp-in-string
  7563. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7564. (org-link-display-format s)
  7565. t t) t t))
  7566. (defvar org-priority-regexp) ; defined later in the file
  7567. (defvar org-after-sorting-entries-or-items-hook nil
  7568. "Hook that is run after a bunch of entries or items have been sorted.
  7569. When children are sorted, the cursor is in the parent line when this
  7570. hook gets called. When a region or a plain list is sorted, the cursor
  7571. will be in the first entry of the sorted region/list.")
  7572. (defun org-sort-entries
  7573. (&optional with-case sorting-type getkey-func compare-func property
  7574. interactive?)
  7575. "Sort entries on a certain level of an outline tree.
  7576. If there is an active region, the entries in the region are sorted.
  7577. Else, if the cursor is before the first entry, sort the top-level items.
  7578. Else, the children of the entry at point are sorted.
  7579. Sorting can be alphabetically, numerically, by date/time as given by
  7580. a time stamp, by a property, by priority order, or by a custom function.
  7581. The command prompts for the sorting type unless it has been given to the
  7582. function through the SORTING-TYPE argument, which needs to be a character,
  7583. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7584. the precise meaning of each character:
  7585. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7586. c By creation time, which is assumed to be the first inactive time stamp
  7587. at the beginning of a line.
  7588. d By deadline date/time.
  7589. k By clocking time.
  7590. n Numerically, by converting the beginning of the entry/item to a number.
  7591. o By order of TODO keywords.
  7592. p By priority according to the cookie.
  7593. r By the value of a property.
  7594. s By scheduled date/time.
  7595. t By date/time, either the first active time stamp in the entry, or, if
  7596. none exist, by the first inactive one.
  7597. Capital letters will reverse the sort order.
  7598. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7599. called with point at the beginning of the record. It must return a
  7600. value that is compatible with COMPARE-FUNC, the function used to
  7601. compare entries.
  7602. Comparing entries ignores case by default. However, with an optional argument
  7603. WITH-CASE, the sorting considers case as well.
  7604. Sorting is done against the visible part of the headlines, it ignores hidden
  7605. links.
  7606. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7607. A non-nil value for INTERACTIVE? is used to signal that this
  7608. function is being called interactively."
  7609. (interactive (list current-prefix-arg nil nil nil nil t))
  7610. (let ((case-func (if with-case 'identity 'downcase))
  7611. start beg end stars re re2
  7612. txt what tmp)
  7613. ;; Find beginning and end of region to sort
  7614. (cond
  7615. ((org-region-active-p)
  7616. ;; we will sort the region
  7617. (setq end (region-end)
  7618. what "region")
  7619. (goto-char (region-beginning))
  7620. (unless (org-at-heading-p) (outline-next-heading))
  7621. (setq start (point)))
  7622. ((or (org-at-heading-p)
  7623. (ignore-errors (progn (org-back-to-heading) t)))
  7624. ;; we will sort the children of the current headline
  7625. (org-back-to-heading)
  7626. (setq start (point)
  7627. end (progn (org-end-of-subtree t t)
  7628. (or (bolp) (insert "\n"))
  7629. (when (>= (org-back-over-empty-lines) 1)
  7630. (forward-line 1))
  7631. (point))
  7632. what "children")
  7633. (goto-char start)
  7634. (outline-show-subtree)
  7635. (outline-next-heading))
  7636. (t
  7637. ;; we will sort the top-level entries in this file
  7638. (goto-char (point-min))
  7639. (or (org-at-heading-p) (outline-next-heading))
  7640. (setq start (point))
  7641. (goto-char (point-max))
  7642. (beginning-of-line 1)
  7643. (when (looking-at ".*?\\S-")
  7644. ;; File ends in a non-white line
  7645. (end-of-line 1)
  7646. (insert "\n"))
  7647. (setq end (point-max))
  7648. (setq what "top-level")
  7649. (goto-char start)
  7650. (org-show-all '(headings blocks))))
  7651. (setq beg (point))
  7652. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7653. (looking-at "\\(\\*+\\)")
  7654. (setq stars (match-string 1)
  7655. re (concat "^" (regexp-quote stars) " +")
  7656. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7657. txt (buffer-substring beg end))
  7658. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7659. (when (and (not (equal stars "*")) (string-match re2 txt))
  7660. (user-error "Region to sort contains a level above the first entry"))
  7661. (unless sorting-type
  7662. (message
  7663. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7664. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7665. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7666. what)
  7667. (setq sorting-type (read-char-exclusive)))
  7668. (unless getkey-func
  7669. (and (= (downcase sorting-type) ?f)
  7670. (setq getkey-func
  7671. (or (and interactive?
  7672. (org-read-function
  7673. "Function for extracting keys: "))
  7674. (error "Missing key extractor")))))
  7675. (and (= (downcase sorting-type) ?r)
  7676. (not property)
  7677. (setq property
  7678. (completing-read "Property: "
  7679. (mapcar #'list (org-buffer-property-keys t))
  7680. nil t)))
  7681. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7682. (message "Sorting entries...")
  7683. (save-restriction
  7684. (narrow-to-region start end)
  7685. (let ((restore-clock?
  7686. ;; The clock marker is lost when using `sort-subr'; mark
  7687. ;; the clock with temporary `:org-clock-marker-backup'
  7688. ;; text property.
  7689. (when (and (eq (org-clock-is-active) (current-buffer))
  7690. (<= start (marker-position org-clock-marker))
  7691. (>= end (marker-position org-clock-marker)))
  7692. (with-silent-modifications
  7693. (put-text-property (1- org-clock-marker) org-clock-marker
  7694. :org-clock-marker-backup t))
  7695. t))
  7696. (dcst (downcase sorting-type))
  7697. (case-fold-search nil)
  7698. (now (current-time)))
  7699. (org-preserve-local-variables
  7700. (sort-subr
  7701. (/= dcst sorting-type)
  7702. ;; This function moves to the beginning character of the
  7703. ;; "record" to be sorted.
  7704. (lambda nil
  7705. (if (re-search-forward re nil t)
  7706. (goto-char (match-beginning 0))
  7707. (goto-char (point-max))))
  7708. ;; This function moves to the last character of the "record" being
  7709. ;; sorted.
  7710. (lambda nil
  7711. (save-match-data
  7712. (condition-case nil
  7713. (outline-forward-same-level 1)
  7714. (error
  7715. (goto-char (point-max))))))
  7716. ;; This function returns the value that gets sorted against.
  7717. (lambda ()
  7718. (cond
  7719. ((= dcst ?n)
  7720. (string-to-number
  7721. (org-sort-remove-invisible (org-get-heading t t t t))))
  7722. ((= dcst ?a)
  7723. (funcall case-func
  7724. (org-sort-remove-invisible (org-get-heading t t t t))))
  7725. ((= dcst ?k)
  7726. (or (get-text-property (point) :org-clock-minutes) 0))
  7727. ((= dcst ?t)
  7728. (let ((end (save-excursion (outline-next-heading) (point))))
  7729. (if (or (re-search-forward org-ts-regexp end t)
  7730. (re-search-forward org-ts-regexp-both end t))
  7731. (org-time-string-to-seconds (match-string 0))
  7732. (float-time now))))
  7733. ((= dcst ?c)
  7734. (let ((end (save-excursion (outline-next-heading) (point))))
  7735. (if (re-search-forward
  7736. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7737. end t)
  7738. (org-time-string-to-seconds (match-string 0))
  7739. (float-time now))))
  7740. ((= dcst ?s)
  7741. (let ((end (save-excursion (outline-next-heading) (point))))
  7742. (if (re-search-forward org-scheduled-time-regexp end t)
  7743. (org-time-string-to-seconds (match-string 1))
  7744. (float-time now))))
  7745. ((= dcst ?d)
  7746. (let ((end (save-excursion (outline-next-heading) (point))))
  7747. (if (re-search-forward org-deadline-time-regexp end t)
  7748. (org-time-string-to-seconds (match-string 1))
  7749. (float-time now))))
  7750. ((= dcst ?p)
  7751. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7752. (string-to-char (match-string 2))
  7753. org-default-priority))
  7754. ((= dcst ?r)
  7755. (or (org-entry-get nil property) ""))
  7756. ((= dcst ?o)
  7757. (when (looking-at org-complex-heading-regexp)
  7758. (let* ((m (match-string 2))
  7759. (s (if (member m org-done-keywords) '- '+)))
  7760. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7761. ((= dcst ?f)
  7762. (if getkey-func
  7763. (progn
  7764. (setq tmp (funcall getkey-func))
  7765. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7766. tmp)
  7767. (error "Invalid key function `%s'" getkey-func)))
  7768. (t (error "Invalid sorting type `%c'" sorting-type))))
  7769. nil
  7770. (cond
  7771. ((= dcst ?a) 'org-string-collate-lessp)
  7772. ((= dcst ?f)
  7773. (or compare-func
  7774. (and interactive?
  7775. (org-read-function
  7776. (concat "Function for comparing keys "
  7777. "(empty for default `sort-subr' predicate): ")
  7778. 'allow-empty))))
  7779. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7780. (when restore-clock?
  7781. (move-marker org-clock-marker
  7782. (1+ (next-single-property-change
  7783. start :org-clock-marker-backup)))
  7784. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7785. '(:org-clock-marker-backup t)))))
  7786. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7787. (message "Sorting entries...done")))
  7788. (defun org-contextualize-keys (alist contexts)
  7789. "Return valid elements in ALIST depending on CONTEXTS.
  7790. `org-agenda-custom-commands' or `org-capture-templates' are the
  7791. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7792. or `org-capture-templates-contexts' are the associated contexts
  7793. definitions."
  7794. (let ((contexts
  7795. ;; normalize contexts
  7796. (mapcar
  7797. (lambda(c) (cond ((listp (cadr c))
  7798. (list (car c) (car c) (nth 1 c)))
  7799. ((string= "" (cadr c))
  7800. (list (car c) (car c) (nth 2 c)))
  7801. (t c)))
  7802. contexts))
  7803. (a alist) r s)
  7804. ;; loop over all commands or templates
  7805. (dolist (c a)
  7806. (let (vrules repl)
  7807. (cond
  7808. ((not (assoc (car c) contexts))
  7809. (push c r))
  7810. ((and (assoc (car c) contexts)
  7811. (setq vrules (org-contextualize-validate-key
  7812. (car c) contexts)))
  7813. (mapc (lambda (vr)
  7814. (unless (equal (car vr) (cadr vr))
  7815. (setq repl vr)))
  7816. vrules)
  7817. (if (not repl) (push c r)
  7818. (push (cadr repl) s)
  7819. (push
  7820. (cons (car c)
  7821. (cdr (or (assoc (cadr repl) alist)
  7822. (error "Undefined key `%s' as contextual replacement for `%s'"
  7823. (cadr repl) (car c)))))
  7824. r))))))
  7825. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7826. (delq
  7827. nil
  7828. (delete-dups
  7829. (mapcar (lambda (x)
  7830. (let ((tpl (car x)))
  7831. (unless (delq
  7832. nil
  7833. (mapcar (lambda (y)
  7834. (equal y tpl))
  7835. s))
  7836. x)))
  7837. (reverse r))))))
  7838. (defun org-contextualize-validate-key (key contexts)
  7839. "Check CONTEXTS for agenda or capture KEY."
  7840. (let (res)
  7841. (dolist (r contexts)
  7842. (dolist (rr (car (last r)))
  7843. (when
  7844. (and (equal key (car r))
  7845. (if (functionp rr) (funcall rr)
  7846. (or (and (eq (car rr) 'in-file)
  7847. (buffer-file-name)
  7848. (string-match (cdr rr) (buffer-file-name)))
  7849. (and (eq (car rr) 'in-mode)
  7850. (string-match (cdr rr) (symbol-name major-mode)))
  7851. (and (eq (car rr) 'in-buffer)
  7852. (string-match (cdr rr) (buffer-name)))
  7853. (when (and (eq (car rr) 'not-in-file)
  7854. (buffer-file-name))
  7855. (not (string-match (cdr rr) (buffer-file-name))))
  7856. (when (eq (car rr) 'not-in-mode)
  7857. (not (string-match (cdr rr) (symbol-name major-mode))))
  7858. (when (eq (car rr) 'not-in-buffer)
  7859. (not (string-match (cdr rr) (buffer-name)))))))
  7860. (push r res))))
  7861. (delete-dups (delq nil res))))
  7862. ;; Defined to provide a value for defcustom, since there is no
  7863. ;; string-collate-greaterp in Emacs.
  7864. (defun org-string-collate-greaterp (s1 s2)
  7865. "Return non-nil if S1 is greater than S2 in collation order."
  7866. (not (org-string-collate-lessp s1 s2)))
  7867. ;;;###autoload
  7868. (defun org-run-like-in-org-mode (cmd)
  7869. "Run a command, pretending that the current buffer is in Org mode.
  7870. This will temporarily bind local variables that are typically bound in
  7871. Org mode to the values they have in Org mode, and then interactively
  7872. call CMD."
  7873. (org-load-modules-maybe)
  7874. (let (binds)
  7875. (dolist (var (org-get-local-variables))
  7876. (when (or (not (boundp (car var)))
  7877. (eq (symbol-value (car var))
  7878. (default-value (car var))))
  7879. (push (list (car var) `(quote ,(cadr var))) binds)))
  7880. (eval `(let ,binds
  7881. (call-interactively (quote ,cmd))))))
  7882. (defun org-get-category (&optional pos force-refresh)
  7883. "Get the category applying to position POS."
  7884. (save-match-data
  7885. (when force-refresh (org-refresh-category-properties))
  7886. (let ((pos (or pos (point))))
  7887. (or (get-text-property pos 'org-category)
  7888. (progn (org-refresh-category-properties)
  7889. (get-text-property pos 'org-category))))))
  7890. ;;; Refresh properties
  7891. (defun org-refresh-properties (dprop tprop)
  7892. "Refresh buffer text properties.
  7893. DPROP is the drawer property and TPROP is either the
  7894. corresponding text property to set, or an alist with each element
  7895. being a text property (as a symbol) and a function to apply to
  7896. the value of the drawer property."
  7897. (let* ((case-fold-search t)
  7898. (inhibit-read-only t)
  7899. (inherit? (org-property-inherit-p dprop))
  7900. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7901. (global (and inherit? (org--property-global-value dprop nil))))
  7902. (with-silent-modifications
  7903. (org-with-point-at 1
  7904. ;; Set global values (e.g., values defined through
  7905. ;; "#+PROPERTY:" keywords) to the whole buffer.
  7906. (when global (put-text-property (point-min) (point-max) tprop global))
  7907. ;; Set local values.
  7908. (while (re-search-forward property-re nil t)
  7909. (when (org-at-property-p)
  7910. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7911. (outline-next-heading))))))
  7912. (defun org-refresh-property (tprop p &optional inherit)
  7913. "Refresh the buffer text property TPROP from the drawer property P.
  7914. The refresh happens only for the current headline, or the whole
  7915. sub-tree if optional argument INHERIT is non-nil."
  7916. (unless (org-before-first-heading-p)
  7917. (save-excursion
  7918. (org-back-to-heading t)
  7919. (let ((start (point))
  7920. (end (save-excursion
  7921. (if inherit (org-end-of-subtree t t)
  7922. (or (outline-next-heading) (point-max))))))
  7923. (if (symbolp tprop)
  7924. ;; TPROP is a text property symbol.
  7925. (put-text-property start end tprop p)
  7926. ;; TPROP is an alist with (property . function) elements.
  7927. (pcase-dolist (`(,prop . ,f) tprop)
  7928. (put-text-property start end prop (funcall f p))))))))
  7929. (defun org-refresh-category-properties ()
  7930. "Refresh category text properties in the buffer."
  7931. (let ((case-fold-search t)
  7932. (inhibit-read-only t)
  7933. (default-category
  7934. (cond ((null org-category)
  7935. (if buffer-file-name
  7936. (file-name-sans-extension
  7937. (file-name-nondirectory buffer-file-name))
  7938. "???"))
  7939. ((symbolp org-category) (symbol-name org-category))
  7940. (t org-category))))
  7941. (with-silent-modifications
  7942. (org-with-wide-buffer
  7943. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  7944. ;; This is the default category for the buffer. If none is
  7945. ;; found, fall-back to `org-category' or buffer file name.
  7946. (put-text-property
  7947. (point-min) (point-max)
  7948. 'org-category
  7949. (catch 'buffer-category
  7950. (goto-char (point-max))
  7951. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7952. (let ((element (org-element-at-point)))
  7953. (when (eq (org-element-type element) 'keyword)
  7954. (throw 'buffer-category
  7955. (org-element-property :value element)))))
  7956. default-category))
  7957. ;; Set sub-tree specific categories.
  7958. (goto-char (point-min))
  7959. (let ((regexp (org-re-property "CATEGORY")))
  7960. (while (re-search-forward regexp nil t)
  7961. (let ((value (match-string-no-properties 3)))
  7962. (when (org-at-property-p)
  7963. (put-text-property
  7964. (save-excursion (org-back-to-heading t) (point))
  7965. (save-excursion (org-end-of-subtree t t) (point))
  7966. 'org-category
  7967. value)))))))))
  7968. (defun org-refresh-stats-properties ()
  7969. "Refresh stats text properties in the buffer."
  7970. (with-silent-modifications
  7971. (org-with-point-at 1
  7972. (let ((regexp (concat org-outline-regexp-bol
  7973. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7974. (while (re-search-forward regexp nil t)
  7975. (let* ((numerator (string-to-number (match-string 1)))
  7976. (denominator (and (match-end 2)
  7977. (string-to-number (match-string 2))))
  7978. (stats (cond ((not denominator) numerator) ;percent
  7979. ((= denominator 0) 0)
  7980. (t (/ (* numerator 100) denominator)))))
  7981. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7982. 'org-stats stats)))))))
  7983. (defun org-refresh-effort-properties ()
  7984. "Refresh effort properties"
  7985. (org-refresh-properties
  7986. org-effort-property
  7987. '((effort . identity)
  7988. (effort-minutes . org-duration-to-minutes))))
  7989. ;;;; Link Stuff
  7990. ;;; Link abbreviations
  7991. (defun org-link-expand-abbrev (link)
  7992. "Apply replacements as defined in `org-link-abbrev-alist'."
  7993. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  7994. (let* ((key (match-string 1 link))
  7995. (as (or (assoc key org-link-abbrev-alist-local)
  7996. (assoc key org-link-abbrev-alist)))
  7997. (tag (and (match-end 2) (match-string 3 link)))
  7998. rpl)
  7999. (if (not as)
  8000. link
  8001. (setq rpl (cdr as))
  8002. (cond
  8003. ((symbolp rpl) (funcall rpl tag))
  8004. ((string-match "%(\\([^)]+\\))" rpl)
  8005. (replace-match
  8006. (save-match-data
  8007. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8008. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8009. ((string-match "%h" rpl)
  8010. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8011. (t (concat rpl tag)))))
  8012. link))
  8013. ;;; Storing and inserting links
  8014. (defvar org-insert-link-history nil
  8015. "Minibuffer history for links inserted with `org-insert-link'.")
  8016. (defvar org-stored-links nil
  8017. "Contains the links stored with `org-store-link'.")
  8018. (defvar org-store-link-plist nil
  8019. "Plist with info about the most recently link created with `org-store-link'.")
  8020. (defun org-store-link-functions ()
  8021. "Return a list of functions that are called to create and store a link.
  8022. The functions defined in the :store property of
  8023. `org-link-parameters'.
  8024. Each function will be called in turn until one returns a non-nil
  8025. value. Each function should check if it is responsible for
  8026. creating this link (for example by looking at the major mode).
  8027. If not, it must exit and return nil. If yes, it should return
  8028. a non-nil value after calling `org-store-link-props' with a list
  8029. of properties and values. Special properties are:
  8030. :type The link prefix, like \"http\". This must be given.
  8031. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8032. This is obligatory as well.
  8033. :description Optional default description for the second pair
  8034. of brackets in an Org mode link. The user can still change
  8035. this when inserting this link into an Org mode buffer.
  8036. In addition to these, any additional properties can be specified
  8037. and then used in capture templates."
  8038. (cl-loop for link in org-link-parameters
  8039. with store-func
  8040. do (setq store-func (org-link-get-parameter (car link) :store))
  8041. if store-func
  8042. collect store-func))
  8043. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8044. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8045. ;;;###autoload
  8046. (defun org-store-link (arg &optional interactive?)
  8047. "Store a link to the current location.
  8048. \\<org-mode-map>
  8049. This link is added to `org-stored-links' and can later be inserted
  8050. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8051. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8052. A single
  8053. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8054. `org-gnus-prefer-web-links' for links to Usenet articles.
  8055. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8056. skipping storing functions that are not
  8057. part of Org core.
  8058. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8059. prefix ARG forces storing a link for each line in the
  8060. active region.
  8061. Assume the function is called interactively if INTERACTIVE? is
  8062. non-nil."
  8063. (interactive "P\np")
  8064. (org-load-modules-maybe)
  8065. (if (and (equal arg '(64)) (org-region-active-p))
  8066. (save-excursion
  8067. (let ((end (region-end)))
  8068. (goto-char (region-beginning))
  8069. (set-mark (point))
  8070. (while (< (point-at-eol) end)
  8071. (move-end-of-line 1) (activate-mark)
  8072. (let (current-prefix-arg)
  8073. (call-interactively 'org-store-link))
  8074. (move-beginning-of-line 2)
  8075. (set-mark (point)))))
  8076. (setq org-store-link-plist nil)
  8077. (let (link cpltxt desc description search txt custom-id agenda-link)
  8078. (cond
  8079. ;; Store a link using an external link type, if any function is
  8080. ;; available. If more than one can generate a link from current
  8081. ;; location, ask which one to use.
  8082. ((and (not (equal arg '(16)))
  8083. (let ((results-alist nil))
  8084. (dolist (f (org-store-link-functions))
  8085. (when (funcall f)
  8086. ;; XXX: return value is not link's plist, so we
  8087. ;; store the new value before it is modified. It
  8088. ;; would be cleaner to ask store link functions to
  8089. ;; return the plist instead.
  8090. (push (cons f (copy-sequence org-store-link-plist))
  8091. results-alist)))
  8092. (pcase results-alist
  8093. (`nil nil)
  8094. (`((,_ . ,_)) t) ;single choice: nothing to do
  8095. (`((,name . ,_) . ,_)
  8096. ;; Reinstate link plist associated to the chosen
  8097. ;; function.
  8098. (apply #'org-store-link-props
  8099. (cdr (assoc-string
  8100. (completing-read
  8101. "Which function for creating the link? "
  8102. (mapcar #'car results-alist)
  8103. nil t (symbol-name name))
  8104. results-alist)))
  8105. t))))
  8106. (setq link (plist-get org-store-link-plist :link))
  8107. (setq desc (or (plist-get org-store-link-plist :description)
  8108. link)))
  8109. ;; Store a link from a remote editing buffer.
  8110. ((org-src-edit-buffer-p)
  8111. (let ((coderef-format (org-src-coderef-format))
  8112. (format-link
  8113. (lambda (label)
  8114. (if org-src-source-file-name
  8115. (format "file:%s::(%s)" org-src-source-file-name label)
  8116. (format "(%s)" label)))))
  8117. (cond
  8118. ;; Code references do not exist in this type of buffer.
  8119. ;; Pretend we're linking from the source buffer directly.
  8120. ((not (memq (org-src-source-type) '(example-block src-block)))
  8121. (with-current-buffer (org-src-source-buffer)
  8122. (org-store-link arg interactive?))
  8123. (setq link nil))
  8124. ;; A code reference exists. Use it.
  8125. ((save-excursion
  8126. (beginning-of-line)
  8127. (re-search-forward (org-src-coderef-regexp coderef-format)
  8128. (line-end-position)
  8129. t))
  8130. (setq link (funcall format-link (match-string-no-properties 3))))
  8131. ;; No code reference. Create a new one then store the link
  8132. ;; to it, but only in the function is called interactively.
  8133. (interactive?
  8134. (end-of-line)
  8135. (let* ((label (read-string "Code line label: "))
  8136. (reference (format coderef-format label))
  8137. (gc (- 79 (length reference))))
  8138. (if (< (current-column) gc)
  8139. (org-move-to-column gc t)
  8140. (insert " "))
  8141. (insert reference)
  8142. (setq link (funcall format-link label))))
  8143. ;; No code reference, and non-interactive call. Don't know
  8144. ;; what to do. Give up.
  8145. (t (setq link nil)))))
  8146. ;; We are in the agenda, link to referenced location
  8147. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8148. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8149. (get-text-property (point) 'org-marker))))
  8150. (when m
  8151. (org-with-point-at m
  8152. (setq agenda-link (org-store-link nil interactive?))))))
  8153. ((eq major-mode 'calendar-mode)
  8154. (let ((cd (calendar-cursor-to-date)))
  8155. (setq link
  8156. (format-time-string
  8157. (car org-time-stamp-formats)
  8158. (apply 'encode-time
  8159. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8160. nil nil nil))))
  8161. (org-store-link-props :type "calendar" :date cd)))
  8162. ((eq major-mode 'help-mode)
  8163. (setq link (concat "help:" (save-excursion
  8164. (goto-char (point-min))
  8165. (looking-at "^[^ ]+")
  8166. (match-string 0))))
  8167. (org-store-link-props :type "help"))
  8168. ((eq major-mode 'w3-mode)
  8169. (setq cpltxt (if (and (buffer-name)
  8170. (not (string-match "Untitled" (buffer-name))))
  8171. (buffer-name)
  8172. (url-view-url t))
  8173. link (url-view-url t))
  8174. (org-store-link-props :type "w3" :url (url-view-url t)))
  8175. ((eq major-mode 'image-mode)
  8176. (setq cpltxt (concat "file:"
  8177. (abbreviate-file-name buffer-file-name))
  8178. link cpltxt)
  8179. (org-store-link-props :type "image" :file buffer-file-name))
  8180. ;; In dired, store a link to the file of the current line
  8181. ((derived-mode-p 'dired-mode)
  8182. (let ((file (dired-get-filename nil t)))
  8183. (setq file (if file
  8184. (abbreviate-file-name
  8185. (expand-file-name (dired-get-filename nil t)))
  8186. ;; otherwise, no file so use current directory.
  8187. default-directory))
  8188. (setq cpltxt (concat "file:" file)
  8189. link cpltxt)))
  8190. ((setq search (run-hook-with-args-until-success
  8191. 'org-create-file-search-functions))
  8192. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8193. "::" search))
  8194. (setq cpltxt (or description link)))
  8195. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8196. (org-with-limited-levels
  8197. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8198. (cond
  8199. ;; Store a link using the target at point
  8200. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8201. (setq cpltxt
  8202. (concat "file:"
  8203. (abbreviate-file-name
  8204. (buffer-file-name (buffer-base-buffer)))
  8205. "::" (match-string 1))
  8206. link cpltxt))
  8207. ((and (featurep 'org-id)
  8208. (or (eq org-id-link-to-org-use-id t)
  8209. (and interactive?
  8210. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8211. (and (eq org-id-link-to-org-use-id
  8212. 'create-if-interactive-and-no-custom-id)
  8213. (not custom-id))))
  8214. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8215. ;; Store a link using the ID at point
  8216. (setq link (condition-case nil
  8217. (prog1 (org-id-store-link)
  8218. (setq desc (or (plist-get org-store-link-plist
  8219. :description)
  8220. "")))
  8221. (error
  8222. ;; Probably before first headline, link only to file
  8223. (concat "file:"
  8224. (abbreviate-file-name
  8225. (buffer-file-name (buffer-base-buffer))))))))
  8226. (t
  8227. ;; Just link to current headline
  8228. (setq cpltxt (concat "file:"
  8229. (abbreviate-file-name
  8230. (buffer-file-name (buffer-base-buffer)))))
  8231. ;; Add a context search string
  8232. (when (org-xor org-context-in-file-links
  8233. (equal arg '(4)))
  8234. (let* ((element (org-element-at-point))
  8235. (name (org-element-property :name element)))
  8236. (setq txt (cond
  8237. ((org-at-heading-p) nil)
  8238. (name)
  8239. ((org-region-active-p)
  8240. (buffer-substring (region-beginning) (region-end)))))
  8241. (when (or (null txt) (string-match "\\S-" txt))
  8242. (setq cpltxt
  8243. (concat cpltxt "::"
  8244. (condition-case nil
  8245. (org-make-org-heading-search-string txt)
  8246. (error "")))
  8247. desc (or name
  8248. (nth 4 (ignore-errors (org-heading-components)))
  8249. "NONE")))))
  8250. (when (string-match "::\\'" cpltxt)
  8251. (setq cpltxt (substring cpltxt 0 -2)))
  8252. (setq link cpltxt)))))
  8253. ((buffer-file-name (buffer-base-buffer))
  8254. ;; Just link to this file here.
  8255. (setq cpltxt (concat "file:"
  8256. (abbreviate-file-name
  8257. (buffer-file-name (buffer-base-buffer)))))
  8258. ;; Add a context string.
  8259. (when (org-xor org-context-in-file-links
  8260. (equal arg '(4)))
  8261. (setq txt (if (org-region-active-p)
  8262. (buffer-substring (region-beginning) (region-end))
  8263. (buffer-substring (point-at-bol) (point-at-eol))))
  8264. ;; Only use search option if there is some text.
  8265. (when (string-match "\\S-" txt)
  8266. (setq cpltxt
  8267. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8268. desc "NONE")))
  8269. (setq link cpltxt))
  8270. (interactive?
  8271. (user-error "No method for storing a link from this buffer"))
  8272. (t (setq link nil)))
  8273. ;; We're done setting link and desc, clean up
  8274. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8275. (setq link (or link cpltxt)
  8276. desc (or desc cpltxt))
  8277. (cond ((not desc))
  8278. ((equal desc "NONE") (setq desc nil))
  8279. (t (setq desc
  8280. (replace-regexp-in-string
  8281. org-bracket-link-analytic-regexp
  8282. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8283. desc))))
  8284. ;; Return the link
  8285. (if (not (and interactive? link))
  8286. (or agenda-link (and link (org-make-link-string link desc)))
  8287. (push (list link desc) org-stored-links)
  8288. (message "Stored: %s" (or desc link))
  8289. (when custom-id
  8290. (setq link (concat "file:" (abbreviate-file-name
  8291. (buffer-file-name)) "::#" custom-id))
  8292. (push (list link desc) org-stored-links))
  8293. (car org-stored-links)))))
  8294. (defun org-store-link-props (&rest plist)
  8295. "Store link properties.
  8296. The properties are pre-processed by extracting names, addresses
  8297. and dates."
  8298. (let ((x (plist-get plist :from)))
  8299. (when x
  8300. (let ((adr (mail-extract-address-components x)))
  8301. (setq plist (plist-put plist :fromname (car adr)))
  8302. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8303. (let ((x (plist-get plist :to)))
  8304. (when x
  8305. (let ((adr (mail-extract-address-components x)))
  8306. (setq plist (plist-put plist :toname (car adr)))
  8307. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8308. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8309. (when x
  8310. (setq plist (plist-put plist :date-timestamp
  8311. (format-time-string
  8312. (org-time-stamp-format t) x)))
  8313. (setq plist (plist-put plist :date-timestamp-inactive
  8314. (format-time-string
  8315. (org-time-stamp-format t t) x)))))
  8316. (let ((from (plist-get plist :from))
  8317. (to (plist-get plist :to)))
  8318. (when (and from to org-from-is-user-regexp)
  8319. (setq plist
  8320. (plist-put plist :fromto
  8321. (if (string-match org-from-is-user-regexp from)
  8322. (concat "to %t")
  8323. (concat "from %f"))))))
  8324. (setq org-store-link-plist plist))
  8325. (defun org-add-link-props (&rest plist)
  8326. "Add these properties to the link property list."
  8327. (let (key value)
  8328. (while plist
  8329. (setq key (pop plist) value (pop plist))
  8330. (setq org-store-link-plist
  8331. (plist-put org-store-link-plist key value)))))
  8332. (defun org-email-link-description (&optional fmt)
  8333. "Return the description part of an email link.
  8334. This takes information from `org-store-link-plist' and formats it
  8335. according to FMT (default from `org-email-link-description-format')."
  8336. (setq fmt (or fmt org-email-link-description-format))
  8337. (let* ((p org-store-link-plist)
  8338. (to (plist-get p :toaddress))
  8339. (from (plist-get p :fromaddress))
  8340. (table
  8341. (list
  8342. (cons "%c" (plist-get p :fromto))
  8343. (cons "%F" (plist-get p :from))
  8344. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8345. (cons "%T" (plist-get p :to))
  8346. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8347. (cons "%s" (plist-get p :subject))
  8348. (cons "%d" (plist-get p :date))
  8349. (cons "%m" (plist-get p :message-id)))))
  8350. (when (string-match "%c" fmt)
  8351. ;; Check if the user wrote this message
  8352. (if (and org-from-is-user-regexp from to
  8353. (save-match-data (string-match org-from-is-user-regexp from)))
  8354. (setq fmt (replace-match "to %t" t t fmt))
  8355. (setq fmt (replace-match "from %f" t t fmt))))
  8356. (org-replace-escapes fmt table)))
  8357. (defun org-make-org-heading-search-string (&optional string)
  8358. "Make search string for the current headline or STRING."
  8359. (let ((s (or string
  8360. (and (derived-mode-p 'org-mode)
  8361. (save-excursion
  8362. (org-back-to-heading t)
  8363. (org-element-property :raw-value (org-element-at-point))))))
  8364. (lines org-context-in-file-links))
  8365. (unless string (setq s (concat "*" s))) ;Add * for headlines
  8366. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8367. (when (and string (integerp lines) (> lines 0))
  8368. (let ((slines (org-split-string s "\n")))
  8369. (when (< lines (length slines))
  8370. (setq s (mapconcat
  8371. 'identity
  8372. (reverse (nthcdr (- (length slines) lines)
  8373. (reverse slines))) "\n")))))
  8374. (mapconcat #'identity (split-string s) " ")))
  8375. (defconst org-link-escape-chars
  8376. ;;%20 %5B %5D %25
  8377. '(?\s ?\[ ?\] ?%)
  8378. "List of characters that should be escaped in a link when stored to Org.
  8379. This is the list that is used for internal purposes.")
  8380. (defun org-make-link-string (link &optional description)
  8381. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8382. (unless (org-string-nw-p link) (error "Empty link"))
  8383. (let ((uri (cond ((string-match org-link-types-re link)
  8384. (concat (match-string 1 link)
  8385. (org-link-escape (substring link (match-end 1)))))
  8386. ((or (file-name-absolute-p link)
  8387. (string-match-p "\\`\\.\\.?/" link))
  8388. (org-link-escape link))
  8389. ;; For readability, do not encode space characters
  8390. ;; in fuzzy links.
  8391. (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
  8392. (description
  8393. (and (org-string-nw-p description)
  8394. ;; Remove brackets from description, as they are fatal.
  8395. (replace-regexp-in-string
  8396. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8397. (org-trim description)))))
  8398. (format "[[%s]%s]"
  8399. uri
  8400. (if description (format "[%s]" description) ""))))
  8401. (defun org-link-escape (text &optional table merge)
  8402. "Return percent escaped representation of TEXT.
  8403. TEXT is a string with the text to escape.
  8404. Optional argument TABLE is a list with characters that should be
  8405. escaped. When nil, `org-link-escape-chars' is used.
  8406. If optional argument MERGE is set, merge TABLE into
  8407. `org-link-escape-chars'."
  8408. (let ((characters-to-encode
  8409. (cond ((null table) org-link-escape-chars)
  8410. (merge (append org-link-escape-chars table))
  8411. (t table))))
  8412. (mapconcat
  8413. (lambda (c)
  8414. (if (or (memq c characters-to-encode)
  8415. (and org-url-hexify-p (or (< c 32) (> c 126))))
  8416. (mapconcat (lambda (e) (format "%%%.2X" e))
  8417. (or (encode-coding-char c 'utf-8)
  8418. (error "Unable to percent escape character: %c" c))
  8419. "")
  8420. (char-to-string c)))
  8421. text "")))
  8422. (defun org-link-unescape (str)
  8423. "Unhex hexified Unicode parts in string STR.
  8424. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  8425. reciprocal of `org-link-escape', which see."
  8426. (if (org-string-nw-p str)
  8427. (replace-regexp-in-string
  8428. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  8429. str))
  8430. (defun org-link-unescape-compound (hex)
  8431. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  8432. Note: this function also decodes single byte encodings like
  8433. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  8434. (save-match-data
  8435. (let* ((bytes (cdr (split-string hex "%")))
  8436. (ret "")
  8437. (eat 0)
  8438. (sum 0))
  8439. (while bytes
  8440. (let* ((val (string-to-number (pop bytes) 16))
  8441. (shift-xor
  8442. (if (= 0 eat)
  8443. (cond
  8444. ((>= val 252) (cons 6 252))
  8445. ((>= val 248) (cons 5 248))
  8446. ((>= val 240) (cons 4 240))
  8447. ((>= val 224) (cons 3 224))
  8448. ((>= val 192) (cons 2 192))
  8449. (t (cons 0 0)))
  8450. (cons 6 128))))
  8451. (when (>= val 192) (setq eat (car shift-xor)))
  8452. (setq val (logxor val (cdr shift-xor)))
  8453. (setq sum (+ (lsh sum (car shift-xor)) val))
  8454. (when (> eat 0) (setq eat (- eat 1)))
  8455. (cond
  8456. ((= 0 eat) ;multi byte
  8457. (setq ret (concat ret (char-to-string sum)))
  8458. (setq sum 0))
  8459. ((not bytes) ; single byte(s)
  8460. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  8461. ret)))
  8462. (defun org-link-unescape-single-byte-sequence (hex)
  8463. "Unhexify hex-encoded single byte character sequences."
  8464. (mapconcat (lambda (byte)
  8465. (char-to-string (string-to-number byte 16)))
  8466. (cdr (split-string hex "%")) ""))
  8467. (defun org-fixup-message-id-for-http (s)
  8468. "Replace special characters in a message id, so it can be used in an http query."
  8469. (when (string-match "%" s)
  8470. (setq s (mapconcat (lambda (c)
  8471. (if (eq c ?%)
  8472. "%25"
  8473. (char-to-string c)))
  8474. s "")))
  8475. (while (string-match "<" s)
  8476. (setq s (replace-match "%3C" t t s)))
  8477. (while (string-match ">" s)
  8478. (setq s (replace-match "%3E" t t s)))
  8479. (while (string-match "@" s)
  8480. (setq s (replace-match "%40" t t s)))
  8481. s)
  8482. (defun org-link-prettify (link)
  8483. "Return a human-readable representation of LINK.
  8484. The car of LINK must be a raw link.
  8485. The cdr of LINK must be either a link description or nil."
  8486. (let ((desc (or (cadr link) "<no description>")))
  8487. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  8488. "<" (car link) ">")))
  8489. ;;;###autoload
  8490. (defun org-insert-link-global ()
  8491. "Insert a link like Org mode does.
  8492. This command can be called in any mode to insert a link in Org syntax."
  8493. (interactive)
  8494. (org-load-modules-maybe)
  8495. (org-run-like-in-org-mode 'org-insert-link))
  8496. (defun org-insert-all-links (arg &optional pre post)
  8497. "Insert all links in `org-stored-links'.
  8498. When a universal prefix, do not delete the links from `org-stored-links'.
  8499. When `ARG' is a number, insert the last N link(s).
  8500. `PRE' and `POST' are optional arguments to define a string to
  8501. prepend or to append."
  8502. (interactive "P")
  8503. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  8504. (links (copy-sequence org-stored-links))
  8505. (pr (or pre "- "))
  8506. (po (or post "\n"))
  8507. (cnt 1) l)
  8508. (if (null org-stored-links)
  8509. (message "No link to insert")
  8510. (while (and (or (listp arg) (>= arg cnt))
  8511. (setq l (if (listp arg)
  8512. (pop links)
  8513. (pop org-stored-links))))
  8514. (setq cnt (1+ cnt))
  8515. (insert pr)
  8516. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  8517. (insert po)))))
  8518. (defun org-insert-last-stored-link (arg)
  8519. "Insert the last link stored in `org-stored-links'."
  8520. (interactive "p")
  8521. (org-insert-all-links arg "" "\n"))
  8522. (defun org-link-fontify-links-to-this-file ()
  8523. "Fontify links to the current file in `org-stored-links'."
  8524. (let ((f (buffer-file-name)) a b)
  8525. (setq a (mapcar (lambda(l)
  8526. (let ((ll (car l)))
  8527. (when (and (string-match "^file:\\(.+\\)::" ll)
  8528. (equal f (expand-file-name (match-string 1 ll))))
  8529. ll)))
  8530. org-stored-links))
  8531. (when (featurep 'org-id)
  8532. (setq b (mapcar (lambda(l)
  8533. (let ((ll (car l)))
  8534. (when (and (string-match "^id:\\(.+\\)$" ll)
  8535. (equal f (expand-file-name
  8536. (or (org-id-find-id-file
  8537. (match-string 1 ll)) ""))))
  8538. ll)))
  8539. org-stored-links)))
  8540. (mapcar (lambda(l)
  8541. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  8542. (delq nil (append a b)))))
  8543. (defvar org--links-history nil)
  8544. (defun org-insert-link (&optional complete-file link-location default-description)
  8545. "Insert a link. At the prompt, enter the link.
  8546. Completion can be used to insert any of the link protocol prefixes in use.
  8547. The history can be used to select a link previously stored with
  8548. `org-store-link'. When the empty string is entered (i.e. if you just
  8549. press `RET' at the prompt), the link defaults to the most recently
  8550. stored link. As `SPC' triggers completion in the minibuffer, you need to
  8551. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  8552. You will also be prompted for a description, and if one is given, it will
  8553. be displayed in the buffer instead of the link.
  8554. If there is already a link at point, this command will allow you to edit
  8555. link and description parts.
  8556. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  8557. file name can be
  8558. selected using completion. The path to the file will be relative to the
  8559. current directory if the file is in the current directory or a subdirectory.
  8560. Otherwise, the link will be the absolute path as completed in the minibuffer
  8561. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  8562. option `org-link-file-path-type'.
  8563. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  8564. absolute path even if the file is in
  8565. the current directory or below.
  8566. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8567. prefix negates `org-keep-stored-link-after-insertion'.
  8568. If the LINK-LOCATION parameter is non-nil, this value will be used as
  8569. the link location instead of reading one interactively.
  8570. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  8571. be used as the default description. Otherwise, if
  8572. `org-make-link-description-function' is non-nil, this function
  8573. will be called with the link target, and the result will be the
  8574. default link description. When called non-interactivily, don't
  8575. allow to edit the default description."
  8576. (interactive "P")
  8577. (let* ((wcf (current-window-configuration))
  8578. (origbuf (current-buffer))
  8579. (region (when (org-region-active-p)
  8580. (buffer-substring (region-beginning) (region-end))))
  8581. (remove (and region (list (region-beginning) (region-end))))
  8582. (desc region)
  8583. (link link-location)
  8584. (abbrevs org-link-abbrev-alist-local)
  8585. entry all-prefixes auto-desc)
  8586. (cond
  8587. (link-location) ; specified by arg, just use it.
  8588. ((org-in-regexp org-bracket-link-regexp 1)
  8589. ;; We do have a link at point, and we are going to edit it.
  8590. (setq remove (list (match-beginning 0) (match-end 0)))
  8591. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  8592. (setq link (read-string "Link: "
  8593. (org-link-unescape
  8594. (match-string-no-properties 1)))))
  8595. ((or (org-in-regexp org-angle-link-re)
  8596. (org-in-regexp org-plain-link-re))
  8597. ;; Convert to bracket link
  8598. (setq remove (list (match-beginning 0) (match-end 0))
  8599. link (read-string "Link: "
  8600. (org-unbracket-string "<" ">" (match-string 0)))))
  8601. ((member complete-file '((4) (16)))
  8602. ;; Completing read for file names.
  8603. (setq link (org-file-complete-link complete-file)))
  8604. (t
  8605. ;; Read link, with completion for stored links.
  8606. (org-link-fontify-links-to-this-file)
  8607. (org-switch-to-buffer-other-window "*Org Links*")
  8608. (with-current-buffer "*Org Links*"
  8609. (erase-buffer)
  8610. (insert "Insert a link.
  8611. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  8612. (when org-stored-links
  8613. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  8614. (insert (mapconcat 'org-link-prettify
  8615. (reverse org-stored-links) "\n")))
  8616. (goto-char (point-min)))
  8617. (let ((cw (selected-window)))
  8618. (select-window (get-buffer-window "*Org Links*" 'visible))
  8619. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  8620. (unless (pos-visible-in-window-p (point-max))
  8621. (org-fit-window-to-buffer))
  8622. (and (window-live-p cw) (select-window cw)))
  8623. (setq all-prefixes (append (mapcar 'car abbrevs)
  8624. (mapcar 'car org-link-abbrev-alist)
  8625. (org-link-types)))
  8626. (unwind-protect
  8627. ;; Fake a link history, containing the stored links.
  8628. (let ((org--links-history
  8629. (append (mapcar #'car org-stored-links)
  8630. org-insert-link-history)))
  8631. (setq link
  8632. (org-completing-read
  8633. "Link: "
  8634. (append
  8635. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  8636. (mapcar #'car org-stored-links))
  8637. nil nil nil
  8638. 'org--links-history
  8639. (caar org-stored-links)))
  8640. (unless (org-string-nw-p link) (user-error "No link selected"))
  8641. (dolist (l org-stored-links)
  8642. (when (equal link (cadr l))
  8643. (setq link (car l))
  8644. (setq auto-desc t)))
  8645. (when (or (member link all-prefixes)
  8646. (and (equal ":" (substring link -1))
  8647. (member (substring link 0 -1) all-prefixes)
  8648. (setq link (substring link 0 -1))))
  8649. (setq link (with-current-buffer origbuf
  8650. (org-link-try-special-completion link)))))
  8651. (set-window-configuration wcf)
  8652. (kill-buffer "*Org Links*"))
  8653. (setq entry (assoc link org-stored-links))
  8654. (or entry (push link org-insert-link-history))
  8655. (setq desc (or desc (nth 1 entry)))))
  8656. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  8657. (not org-keep-stored-link-after-insertion))
  8658. (setq org-stored-links (delq (assoc link org-stored-links)
  8659. org-stored-links)))
  8660. (when (and (string-match org-plain-link-re link)
  8661. (not (string-match org-ts-regexp link)))
  8662. ;; URL-like link, normalize the use of angular brackets.
  8663. (setq link (org-unbracket-string "<" ">" link)))
  8664. ;; Check if we are linking to the current file with a search
  8665. ;; option If yes, simplify the link by using only the search
  8666. ;; option.
  8667. (when (and buffer-file-name
  8668. (let ((case-fold-search nil))
  8669. (string-match "\\`file:\\(.+?\\)::" link)))
  8670. (let ((path (match-string-no-properties 1 link))
  8671. (search (substring-no-properties link (match-end 0))))
  8672. (save-match-data
  8673. (when (equal (file-truename buffer-file-name) (file-truename path))
  8674. ;; We are linking to this same file, with a search option
  8675. (setq link search)))))
  8676. ;; Check if we can/should use a relative path. If yes, simplify
  8677. ;; the link.
  8678. (let ((case-fold-search nil))
  8679. (when (string-match "\\`\\(file\\|docview\\):" link)
  8680. (let* ((type (match-string-no-properties 0 link))
  8681. (path-start (match-end 0))
  8682. (search (and (string-match "::\\(.*\\)\\'" link)
  8683. (match-string 1 link)))
  8684. (path
  8685. (if search
  8686. (substring-no-properties
  8687. link path-start (match-beginning 0))
  8688. (substring-no-properties link (match-end 0))))
  8689. (origpath path))
  8690. (cond
  8691. ((or (eq org-link-file-path-type 'absolute)
  8692. (equal complete-file '(16)))
  8693. (setq path (abbreviate-file-name (expand-file-name path))))
  8694. ((eq org-link-file-path-type 'noabbrev)
  8695. (setq path (expand-file-name path)))
  8696. ((eq org-link-file-path-type 'relative)
  8697. (setq path (file-relative-name path)))
  8698. (t
  8699. (save-match-data
  8700. (if (string-match (concat "^" (regexp-quote
  8701. (expand-file-name
  8702. (file-name-as-directory
  8703. default-directory))))
  8704. (expand-file-name path))
  8705. ;; We are linking a file with relative path name.
  8706. (setq path (substring (expand-file-name path)
  8707. (match-end 0)))
  8708. (setq path (abbreviate-file-name (expand-file-name path)))))))
  8709. (setq link (concat type path (and search (concat "::" search))))
  8710. (when (equal desc origpath)
  8711. (setq desc path)))))
  8712. (unless auto-desc
  8713. (let ((initial-input
  8714. (cond
  8715. (default-description)
  8716. ((not org-make-link-description-function) desc)
  8717. (t (condition-case nil
  8718. (funcall org-make-link-description-function link desc)
  8719. (error
  8720. (message "Can't get link description from `%s'"
  8721. (symbol-name org-make-link-description-function))
  8722. (sit-for 2)
  8723. nil))))))
  8724. (setq desc (if (called-interactively-p 'any)
  8725. (read-string "Description: " initial-input)
  8726. initial-input))))
  8727. (unless (string-match "\\S-" desc) (setq desc nil))
  8728. (when remove (apply 'delete-region remove))
  8729. (insert (org-make-link-string link desc))
  8730. ;; Redisplay so as the new link has proper invisible characters.
  8731. (sit-for 0)))
  8732. (defun org-link-try-special-completion (type)
  8733. "If there is completion support for link type TYPE, offer it."
  8734. (let ((fun (org-link-get-parameter type :complete)))
  8735. (if (functionp fun)
  8736. (funcall fun)
  8737. (read-string "Link (no completion support): " (concat type ":")))))
  8738. (defun org-file-complete-link (&optional arg)
  8739. "Create a file link using completion."
  8740. (let ((file (read-file-name "File: "))
  8741. (pwd (file-name-as-directory (expand-file-name ".")))
  8742. (pwd1 (file-name-as-directory (abbreviate-file-name
  8743. (expand-file-name ".")))))
  8744. (cond ((equal arg '(16))
  8745. (concat "file:"
  8746. (abbreviate-file-name (expand-file-name file))))
  8747. ((string-match
  8748. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  8749. (concat "file:" (match-string 1 file)))
  8750. ((string-match
  8751. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  8752. (expand-file-name file))
  8753. (concat "file:"
  8754. (match-string 1 (expand-file-name file))))
  8755. (t (concat "file:" file)))))
  8756. ;;; Opening/following a link
  8757. (defvar org-link-search-failed nil)
  8758. (defvar org-open-link-functions nil
  8759. "Hook for functions finding a plain text link.
  8760. These functions must take a single argument, the link content.
  8761. They will be called for links that look like [[link text][description]]
  8762. when LINK TEXT does not have a protocol like \"http:\" and does not look
  8763. like a filename (e.g. \"./blue.png\").
  8764. These functions will be called *before* Org attempts to resolve the
  8765. link by doing text searches in the current buffer - so if you want a
  8766. link \"[[target]]\" to still find \"<<target>>\", your function should
  8767. handle this as a special case.
  8768. When the function does handle the link, it must return a non-nil value.
  8769. If it decides that it is not responsible for this link, it must return
  8770. nil to indicate that that Org can continue with other options like
  8771. exact and fuzzy text search.")
  8772. (defun org-next-link (&optional search-backward)
  8773. "Move forward to the next link.
  8774. If the link is in hidden text, expose it."
  8775. (interactive "P")
  8776. (when (and org-link-search-failed (eq this-command last-command))
  8777. (goto-char (point-min))
  8778. (message "Link search wrapped back to beginning of buffer"))
  8779. (setq org-link-search-failed nil)
  8780. (let* ((pos (point))
  8781. (ct (org-context))
  8782. (a (assq :link ct))
  8783. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  8784. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  8785. ((looking-at org-any-link-re)
  8786. ;; Don't stay stuck at link without an org-link face
  8787. (forward-char (if search-backward -1 1))))
  8788. (if (funcall srch-fun org-any-link-re nil t)
  8789. (progn
  8790. (goto-char (match-beginning 0))
  8791. (when (org-invisible-p) (org-show-context)))
  8792. (goto-char pos)
  8793. (setq org-link-search-failed t)
  8794. (message "No further link found"))))
  8795. (defun org-previous-link ()
  8796. "Move backward to the previous link.
  8797. If the link is in hidden text, expose it."
  8798. (interactive)
  8799. (org-next-link t))
  8800. (defun org-translate-link (s)
  8801. "Translate a link string if a translation function has been defined."
  8802. (with-temp-buffer
  8803. (insert (org-trim s))
  8804. (org-trim (org-element-interpret-data (org-element-context)))))
  8805. (defun org-translate-link-from-planner (type path)
  8806. "Translate a link from Emacs Planner syntax so that Org can follow it.
  8807. This is still an experimental function, your mileage may vary."
  8808. (cond
  8809. ((member type '("http" "https" "news" "ftp"))
  8810. ;; standard Internet links are the same.
  8811. nil)
  8812. ((and (equal type "irc") (string-match "^//" path))
  8813. ;; Planner has two / at the beginning of an irc link, we have 1.
  8814. ;; We should have zero, actually....
  8815. (setq path (substring path 1)))
  8816. ((and (equal type "lisp") (string-match "^/" path))
  8817. ;; Planner has a slash, we do not.
  8818. (setq type "elisp" path (substring path 1)))
  8819. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  8820. ;; A typical message link. Planner has the id after the final slash,
  8821. ;; we separate it with a hash mark
  8822. (setq path (concat (match-string 1 path) "#"
  8823. (org-unbracket-string "<" ">" (match-string 2 path))))))
  8824. (cons type path))
  8825. (defun org-find-file-at-mouse (ev)
  8826. "Open file link or URL at mouse."
  8827. (interactive "e")
  8828. (mouse-set-point ev)
  8829. (org-open-at-point 'in-emacs))
  8830. (defun org-open-at-mouse (ev)
  8831. "Open file link or URL at mouse.
  8832. See the docstring of `org-open-file' for details."
  8833. (interactive "e")
  8834. (mouse-set-point ev)
  8835. (when (eq major-mode 'org-agenda-mode)
  8836. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  8837. (org-open-at-point))
  8838. (defvar org-window-config-before-follow-link nil
  8839. "The window configuration before following a link.
  8840. This is saved in case the need arises to restore it.")
  8841. ;;;###autoload
  8842. (defun org-open-at-point-global ()
  8843. "Follow a link or a time-stamp like Org mode does.
  8844. Also follow links and emails as seen by `thing-at-point'.
  8845. This command can be called in any mode to follow an external
  8846. link or a time-stamp that has Org mode syntax. Its behavior
  8847. is undefined when called on internal links like fuzzy links.
  8848. Raise a user error when there is nothing to follow."
  8849. (interactive)
  8850. (let ((tap-url (thing-at-point 'url))
  8851. (tap-email (thing-at-point 'email)))
  8852. (cond ((org-in-regexp org-any-link-re)
  8853. (org-open-link-from-string (match-string-no-properties 0)))
  8854. ((or (org-in-regexp org-ts-regexp-both nil t)
  8855. (org-in-regexp org-tsr-regexp-both nil t))
  8856. (org-follow-timestamp-link))
  8857. (tap-url (org-open-link-from-string tap-url))
  8858. (tap-email (org-open-link-from-string
  8859. (concat "mailto:" tap-email)))
  8860. (t (user-error "No link found")))))
  8861. ;;;###autoload
  8862. (defun org-open-link-from-string (s &optional arg reference-buffer)
  8863. "Open a link in the string S, as if it was in Org mode."
  8864. (interactive "sLink: \nP")
  8865. (let ((reference-buffer (or reference-buffer (current-buffer))))
  8866. (with-temp-buffer
  8867. (let ((org-inhibit-startup (not reference-buffer)))
  8868. (org-mode)
  8869. (insert s)
  8870. (goto-char (point-min))
  8871. (when reference-buffer
  8872. (setq org-link-abbrev-alist-local
  8873. (with-current-buffer reference-buffer
  8874. org-link-abbrev-alist-local)))
  8875. (org-open-at-point arg reference-buffer)))))
  8876. (defvar org-open-at-point-functions nil
  8877. "Hook that is run when following a link at point.
  8878. Functions in this hook must return t if they identify and follow
  8879. a link at point. If they don't find anything interesting at point,
  8880. they must return nil.")
  8881. (defvar org-link-search-inhibit-query nil)
  8882. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  8883. (defun org--open-doi-link (path)
  8884. "Open a \"doi\" type link.
  8885. PATH is a the path to search for, as a string."
  8886. (browse-url (url-encode-url (concat org-doi-server-url path))))
  8887. (defun org--open-elisp-link (path)
  8888. "Open a \"elisp\" type link.
  8889. PATH is the sexp to evaluate, as a string."
  8890. (let ((cmd path))
  8891. (if (or (and (org-string-nw-p
  8892. org-confirm-elisp-link-not-regexp)
  8893. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  8894. (not org-confirm-elisp-link-function)
  8895. (funcall org-confirm-elisp-link-function
  8896. (format "Execute \"%s\" as elisp? "
  8897. (org-add-props cmd nil 'face 'org-warning))))
  8898. (message "%s => %s" cmd
  8899. (if (eq (string-to-char cmd) ?\()
  8900. (eval (read cmd))
  8901. (call-interactively (read cmd))))
  8902. (user-error "Abort"))))
  8903. (defun org--open-help-link (path)
  8904. "Open a \"help\" type link.
  8905. PATH is a symbol name, as a string."
  8906. (pcase (intern path)
  8907. ((and (pred fboundp) variable) (describe-function variable))
  8908. ((and (pred boundp) function) (describe-variable function))
  8909. (name (user-error "Unknown function or variable: %s" name))))
  8910. (defun org--open-shell-link (path)
  8911. "Open a \"shell\" type link.
  8912. PATH is the command to execute, as a string."
  8913. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  8914. (cmd path))
  8915. (if (or (and (org-string-nw-p
  8916. org-confirm-shell-link-not-regexp)
  8917. (string-match
  8918. org-confirm-shell-link-not-regexp cmd))
  8919. (not org-confirm-shell-link-function)
  8920. (funcall org-confirm-shell-link-function
  8921. (format "Execute \"%s\" in shell? "
  8922. (org-add-props cmd nil
  8923. 'face 'org-warning))))
  8924. (progn
  8925. (message "Executing %s" cmd)
  8926. (shell-command cmd buf)
  8927. (when (featurep 'midnight)
  8928. (setq clean-buffer-list-kill-buffer-names
  8929. (cons (buffer-name buf)
  8930. clean-buffer-list-kill-buffer-names))))
  8931. (user-error "Abort"))))
  8932. (defun org-open-at-point (&optional arg reference-buffer)
  8933. "Open link, timestamp, footnote or tags at point.
  8934. When point is on a link, follow it. Normally, files will be
  8935. opened by an appropriate application. If the optional prefix
  8936. argument ARG is non-nil, Emacs will visit the file. With
  8937. a double prefix argument, try to open outside of Emacs, in the
  8938. application the system uses for this file type.
  8939. When point is on a timestamp, open the agenda at the day
  8940. specified.
  8941. When point is a footnote definition, move to the first reference
  8942. found. If it is on a reference, move to the associated
  8943. definition.
  8944. When point is on a headline, display a list of every link in the
  8945. entry, so it is possible to pick one, or all, of them. If point
  8946. is on a tag, call `org-tags-view' instead.
  8947. When optional argument REFERENCE-BUFFER is non-nil, it should
  8948. specify a buffer from where the link search should happen. This
  8949. is used internally by `org-open-link-from-string'.
  8950. On top of syntactically correct links, this function also tries
  8951. to open links and time-stamps in comments, node properties, and
  8952. keywords if point is on something looking like a timestamp or
  8953. a link."
  8954. (interactive "P")
  8955. (org-load-modules-maybe)
  8956. (setq org-window-config-before-follow-link (current-window-configuration))
  8957. (org-remove-occur-highlights nil nil t)
  8958. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  8959. (let* ((context
  8960. ;; Only consider supported types, even if they are not the
  8961. ;; closest one.
  8962. (org-element-lineage
  8963. (org-element-context)
  8964. '(clock comment comment-block footnote-definition
  8965. footnote-reference headline inline-src-block inlinetask
  8966. keyword link node-property src-block timestamp)
  8967. t))
  8968. (type (org-element-type context))
  8969. (value (org-element-property :value context)))
  8970. (cond
  8971. ((not type) (user-error "No link found"))
  8972. ;; No valid link at point. For convenience, look if something
  8973. ;; looks like a link under point in some specific places.
  8974. ((memq type '(comment comment-block node-property keyword))
  8975. (call-interactively #'org-open-at-point-global))
  8976. ;; On a headline or an inlinetask, but not on a timestamp,
  8977. ;; a link, a footnote reference.
  8978. ((memq type '(headline inlinetask))
  8979. (org-match-line org-complex-heading-regexp)
  8980. (if (and (match-beginning 5)
  8981. (>= (point) (match-beginning 5))
  8982. (< (point) (match-end 5)))
  8983. ;; On tags.
  8984. (org-tags-view arg (substring (match-string 5) 0 -1))
  8985. ;; Not on tags.
  8986. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  8987. (`(nil . ,_)
  8988. (require 'org-attach)
  8989. (org-attach-reveal 'if-exists))
  8990. (`(,links . ,links-end)
  8991. (dolist (link (if (stringp links) (list links) links))
  8992. (search-forward link nil links-end)
  8993. (goto-char (match-beginning 0))
  8994. (org-open-at-point))))))
  8995. ;; On a footnote reference or at definition's label.
  8996. ((or (eq type 'footnote-reference)
  8997. (and (eq type 'footnote-definition)
  8998. (save-excursion
  8999. ;; Do not validate action when point is on the
  9000. ;; spaces right after the footnote label, in order
  9001. ;; to be on par with behavior on links.
  9002. (skip-chars-forward " \t")
  9003. (let ((begin
  9004. (org-element-property :contents-begin context)))
  9005. (if begin (< (point) begin)
  9006. (= (org-element-property :post-affiliated context)
  9007. (line-beginning-position)))))))
  9008. (org-footnote-action))
  9009. ;; On a clock line, make sure point is on the timestamp
  9010. ;; before opening it.
  9011. ((and (eq type 'clock)
  9012. value
  9013. (>= (point) (org-element-property :begin value))
  9014. (<= (point) (org-element-property :end value)))
  9015. (org-follow-timestamp-link))
  9016. ((eq type 'src-block) (org-babel-open-src-block-result))
  9017. ;; Do nothing on white spaces after an object.
  9018. ((>= (point)
  9019. (save-excursion
  9020. (goto-char (org-element-property :end context))
  9021. (skip-chars-backward " \t")
  9022. (point)))
  9023. (user-error "No link found"))
  9024. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  9025. ((eq type 'timestamp) (org-follow-timestamp-link))
  9026. ((eq type 'link)
  9027. (let ((type (org-element-property :type context))
  9028. (path (org-link-unescape (org-element-property :path context))))
  9029. ;; Switch back to REFERENCE-BUFFER needed when called in
  9030. ;; a temporary buffer through `org-open-link-from-string'.
  9031. (with-current-buffer (or reference-buffer (current-buffer))
  9032. (cond
  9033. ((equal type "file")
  9034. (if (string-match "[*?{]" (file-name-nondirectory path))
  9035. (dired path)
  9036. ;; Look into `org-link-parameters' in order to find
  9037. ;; a DEDICATED-FUNCTION to open file. The function
  9038. ;; will be applied on raw link instead of parsed link
  9039. ;; due to the limitation in `org-add-link-type'
  9040. ;; ("open" function called with a single argument).
  9041. ;; If no such function is found, fallback to
  9042. ;; `org-open-file'.
  9043. (let* ((option (org-element-property :search-option context))
  9044. (app (org-element-property :application context))
  9045. (dedicated-function
  9046. (org-link-get-parameter
  9047. (if app (concat type "+" app) type)
  9048. :follow)))
  9049. (if dedicated-function
  9050. (funcall dedicated-function
  9051. (concat path
  9052. (and option (concat "::" option))))
  9053. (apply #'org-open-file
  9054. path
  9055. (cond (arg)
  9056. ((equal app "emacs") 'emacs)
  9057. ((equal app "sys") 'system))
  9058. (cond ((not option) nil)
  9059. ((string-match-p "\\`[0-9]+\\'" option)
  9060. (list (string-to-number option)))
  9061. (t (list nil
  9062. (org-link-unescape option)))))))))
  9063. ((functionp (org-link-get-parameter type :follow))
  9064. (funcall (org-link-get-parameter type :follow) path))
  9065. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9066. (unless (run-hook-with-args-until-success
  9067. 'org-open-link-functions path)
  9068. (if (not arg) (org-mark-ring-push)
  9069. (switch-to-buffer-other-window
  9070. (org-get-buffer-for-internal-link (current-buffer))))
  9071. (let ((destination
  9072. (org-with-wide-buffer
  9073. (if (equal type "radio")
  9074. (org-search-radio-target
  9075. (org-element-property :path context))
  9076. (org-link-search
  9077. (pcase type
  9078. ("custom-id" (concat "#" path))
  9079. ("coderef" (format "(%s)" path))
  9080. (_ path))
  9081. ;; Prevent fuzzy links from matching
  9082. ;; themselves.
  9083. (and (equal type "fuzzy")
  9084. (+ 2 (org-element-property :begin context)))))
  9085. (point))))
  9086. (unless (and (<= (point-min) destination)
  9087. (>= (point-max) destination))
  9088. (widen))
  9089. (goto-char destination))))
  9090. (t (browse-url-at-point))))))
  9091. (t (user-error "No link found")))))
  9092. (run-hook-with-args 'org-follow-link-hook))
  9093. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9094. "Offer links in the current entry and return the selected link.
  9095. If there is only one link, return it.
  9096. If NTH is an integer, return the NTH link found.
  9097. If ZERO is a string, check also this string for a link, and if
  9098. there is one, return it."
  9099. (with-current-buffer buffer
  9100. (org-with-wide-buffer
  9101. (goto-char marker)
  9102. (let ((cnt ?0)
  9103. have-zero end links link c)
  9104. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9105. (push (match-string 0 zero) links)
  9106. (setq cnt (1- cnt) have-zero t))
  9107. (save-excursion
  9108. (org-back-to-heading t)
  9109. (setq end (save-excursion (outline-next-heading) (point)))
  9110. (while (re-search-forward org-any-link-re end t)
  9111. (push (match-string 0) links))
  9112. (setq links (org-uniquify (reverse links))))
  9113. (cond
  9114. ((null links)
  9115. (message "No links"))
  9116. ((equal (length links) 1)
  9117. (setq link (car links)))
  9118. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9119. (setq link (nth (if have-zero nth (1- nth)) links)))
  9120. (t ; we have to select a link
  9121. (save-excursion
  9122. (save-window-excursion
  9123. (delete-other-windows)
  9124. (with-output-to-temp-buffer "*Select Link*"
  9125. (dolist (l links)
  9126. (cond
  9127. ((not (string-match org-bracket-link-regexp l))
  9128. (princ (format "[%c] %s\n" (cl-incf cnt)
  9129. (org-unbracket-string "<" ">" l))))
  9130. ((match-end 3)
  9131. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9132. (match-string 3 l) (match-string 1 l))))
  9133. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9134. (match-string 1 l)))))))
  9135. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9136. (message "Select link to open, RET to open all:")
  9137. (setq c (read-char-exclusive))
  9138. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9139. (when (equal c ?q) (user-error "Abort"))
  9140. (if (equal c ?\C-m)
  9141. (setq link links)
  9142. (setq nth (- c ?0))
  9143. (when have-zero (setq nth (1+ nth)))
  9144. (unless (and (integerp nth) (>= (length links) nth))
  9145. (user-error "Invalid link selection"))
  9146. (setq link (nth (1- nth) links)))))
  9147. (cons link end)))))
  9148. ;; TODO: These functions are deprecated since `org-open-at-point'
  9149. ;; hard-codes behavior for "file+emacs" and "file+sys" types.
  9150. (defun org-open-file-with-system (path)
  9151. "Open file at PATH using the system way of opening it."
  9152. (org-open-file path 'system))
  9153. (defun org-open-file-with-emacs (path)
  9154. "Open file at PATH in Emacs."
  9155. (org-open-file path 'emacs))
  9156. ;;; File search
  9157. (defvar org-create-file-search-functions nil
  9158. "List of functions to construct the right search string for a file link.
  9159. These functions are called in turn with point at the location to
  9160. which the link should point.
  9161. A function in the hook should first test if it would like to
  9162. handle this file type, for example by checking the `major-mode'
  9163. or the file extension. If it decides not to handle this file, it
  9164. should just return nil to give other functions a chance. If it
  9165. does handle the file, it must return the search string to be used
  9166. when following the link. The search string will be part of the
  9167. file link, given after a double colon, and `org-open-at-point'
  9168. will automatically search for it. If special measures must be
  9169. taken to make the search successful, another function should be
  9170. added to the companion hook `org-execute-file-search-functions',
  9171. which see.
  9172. A function in this hook may also use `setq' to set the variable
  9173. `description' to provide a suggestion for the descriptive text to
  9174. be used for this link when it gets inserted into an Org buffer
  9175. with \\[org-insert-link].")
  9176. (defvar org-execute-file-search-functions nil
  9177. "List of functions to execute a file search triggered by a link.
  9178. Functions added to this hook must accept a single argument, the
  9179. search string that was part of the file link, the part after the
  9180. double colon. The function must first check if it would like to
  9181. handle this search, for example by checking the `major-mode' or
  9182. the file extension. If it decides not to handle this search, it
  9183. should just return nil to give other functions a chance. If it
  9184. does handle the search, it must return a non-nil value to keep
  9185. other functions from trying.
  9186. Each function can access the current prefix argument through the
  9187. variable `current-prefix-arg'. Note that a single prefix is used
  9188. to force opening a link in Emacs, so it may be good to only use a
  9189. numeric or double prefix to guide the search function.
  9190. In case this is needed, a function in this hook can also restore
  9191. the window configuration before `org-open-at-point' was called using:
  9192. (set-window-configuration org-window-config-before-follow-link)")
  9193. (defun org-search-radio-target (target)
  9194. "Search a radio target matching TARGET in current buffer.
  9195. White spaces are not significant."
  9196. (let ((re (format "<<<%s>>>"
  9197. (mapconcat #'regexp-quote
  9198. (split-string target)
  9199. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9200. (origin (point)))
  9201. (goto-char (point-min))
  9202. (catch :radio-match
  9203. (while (re-search-forward re nil t)
  9204. (backward-char)
  9205. (let ((object (org-element-context)))
  9206. (when (eq (org-element-type object) 'radio-target)
  9207. (goto-char (org-element-property :begin object))
  9208. (org-show-context 'link-search)
  9209. (throw :radio-match nil))))
  9210. (goto-char origin)
  9211. (user-error "No match for radio target: %s" target))))
  9212. (defun org-link-search (s &optional avoid-pos stealth)
  9213. "Search for a search string S.
  9214. If S starts with \"#\", it triggers a custom ID search.
  9215. If S is enclosed within parenthesis, it initiates a coderef
  9216. search.
  9217. If S is surrounded by forward slashes, it is interpreted as
  9218. a regular expression. In Org mode files, this will create an
  9219. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9220. to list matches. If the current buffer is in `dired-mode', grep
  9221. will be used to search in all files.
  9222. When AVOID-POS is given, ignore matches near that position.
  9223. When optional argument STEALTH is non-nil, do not modify
  9224. visibility around point, thus ignoring `org-show-context-detail'
  9225. variable.
  9226. Search is case-insensitive and ignores white spaces. Return type
  9227. of matched result, which is either `dedicated' or `fuzzy'."
  9228. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9229. (let* ((case-fold-search t)
  9230. (origin (point))
  9231. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9232. (starred (eq (string-to-char normalized) ?*))
  9233. (words (split-string (if starred (substring s 1) s)))
  9234. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9235. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9236. type)
  9237. (cond
  9238. ;; Check if there are any special search functions.
  9239. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9240. ((eq (string-to-char s) ?#)
  9241. ;; Look for a custom ID S if S starts with "#".
  9242. (let* ((id (substring normalized 1))
  9243. (match (org-find-property "CUSTOM_ID" id)))
  9244. (if match (progn (goto-char match) (setf type 'dedicated))
  9245. (error "No match for custom ID: %s" id))))
  9246. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9247. ;; Look for coderef targets if S is enclosed within parenthesis.
  9248. (let ((coderef (match-string-no-properties 1 normalized))
  9249. (re (substring s-single-re 1 -1)))
  9250. (goto-char (point-min))
  9251. (catch :coderef-match
  9252. (while (re-search-forward re nil t)
  9253. (let ((element (org-element-at-point)))
  9254. (when (and (memq (org-element-type element)
  9255. '(example-block src-block))
  9256. (org-match-line
  9257. (concat ".*?" (org-src-coderef-regexp
  9258. (org-src-coderef-format element)
  9259. coderef))))
  9260. (setq type 'dedicated)
  9261. (goto-char (match-beginning 2))
  9262. (throw :coderef-match nil))))
  9263. (goto-char origin)
  9264. (error "No match for coderef: %s" coderef))))
  9265. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9266. ;; Look for a regular expression.
  9267. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9268. (match-string 1 s)))
  9269. ;; From here, we handle fuzzy links.
  9270. ;;
  9271. ;; Look for targets, only if not in a headline search.
  9272. ((and (not starred)
  9273. (let ((target (format "<<%s>>" s-multi-re)))
  9274. (catch :target-match
  9275. (goto-char (point-min))
  9276. (while (re-search-forward target nil t)
  9277. (backward-char)
  9278. (let ((context (org-element-context)))
  9279. (when (eq (org-element-type context) 'target)
  9280. (setq type 'dedicated)
  9281. (goto-char (org-element-property :begin context))
  9282. (throw :target-match t))))
  9283. nil))))
  9284. ;; Look for elements named after S, only if not in a headline
  9285. ;; search.
  9286. ((and (not starred)
  9287. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9288. (catch :name-match
  9289. (goto-char (point-min))
  9290. (while (re-search-forward name nil t)
  9291. (let ((element (org-element-at-point)))
  9292. (when (equal words
  9293. (split-string
  9294. (org-element-property :name element)))
  9295. (setq type 'dedicated)
  9296. (beginning-of-line)
  9297. (throw :name-match t))))
  9298. nil))))
  9299. ;; Regular text search. Prefer headlines in Org mode buffers.
  9300. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9301. ;; statistics cookies and tags.
  9302. ((and (derived-mode-p 'org-mode)
  9303. (let ((title-re
  9304. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9305. org-outline-regexp-bol
  9306. org-comment-string
  9307. (mapconcat #'regexp-quote words ".+")))
  9308. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9309. (comment-re (eval-when-compile
  9310. (format "\\`%s[ \t]+" org-comment-string))))
  9311. (goto-char (point-min))
  9312. (catch :found
  9313. (while (re-search-forward title-re nil t)
  9314. (when (equal words
  9315. (split-string
  9316. (replace-regexp-in-string
  9317. cookie-re ""
  9318. (replace-regexp-in-string
  9319. comment-re "" (org-get-heading t t t)))))
  9320. (throw :found t)))
  9321. nil)))
  9322. (beginning-of-line)
  9323. (setq type 'dedicated))
  9324. ;; Offer to create non-existent headline depending on
  9325. ;; `org-link-search-must-match-exact-headline'.
  9326. ((and (derived-mode-p 'org-mode)
  9327. (not org-link-search-inhibit-query)
  9328. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9329. (yes-or-no-p "No match - create this as a new heading? "))
  9330. (goto-char (point-max))
  9331. (unless (bolp) (newline))
  9332. (org-insert-heading nil t t)
  9333. (insert s "\n")
  9334. (beginning-of-line 0))
  9335. ;; Only headlines are looked after. No need to process
  9336. ;; further: throw an error.
  9337. ((and (derived-mode-p 'org-mode)
  9338. (or starred org-link-search-must-match-exact-headline))
  9339. (goto-char origin)
  9340. (error "No match for fuzzy expression: %s" normalized))
  9341. ;; Regular text search.
  9342. ((catch :fuzzy-match
  9343. (goto-char (point-min))
  9344. (while (re-search-forward s-multi-re nil t)
  9345. ;; Skip match if it contains AVOID-POS or it is included in
  9346. ;; a link with a description but outside the description.
  9347. (unless (or (and avoid-pos
  9348. (<= (match-beginning 0) avoid-pos)
  9349. (> (match-end 0) avoid-pos))
  9350. (and (save-match-data
  9351. (org-in-regexp org-bracket-link-regexp))
  9352. (match-beginning 3)
  9353. (or (> (match-beginning 3) (point))
  9354. (<= (match-end 3) (point)))
  9355. (org-element-lineage
  9356. (save-match-data (org-element-context))
  9357. '(link) t)))
  9358. (goto-char (match-beginning 0))
  9359. (setq type 'fuzzy)
  9360. (throw :fuzzy-match t)))
  9361. nil))
  9362. ;; All failed. Throw an error.
  9363. (t (goto-char origin)
  9364. (error "No match for fuzzy expression: %s" normalized)))
  9365. ;; Disclose surroundings of match, if appropriate.
  9366. (when (and (derived-mode-p 'org-mode) (not stealth))
  9367. (org-show-context 'link-search))
  9368. type))
  9369. (defun org-get-buffer-for-internal-link (buffer)
  9370. "Return a buffer to be used for displaying the link target of internal links."
  9371. (cond
  9372. ((not org-display-internal-link-with-indirect-buffer)
  9373. buffer)
  9374. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9375. (message "Buffer is already a clone, not making another one")
  9376. ;; we also do not modify visibility in this case
  9377. buffer)
  9378. (t ; make a new indirect buffer for displaying the link
  9379. (let* ((bn (buffer-name buffer))
  9380. (ibn (concat bn "(Clone)"))
  9381. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9382. (with-current-buffer ib (org-overview))
  9383. ib))))
  9384. (defun org-do-occur (regexp &optional cleanup)
  9385. "Call the Emacs command `occur'.
  9386. If CLEANUP is non-nil, remove the printout of the regular expression
  9387. in the *Occur* buffer. This is useful if the regex is long and not useful
  9388. to read."
  9389. (occur regexp)
  9390. (when cleanup
  9391. (let ((cwin (selected-window)) win beg end)
  9392. (when (setq win (get-buffer-window "*Occur*"))
  9393. (select-window win))
  9394. (goto-char (point-min))
  9395. (when (re-search-forward "match[a-z]+" nil t)
  9396. (setq beg (match-end 0))
  9397. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  9398. (setq end (1- (match-beginning 0)))))
  9399. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  9400. (goto-char (point-min))
  9401. (select-window cwin))))
  9402. ;;; The Mark Ring
  9403. (defvar org-mark-ring nil
  9404. "Mark ring for positions before jumps in Org mode.")
  9405. (defvar org-mark-ring-last-goto nil
  9406. "Last position in the mark ring used to go back.")
  9407. ;; Fill and close the ring
  9408. (setq org-mark-ring nil)
  9409. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  9410. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  9411. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  9412. org-mark-ring)
  9413. (defun org-mark-ring-push (&optional pos buffer)
  9414. "Put the current position into the mark ring and rotate it.
  9415. Also push position into the Emacs mark ring. If optional
  9416. argument POS and BUFFER are not nil, mark this location instead."
  9417. (interactive)
  9418. (let ((pos (or pos (point)))
  9419. (buffer (or buffer (current-buffer))))
  9420. (with-current-buffer buffer
  9421. (org-with-point-at pos (push-mark nil t)))
  9422. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  9423. (move-marker (car org-mark-ring) pos buffer))
  9424. (message
  9425. (substitute-command-keys
  9426. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  9427. (defun org-mark-ring-goto (&optional n)
  9428. "Jump to the previous position in the mark ring.
  9429. With prefix arg N, jump back that many stored positions. When
  9430. called several times in succession, walk through the entire ring.
  9431. Org mode commands jumping to a different position in the current file,
  9432. or to another Org file, automatically push the old position onto the ring."
  9433. (interactive "p")
  9434. (let (p m)
  9435. (if (eq last-command this-command)
  9436. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  9437. (setq p org-mark-ring))
  9438. (setq org-mark-ring-last-goto p)
  9439. (setq m (car p))
  9440. (pop-to-buffer-same-window (marker-buffer m))
  9441. (goto-char m)
  9442. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  9443. (defun org-add-angle-brackets (s)
  9444. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  9445. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  9446. s)
  9447. ;;; Following specific links
  9448. (defvar org-agenda-buffer-tmp-name)
  9449. (defvar org-agenda-start-on-weekday)
  9450. (defun org-follow-timestamp-link ()
  9451. "Open an agenda view for the time-stamp date/range at point."
  9452. (cond
  9453. ((org-at-date-range-p t)
  9454. (let ((org-agenda-start-on-weekday)
  9455. (t1 (match-string 1))
  9456. (t2 (match-string 2)) tt1 tt2)
  9457. (setq tt1 (time-to-days (org-time-string-to-time t1))
  9458. tt2 (time-to-days (org-time-string-to-time t2)))
  9459. (let ((org-agenda-buffer-tmp-name
  9460. (format "*Org Agenda(a:%s)"
  9461. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  9462. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  9463. ((org-at-timestamp-p 'lax)
  9464. (let ((org-agenda-buffer-tmp-name
  9465. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  9466. (org-agenda-list nil (time-to-days (org-time-string-to-time
  9467. (substring (match-string 1) 0 10)))
  9468. 1)))
  9469. (t (error "This should not happen"))))
  9470. ;;; Following file links
  9471. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  9472. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  9473. (declare-function mailcap-mime-info
  9474. "mailcap" (string &optional request no-decode))
  9475. (defvar org-wait nil)
  9476. (defun org-open-file (path &optional in-emacs line search)
  9477. "Open the file at PATH.
  9478. First, this expands any special file name abbreviations. Then the
  9479. configuration variable `org-file-apps' is checked if it contains an
  9480. entry for this file type, and if yes, the corresponding command is launched.
  9481. If no application is found, Emacs simply visits the file.
  9482. With optional prefix argument IN-EMACS, Emacs will visit the file.
  9483. With a double \\[universal-argument] \\[universal-argument] \
  9484. prefix arg, Org tries to avoid opening in Emacs
  9485. and to use an external application to visit the file.
  9486. Optional LINE specifies a line to go to, optional SEARCH a string
  9487. to search for. If LINE or SEARCH is given, the file will be
  9488. opened in Emacs, unless an entry from org-file-apps that makes
  9489. use of groups in a regexp matches.
  9490. If you want to change the way frames are used when following a
  9491. link, please customize `org-link-frame-setup'.
  9492. If the file does not exist, an error is thrown."
  9493. (let* ((file (if (equal path "")
  9494. buffer-file-name
  9495. (substitute-in-file-name (expand-file-name path))))
  9496. (file-apps (append org-file-apps (org-default-apps)))
  9497. (apps (cl-remove-if
  9498. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9499. (apps-dlink (cl-remove-if-not
  9500. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9501. (remp (and (assq 'remote apps) (file-remote-p file)))
  9502. (dirp (unless remp (file-directory-p file)))
  9503. (file (if (and dirp org-open-directory-means-index-dot-org)
  9504. (concat (file-name-as-directory file) "index.org")
  9505. file))
  9506. (a-m-a-p (assq 'auto-mode apps))
  9507. (dfile (downcase file))
  9508. ;; Reconstruct the original link from the PATH, LINE and
  9509. ;; SEARCH args.
  9510. (link (cond (line (concat file "::" (number-to-string line)))
  9511. (search (concat file "::" search))
  9512. (t file)))
  9513. (dlink (downcase link))
  9514. (ext
  9515. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  9516. (match-string 1 dfile)))
  9517. (save-position-maybe
  9518. (let ((old-buffer (current-buffer))
  9519. (old-pos (point))
  9520. (old-mode major-mode))
  9521. (lambda ()
  9522. (and (derived-mode-p 'org-mode)
  9523. (eq old-mode 'org-mode)
  9524. (or (not (eq old-buffer (current-buffer)))
  9525. (not (eq old-pos (point))))
  9526. (org-mark-ring-push old-pos old-buffer)))))
  9527. cmd link-match-data)
  9528. (cond
  9529. ((member in-emacs '((16) system))
  9530. (setq cmd (cdr (assq 'system apps))))
  9531. (in-emacs (setq cmd 'emacs))
  9532. (t
  9533. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  9534. (and dirp (cdr (assq 'directory apps)))
  9535. ;; First, try matching against apps-dlink if we
  9536. ;; get a match here, store the match data for
  9537. ;; later.
  9538. (let ((match (assoc-default dlink apps-dlink
  9539. 'string-match)))
  9540. (if match
  9541. (progn (setq link-match-data (match-data))
  9542. match)
  9543. (progn (setq in-emacs (or in-emacs line search))
  9544. nil))) ; if we have no match in apps-dlink,
  9545. ; always open the file in emacs if line or search
  9546. ; is given (for backwards compatibility)
  9547. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  9548. 'string-match)
  9549. (cdr (assoc ext apps))
  9550. (cdr (assq t apps))))))
  9551. (when (eq cmd 'system)
  9552. (setq cmd (cdr (assq 'system apps))))
  9553. (when (eq cmd 'default)
  9554. (setq cmd (cdr (assoc t apps))))
  9555. (when (eq cmd 'mailcap)
  9556. (require 'mailcap)
  9557. (mailcap-parse-mailcaps)
  9558. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  9559. (command (mailcap-mime-info mime-type)))
  9560. (if (stringp command)
  9561. (setq cmd command)
  9562. (setq cmd 'emacs))))
  9563. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  9564. (not (file-exists-p file))
  9565. (not org-open-non-existing-files))
  9566. (user-error "No such file: %s" file))
  9567. (cond
  9568. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  9569. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  9570. (while (string-match "['\"]%s['\"]" cmd)
  9571. (setq cmd (replace-match "%s" t t cmd)))
  9572. (setq cmd (replace-regexp-in-string
  9573. "%s"
  9574. (shell-quote-argument (convert-standard-filename file))
  9575. cmd
  9576. nil t))
  9577. ;; Replace "%1", "%2" etc. in command with group matches from regex
  9578. (save-match-data
  9579. (let ((match-index 1)
  9580. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  9581. (set-match-data link-match-data)
  9582. (while (<= match-index number-of-groups)
  9583. (let ((regex (concat "%" (number-to-string match-index)))
  9584. (replace-with (match-string match-index dlink)))
  9585. (while (string-match regex cmd)
  9586. (setq cmd (replace-match replace-with t t cmd))))
  9587. (setq match-index (+ match-index 1)))))
  9588. (save-window-excursion
  9589. (message "Running %s...done" cmd)
  9590. (start-process-shell-command cmd nil cmd)
  9591. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  9592. ((or (stringp cmd)
  9593. (eq cmd 'emacs))
  9594. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  9595. (widen)
  9596. (cond (line (org-goto-line line)
  9597. (when (derived-mode-p 'org-mode) (org-reveal)))
  9598. (search (condition-case err
  9599. (org-link-search search)
  9600. ;; Save position before error-ing out so user
  9601. ;; can easily move back to the original buffer.
  9602. (error (funcall save-position-maybe)
  9603. (error (nth 1 err)))))))
  9604. ((functionp cmd)
  9605. (save-match-data
  9606. (set-match-data link-match-data)
  9607. (condition-case nil
  9608. (funcall cmd file link)
  9609. ;; FIXME: Remove this check when most default installations
  9610. ;; of Emacs have at least Org 9.0.
  9611. ((debug wrong-number-of-arguments wrong-type-argument
  9612. invalid-function)
  9613. (user-error "Please see Org News for version 9.0 about \
  9614. `org-file-apps'--Lisp error: %S" cmd)))))
  9615. ((consp cmd)
  9616. ;; FIXME: Remove this check when most default installations of
  9617. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  9618. ;; fall back to `org-link-frame-setup' for an old usage of
  9619. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  9620. (user-error "Please see Org News for version 9.0 about \
  9621. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  9622. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  9623. (funcall save-position-maybe)))
  9624. (defun org-file-apps-entry-match-against-dlink-p (entry)
  9625. "This function returns non-nil if `entry' uses a regular
  9626. expression which should be matched against the whole link by
  9627. org-open-file.
  9628. It assumes that is the case when the entry uses a regular
  9629. expression which has at least one grouping construct and the
  9630. action is either a lisp form or a command string containing
  9631. `%1', i.e. using at least one subexpression match as a
  9632. parameter."
  9633. (let ((selector (car entry))
  9634. (action (cdr entry)))
  9635. (if (stringp selector)
  9636. (and (> (regexp-opt-depth selector) 0)
  9637. (or (and (stringp action)
  9638. (string-match "%[0-9]" action))
  9639. (consp action)))
  9640. nil)))
  9641. (defun org-default-apps ()
  9642. "Return the default applications for this operating system."
  9643. (cond
  9644. ((eq system-type 'darwin)
  9645. org-file-apps-defaults-macosx)
  9646. ((eq system-type 'windows-nt)
  9647. org-file-apps-defaults-windowsnt)
  9648. (t org-file-apps-defaults-gnu)))
  9649. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  9650. "Convert extensions to regular expressions in the cars of LIST.
  9651. Also, weed out any non-string entries, because the return value is used
  9652. only for regexp matching.
  9653. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  9654. point to the symbol `emacs', indicating that the file should
  9655. be opened in Emacs."
  9656. (append
  9657. (delq nil
  9658. (mapcar (lambda (x)
  9659. (unless (not (stringp (car x)))
  9660. (if (string-match "\\W" (car x))
  9661. x
  9662. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  9663. list))
  9664. (when add-auto-mode
  9665. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  9666. ;;;; Refiling
  9667. (defun org-get-org-file ()
  9668. "Read a filename, with default directory `org-directory'."
  9669. (let ((default (or org-default-notes-file remember-data-file)))
  9670. (read-file-name (format "File name [%s]: " default)
  9671. (file-name-as-directory org-directory)
  9672. default)))
  9673. (defun org-notes-order-reversed-p ()
  9674. "Check if the current file should receive notes in reversed order."
  9675. (cond
  9676. ((not org-reverse-note-order) nil)
  9677. ((eq t org-reverse-note-order) t)
  9678. ((not (listp org-reverse-note-order)) nil)
  9679. (t (catch 'exit
  9680. (dolist (entry org-reverse-note-order)
  9681. (when (string-match (car entry) buffer-file-name)
  9682. (throw 'exit (cdr entry))))))))
  9683. (defvar org-refile-target-table nil
  9684. "The list of refile targets, created by `org-refile'.")
  9685. (defvar org-agenda-new-buffers nil
  9686. "Buffers created to visit agenda files.")
  9687. (defvar org-refile-cache nil
  9688. "Cache for refile targets.")
  9689. (defvar org-refile-markers nil
  9690. "All the markers used for caching refile locations.")
  9691. (defun org-refile-marker (pos)
  9692. "Get a new refile marker, but only if caching is in use."
  9693. (if (not org-refile-use-cache)
  9694. pos
  9695. (let ((m (make-marker)))
  9696. (move-marker m pos)
  9697. (push m org-refile-markers)
  9698. m)))
  9699. (defun org-refile-cache-clear ()
  9700. "Clear the refile cache and disable all the markers."
  9701. (dolist (m org-refile-markers) (move-marker m nil))
  9702. (setq org-refile-markers nil)
  9703. (setq org-refile-cache nil)
  9704. (message "Refile cache has been cleared"))
  9705. (defun org-refile-cache-check-set (set)
  9706. "Check if all the markers in the cache still have live buffers."
  9707. (let (marker)
  9708. (catch 'exit
  9709. (while (and set (setq marker (nth 3 (pop set))))
  9710. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  9711. (when (and marker (null (marker-buffer marker)))
  9712. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  9713. (sit-for 3)
  9714. (throw 'exit nil)))
  9715. t)))
  9716. (defun org-refile-cache-put (set &rest identifiers)
  9717. "Push the refile targets SET into the cache, under IDENTIFIERS."
  9718. (let* ((key (sha1 (prin1-to-string identifiers)))
  9719. (entry (assoc key org-refile-cache)))
  9720. (if entry
  9721. (setcdr entry set)
  9722. (push (cons key set) org-refile-cache))))
  9723. (defun org-refile-cache-get (&rest identifiers)
  9724. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  9725. (cond
  9726. ((not org-refile-cache) nil)
  9727. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  9728. (t
  9729. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  9730. org-refile-cache))))
  9731. (and set (org-refile-cache-check-set set) set)))))
  9732. (defvar org-outline-path-cache nil
  9733. "Alist between buffer positions and outline paths.
  9734. It value is an alist (POSITION . PATH) where POSITION is the
  9735. buffer position at the beginning of an entry and PATH is a list
  9736. of strings describing the outline path for that entry, in reverse
  9737. order.")
  9738. (defun org-refile-get-targets (&optional default-buffer)
  9739. "Produce a table with refile targets."
  9740. (let ((case-fold-search nil)
  9741. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  9742. (entries (or org-refile-targets '((nil . (:level . 1)))))
  9743. targets tgs files desc descre)
  9744. (message "Getting targets...")
  9745. (with-current-buffer (or default-buffer (current-buffer))
  9746. (dolist (entry entries)
  9747. (setq files (car entry) desc (cdr entry))
  9748. (cond
  9749. ((null files) (setq files (list (current-buffer))))
  9750. ((eq files 'org-agenda-files)
  9751. (setq files (org-agenda-files 'unrestricted)))
  9752. ((and (symbolp files) (fboundp files))
  9753. (setq files (funcall files)))
  9754. ((and (symbolp files) (boundp files))
  9755. (setq files (symbol-value files))))
  9756. (when (stringp files) (setq files (list files)))
  9757. (cond
  9758. ((eq (car desc) :tag)
  9759. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  9760. ((eq (car desc) :todo)
  9761. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  9762. ((eq (car desc) :regexp)
  9763. (setq descre (cdr desc)))
  9764. ((eq (car desc) :level)
  9765. (setq descre (concat "^\\*\\{" (number-to-string
  9766. (if org-odd-levels-only
  9767. (1- (* 2 (cdr desc)))
  9768. (cdr desc)))
  9769. "\\}[ \t]")))
  9770. ((eq (car desc) :maxlevel)
  9771. (setq descre (concat "^\\*\\{1," (number-to-string
  9772. (if org-odd-levels-only
  9773. (1- (* 2 (cdr desc)))
  9774. (cdr desc)))
  9775. "\\}[ \t]")))
  9776. (t (error "Bad refiling target description %s" desc)))
  9777. (dolist (f files)
  9778. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  9779. (or
  9780. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  9781. (progn
  9782. (when (bufferp f)
  9783. (setq f (buffer-file-name (buffer-base-buffer f))))
  9784. (setq f (and f (expand-file-name f)))
  9785. (when (eq org-refile-use-outline-path 'file)
  9786. (push (list (file-name-nondirectory f) f nil nil) tgs))
  9787. (when (eq org-refile-use-outline-path 'buffer-name)
  9788. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  9789. (when (eq org-refile-use-outline-path 'full-file-path)
  9790. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  9791. (org-with-wide-buffer
  9792. (goto-char (point-min))
  9793. (setq org-outline-path-cache nil)
  9794. (while (re-search-forward descre nil t)
  9795. (beginning-of-line)
  9796. (let ((case-fold-search nil))
  9797. (looking-at org-complex-heading-regexp))
  9798. (let ((begin (point))
  9799. (heading (match-string-no-properties 4)))
  9800. (unless (or (and
  9801. org-refile-target-verify-function
  9802. (not
  9803. (funcall org-refile-target-verify-function)))
  9804. (not heading))
  9805. (let ((re (format org-complex-heading-regexp-format
  9806. (regexp-quote heading)))
  9807. (target
  9808. (if (not org-refile-use-outline-path) heading
  9809. (mapconcat
  9810. #'identity
  9811. (append
  9812. (pcase org-refile-use-outline-path
  9813. (`file (list (file-name-nondirectory
  9814. (buffer-file-name
  9815. (buffer-base-buffer)))))
  9816. (`full-file-path
  9817. (list (buffer-file-name
  9818. (buffer-base-buffer))))
  9819. (`buffer-name
  9820. (list (buffer-name
  9821. (buffer-base-buffer))))
  9822. (_ nil))
  9823. (mapcar (lambda (s) (replace-regexp-in-string
  9824. "/" "\\/" s nil t))
  9825. (org-get-outline-path t t)))
  9826. "/"))))
  9827. (push (list target f re (org-refile-marker (point)))
  9828. tgs)))
  9829. (when (= (point) begin)
  9830. ;; Verification function has not moved point.
  9831. (end-of-line)))))))
  9832. (when org-refile-use-cache
  9833. (org-refile-cache-put tgs (buffer-file-name) descre))
  9834. (setq targets (append tgs targets))))))
  9835. (message "Getting targets...done")
  9836. (delete-dups (nreverse targets))))
  9837. (defun org--get-outline-path-1 (&optional use-cache)
  9838. "Return outline path to current headline.
  9839. Outline path is a list of strings, in reverse order. When
  9840. optional argument USE-CACHE is non-nil, make use of a cache. See
  9841. `org-get-outline-path' for details.
  9842. Assume buffer is widened and point is on a headline."
  9843. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  9844. (let ((p (point))
  9845. (heading (let ((case-fold-search nil))
  9846. (looking-at org-complex-heading-regexp)
  9847. (if (not (match-end 4)) ""
  9848. ;; Remove statistics cookies.
  9849. (org-trim
  9850. (org-link-display-format
  9851. (replace-regexp-in-string
  9852. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  9853. (match-string-no-properties 4))))))))
  9854. (if (org-up-heading-safe)
  9855. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  9856. (when use-cache
  9857. (push (cons p path) org-outline-path-cache))
  9858. path)
  9859. ;; This is a new root node. Since we assume we are moving
  9860. ;; forward, we can drop previous cache so as to limit number
  9861. ;; of associations there.
  9862. (let ((path (list heading)))
  9863. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  9864. path)))))
  9865. (defun org-get-outline-path (&optional with-self use-cache)
  9866. "Return the outline path to the current entry.
  9867. An outline path is a list of ancestors for current headline, as
  9868. a list of strings. Statistics cookies are removed and links are
  9869. replaced with their description, if any, or their path otherwise.
  9870. When optional argument WITH-SELF is non-nil, the path also
  9871. includes the current headline.
  9872. When optional argument USE-CACHE is non-nil, cache outline paths
  9873. between calls to this function so as to avoid backtracking. This
  9874. argument is useful when planning to find more than one outline
  9875. path in the same document. In that case, there are two
  9876. conditions to satisfy:
  9877. - `org-outline-path-cache' is set to nil before starting the
  9878. process;
  9879. - outline paths are computed by increasing buffer positions."
  9880. (org-with-wide-buffer
  9881. (and (or (and with-self (org-back-to-heading t))
  9882. (org-up-heading-safe))
  9883. (reverse (org--get-outline-path-1 use-cache)))))
  9884. (defun org-format-outline-path (path &optional width prefix separator)
  9885. "Format the outline path PATH for display.
  9886. WIDTH is the maximum number of characters that is available.
  9887. PREFIX is a prefix to be included in the returned string,
  9888. such as the file name.
  9889. SEPARATOR is inserted between the different parts of the path,
  9890. the default is \"/\"."
  9891. (setq width (or width 79))
  9892. (setq path (delq nil path))
  9893. (unless (> width 0)
  9894. (user-error "Argument `width' must be positive"))
  9895. (setq separator (or separator "/"))
  9896. (let* ((org-odd-levels-only nil)
  9897. (fpath (concat
  9898. prefix (and prefix path separator)
  9899. (mapconcat
  9900. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  9901. (cl-loop for head in path
  9902. for n from 0
  9903. collect (org-add-props
  9904. head nil 'face
  9905. (nth (% n org-n-level-faces) org-level-faces)))
  9906. separator))))
  9907. (when (> (length fpath) width)
  9908. (if (< width 7)
  9909. ;; It's unlikely that `width' will be this small, but don't
  9910. ;; waste characters by adding ".." if it is.
  9911. (setq fpath (substring fpath 0 width))
  9912. (setf (substring fpath (- width 2)) "..")))
  9913. fpath))
  9914. (defun org-display-outline-path (&optional file current separator just-return-string)
  9915. "Display the current outline path in the echo area.
  9916. If FILE is non-nil, prepend the output with the file name.
  9917. If CURRENT is non-nil, append the current heading to the output.
  9918. SEPARATOR is passed through to `org-format-outline-path'. It separates
  9919. the different parts of the path and defaults to \"/\".
  9920. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  9921. (interactive "P")
  9922. (let* (case-fold-search
  9923. (bfn (buffer-file-name (buffer-base-buffer)))
  9924. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  9925. res)
  9926. (when current (setq path (append path
  9927. (save-excursion
  9928. (org-back-to-heading t)
  9929. (when (looking-at org-complex-heading-regexp)
  9930. (list (match-string 4)))))))
  9931. (setq res
  9932. (org-format-outline-path
  9933. path
  9934. (1- (frame-width))
  9935. (and file bfn (concat (file-name-nondirectory bfn) separator))
  9936. separator))
  9937. (if just-return-string
  9938. (org-no-properties res)
  9939. (org-unlogged-message "%s" res))))
  9940. (defvar org-refile-history nil
  9941. "History for refiling operations.")
  9942. (defvar org-after-refile-insert-hook nil
  9943. "Hook run after `org-refile' has inserted its stuff at the new location.
  9944. Note that this is still *before* the stuff will be removed from
  9945. the *old* location.")
  9946. (defvar org-capture-last-stored-marker)
  9947. (defvar org-refile-keep nil
  9948. "Non-nil means `org-refile' will copy instead of refile.")
  9949. (defun org-copy ()
  9950. "Like `org-refile', but copy."
  9951. (interactive)
  9952. (let ((org-refile-keep t))
  9953. (org-refile nil nil nil "Copy")))
  9954. (defun org-refile (&optional arg default-buffer rfloc msg)
  9955. "Move the entry or entries at point to another heading.
  9956. The list of target headings is compiled using the information in
  9957. `org-refile-targets', which see.
  9958. At the target location, the entry is filed as a subitem of the
  9959. target heading. Depending on `org-reverse-note-order', the new
  9960. subitem will either be the first or the last subitem.
  9961. If there is an active region, all entries in that region will be
  9962. refiled. However, the region must fulfill the requirement that
  9963. the first heading sets the top-level of the moved text.
  9964. With a `\\[universal-argument]' ARG, the command will only visit the target \
  9965. location
  9966. and not actually move anything.
  9967. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  9968. location where the last
  9969. refiling operation has put the subtree.
  9970. With a numeric prefix argument of `2', refile to the running clock.
  9971. With a numeric prefix argument of `3', emulate `org-refile-keep'
  9972. being set to t and copy to the target location, don't move it.
  9973. Beware that keeping refiled entries may result in duplicated ID
  9974. properties.
  9975. RFLOC can be a refile location obtained in a different way.
  9976. MSG is a string to replace \"Refile\" in the default prompt with
  9977. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  9978. See also `org-refile-use-outline-path'.
  9979. If you are using target caching (see `org-refile-use-cache'), you
  9980. have to clear the target cache in order to find new targets.
  9981. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  9982. prefix argument (`C-u C-u C-u C-c C-w')."
  9983. (interactive "P")
  9984. (if (member arg '(0 (64)))
  9985. (org-refile-cache-clear)
  9986. (let* ((actionmsg (cond (msg msg)
  9987. ((equal arg 3) "Refile (and keep)")
  9988. (t "Refile")))
  9989. (regionp (org-region-active-p))
  9990. (region-start (and regionp (region-beginning)))
  9991. (region-end (and regionp (region-end)))
  9992. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  9993. pos it nbuf file level reversed)
  9994. (setq last-command nil)
  9995. (when regionp
  9996. (goto-char region-start)
  9997. (or (bolp) (goto-char (point-at-bol)))
  9998. (setq region-start (point))
  9999. (unless (or (org-kill-is-subtree-p
  10000. (buffer-substring region-start region-end))
  10001. (prog1 org-refile-active-region-within-subtree
  10002. (let ((s (point-at-eol)))
  10003. (org-toggle-heading)
  10004. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10005. (user-error "The region is not a (sequence of) subtree(s)")))
  10006. (if (equal arg '(16))
  10007. (org-refile-goto-last-stored)
  10008. (when (or
  10009. (and (equal arg 2)
  10010. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10011. (prog1
  10012. (setq it (list (or org-clock-heading "running clock")
  10013. (buffer-file-name
  10014. (marker-buffer org-clock-hd-marker))
  10015. ""
  10016. (marker-position org-clock-hd-marker)))
  10017. (setq arg nil)))
  10018. (setq it
  10019. (or rfloc
  10020. (let (heading-text)
  10021. (save-excursion
  10022. (unless (and arg (listp arg))
  10023. (org-back-to-heading t)
  10024. (setq heading-text
  10025. (replace-regexp-in-string
  10026. org-bracket-link-regexp
  10027. "\\3"
  10028. (or (nth 4 (org-heading-components))
  10029. ""))))
  10030. (org-refile-get-location
  10031. (cond ((and arg (listp arg)) "Goto")
  10032. (regionp (concat actionmsg " region to"))
  10033. (t (concat actionmsg " subtree \""
  10034. heading-text "\" to")))
  10035. default-buffer
  10036. (and (not (equal '(4) arg))
  10037. org-refile-allow-creating-parent-nodes)))))))
  10038. (setq file (nth 1 it)
  10039. pos (nth 3 it))
  10040. (when (and (not arg)
  10041. pos
  10042. (equal (buffer-file-name) file)
  10043. (if regionp
  10044. (and (>= pos region-start)
  10045. (<= pos region-end))
  10046. (and (>= pos (point))
  10047. (< pos (save-excursion
  10048. (org-end-of-subtree t t))))))
  10049. (error "Cannot refile to position inside the tree or region"))
  10050. (setq nbuf (or (find-buffer-visiting file)
  10051. (find-file-noselect file)))
  10052. (if (and arg (not (equal arg 3)))
  10053. (progn
  10054. (pop-to-buffer-same-window nbuf)
  10055. (goto-char (cond (pos)
  10056. ((org-notes-order-reversed-p) (point-min))
  10057. (t (point-max))))
  10058. (org-show-context 'org-goto))
  10059. (if regionp
  10060. (progn
  10061. (org-kill-new (buffer-substring region-start region-end))
  10062. (org-save-markers-in-region region-start region-end))
  10063. (org-copy-subtree 1 nil t))
  10064. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10065. (find-file-noselect file)))
  10066. (setq reversed (org-notes-order-reversed-p))
  10067. (org-with-wide-buffer
  10068. (if pos
  10069. (progn
  10070. (goto-char pos)
  10071. (setq level (org-get-valid-level (funcall outline-level) 1))
  10072. (goto-char
  10073. (if reversed
  10074. (or (outline-next-heading) (point-max))
  10075. (or (save-excursion (org-get-next-sibling))
  10076. (org-end-of-subtree t t)
  10077. (point-max)))))
  10078. (setq level 1)
  10079. (if (not reversed)
  10080. (goto-char (point-max))
  10081. (goto-char (point-min))
  10082. (or (outline-next-heading) (goto-char (point-max)))))
  10083. (unless (bolp) (newline))
  10084. (org-paste-subtree level nil nil t)
  10085. (when org-log-refile
  10086. (org-add-log-setup 'refile nil nil org-log-refile)
  10087. (unless (eq org-log-refile 'note)
  10088. (save-excursion (org-add-log-note))))
  10089. (and org-auto-align-tags
  10090. (let ((org-loop-over-headlines-in-active-region nil))
  10091. (org-align-tags)))
  10092. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10093. :last-refile)))
  10094. (when bookmark-name
  10095. (with-demoted-errors
  10096. (bookmark-set bookmark-name))))
  10097. ;; If we are refiling for capture, make sure that the
  10098. ;; last-capture pointers point here
  10099. (when (bound-and-true-p org-capture-is-refiling)
  10100. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10101. :last-capture-marker)))
  10102. (when bookmark-name
  10103. (with-demoted-errors
  10104. (bookmark-set bookmark-name))))
  10105. (move-marker org-capture-last-stored-marker (point)))
  10106. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10107. (run-hooks 'org-after-refile-insert-hook)))
  10108. (unless org-refile-keep
  10109. (if regionp
  10110. (delete-region (point) (+ (point) (- region-end region-start)))
  10111. (org-preserve-local-variables
  10112. (delete-region
  10113. (and (org-back-to-heading t) (point))
  10114. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
  10115. (when (featurep 'org-inlinetask)
  10116. (org-inlinetask-remove-END-maybe))
  10117. (setq org-markers-to-move nil)
  10118. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10119. (defun org-refile-goto-last-stored ()
  10120. "Go to the location where the last refile was stored."
  10121. (interactive)
  10122. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10123. (message "This is the location of the last refile"))
  10124. (defun org-refile--get-location (refloc tbl)
  10125. "When user refile to REFLOC, find the associated target in TBL.
  10126. Also check `org-refile-target-table'."
  10127. (car (delq
  10128. nil
  10129. (mapcar
  10130. (lambda (r) (or (assoc r tbl)
  10131. (assoc r org-refile-target-table)))
  10132. (list (replace-regexp-in-string "/$" "" refloc)
  10133. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10134. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10135. "Prompt the user for a refile location, using PROMPT.
  10136. PROMPT should not be suffixed with a colon and a space, because
  10137. this function appends the default value from
  10138. `org-refile-history' automatically, if that is not empty."
  10139. (let ((org-refile-targets org-refile-targets)
  10140. (org-refile-use-outline-path org-refile-use-outline-path))
  10141. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10142. (unless org-refile-target-table
  10143. (user-error "No refile targets"))
  10144. (let* ((cbuf (current-buffer))
  10145. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10146. (cfunc (if (and org-refile-use-outline-path
  10147. org-outline-path-complete-in-steps)
  10148. #'org-olpath-completing-read
  10149. #'completing-read))
  10150. (extra (if org-refile-use-outline-path "/" ""))
  10151. (cbnex (concat (buffer-name) extra))
  10152. (filename (and cfn (expand-file-name cfn)))
  10153. (tbl (mapcar
  10154. (lambda (x)
  10155. (if (and (not (member org-refile-use-outline-path
  10156. '(file full-file-path)))
  10157. (not (equal filename (nth 1 x))))
  10158. (cons (concat (car x) extra " ("
  10159. (file-name-nondirectory (nth 1 x)) ")")
  10160. (cdr x))
  10161. (cons (concat (car x) extra) (cdr x))))
  10162. org-refile-target-table))
  10163. (completion-ignore-case t)
  10164. cdef
  10165. (prompt (concat prompt
  10166. (or (and (car org-refile-history)
  10167. (concat " (default " (car org-refile-history) ")"))
  10168. (and (assoc cbnex tbl) (setq cdef cbnex)
  10169. (concat " (default " cbnex ")"))) ": "))
  10170. pa answ parent-target child parent old-hist)
  10171. (setq old-hist org-refile-history)
  10172. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10173. nil 'org-refile-history (or cdef (car org-refile-history))))
  10174. (if (setq pa (org-refile--get-location answ tbl))
  10175. (progn
  10176. (org-refile-check-position pa)
  10177. (when (or (not org-refile-history)
  10178. (not (eq old-hist org-refile-history))
  10179. (not (equal (car pa) (car org-refile-history))))
  10180. (setq org-refile-history
  10181. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10182. org-refile-history
  10183. (cdr org-refile-history))))
  10184. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10185. (pop org-refile-history)))
  10186. pa)
  10187. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10188. (progn
  10189. (setq parent (match-string 1 answ)
  10190. child (match-string 2 answ))
  10191. (setq parent-target (org-refile--get-location parent tbl))
  10192. (when (and parent-target
  10193. (or (eq new-nodes t)
  10194. (and (eq new-nodes 'confirm)
  10195. (y-or-n-p (format "Create new node \"%s\"? "
  10196. child)))))
  10197. (org-refile-new-child parent-target child)))
  10198. (user-error "Invalid target location")))))
  10199. (declare-function org-string-nw-p "org-macs" (s))
  10200. (defun org-refile-check-position (refile-pointer)
  10201. "Check if the refile pointer matches the headline to which it points."
  10202. (let* ((file (nth 1 refile-pointer))
  10203. (re (nth 2 refile-pointer))
  10204. (pos (nth 3 refile-pointer))
  10205. buffer)
  10206. (if (and (not (markerp pos)) (not file))
  10207. (user-error "Please indicate a target file in the refile path")
  10208. (when (org-string-nw-p re)
  10209. (setq buffer (if (markerp pos)
  10210. (marker-buffer pos)
  10211. (or (find-buffer-visiting file)
  10212. (find-file-noselect file))))
  10213. (with-current-buffer buffer
  10214. (org-with-wide-buffer
  10215. (goto-char pos)
  10216. (beginning-of-line 1)
  10217. (unless (looking-at-p re)
  10218. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10219. (defun org-refile-new-child (parent-target child)
  10220. "Use refile target PARENT-TARGET to add new CHILD below it."
  10221. (unless parent-target
  10222. (error "Cannot find parent for new node"))
  10223. (let ((file (nth 1 parent-target))
  10224. (pos (nth 3 parent-target))
  10225. level)
  10226. (with-current-buffer (or (find-buffer-visiting file)
  10227. (find-file-noselect file))
  10228. (org-with-wide-buffer
  10229. (if pos
  10230. (goto-char pos)
  10231. (goto-char (point-max))
  10232. (unless (bolp) (newline)))
  10233. (when (looking-at org-outline-regexp)
  10234. (setq level (funcall outline-level))
  10235. (org-end-of-subtree t t))
  10236. (org-back-over-empty-lines)
  10237. (insert "\n" (make-string
  10238. (if pos (org-get-valid-level level 1) 1) ?*)
  10239. " " child "\n")
  10240. (beginning-of-line 0)
  10241. (list (concat (car parent-target) "/" child) file "" (point))))))
  10242. (defun org-olpath-completing-read (prompt collection &rest args)
  10243. "Read an outline path like a file name."
  10244. (let ((thetable collection))
  10245. (apply #'completing-read
  10246. prompt
  10247. (lambda (string predicate &optional flag)
  10248. (cond
  10249. ((eq flag nil) (try-completion string thetable))
  10250. ((eq flag t)
  10251. (let ((l (length string)))
  10252. (mapcar (lambda (x)
  10253. (let ((r (substring x l))
  10254. (f (if (string-match " ([^)]*)$" x)
  10255. (match-string 0 x)
  10256. "")))
  10257. (if (string-match "/" r)
  10258. (concat string (substring r 0 (match-end 0)) f)
  10259. x)))
  10260. (all-completions string thetable predicate))))
  10261. ;; Exact match?
  10262. ((eq flag 'lambda) (assoc string thetable))))
  10263. args)))
  10264. ;;;; Dynamic blocks
  10265. (defun org-find-dblock (name)
  10266. "Find the first dynamic block with name NAME in the buffer.
  10267. If not found, stay at current position and return nil."
  10268. (let ((case-fold-search t) pos)
  10269. (save-excursion
  10270. (goto-char (point-min))
  10271. (setq pos (and (re-search-forward
  10272. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10273. (match-beginning 0))))
  10274. (when pos (goto-char pos))
  10275. pos))
  10276. (defun org-create-dblock (plist)
  10277. "Create a dynamic block section, with parameters taken from PLIST.
  10278. PLIST must contain a :name entry which is used as the name of the block."
  10279. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10280. (end-of-line 1)
  10281. (newline))
  10282. (let ((col (current-column))
  10283. (name (plist-get plist :name)))
  10284. (insert "#+BEGIN: " name)
  10285. (while plist
  10286. (if (eq (car plist) :name)
  10287. (setq plist (cddr plist))
  10288. (insert " " (prin1-to-string (pop plist)))))
  10289. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10290. (beginning-of-line -2)))
  10291. (defun org-prepare-dblock ()
  10292. "Prepare dynamic block for refresh.
  10293. This empties the block, puts the cursor at the insert position and returns
  10294. the property list including an extra property :name with the block name."
  10295. (unless (looking-at org-dblock-start-re)
  10296. (user-error "Not at a dynamic block"))
  10297. (let* ((begdel (1+ (match-end 0)))
  10298. (name (org-no-properties (match-string 1)))
  10299. (params (append (list :name name)
  10300. (read (concat "(" (match-string 3) ")")))))
  10301. (save-excursion
  10302. (beginning-of-line 1)
  10303. (skip-chars-forward " \t")
  10304. (setq params (plist-put params :indentation-column (current-column))))
  10305. (unless (re-search-forward org-dblock-end-re nil t)
  10306. (error "Dynamic block not terminated"))
  10307. (setq params
  10308. (append params
  10309. (list :content (buffer-substring
  10310. begdel (match-beginning 0)))))
  10311. (delete-region begdel (match-beginning 0))
  10312. (goto-char begdel)
  10313. (open-line 1)
  10314. params))
  10315. (defun org-map-dblocks (&optional command)
  10316. "Apply COMMAND to all dynamic blocks in the current buffer.
  10317. If COMMAND is not given, use `org-update-dblock'."
  10318. (let ((cmd (or command 'org-update-dblock)))
  10319. (save-excursion
  10320. (goto-char (point-min))
  10321. (while (re-search-forward org-dblock-start-re nil t)
  10322. (goto-char (match-beginning 0))
  10323. (save-excursion
  10324. (condition-case nil
  10325. (funcall cmd)
  10326. (error (message "Error during update of dynamic block"))))
  10327. (unless (re-search-forward org-dblock-end-re nil t)
  10328. (error "Dynamic block not terminated"))))))
  10329. (defun org-dblock-update (&optional arg)
  10330. "User command for updating dynamic blocks.
  10331. Update the dynamic block at point. With prefix ARG, update all dynamic
  10332. blocks in the buffer."
  10333. (interactive "P")
  10334. (if arg
  10335. (org-update-all-dblocks)
  10336. (or (looking-at org-dblock-start-re)
  10337. (org-beginning-of-dblock))
  10338. (org-update-dblock)))
  10339. (defun org-update-dblock ()
  10340. "Update the dynamic block at point.
  10341. This means to empty the block, parse for parameters and then call
  10342. the correct writing function."
  10343. (interactive)
  10344. (save-excursion
  10345. (let* ((win (selected-window))
  10346. (pos (point))
  10347. (line (org-current-line))
  10348. (params (org-prepare-dblock))
  10349. (name (plist-get params :name))
  10350. (indent (plist-get params :indentation-column))
  10351. (cmd (intern (concat "org-dblock-write:" name))))
  10352. (message "Updating dynamic block `%s' at line %d..." name line)
  10353. (funcall cmd params)
  10354. (message "Updating dynamic block `%s' at line %d...done" name line)
  10355. (goto-char pos)
  10356. (when (and indent (> indent 0))
  10357. (setq indent (make-string indent ?\ ))
  10358. (save-excursion
  10359. (select-window win)
  10360. (org-beginning-of-dblock)
  10361. (forward-line 1)
  10362. (while (not (looking-at org-dblock-end-re))
  10363. (insert indent)
  10364. (beginning-of-line 2))
  10365. (when (looking-at org-dblock-end-re)
  10366. (and (looking-at "[ \t]+")
  10367. (replace-match ""))
  10368. (insert indent)))))))
  10369. (defun org-beginning-of-dblock ()
  10370. "Find the beginning of the dynamic block at point.
  10371. Error if there is no such block at point."
  10372. (let ((pos (point))
  10373. beg)
  10374. (end-of-line 1)
  10375. (if (and (re-search-backward org-dblock-start-re nil t)
  10376. (setq beg (match-beginning 0))
  10377. (re-search-forward org-dblock-end-re nil t)
  10378. (> (match-end 0) pos))
  10379. (goto-char beg)
  10380. (goto-char pos)
  10381. (error "Not in a dynamic block"))))
  10382. (defun org-update-all-dblocks ()
  10383. "Update all dynamic blocks in the buffer.
  10384. This function can be used in a hook."
  10385. (interactive)
  10386. (when (derived-mode-p 'org-mode)
  10387. (org-map-dblocks 'org-update-dblock)))
  10388. ;;;; Completion
  10389. (declare-function org-export-backend-options "ox" (cl-x) t)
  10390. (defun org-get-export-keywords ()
  10391. "Return a list of all currently understood export keywords.
  10392. Export keywords include options, block names, attributes and
  10393. keywords relative to each registered export back-end."
  10394. (let (keywords)
  10395. (dolist (backend
  10396. (bound-and-true-p org-export-registered-backends)
  10397. (delq nil keywords))
  10398. ;; Back-end name (for keywords, like #+LATEX:)
  10399. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  10400. (dolist (option-entry (org-export-backend-options backend))
  10401. ;; Back-end options.
  10402. (push (nth 1 option-entry) keywords)))))
  10403. (defconst org-options-keywords
  10404. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  10405. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  10406. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  10407. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  10408. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  10409. (defcustom org-structure-template-alist
  10410. '(("a" . "export ascii")
  10411. ("c" . "center")
  10412. ("C" . "comment")
  10413. ("e" . "example")
  10414. ("E" . "export")
  10415. ("h" . "export html")
  10416. ("l" . "export latex")
  10417. ("q" . "quote")
  10418. ("s" . "src")
  10419. ("v" . "verse"))
  10420. "An alist of keys and block types.
  10421. `org-insert-structure-template' will display a menu with this
  10422. list of templates to choose from. The block type is inserted,
  10423. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  10424. The menu keys are defined by the car of each entry in this alist.
  10425. If two entries have the keys \"a\" and \"aa\" respectively, the
  10426. former will be inserted by typing \"a TAB/RET/SPC\" and the
  10427. latter will be inserted by typing \"aa\". If an entry with the
  10428. key \"aab\" is later added, it can be inserted by typing \"ab\".
  10429. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  10430. block can be inserted by pressing TAB after the string \"<KEY\"."
  10431. :group 'org-edit-structure
  10432. :type '(repeat
  10433. (cons (string :tag "Key")
  10434. (string :tag "Template")))
  10435. :package-version '(Org . "9.2"))
  10436. (defun org--check-org-structure-template-alist (&optional checklist)
  10437. "Check whether `org-structure-template-alist' is set up correctly.
  10438. In particular, check if the Org 9.2 format is used as opposed to
  10439. previous format.
  10440. "
  10441. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  10442. (or (eval checklist)
  10443. org-structure-template-alist))))
  10444. (when elm
  10445. (org-display-warning
  10446. (format "
  10447. Please update the entries of `%s'.
  10448. In Org 9.2 the format was changed from something like
  10449. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  10450. to something like
  10451. (\"s\" . \"src\")
  10452. Please refer to the documentation of `org-structure-template-alist'.
  10453. The following entries must be updated:
  10454. %s"
  10455. (or checklist 'org-structure-template-alist)
  10456. (pp-to-string elm))))))
  10457. (defun org--insert-structure-template-mks ()
  10458. "Present `org-structure-template-alist' with `org-mks'.
  10459. Menus are added if keys require more than one keystroke. Tabs
  10460. are added to single key entries when more than one stroke is
  10461. needed. Keys longer than two characters are reduced to two
  10462. characters."
  10463. (org--check-org-structure-template-alist)
  10464. (let* (case-fold-search
  10465. (templates (append org-structure-template-alist
  10466. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  10467. (keys (mapcar #'car templates))
  10468. (start-letters
  10469. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  10470. ;; Sort each element of `org-structure-template-alist' into
  10471. ;; sublists according to the first letter.
  10472. (superlist
  10473. (mapcar (lambda (letter)
  10474. (list letter
  10475. (cl-remove-if-not
  10476. (apply-partially #'string-match-p (concat "^" letter))
  10477. templates :key #'car)))
  10478. start-letters)))
  10479. (org-mks
  10480. (apply #'append
  10481. ;; Make an `org-mks' table. If only one element is
  10482. ;; present in a sublist, make it part of the top-menu,
  10483. ;; otherwise make a submenu according to the starting
  10484. ;; letter and populate it.
  10485. (mapcar (lambda (sublist)
  10486. (if (eq 1 (length (cadr sublist)))
  10487. (mapcar (lambda (elm)
  10488. (list (substring (car elm) 0 1)
  10489. (cdr elm) ""))
  10490. (cadr sublist))
  10491. ;; Create submenu.
  10492. (let* ((topkey (car sublist))
  10493. (elms (cadr sublist))
  10494. (keys (mapcar #'car elms))
  10495. (long (> (length elms) 3)))
  10496. (append
  10497. (list
  10498. ;; Make a description of the submenu.
  10499. (list topkey
  10500. (concat
  10501. (mapconcat #'cdr
  10502. (cl-subseq elms 0 (if long 3 (length elms)))
  10503. ", ")
  10504. (when long ", ..."))))
  10505. ;; List of entries in submenu.
  10506. (cl-mapcar #'list
  10507. (org--insert-structure-template-unique-keys keys)
  10508. (mapcar #'cdr elms)
  10509. (make-list (length elms) ""))))))
  10510. superlist))
  10511. "Select a key\n============"
  10512. "Key: ")))
  10513. (defun org--insert-structure-template-unique-keys (keys)
  10514. "Make a list of unique, two characters long elements from KEYS.
  10515. Elements of length one have a tab appended. Elements of length
  10516. two are kept as is. Longer elements are truncated to length two.
  10517. If an element cannot be made unique, an error is raised."
  10518. (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  10519. menu-keys)
  10520. (dolist (key orderd-keys)
  10521. (let ((potential-key
  10522. (cl-case (length key)
  10523. (1 (concat key "\t"))
  10524. (2 key)
  10525. (otherwise
  10526. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  10527. (mapcar (apply-partially #'concat (substring key 0 1))
  10528. (split-string (substring key 1) "" t)))))))
  10529. (if (or (not potential-key) (assoc potential-key menu-keys))
  10530. (user-error "Could not make unique key for %s." key)
  10531. (push (cons potential-key key) menu-keys))))
  10532. (mapcar #'car
  10533. (cl-sort menu-keys #'<
  10534. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  10535. (defun org-insert-structure-template (type)
  10536. "Insert a block structure of the type #+begin_foo/#+end_foo.
  10537. Select a block from `org-structure-template-alist' then type
  10538. either RET, TAB or SPC to write the block type. With an active
  10539. region, wrap the region in the block. Otherwise, insert an empty
  10540. block."
  10541. (interactive
  10542. (list (pcase (org--insert-structure-template-mks)
  10543. (`("\t" . ,_) (read-string "Structure type: "))
  10544. (`(,_ ,choice . ,_) choice))))
  10545. (let* ((region? (use-region-p))
  10546. (region-start (and region? (region-beginning)))
  10547. (region-end (and region? (copy-marker (region-end))))
  10548. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  10549. (verbatim? (string-match-p
  10550. (concat "\\`" (regexp-opt '("example" "export" "src")))
  10551. type)))
  10552. (when region? (goto-char region-start))
  10553. (let ((column (current-indentation)))
  10554. (if (save-excursion (skip-chars-backward " \t") (bolp))
  10555. (beginning-of-line)
  10556. (insert "\n"))
  10557. (save-excursion
  10558. (indent-to column)
  10559. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  10560. (when region?
  10561. (when verbatim? (org-escape-code-in-region (point) region-end))
  10562. (goto-char region-end)
  10563. ;; Ignore empty lines at the end of the region.
  10564. (skip-chars-backward " \r\t\n")
  10565. (end-of-line))
  10566. (unless (bolp) (insert "\n"))
  10567. (indent-to column)
  10568. (insert (format "#+end_%s" (car (split-string type))))
  10569. (if (looking-at "[ \t]*$") (replace-match "")
  10570. (insert "\n"))
  10571. (when (and (eobp) (not (bolp))) (insert "\n")))
  10572. (if extended? (end-of-line)
  10573. (forward-line)
  10574. (skip-chars-forward " \t")))))
  10575. ;;;; TODO, DEADLINE, Comments
  10576. (defun org-toggle-comment ()
  10577. "Change the COMMENT state of an entry."
  10578. (interactive)
  10579. (save-excursion
  10580. (org-back-to-heading)
  10581. (let ((case-fold-search nil))
  10582. (looking-at org-complex-heading-regexp))
  10583. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  10584. (skip-chars-forward " \t")
  10585. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  10586. (if (org-in-commented-heading-p t)
  10587. (delete-region (point)
  10588. (progn (search-forward " " (line-end-position) 'move)
  10589. (skip-chars-forward " \t")
  10590. (point)))
  10591. (insert org-comment-string)
  10592. (unless (eolp) (insert " ")))))
  10593. (defvar org-last-todo-state-is-todo nil
  10594. "This is non-nil when the last TODO state change led to a TODO state.
  10595. If the last change removed the TODO tag or switched to DONE, then
  10596. this is nil.")
  10597. (defvar org-todo-setup-filter-hook nil
  10598. "Hook for functions that pre-filter todo specs.
  10599. Each function takes a todo spec and returns either nil or the spec
  10600. transformed into canonical form." )
  10601. (defvar org-todo-get-default-hook nil
  10602. "Hook for functions that get a default item for todo.
  10603. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  10604. nil or a string to be used for the todo mark." )
  10605. (defvar org-agenda-headline-snapshot-before-repeat)
  10606. (defun org-current-effective-time ()
  10607. "Return current time adjusted for `org-extend-today-until' variable."
  10608. (let* ((ct (org-current-time))
  10609. (dct (decode-time ct))
  10610. (ct1
  10611. (cond
  10612. (org-use-last-clock-out-time-as-effective-time
  10613. (or (org-clock-get-last-clock-out-time) ct))
  10614. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  10615. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  10616. (t ct))))
  10617. ct1))
  10618. (defun org-todo-yesterday (&optional arg)
  10619. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  10620. (interactive "P")
  10621. (if (eq major-mode 'org-agenda-mode)
  10622. (apply 'org-agenda-todo-yesterday arg)
  10623. (let* ((org-use-effective-time t)
  10624. (hour (nth 2 (decode-time (org-current-time))))
  10625. (org-extend-today-until (1+ hour)))
  10626. (org-todo arg))))
  10627. (defvar org-block-entry-blocking ""
  10628. "First entry preventing the TODO state change.")
  10629. (defun org-cancel-repeater ()
  10630. "Cancel a repeater by setting its numeric value to zero."
  10631. (interactive)
  10632. (save-excursion
  10633. (org-back-to-heading t)
  10634. (let ((bound1 (point))
  10635. (bound0 (save-excursion (outline-next-heading) (point))))
  10636. (when (and (re-search-forward
  10637. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  10638. org-deadline-time-regexp "\\)\\|\\("
  10639. org-ts-regexp "\\)")
  10640. bound0 t)
  10641. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  10642. bound1 t))
  10643. (replace-match "0" t nil nil 1)))))
  10644. (defvar org-state)
  10645. (defvar org-blocked-by-checkboxes)
  10646. (defun org-todo (&optional arg)
  10647. "Change the TODO state of an item.
  10648. The state of an item is given by a keyword at the start of the heading,
  10649. like
  10650. *** TODO Write paper
  10651. *** DONE Call mom
  10652. The different keywords are specified in the variable `org-todo-keywords'.
  10653. By default the available states are \"TODO\" and \"DONE\". So, for this
  10654. example: when the item starts with TODO, it is changed to DONE.
  10655. When it starts with DONE, the DONE is removed. And when neither TODO nor
  10656. DONE are present, add TODO at the beginning of the heading.
  10657. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  10658. state.
  10659. With numeric prefix ARG, switch to that state.
  10660. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  10661. next set of TODO \
  10662. keywords (nextset).
  10663. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  10664. prefix, circumvent any state blocking.
  10665. With a numeric prefix arg of 0, inhibit note taking for the change.
  10666. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  10667. When called through ELisp, arg is also interpreted in the following way:
  10668. `none' -> empty state
  10669. \"\" -> switch to empty state
  10670. `done' -> switch to DONE
  10671. `nextset' -> switch to the next set of keywords
  10672. `previousset' -> switch to the previous set of keywords
  10673. \"WAITING\" -> switch to the specified keyword, but only if it
  10674. really is a member of `org-todo-keywords'."
  10675. (interactive "P")
  10676. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10677. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10678. 'region-start-level 'region))
  10679. org-loop-over-headlines-in-active-region)
  10680. (org-map-entries
  10681. `(org-todo ,arg)
  10682. org-loop-over-headlines-in-active-region
  10683. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  10684. (when (equal arg '(16)) (setq arg 'nextset))
  10685. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  10686. (let ((org-blocker-hook org-blocker-hook)
  10687. commentp
  10688. case-fold-search)
  10689. (when (equal arg '(64))
  10690. (setq arg nil org-blocker-hook nil))
  10691. (when (and org-blocker-hook
  10692. (or org-inhibit-blocking
  10693. (org-entry-get nil "NOBLOCKING")))
  10694. (setq org-blocker-hook nil))
  10695. (save-excursion
  10696. (catch 'exit
  10697. (org-back-to-heading t)
  10698. (when (org-in-commented-heading-p t)
  10699. (org-toggle-comment)
  10700. (setq commentp t))
  10701. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  10702. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  10703. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  10704. (let* ((match-data (match-data))
  10705. (startpos (copy-marker (line-beginning-position)))
  10706. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  10707. (org-log-done org-log-done)
  10708. (org-log-repeat org-log-repeat)
  10709. (org-todo-log-states org-todo-log-states)
  10710. (org-inhibit-logging
  10711. (if (equal arg 0)
  10712. (progn (setq arg nil) 'note) org-inhibit-logging))
  10713. (this (match-string 1))
  10714. (hl-pos (match-beginning 0))
  10715. (head (org-get-todo-sequence-head this))
  10716. (ass (assoc head org-todo-kwd-alist))
  10717. (interpret (nth 1 ass))
  10718. (done-word (nth 3 ass))
  10719. (final-done-word (nth 4 ass))
  10720. (org-last-state (or this ""))
  10721. (completion-ignore-case t)
  10722. (member (member this org-todo-keywords-1))
  10723. (tail (cdr member))
  10724. (org-state (cond
  10725. ((and org-todo-key-trigger
  10726. (or (and (equal arg '(4))
  10727. (eq org-use-fast-todo-selection 'prefix))
  10728. (and (not arg) org-use-fast-todo-selection
  10729. (not (eq org-use-fast-todo-selection
  10730. 'prefix)))))
  10731. ;; Use fast selection.
  10732. (org-fast-todo-selection))
  10733. ((and (equal arg '(4))
  10734. (or (not org-use-fast-todo-selection)
  10735. (not org-todo-key-trigger)))
  10736. ;; Read a state with completion.
  10737. (completing-read
  10738. "State: " (mapcar #'list org-todo-keywords-1)
  10739. nil t))
  10740. ((eq arg 'right)
  10741. (if this
  10742. (if tail (car tail) nil)
  10743. (car org-todo-keywords-1)))
  10744. ((eq arg 'left)
  10745. (unless (equal member org-todo-keywords-1)
  10746. (if this
  10747. (nth (- (length org-todo-keywords-1)
  10748. (length tail) 2)
  10749. org-todo-keywords-1)
  10750. (org-last org-todo-keywords-1))))
  10751. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  10752. (setq arg nil))) ;hack to fall back to cycling
  10753. (arg
  10754. ;; User or caller requests a specific state.
  10755. (cond
  10756. ((equal arg "") nil)
  10757. ((eq arg 'none) nil)
  10758. ((eq arg 'done) (or done-word (car org-done-keywords)))
  10759. ((eq arg 'nextset)
  10760. (or (car (cdr (member head org-todo-heads)))
  10761. (car org-todo-heads)))
  10762. ((eq arg 'previousset)
  10763. (let ((org-todo-heads (reverse org-todo-heads)))
  10764. (or (car (cdr (member head org-todo-heads)))
  10765. (car org-todo-heads))))
  10766. ((car (member arg org-todo-keywords-1)))
  10767. ((stringp arg)
  10768. (user-error "State `%s' not valid in this file" arg))
  10769. ((nth (1- (prefix-numeric-value arg))
  10770. org-todo-keywords-1))))
  10771. ((null member) (or head (car org-todo-keywords-1)))
  10772. ((equal this final-done-word) nil) ;-> make empty
  10773. ((null tail) nil) ;-> first entry
  10774. ((memq interpret '(type priority))
  10775. (if (eq this-command last-command)
  10776. (car tail)
  10777. (if (> (length tail) 0)
  10778. (or done-word (car org-done-keywords))
  10779. nil)))
  10780. (t
  10781. (car tail))))
  10782. (org-state (or
  10783. (run-hook-with-args-until-success
  10784. 'org-todo-get-default-hook org-state org-last-state)
  10785. org-state))
  10786. (next (if org-state (concat " " org-state " ") " "))
  10787. (change-plist (list :type 'todo-state-change :from this :to org-state
  10788. :position startpos))
  10789. dolog now-done-p)
  10790. (when org-blocker-hook
  10791. (let (org-blocked-by-checkboxes block-reason)
  10792. (setq org-last-todo-state-is-todo
  10793. (not (member this org-done-keywords)))
  10794. (unless (save-excursion
  10795. (save-match-data
  10796. (org-with-wide-buffer
  10797. (run-hook-with-args-until-failure
  10798. 'org-blocker-hook change-plist))))
  10799. (setq block-reason (if org-blocked-by-checkboxes
  10800. "contained checkboxes"
  10801. (format "\"%s\"" org-block-entry-blocking)))
  10802. (if (called-interactively-p 'interactive)
  10803. (user-error "TODO state change from %s to %s blocked (by %s)"
  10804. this org-state block-reason)
  10805. ;; Fail silently.
  10806. (message "TODO state change from %s to %s blocked (by %s)"
  10807. this org-state block-reason)
  10808. (throw 'exit nil)))))
  10809. (store-match-data match-data)
  10810. (replace-match next t t)
  10811. (cond ((equal this org-state)
  10812. (message "TODO state was already %s" (org-trim next)))
  10813. ((not (pos-visible-in-window-p hl-pos))
  10814. (message "TODO state changed to %s" (org-trim next))))
  10815. (unless head
  10816. (setq head (org-get-todo-sequence-head org-state)
  10817. ass (assoc head org-todo-kwd-alist)
  10818. interpret (nth 1 ass)
  10819. done-word (nth 3 ass)
  10820. final-done-word (nth 4 ass)))
  10821. (when (memq arg '(nextset previousset))
  10822. (message "Keyword-Set %d/%d: %s"
  10823. (- (length org-todo-sets) -1
  10824. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  10825. (length org-todo-sets)
  10826. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  10827. (setq org-last-todo-state-is-todo
  10828. (not (member org-state org-done-keywords)))
  10829. (setq now-done-p (and (member org-state org-done-keywords)
  10830. (not (member this org-done-keywords))))
  10831. (and logging (org-local-logging logging))
  10832. (when (and (or org-todo-log-states org-log-done)
  10833. (not (eq org-inhibit-logging t))
  10834. (not (memq arg '(nextset previousset))))
  10835. ;; We need to look at recording a time and note.
  10836. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  10837. (nth 2 (assoc this org-todo-log-states))))
  10838. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  10839. (setq dolog 'time))
  10840. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  10841. (and org-state
  10842. (member org-state org-not-done-keywords)
  10843. (not (member this org-not-done-keywords))))
  10844. ;; This is now a todo state and was not one before
  10845. ;; If there was a CLOSED time stamp, get rid of it.
  10846. (org-add-planning-info nil nil 'closed))
  10847. (when (and now-done-p org-log-done)
  10848. ;; It is now done, and it was not done before.
  10849. (org-add-planning-info 'closed (org-current-effective-time))
  10850. (when (and (not dolog) (eq 'note org-log-done))
  10851. (org-add-log-setup 'done org-state this 'note)))
  10852. (when (and org-state dolog)
  10853. ;; This is a non-nil state, and we need to log it.
  10854. (org-add-log-setup 'state org-state this dolog)))
  10855. ;; Fixup tag positioning.
  10856. (org-todo-trigger-tag-changes org-state)
  10857. (when org-auto-align-tags (org-align-tags))
  10858. (when org-provide-todo-statistics
  10859. (org-update-parent-todo-statistics))
  10860. (run-hooks 'org-after-todo-state-change-hook)
  10861. (when (and arg (not (member org-state org-done-keywords)))
  10862. (setq head (org-get-todo-sequence-head org-state)))
  10863. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  10864. ;; Do we need to trigger a repeat?
  10865. (when now-done-p
  10866. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  10867. ;; This is for the agenda, take a snapshot of the headline.
  10868. (save-match-data
  10869. (setq org-agenda-headline-snapshot-before-repeat
  10870. (org-get-heading))))
  10871. (org-auto-repeat-maybe org-state))
  10872. ;; Fixup cursor location if close to the keyword.
  10873. (when (and (outline-on-heading-p)
  10874. (not (bolp))
  10875. (save-excursion (beginning-of-line 1)
  10876. (looking-at org-todo-line-regexp))
  10877. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  10878. (goto-char (or (match-end 2) (match-end 1)))
  10879. (and (looking-at " ") (just-one-space)))
  10880. (when org-trigger-hook
  10881. (save-excursion
  10882. (run-hook-with-args 'org-trigger-hook change-plist)))
  10883. (when commentp (org-toggle-comment))))))))
  10884. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  10885. "Block turning an entry into a TODO, using the hierarchy.
  10886. This checks whether the current task should be blocked from state
  10887. changes. Such blocking occurs when:
  10888. 1. The task has children which are not all in a completed state.
  10889. 2. A task has a parent with the property :ORDERED:, and there
  10890. are siblings prior to the current task with incomplete
  10891. status.
  10892. 3. The parent of the task is blocked because it has siblings that should
  10893. be done first, or is child of a block grandparent TODO entry."
  10894. (if (not org-enforce-todo-dependencies)
  10895. t ; if locally turned off don't block
  10896. (catch 'dont-block
  10897. ;; If this is not a todo state change, or if this entry is already DONE,
  10898. ;; do not block
  10899. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  10900. (member (plist-get change-plist :from)
  10901. (cons 'done org-done-keywords))
  10902. (member (plist-get change-plist :to)
  10903. (cons 'todo org-not-done-keywords))
  10904. (not (plist-get change-plist :to)))
  10905. (throw 'dont-block t))
  10906. ;; If this task has children, and any are undone, it's blocked
  10907. (save-excursion
  10908. (org-back-to-heading t)
  10909. (let ((this-level (funcall outline-level)))
  10910. (outline-next-heading)
  10911. (let ((child-level (funcall outline-level)))
  10912. (while (and (not (eobp))
  10913. (> child-level this-level))
  10914. ;; this todo has children, check whether they are all
  10915. ;; completed
  10916. (when (and (not (org-entry-is-done-p))
  10917. (org-entry-is-todo-p))
  10918. (setq org-block-entry-blocking (org-get-heading))
  10919. (throw 'dont-block nil))
  10920. (outline-next-heading)
  10921. (setq child-level (funcall outline-level))))))
  10922. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  10923. ;; any previous siblings are undone, it's blocked
  10924. (save-excursion
  10925. (org-back-to-heading t)
  10926. (let* ((pos (point))
  10927. (parent-pos (and (org-up-heading-safe) (point)))
  10928. (case-fold-search nil))
  10929. (unless parent-pos (throw 'dont-block t)) ; no parent
  10930. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  10931. (forward-line 1)
  10932. (re-search-forward org-not-done-heading-regexp pos t))
  10933. (setq org-block-entry-blocking (match-string 0))
  10934. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  10935. ;; Search further up the hierarchy, to see if an ancestor is blocked
  10936. (while t
  10937. (goto-char parent-pos)
  10938. (unless (looking-at org-not-done-heading-regexp)
  10939. (throw 'dont-block t)) ; do not block, parent is not a TODO
  10940. (setq pos (point))
  10941. (setq parent-pos (and (org-up-heading-safe) (point)))
  10942. (unless parent-pos (throw 'dont-block t)) ; no parent
  10943. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  10944. (forward-line 1)
  10945. (re-search-forward org-not-done-heading-regexp pos t)
  10946. (setq org-block-entry-blocking (org-get-heading)))
  10947. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  10948. (defcustom org-track-ordered-property-with-tag nil
  10949. "Should the ORDERED property also be shown as a tag?
  10950. The ORDERED property decides if an entry should require subtasks to be
  10951. completed in sequence. Since a property is not very visible, setting
  10952. this option means that toggling the ORDERED property with the command
  10953. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  10954. not relevant for the behavior, but it makes things more visible.
  10955. Note that toggling the tag with tags commands will not change the property
  10956. and therefore not influence behavior!
  10957. This can be t, meaning the tag ORDERED should be used, It can also be a
  10958. string to select a different tag for this task."
  10959. :group 'org-todo
  10960. :type '(choice
  10961. (const :tag "No tracking" nil)
  10962. (const :tag "Track with ORDERED tag" t)
  10963. (string :tag "Use other tag")))
  10964. (defun org-toggle-ordered-property ()
  10965. "Toggle the ORDERED property of the current entry.
  10966. For better visibility, you can track the value of this property with a tag.
  10967. See variable `org-track-ordered-property-with-tag'."
  10968. (interactive)
  10969. (let* ((t1 org-track-ordered-property-with-tag)
  10970. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  10971. (save-excursion
  10972. (org-back-to-heading)
  10973. (if (org-entry-get nil "ORDERED")
  10974. (progn
  10975. (org-delete-property "ORDERED")
  10976. (and tag (org-toggle-tag tag 'off))
  10977. (message "Subtasks can be completed in arbitrary order"))
  10978. (org-entry-put nil "ORDERED" "t")
  10979. (and tag (org-toggle-tag tag 'on))
  10980. (message "Subtasks must be completed in sequence")))))
  10981. (defun org-block-todo-from-checkboxes (change-plist)
  10982. "Block turning an entry into a TODO, using checkboxes.
  10983. This checks whether the current task should be blocked from state
  10984. changes because there are unchecked boxes in this entry."
  10985. (if (not org-enforce-todo-checkbox-dependencies)
  10986. t ; if locally turned off don't block
  10987. (catch 'dont-block
  10988. ;; If this is not a todo state change, or if this entry is already DONE,
  10989. ;; do not block
  10990. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  10991. (member (plist-get change-plist :from)
  10992. (cons 'done org-done-keywords))
  10993. (member (plist-get change-plist :to)
  10994. (cons 'todo org-not-done-keywords))
  10995. (not (plist-get change-plist :to)))
  10996. (throw 'dont-block t))
  10997. ;; If this task has checkboxes that are not checked, it's blocked
  10998. (save-excursion
  10999. (org-back-to-heading t)
  11000. (let ((beg (point)) end)
  11001. (outline-next-heading)
  11002. (setq end (point))
  11003. (goto-char beg)
  11004. (when (org-list-search-forward
  11005. (concat (org-item-beginning-re)
  11006. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11007. "\\[[- ]\\]")
  11008. end t)
  11009. (when (boundp 'org-blocked-by-checkboxes)
  11010. (setq org-blocked-by-checkboxes t))
  11011. (throw 'dont-block nil))))
  11012. t))) ; do not block
  11013. (defun org-entry-blocked-p ()
  11014. "Non-nil if entry at point is blocked."
  11015. (and (not (org-entry-get nil "NOBLOCKING"))
  11016. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11017. (not (run-hook-with-args-until-failure
  11018. 'org-blocker-hook
  11019. (list :type 'todo-state-change
  11020. :position (point)
  11021. :from 'todo
  11022. :to 'done)))))
  11023. (defun org-update-statistics-cookies (all)
  11024. "Update the statistics cookie, either from TODO or from checkboxes.
  11025. This should be called with the cursor in a line with a statistics
  11026. cookie. When called with a \\[universal-argument] prefix, update
  11027. all statistics cookies in the buffer."
  11028. (interactive "P")
  11029. (if all
  11030. (progn
  11031. (org-update-checkbox-count 'all)
  11032. (org-map-entries 'org-update-parent-todo-statistics))
  11033. (if (not (org-at-heading-p))
  11034. (org-update-checkbox-count)
  11035. (let ((pos (point-marker))
  11036. end l1 l2)
  11037. (ignore-errors (org-back-to-heading t))
  11038. (if (not (org-at-heading-p))
  11039. (org-update-checkbox-count)
  11040. (setq l1 (org-outline-level))
  11041. (setq end (save-excursion
  11042. (outline-next-heading)
  11043. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11044. (point)))
  11045. (if (and (save-excursion
  11046. (re-search-forward
  11047. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11048. (not (save-excursion (re-search-forward
  11049. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11050. (org-update-checkbox-count)
  11051. (if (and l2 (> l2 l1))
  11052. (progn
  11053. (goto-char end)
  11054. (org-update-parent-todo-statistics))
  11055. (goto-char pos)
  11056. (beginning-of-line 1)
  11057. (while (re-search-forward
  11058. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11059. (point-at-eol) t)
  11060. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11061. (goto-char pos)
  11062. (move-marker pos nil)))))
  11063. (defvar org-entry-property-inherited-from) ;; defined below
  11064. (defun org-update-parent-todo-statistics ()
  11065. "Update any statistics cookie in the parent of the current headline.
  11066. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11067. the entire subtree and this will travel up the hierarchy and update
  11068. statistics everywhere."
  11069. (let* ((prop (save-excursion (org-up-heading-safe)
  11070. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11071. (recursive (or (not org-hierarchical-todo-statistics)
  11072. (and prop (string-match "\\<recursive\\>" prop))))
  11073. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11074. 0))
  11075. (first t)
  11076. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11077. level ltoggle l1 new ndel
  11078. (cnt-all 0) (cnt-done 0) is-percent kwd
  11079. checkbox-beg cookie-present)
  11080. (catch 'exit
  11081. (save-excursion
  11082. (beginning-of-line 1)
  11083. (setq ltoggle (funcall outline-level))
  11084. ;; Three situations are to consider:
  11085. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11086. ;; to the top-level ancestor on the headline;
  11087. ;; 2. If parent has "recursive" property, repeat up to the
  11088. ;; headline setting that property, taking inheritance into
  11089. ;; account;
  11090. ;; 3. Else, move up to direct parent and proceed only once.
  11091. (while (and (setq level (org-up-heading-safe))
  11092. (or recursive first)
  11093. (>= (point) lim))
  11094. (setq first nil cookie-present nil)
  11095. (unless (and level
  11096. (not (string-match
  11097. "\\<checkbox\\>"
  11098. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11099. "")))))
  11100. (throw 'exit nil))
  11101. (while (re-search-forward box-re (point-at-eol) t)
  11102. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11103. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11104. (save-match-data
  11105. (unless (outline-next-heading) (throw 'exit nil))
  11106. (while (and (looking-at org-complex-heading-regexp)
  11107. (> (setq l1 (length (match-string 1))) level))
  11108. (setq kwd (and (or recursive (= l1 ltoggle))
  11109. (match-string 2)))
  11110. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11111. (and (eq org-provide-todo-statistics t)
  11112. (or (member kwd org-done-keywords)))
  11113. (and (listp org-provide-todo-statistics)
  11114. (stringp (car org-provide-todo-statistics))
  11115. (or (member kwd org-provide-todo-statistics)
  11116. (member kwd org-done-keywords)))
  11117. (and (listp org-provide-todo-statistics)
  11118. (listp (car org-provide-todo-statistics))
  11119. (or (member kwd (car org-provide-todo-statistics))
  11120. (and (member kwd org-done-keywords)
  11121. (member kwd (cadr org-provide-todo-statistics))))))
  11122. (setq cnt-all (1+ cnt-all))
  11123. (and (eq org-provide-todo-statistics t)
  11124. kwd
  11125. (setq cnt-all (1+ cnt-all))))
  11126. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11127. (member kwd org-done-keywords))
  11128. (and (listp org-provide-todo-statistics)
  11129. (listp (car org-provide-todo-statistics))
  11130. (member kwd org-done-keywords)
  11131. (member kwd (cadr org-provide-todo-statistics)))
  11132. (and (listp org-provide-todo-statistics)
  11133. (stringp (car org-provide-todo-statistics))
  11134. (member kwd org-done-keywords)))
  11135. (setq cnt-done (1+ cnt-done)))
  11136. (outline-next-heading)))
  11137. (setq new
  11138. (if is-percent
  11139. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11140. (max 1 cnt-all)))
  11141. (format "[%d/%d]" cnt-done cnt-all))
  11142. ndel (- (match-end 0) checkbox-beg))
  11143. (goto-char checkbox-beg)
  11144. (insert new)
  11145. (delete-region (point) (+ (point) ndel))
  11146. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11147. (when cookie-present
  11148. (run-hook-with-args 'org-after-todo-statistics-hook
  11149. cnt-done (- cnt-all cnt-done))))))
  11150. (run-hooks 'org-todo-statistics-hook)))
  11151. (defvar org-after-todo-statistics-hook nil
  11152. "Hook that is called after a TODO statistics cookie has been updated.
  11153. Each function is called with two arguments: the number of not-done entries
  11154. and the number of done entries.
  11155. For example, the following function, when added to this hook, will switch
  11156. an entry to DONE when all children are done, and back to TODO when new
  11157. entries are set to a TODO status. Note that this hook is only called
  11158. when there is a statistics cookie in the headline!
  11159. (defun org-summary-todo (n-done n-not-done)
  11160. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11161. (let (org-log-done org-log-states) ; turn off logging
  11162. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11163. ")
  11164. (defvar org-todo-statistics-hook nil
  11165. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11166. This hook runs even if there is no statistics cookie present, in which case
  11167. `org-after-todo-statistics-hook' would not run.")
  11168. (defun org-todo-trigger-tag-changes (state)
  11169. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11170. (let ((l org-todo-state-tags-triggers)
  11171. changes)
  11172. (when (or (not state) (equal state ""))
  11173. (setq changes (append changes (cdr (assoc "" l)))))
  11174. (when (and (stringp state) (> (length state) 0))
  11175. (setq changes (append changes (cdr (assoc state l)))))
  11176. (when (member state org-not-done-keywords)
  11177. (setq changes (append changes (cdr (assq 'todo l)))))
  11178. (when (member state org-done-keywords)
  11179. (setq changes (append changes (cdr (assq 'done l)))))
  11180. (dolist (c changes)
  11181. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11182. (defun org-local-logging (value)
  11183. "Get logging settings from a property VALUE."
  11184. ;; Directly set the variables, they are already local.
  11185. (setq org-log-done nil
  11186. org-log-repeat nil
  11187. org-todo-log-states nil)
  11188. (dolist (w (split-string value))
  11189. (let (a)
  11190. (cond
  11191. ((setq a (assoc w org-startup-options))
  11192. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11193. (set (nth 1 a) (nth 2 a))))
  11194. ((setq a (org-extract-log-state-settings w))
  11195. (and (member (car a) org-todo-keywords-1)
  11196. (push a org-todo-log-states)))))))
  11197. (defun org-get-todo-sequence-head (kwd)
  11198. "Return the head of the TODO sequence to which KWD belongs.
  11199. If KWD is not set, check if there is a text property remembering the
  11200. right sequence."
  11201. (let (p)
  11202. (cond
  11203. ((not kwd)
  11204. (or (get-text-property (point-at-bol) 'org-todo-head)
  11205. (progn
  11206. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11207. nil (point-at-eol)))
  11208. (get-text-property p 'org-todo-head))))
  11209. ((not (member kwd org-todo-keywords-1))
  11210. (car org-todo-keywords-1))
  11211. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11212. (defun org-fast-todo-selection ()
  11213. "Fast TODO keyword selection with single keys.
  11214. Returns the new TODO keyword, or nil if no state change should occur."
  11215. (let* ((fulltable org-todo-key-alist)
  11216. (done-keywords org-done-keywords) ;; needed for the faces.
  11217. (maxlen (apply 'max (mapcar
  11218. (lambda (x)
  11219. (if (stringp (car x)) (string-width (car x)) 0))
  11220. fulltable)))
  11221. (expert nil)
  11222. (fwidth (+ maxlen 3 1 3))
  11223. (ncol (/ (- (window-width) 4) fwidth))
  11224. tg cnt e c tbl
  11225. groups ingroup)
  11226. (save-excursion
  11227. (save-window-excursion
  11228. (if expert
  11229. (set-buffer (get-buffer-create " *Org todo*"))
  11230. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11231. (erase-buffer)
  11232. (setq-local org-done-keywords done-keywords)
  11233. (setq tbl fulltable cnt 0)
  11234. (while (setq e (pop tbl))
  11235. (cond
  11236. ((equal e '(:startgroup))
  11237. (push '() groups) (setq ingroup t)
  11238. (unless (= cnt 0)
  11239. (setq cnt 0)
  11240. (insert "\n"))
  11241. (insert "{ "))
  11242. ((equal e '(:endgroup))
  11243. (setq ingroup nil cnt 0)
  11244. (insert "}\n"))
  11245. ((equal e '(:newline))
  11246. (unless (= cnt 0)
  11247. (setq cnt 0)
  11248. (insert "\n")
  11249. (setq e (car tbl))
  11250. (while (equal (car tbl) '(:newline))
  11251. (insert "\n")
  11252. (setq tbl (cdr tbl)))))
  11253. (t
  11254. (setq tg (car e) c (cdr e))
  11255. (when ingroup (push tg (car groups)))
  11256. (setq tg (org-add-props tg nil 'face
  11257. (org-get-todo-face tg)))
  11258. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11259. (insert "[" c "] " tg (make-string
  11260. (- fwidth 4 (length tg)) ?\ ))
  11261. (when (= (setq cnt (1+ cnt)) ncol)
  11262. (insert "\n")
  11263. (when ingroup (insert " "))
  11264. (setq cnt 0)))))
  11265. (insert "\n")
  11266. (goto-char (point-min))
  11267. (unless expert (org-fit-window-to-buffer))
  11268. (message "[a-z..]:Set [SPC]:clear")
  11269. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11270. (cond
  11271. ((or (= c ?\C-g)
  11272. (and (= c ?q) (not (rassoc c fulltable))))
  11273. (setq quit-flag t))
  11274. ((= c ?\ ) nil)
  11275. ((setq e (rassoc c fulltable) tg (car e))
  11276. tg)
  11277. (t (setq quit-flag t)))))))
  11278. (defun org-entry-is-todo-p ()
  11279. (member (org-get-todo-state) org-not-done-keywords))
  11280. (defun org-entry-is-done-p ()
  11281. (member (org-get-todo-state) org-done-keywords))
  11282. (defun org-get-todo-state ()
  11283. "Return the TODO keyword of the current subtree."
  11284. (save-excursion
  11285. (org-back-to-heading t)
  11286. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11287. (match-end 2)
  11288. (match-string 2))))
  11289. (defun org-at-date-range-p (&optional inactive-ok)
  11290. "Non-nil if point is inside a date range.
  11291. When optional argument INACTIVE-OK is non-nil, also consider
  11292. inactive time ranges.
  11293. When this function returns a non-nil value, match data is set
  11294. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11295. on INACTIVE-OK."
  11296. (interactive)
  11297. (save-excursion
  11298. (catch 'exit
  11299. (let ((pos (point)))
  11300. (skip-chars-backward "^[<\r\n")
  11301. (skip-chars-backward "<[")
  11302. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11303. (>= (match-end 0) pos)
  11304. (throw 'exit t))
  11305. (skip-chars-backward "^<[\r\n")
  11306. (skip-chars-backward "<[")
  11307. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11308. (>= (match-end 0) pos)
  11309. (throw 'exit t)))
  11310. nil)))
  11311. (defun org-get-repeat (&optional timestamp)
  11312. "Check if there is a time-stamp with repeater in this entry.
  11313. Return the repeater, as a string, or nil. Also return nil when
  11314. this function is called before first heading.
  11315. When optional argument TIMESTAMP is a string, extract the
  11316. repeater from there instead."
  11317. (save-match-data
  11318. (cond (timestamp
  11319. (and (string-match org-repeat-re timestamp)
  11320. (match-string-no-properties 1 timestamp)))
  11321. ((org-before-first-heading-p) nil)
  11322. (t
  11323. (save-excursion
  11324. (org-back-to-heading t)
  11325. (let ((end (org-entry-end-position)))
  11326. (catch :repeat
  11327. (while (re-search-forward org-repeat-re end t)
  11328. (when (save-match-data (org-at-timestamp-p 'agenda))
  11329. (throw :repeat (match-string-no-properties 1)))))))))))
  11330. (defvar org-last-changed-timestamp)
  11331. (defvar org-last-inserted-timestamp)
  11332. (defvar org-log-post-message)
  11333. (defvar org-log-note-purpose)
  11334. (defvar org-log-note-how nil)
  11335. (defvar org-log-note-extra)
  11336. (defun org-auto-repeat-maybe (done-word)
  11337. "Check if the current headline contains a repeated time-stamp.
  11338. If yes, set TODO state back to what it was and change the base date
  11339. of repeating deadline/scheduled time stamps to new date.
  11340. This function is run automatically after each state change to a DONE state."
  11341. (let* ((repeat (org-get-repeat))
  11342. (aa (assoc org-last-state org-todo-kwd-alist))
  11343. (interpret (nth 1 aa))
  11344. (head (nth 2 aa))
  11345. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11346. (msg "Entry repeats: ")
  11347. (org-log-done nil)
  11348. (org-todo-log-states nil)
  11349. (end (copy-marker (org-entry-end-position))))
  11350. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  11351. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11352. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11353. (and (stringp org-todo-repeat-to-state)
  11354. org-todo-repeat-to-state)
  11355. (and org-todo-repeat-to-state org-last-state))))
  11356. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  11357. to-state)
  11358. ((eq interpret 'type) org-last-state)
  11359. (head)
  11360. (t 'none))))
  11361. (org-back-to-heading t)
  11362. (org-add-planning-info nil nil 'closed)
  11363. ;; When `org-log-repeat' is non-nil or entry contains
  11364. ;; a clock, set LAST_REPEAT property.
  11365. (when (or org-log-repeat
  11366. (catch :clock
  11367. (save-excursion
  11368. (while (re-search-forward org-clock-line-re end t)
  11369. (when (org-at-clock-log-p) (throw :clock t))))))
  11370. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11371. (org-time-stamp-format t t)
  11372. (current-time))))
  11373. (when org-log-repeat
  11374. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11375. (memq 'org-add-log-note post-command-hook))
  11376. ;; We are already setup for some record.
  11377. (when (eq org-log-repeat 'note)
  11378. ;; Make sure we take a note, not only a time stamp.
  11379. (setq org-log-note-how 'note))
  11380. ;; Set up for taking a record.
  11381. (org-add-log-setup 'state
  11382. (or done-word (car org-done-keywords))
  11383. org-last-state
  11384. org-log-repeat)))
  11385. ;; Time-stamps without a repeater are usually skipped. However,
  11386. ;; a SCHEDULED time-stamp without one is removed, as they are no
  11387. ;; longer relevant.
  11388. (save-excursion
  11389. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  11390. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  11391. (org-remove-timestamp-with-keyword org-scheduled-string))))
  11392. ;; Update every time-stamp with a repeater in the entry.
  11393. (let ((planning-re (regexp-opt
  11394. (list org-scheduled-string org-deadline-string))))
  11395. (while (re-search-forward org-repeat-re end t)
  11396. (let* ((ts (match-string 0))
  11397. (type (if (not (org-at-planning-p)) "Plain:"
  11398. (save-excursion
  11399. (re-search-backward
  11400. planning-re (line-beginning-position) t)
  11401. (match-string 0)))))
  11402. (when (and (org-at-timestamp-p 'agenda)
  11403. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  11404. (let ((n (string-to-number (match-string 2 ts)))
  11405. (what (match-string 3 ts)))
  11406. (when (equal what "w") (setq n (* n 7) what "d"))
  11407. (when (and (equal what "h")
  11408. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11409. ts)))
  11410. (user-error
  11411. "Cannot repeat in %d hour(s) because no hour has been set"
  11412. n))
  11413. ;; Preparation, see if we need to modify the start
  11414. ;; date for the change.
  11415. (when (match-end 1)
  11416. (let ((time (save-match-data (org-time-string-to-time ts)))
  11417. (repeater-type (match-string 1 ts)))
  11418. (cond
  11419. ((equal "." repeater-type)
  11420. ;; Shift starting date to today.
  11421. (org-timestamp-change (- (org-today) (time-to-days time))
  11422. 'day))
  11423. ((equal "+" repeater-type)
  11424. (let ((nshiftmax 10)
  11425. (nshift 0))
  11426. (while (or (= nshift 0)
  11427. (not (time-less-p (current-time) time)))
  11428. (when (= nshiftmax (cl-incf nshift))
  11429. (or (y-or-n-p
  11430. (format "%d repeater intervals were not \
  11431. enough to shift date past today. Continue? "
  11432. nshift))
  11433. (user-error "Abort")))
  11434. (org-timestamp-change n (cdr (assoc what whata)))
  11435. (org-in-regexp org-ts-regexp3)
  11436. (setq ts (match-string 1))
  11437. (setq time
  11438. (save-match-data
  11439. (org-time-string-to-time ts)))))
  11440. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11441. ;; Rematch, so that we have everything in place
  11442. ;; for the real shift.
  11443. (org-in-regexp org-ts-regexp3)
  11444. (setq ts (match-string 1))
  11445. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11446. ts)))))
  11447. (save-excursion
  11448. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11449. (setq msg
  11450. (concat msg type " " org-last-changed-timestamp " ")))))))
  11451. (setq org-log-post-message msg)
  11452. (message msg))))
  11453. (defun org-show-todo-tree (arg)
  11454. "Make a compact tree which shows all headlines marked with TODO.
  11455. The tree will show the lines where the regexp matches, and all higher
  11456. headlines above the match.
  11457. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11458. With a numeric prefix N, construct a sparse tree for the Nth element
  11459. of `org-todo-keywords-1'."
  11460. (interactive "P")
  11461. (let ((case-fold-search nil)
  11462. (kwd-re
  11463. (cond ((null arg) org-not-done-regexp)
  11464. ((equal arg '(4))
  11465. (let ((kwd
  11466. (completing-read "Keyword (or KWD1|KWD2|...): "
  11467. (mapcar #'list org-todo-keywords-1))))
  11468. (concat "\\("
  11469. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11470. "\\)\\>")))
  11471. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11472. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11473. org-todo-keywords-1)))
  11474. (t (user-error "Invalid prefix argument: %s" arg)))))
  11475. (message "%d TODO entries found"
  11476. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11477. (defun org--deadline-or-schedule (arg type time)
  11478. "Insert DEADLINE or SCHEDULE information in current entry.
  11479. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  11480. `org-schedule' for information about ARG and TIME arguments."
  11481. (let* ((deadline? (eq type 'deadline))
  11482. (keyword (if deadline? org-deadline-string org-scheduled-string))
  11483. (log (if deadline? org-log-redeadline org-log-reschedule))
  11484. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  11485. (old-date-time (and old-date (org-time-string-to-time old-date)))
  11486. ;; Save repeater cookie from either TIME or current scheduled
  11487. ;; time stamp. We are going to insert it back at the end of
  11488. ;; the process.
  11489. (repeater (or (and (org-string-nw-p time)
  11490. ;; We use `org-repeat-re' because we need
  11491. ;; to tell the difference between a real
  11492. ;; repeater and a time delta, e.g. "+2d".
  11493. (string-match org-repeat-re time)
  11494. (match-string 1 time))
  11495. (and (org-string-nw-p old-date)
  11496. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  11497. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  11498. old-date)
  11499. (match-string 1 old-date)))))
  11500. (pcase arg
  11501. (`(4)
  11502. (if (not old-date)
  11503. (message (if deadline? "Entry had no deadline to remove"
  11504. "Entry was not scheduled"))
  11505. (when (and old-date log)
  11506. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  11507. nil old-date log))
  11508. (org-remove-timestamp-with-keyword keyword)
  11509. (message (if deadline? "Entry no longer has a deadline."
  11510. "Entry is no longer scheduled."))))
  11511. (`(16)
  11512. (save-excursion
  11513. (org-back-to-heading t)
  11514. (let ((regexp (if deadline? org-deadline-time-regexp
  11515. org-scheduled-time-regexp)))
  11516. (if (not (re-search-forward regexp (line-end-position 2) t))
  11517. (user-error (if deadline? "No deadline information to update"
  11518. "No scheduled information to update"))
  11519. (let* ((rpl0 (match-string 1))
  11520. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  11521. (msg (if deadline? "Warn starting from" "Delay until")))
  11522. (replace-match
  11523. (concat keyword
  11524. " <" rpl
  11525. (format " -%dd"
  11526. (abs (- (time-to-days
  11527. (save-match-data
  11528. (org-read-date
  11529. nil t nil msg old-date-time)))
  11530. (time-to-days old-date-time))))
  11531. ">") t t))))))
  11532. (_
  11533. (org-add-planning-info type time 'closed)
  11534. (when (and old-date
  11535. log
  11536. (not (equal old-date org-last-inserted-timestamp)))
  11537. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  11538. org-last-inserted-timestamp
  11539. old-date
  11540. log))
  11541. (when repeater
  11542. (save-excursion
  11543. (org-back-to-heading t)
  11544. (when (re-search-forward
  11545. (concat keyword " " org-last-inserted-timestamp)
  11546. (line-end-position 2)
  11547. t)
  11548. (goto-char (1- (match-end 0)))
  11549. (insert " " repeater)
  11550. (setq org-last-inserted-timestamp
  11551. (concat (substring org-last-inserted-timestamp 0 -1)
  11552. " " repeater
  11553. (substring org-last-inserted-timestamp -1))))))
  11554. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  11555. org-last-inserted-timestamp)))))
  11556. (defun org-deadline (arg &optional time)
  11557. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  11558. With one universal prefix argument, remove any deadline from the item.
  11559. With two universal prefix arguments, prompt for a warning delay.
  11560. With argument TIME, set the deadline at the corresponding date. TIME
  11561. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11562. (interactive "P")
  11563. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11564. (org-map-entries
  11565. (lambda () (org--deadline-or-schedule arg 'deadline time))
  11566. nil
  11567. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11568. 'region-start-level
  11569. 'region)
  11570. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11571. (org--deadline-or-schedule arg 'deadline time)))
  11572. (defun org-schedule (arg &optional time)
  11573. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  11574. With one universal prefix argument, remove any scheduling date from the item.
  11575. With two universal prefix arguments, prompt for a delay cookie.
  11576. With argument TIME, scheduled at the corresponding date. TIME can
  11577. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11578. (interactive "P")
  11579. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11580. (org-map-entries
  11581. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  11582. nil
  11583. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11584. 'region-start-level
  11585. 'region)
  11586. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11587. (org--deadline-or-schedule arg 'scheduled time)))
  11588. (defun org-get-scheduled-time (pom &optional inherit)
  11589. "Get the scheduled time as a time tuple, of a format suitable
  11590. for calling org-schedule with, or if there is no scheduling,
  11591. returns nil."
  11592. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  11593. (when time
  11594. (apply 'encode-time (org-parse-time-string time)))))
  11595. (defun org-get-deadline-time (pom &optional inherit)
  11596. "Get the deadline as a time tuple, of a format suitable for
  11597. calling org-deadline with, or if there is no scheduling, returns
  11598. nil."
  11599. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  11600. (when time
  11601. (apply 'encode-time (org-parse-time-string time)))))
  11602. (defun org-remove-timestamp-with-keyword (keyword)
  11603. "Remove all time stamps with KEYWORD in the current entry."
  11604. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  11605. beg)
  11606. (save-excursion
  11607. (org-back-to-heading t)
  11608. (setq beg (point))
  11609. (outline-next-heading)
  11610. (while (re-search-backward re beg t)
  11611. (replace-match "")
  11612. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  11613. (equal (char-before) ?\ ))
  11614. (backward-delete-char 1)
  11615. (when (string-match "^[ \t]*$" (buffer-substring
  11616. (point-at-bol) (point-at-eol)))
  11617. (delete-region (point-at-bol)
  11618. (min (point-max) (1+ (point-at-eol))))))))))
  11619. (defvar org-time-was-given) ; dynamically scoped parameter
  11620. (defvar org-end-time-was-given) ; dynamically scoped parameter
  11621. (defun org-at-planning-p ()
  11622. "Non-nil when point is on a planning info line."
  11623. ;; This is as accurate and faster than `org-element-at-point' since
  11624. ;; planning info location is fixed in the section.
  11625. (org-with-wide-buffer
  11626. (beginning-of-line)
  11627. (and (looking-at-p org-planning-line-re)
  11628. (eq (point)
  11629. (ignore-errors
  11630. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  11631. (org-back-to-heading t)
  11632. (org-with-limited-levels (org-back-to-heading t)))
  11633. (line-beginning-position 2))))))
  11634. (defun org-add-planning-info (what &optional time &rest remove)
  11635. "Insert new timestamp with keyword in the planning line.
  11636. WHAT indicates what kind of time stamp to add. It is a symbol
  11637. among `closed', `deadline', `scheduled' and nil. TIME indicates
  11638. the time to use. If none is given, the user is prompted for
  11639. a date. REMOVE indicates what kind of entries to remove. An old
  11640. WHAT entry will also be removed."
  11641. (let (org-time-was-given org-end-time-was-given default-time default-input)
  11642. (catch 'exit
  11643. (when (and (memq what '(scheduled deadline))
  11644. (or (not time)
  11645. (and (stringp time)
  11646. (string-match "^[-+]+[0-9]" time))))
  11647. ;; Try to get a default date/time from existing timestamp
  11648. (save-excursion
  11649. (org-back-to-heading t)
  11650. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  11651. (when (re-search-forward (if (eq what 'scheduled)
  11652. org-scheduled-time-regexp
  11653. org-deadline-time-regexp)
  11654. end t)
  11655. (setq ts (match-string 1)
  11656. default-time (apply 'encode-time (org-parse-time-string ts))
  11657. default-input (and ts (org-get-compact-tod ts)))))))
  11658. (when what
  11659. (setq time
  11660. (if (stringp time)
  11661. ;; This is a string (relative or absolute), set
  11662. ;; proper date.
  11663. (apply #'encode-time
  11664. (org-read-date-analyze
  11665. time default-time (decode-time default-time)))
  11666. ;; If necessary, get the time from the user
  11667. (or time (org-read-date nil 'to-time nil
  11668. (cl-case what
  11669. (deadline "DEADLINE")
  11670. (scheduled "SCHEDULED")
  11671. (otherwise nil))
  11672. default-time default-input)))))
  11673. (org-with-wide-buffer
  11674. (org-back-to-heading t)
  11675. (forward-line)
  11676. (unless (bolp) (insert "\n"))
  11677. (cond ((looking-at-p org-planning-line-re)
  11678. ;; Move to current indentation.
  11679. (skip-chars-forward " \t")
  11680. ;; Check if we have to remove something.
  11681. (dolist (type (if what (cons what remove) remove))
  11682. (save-excursion
  11683. (when (re-search-forward
  11684. (cl-case type
  11685. (closed org-closed-time-regexp)
  11686. (deadline org-deadline-time-regexp)
  11687. (scheduled org-scheduled-time-regexp)
  11688. (otherwise
  11689. (error "Invalid planning type: %s" type)))
  11690. (line-end-position) t)
  11691. ;; Delete until next keyword or end of line.
  11692. (delete-region
  11693. (match-beginning 0)
  11694. (if (re-search-forward org-keyword-time-not-clock-regexp
  11695. (line-end-position)
  11696. t)
  11697. (match-beginning 0)
  11698. (line-end-position))))))
  11699. ;; If there is nothing more to add and no more keyword
  11700. ;; is left, remove the line completely.
  11701. (if (and (looking-at-p "[ \t]*$") (not what))
  11702. (delete-region (line-beginning-position)
  11703. (line-beginning-position 2))
  11704. ;; If we removed last keyword, do not leave trailing
  11705. ;; white space at the end of line.
  11706. (let ((p (point)))
  11707. (save-excursion
  11708. (end-of-line)
  11709. (unless (= (skip-chars-backward " \t" p) 0)
  11710. (delete-region (point) (line-end-position)))))))
  11711. ((not what) (throw 'exit nil)) ; Nothing to do.
  11712. (t (insert-before-markers "\n")
  11713. (backward-char 1)
  11714. (when org-adapt-indentation
  11715. (indent-to-column (1+ (org-outline-level))))))
  11716. (when what
  11717. ;; Insert planning keyword.
  11718. (insert (cl-case what
  11719. (closed org-closed-string)
  11720. (deadline org-deadline-string)
  11721. (scheduled org-scheduled-string)
  11722. (otherwise (error "Invalid planning type: %s" what)))
  11723. " ")
  11724. ;; Insert associated timestamp.
  11725. (let ((ts (org-insert-time-stamp
  11726. time
  11727. (or org-time-was-given
  11728. (and (eq what 'closed) org-log-done-with-time))
  11729. (eq what 'closed)
  11730. nil nil (list org-end-time-was-given))))
  11731. (unless (eolp) (insert " "))
  11732. ts))))))
  11733. (defvar org-log-note-marker (make-marker)
  11734. "Marker pointing at the entry where the note is to be inserted.")
  11735. (defvar org-log-note-purpose nil)
  11736. (defvar org-log-note-state nil)
  11737. (defvar org-log-note-previous-state nil)
  11738. (defvar org-log-note-extra nil)
  11739. (defvar org-log-note-window-configuration nil)
  11740. (defvar org-log-note-return-to (make-marker))
  11741. (defvar org-log-note-effective-time nil
  11742. "Remembered current time so that dynamically scoped
  11743. `org-extend-today-until' affects timestamps in state change log")
  11744. (defvar org-log-post-message nil
  11745. "Message to be displayed after a log note has been stored.
  11746. The auto-repeater uses this.")
  11747. (defun org-add-note ()
  11748. "Add a note to the current entry.
  11749. This is done in the same way as adding a state change note."
  11750. (interactive)
  11751. (org-add-log-setup 'note))
  11752. (defun org-log-beginning (&optional create)
  11753. "Return expected start of log notes in current entry.
  11754. When optional argument CREATE is non-nil, the function creates
  11755. a drawer to store notes, if necessary. Returned position ignores
  11756. narrowing."
  11757. (org-with-wide-buffer
  11758. (let ((drawer (org-log-into-drawer)))
  11759. (cond
  11760. (drawer
  11761. (org-end-of-meta-data)
  11762. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  11763. (end (if (org-at-heading-p) (point)
  11764. (save-excursion (outline-next-heading) (point))))
  11765. (case-fold-search t))
  11766. (catch 'exit
  11767. ;; Try to find existing drawer.
  11768. (while (re-search-forward regexp end t)
  11769. (let ((element (org-element-at-point)))
  11770. (when (eq (org-element-type element) 'drawer)
  11771. (let ((cend (org-element-property :contents-end element)))
  11772. (when (and (not org-log-states-order-reversed) cend)
  11773. (goto-char cend)))
  11774. (throw 'exit nil))))
  11775. ;; No drawer found. Create one, if permitted.
  11776. (when create
  11777. (unless (bolp) (insert "\n"))
  11778. (let ((beg (point)))
  11779. (insert ":" drawer ":\n:END:\n")
  11780. (org-indent-region beg (point))
  11781. (org-flag-region
  11782. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  11783. (end-of-line -1)))))
  11784. (t
  11785. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  11786. (skip-chars-forward " \t\n")
  11787. (beginning-of-line)
  11788. (unless org-log-states-order-reversed
  11789. (org-skip-over-state-notes)
  11790. (skip-chars-backward " \t\n")
  11791. (forward-line)))))
  11792. (if (bolp) (point) (line-beginning-position 2))))
  11793. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  11794. "Set up the post command hook to take a note.
  11795. If this is about to TODO state change, the new state is expected in STATE.
  11796. HOW is an indicator what kind of note should be created.
  11797. EXTRA is additional text that will be inserted into the notes buffer."
  11798. (move-marker org-log-note-marker (point))
  11799. (setq org-log-note-purpose purpose
  11800. org-log-note-state state
  11801. org-log-note-previous-state prev-state
  11802. org-log-note-how how
  11803. org-log-note-extra extra
  11804. org-log-note-effective-time (org-current-effective-time))
  11805. (add-hook 'post-command-hook 'org-add-log-note 'append))
  11806. (defun org-skip-over-state-notes ()
  11807. "Skip past the list of State notes in an entry."
  11808. (when (ignore-errors (goto-char (org-in-item-p)))
  11809. (let* ((struct (org-list-struct))
  11810. (prevs (org-list-prevs-alist struct))
  11811. (regexp
  11812. (concat "[ \t]*- +"
  11813. (replace-regexp-in-string
  11814. " +" " +"
  11815. (org-replace-escapes
  11816. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  11817. `(("%d" . ,org-ts-regexp-inactive)
  11818. ("%D" . ,org-ts-regexp)
  11819. ("%s" . "\\(?:\"\\S-+\"\\)?")
  11820. ("%S" . "\\(?:\"\\S-+\"\\)?")
  11821. ("%t" . ,org-ts-regexp-inactive)
  11822. ("%T" . ,org-ts-regexp)
  11823. ("%u" . ".*?")
  11824. ("%U" . ".*?")))))))
  11825. (while (looking-at-p regexp)
  11826. (goto-char (or (org-list-get-next-item (point) struct prevs)
  11827. (org-list-get-item-end (point) struct)))))))
  11828. (defun org-add-log-note (&optional _purpose)
  11829. "Pop up a window for taking a note, and add this note later."
  11830. (remove-hook 'post-command-hook 'org-add-log-note)
  11831. (setq org-log-note-window-configuration (current-window-configuration))
  11832. (delete-other-windows)
  11833. (move-marker org-log-note-return-to (point))
  11834. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  11835. (goto-char org-log-note-marker)
  11836. (org-switch-to-buffer-other-window "*Org Note*")
  11837. (erase-buffer)
  11838. (if (memq org-log-note-how '(time state))
  11839. (org-store-log-note)
  11840. (let ((org-inhibit-startup t)) (org-mode))
  11841. (insert (format "# Insert note for %s.
  11842. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  11843. (cl-case org-log-note-purpose
  11844. (clock-out "stopped clock")
  11845. (done "closed todo item")
  11846. (reschedule "rescheduling")
  11847. (delschedule "no longer scheduled")
  11848. (redeadline "changing deadline")
  11849. (deldeadline "removing deadline")
  11850. (refile "refiling")
  11851. (note "this entry")
  11852. (state
  11853. (format "state change from \"%s\" to \"%s\""
  11854. (or org-log-note-previous-state "")
  11855. (or org-log-note-state "")))
  11856. (t (error "This should not happen")))))
  11857. (when org-log-note-extra (insert org-log-note-extra))
  11858. (setq-local org-finish-function 'org-store-log-note)
  11859. (run-hooks 'org-log-buffer-setup-hook)))
  11860. (defvar org-note-abort nil) ; dynamically scoped
  11861. (defun org-store-log-note ()
  11862. "Finish taking a log note, and insert it to where it belongs."
  11863. (let ((txt (prog1 (buffer-string)
  11864. (kill-buffer)))
  11865. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  11866. lines)
  11867. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  11868. (setq txt (replace-match "" t t txt)))
  11869. (when (string-match "\\s-+\\'" txt)
  11870. (setq txt (replace-match "" t t txt)))
  11871. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  11872. (when (org-string-nw-p note)
  11873. (setq note
  11874. (org-replace-escapes
  11875. note
  11876. (list (cons "%u" (user-login-name))
  11877. (cons "%U" user-full-name)
  11878. (cons "%t" (format-time-string
  11879. (org-time-stamp-format 'long 'inactive)
  11880. org-log-note-effective-time))
  11881. (cons "%T" (format-time-string
  11882. (org-time-stamp-format 'long nil)
  11883. org-log-note-effective-time))
  11884. (cons "%d" (format-time-string
  11885. (org-time-stamp-format nil 'inactive)
  11886. org-log-note-effective-time))
  11887. (cons "%D" (format-time-string
  11888. (org-time-stamp-format nil nil)
  11889. org-log-note-effective-time))
  11890. (cons "%s" (cond
  11891. ((not org-log-note-state) "")
  11892. ((string-match-p org-ts-regexp
  11893. org-log-note-state)
  11894. (format "\"[%s]\""
  11895. (substring org-log-note-state 1 -1)))
  11896. (t (format "\"%s\"" org-log-note-state))))
  11897. (cons "%S"
  11898. (cond
  11899. ((not org-log-note-previous-state) "")
  11900. ((string-match-p org-ts-regexp
  11901. org-log-note-previous-state)
  11902. (format "\"[%s]\""
  11903. (substring
  11904. org-log-note-previous-state 1 -1)))
  11905. (t (format "\"%s\""
  11906. org-log-note-previous-state)))))))
  11907. (when lines (setq note (concat note " \\\\")))
  11908. (push note lines))
  11909. (when (and lines (not org-note-abort))
  11910. (with-current-buffer (marker-buffer org-log-note-marker)
  11911. (org-with-wide-buffer
  11912. ;; Find location for the new note.
  11913. (goto-char org-log-note-marker)
  11914. (set-marker org-log-note-marker nil)
  11915. ;; Note associated to a clock is to be located right after
  11916. ;; the clock. Do not move point.
  11917. (unless (eq org-log-note-purpose 'clock-out)
  11918. (goto-char (org-log-beginning t)))
  11919. ;; Make sure point is at the beginning of an empty line.
  11920. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  11921. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  11922. ;; In an existing list, add a new item at the top level.
  11923. ;; Otherwise, indent line like a regular one.
  11924. (let ((itemp (org-in-item-p)))
  11925. (if itemp
  11926. (indent-line-to
  11927. (let ((struct (save-excursion
  11928. (goto-char itemp) (org-list-struct))))
  11929. (org-list-get-ind (org-list-get-top-point struct) struct)))
  11930. (org-indent-line)))
  11931. (insert (org-list-bullet-string "-") (pop lines))
  11932. (let ((ind (org-list-item-body-column (line-beginning-position))))
  11933. (dolist (line lines)
  11934. (insert "\n")
  11935. (indent-line-to ind)
  11936. (insert line)))
  11937. (message "Note stored")
  11938. (org-back-to-heading t))
  11939. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  11940. ;; from within `org-add-log-note' because `buffer-undo-list'
  11941. ;; is then modified outside of `org-with-remote-undo'.
  11942. (when (eq this-command 'org-agenda-todo)
  11943. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  11944. ;; Don't add undo information when called from `org-agenda-todo'.
  11945. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  11946. (set-window-configuration org-log-note-window-configuration)
  11947. (with-current-buffer (marker-buffer org-log-note-return-to)
  11948. (goto-char org-log-note-return-to))
  11949. (move-marker org-log-note-return-to nil)
  11950. (when org-log-post-message (message "%s" org-log-post-message))))
  11951. (defun org-remove-empty-drawer-at (pos)
  11952. "Remove an empty drawer at position POS.
  11953. POS may also be a marker."
  11954. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  11955. (org-with-wide-buffer
  11956. (goto-char pos)
  11957. (let ((drawer (org-element-at-point)))
  11958. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  11959. (not (org-element-property :contents-begin drawer)))
  11960. (delete-region (org-element-property :begin drawer)
  11961. (progn (goto-char (org-element-property :end drawer))
  11962. (skip-chars-backward " \r\t\n")
  11963. (forward-line)
  11964. (point))))))))
  11965. (defvar org-ts-type nil)
  11966. (defun org-sparse-tree (&optional arg type)
  11967. "Create a sparse tree, prompt for the details.
  11968. This command can create sparse trees. You first need to select the type
  11969. of match used to create the tree:
  11970. t Show all TODO entries.
  11971. T Show entries with a specific TODO keyword.
  11972. m Show entries selected by a tags/property match.
  11973. p Enter a property name and its value (both with completion on existing
  11974. names/values) and show entries with that property.
  11975. r Show entries matching a regular expression (`/' can be used as well).
  11976. b Show deadlines and scheduled items before a date.
  11977. a Show deadlines and scheduled items after a date.
  11978. d Show deadlines due within `org-deadline-warning-days'.
  11979. D Show deadlines and scheduled items between a date range."
  11980. (interactive "P")
  11981. (setq type (or type org-sparse-tree-default-date-type))
  11982. (setq org-ts-type type)
  11983. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  11984. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  11985. \[c]ycle through date types: %s"
  11986. (cl-case type
  11987. (all "all timestamps")
  11988. (scheduled "only scheduled")
  11989. (deadline "only deadline")
  11990. (active "only active timestamps")
  11991. (inactive "only inactive timestamps")
  11992. (closed "with a closed time-stamp")
  11993. (otherwise "scheduled/deadline")))
  11994. (let ((answer (read-char-exclusive)))
  11995. (cl-case answer
  11996. (?c
  11997. (org-sparse-tree
  11998. arg
  11999. (cadr
  12000. (memq type '(nil all scheduled deadline active inactive closed)))))
  12001. (?d (call-interactively 'org-check-deadlines))
  12002. (?b (call-interactively 'org-check-before-date))
  12003. (?a (call-interactively 'org-check-after-date))
  12004. (?D (call-interactively 'org-check-dates-range))
  12005. (?t (call-interactively 'org-show-todo-tree))
  12006. (?T (org-show-todo-tree '(4)))
  12007. (?m (call-interactively 'org-match-sparse-tree))
  12008. ((?p ?P)
  12009. (let* ((kwd (completing-read
  12010. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12011. (value (completing-read
  12012. "Value: " (mapcar #'list (org-property-values kwd)))))
  12013. (unless (string-match "\\`{.*}\\'" value)
  12014. (setq value (concat "\"" value "\"")))
  12015. (org-match-sparse-tree arg (concat kwd "=" value))))
  12016. ((?r ?R ?/) (call-interactively 'org-occur))
  12017. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12018. (defvar-local org-occur-highlights nil
  12019. "List of overlays used for occur matches.")
  12020. (defvar-local org-occur-parameters nil
  12021. "Parameters of the active org-occur calls.
  12022. This is a list, each call to org-occur pushes as cons cell,
  12023. containing the regular expression and the callback, onto the list.
  12024. The list can contain several entries if `org-occur' has been called
  12025. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12026. will only contain one set of parameters. When the highlights are
  12027. removed (for example with `C-c C-c', or with the next edit (depending
  12028. on `org-remove-highlights-with-change'), this variable is emptied
  12029. as well.")
  12030. (defun org-occur (regexp &optional keep-previous callback)
  12031. "Make a compact tree which shows all matches of REGEXP.
  12032. The tree will show the lines where the regexp matches, and any other context
  12033. defined in `org-show-context-detail', which see.
  12034. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12035. done by a previous call to `org-occur' will be kept, to allow stacking of
  12036. calls to this command.
  12037. Optional argument CALLBACK can be a function of no argument. In this case,
  12038. it is called with point at the end of the match, match data being set
  12039. accordingly. Current match is shown only if the return value is non-nil.
  12040. The function must neither move point nor alter narrowing."
  12041. (interactive "sRegexp: \nP")
  12042. (when (equal regexp "")
  12043. (user-error "Regexp cannot be empty"))
  12044. (unless keep-previous
  12045. (org-remove-occur-highlights nil nil t))
  12046. (push (cons regexp callback) org-occur-parameters)
  12047. (let ((cnt 0))
  12048. (save-excursion
  12049. (goto-char (point-min))
  12050. (when (or (not keep-previous) ; do not want to keep
  12051. (not org-occur-highlights)) ; no previous matches
  12052. ;; hide everything
  12053. (org-overview))
  12054. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12055. (isearch-no-upper-case-p regexp t)
  12056. org-occur-case-fold-search)))
  12057. (while (re-search-forward regexp nil t)
  12058. (when (or (not callback)
  12059. (save-match-data (funcall callback)))
  12060. (setq cnt (1+ cnt))
  12061. (when org-highlight-sparse-tree-matches
  12062. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12063. (org-show-context 'occur-tree)))))
  12064. (when org-remove-highlights-with-change
  12065. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12066. nil 'local))
  12067. (unless org-sparse-tree-open-archived-trees
  12068. (org-hide-archived-subtrees (point-min) (point-max)))
  12069. (run-hooks 'org-occur-hook)
  12070. (when (called-interactively-p 'interactive)
  12071. (message "%d match(es) for regexp %s" cnt regexp))
  12072. cnt))
  12073. (defun org-occur-next-match (&optional n _reset)
  12074. "Function for `next-error-function' to find sparse tree matches.
  12075. N is the number of matches to move, when negative move backwards.
  12076. This function always goes back to the starting point when no
  12077. match is found."
  12078. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12079. (search-func (if (< n 0)
  12080. 'previous-single-char-property-change
  12081. 'next-single-char-property-change))
  12082. (n (abs n))
  12083. (pos (point))
  12084. p1)
  12085. (catch 'exit
  12086. (while (setq p1 (funcall search-func (point) 'org-type))
  12087. (when (equal p1 limit)
  12088. (goto-char pos)
  12089. (user-error "No more matches"))
  12090. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12091. (setq n (1- n))
  12092. (when (= n 0)
  12093. (goto-char p1)
  12094. (throw 'exit (point))))
  12095. (goto-char p1))
  12096. (goto-char p1)
  12097. (user-error "No more matches"))))
  12098. (defun org-highlight-new-match (beg end)
  12099. "Highlight from BEG to END and mark the highlight is an occur headline."
  12100. (let ((ov (make-overlay beg end)))
  12101. (overlay-put ov 'face 'secondary-selection)
  12102. (overlay-put ov 'org-type 'org-occur)
  12103. (push ov org-occur-highlights)))
  12104. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12105. "Remove the occur highlights from the buffer.
  12106. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12107. from the `before-change-functions' in the current buffer."
  12108. (interactive)
  12109. (unless org-inhibit-highlight-removal
  12110. (mapc #'delete-overlay org-occur-highlights)
  12111. (setq org-occur-highlights nil)
  12112. (setq org-occur-parameters nil)
  12113. (unless noremove
  12114. (remove-hook 'before-change-functions
  12115. 'org-remove-occur-highlights 'local))))
  12116. ;;;; Priorities
  12117. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12118. "Regular expression matching the priority indicator.")
  12119. (defvar org-remove-priority-next-time nil)
  12120. (defun org-priority-up ()
  12121. "Increase the priority of the current item."
  12122. (interactive)
  12123. (org-priority 'up))
  12124. (defun org-priority-down ()
  12125. "Decrease the priority of the current item."
  12126. (interactive)
  12127. (org-priority 'down))
  12128. (defun org-priority (&optional action show)
  12129. "Change the priority of an item.
  12130. When called interactively with a `\\[universal-argument]' prefix,
  12131. show the priority in the minibuffer instead of changing it.
  12132. When called programatically, ACTION can be `set', `up', `down',
  12133. or a character."
  12134. (interactive "P")
  12135. (when show
  12136. ;; Deprecation warning inserted for Org 9.2; once enough time has
  12137. ;; passed the SHOW argument should be removed.
  12138. (warn "`org-priority' called with deprecated SHOW argument"))
  12139. (if (equal action '(4))
  12140. (org-show-priority)
  12141. (unless org-enable-priority-commands
  12142. (user-error "Priority commands are disabled"))
  12143. (setq action (or action 'set))
  12144. (let (current new news have remove)
  12145. (save-excursion
  12146. (org-back-to-heading t)
  12147. (when (looking-at org-priority-regexp)
  12148. (setq current (string-to-char (match-string 2))
  12149. have t))
  12150. (cond
  12151. ((eq action 'remove)
  12152. (setq remove t new ?\ ))
  12153. ((or (eq action 'set)
  12154. (integerp action))
  12155. (if (not (eq action 'set))
  12156. (setq new action)
  12157. (message "Priority %c-%c, SPC to remove: "
  12158. org-highest-priority org-lowest-priority)
  12159. (save-match-data
  12160. (setq new (read-char-exclusive))))
  12161. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12162. (= (upcase org-lowest-priority) org-lowest-priority))
  12163. (setq new (upcase new)))
  12164. (cond ((equal new ?\s) (setq remove t))
  12165. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12166. (user-error "Priority must be between `%c' and `%c'"
  12167. org-highest-priority org-lowest-priority))))
  12168. ((eq action 'up)
  12169. (setq new (if have
  12170. (1- current) ; normal cycling
  12171. ;; last priority was empty
  12172. (if (eq last-command this-command)
  12173. org-lowest-priority ; wrap around empty to lowest
  12174. ;; default
  12175. (if org-priority-start-cycle-with-default
  12176. org-default-priority
  12177. (1- org-default-priority))))))
  12178. ((eq action 'down)
  12179. (setq new (if have
  12180. (1+ current) ; normal cycling
  12181. ;; last priority was empty
  12182. (if (eq last-command this-command)
  12183. org-highest-priority ; wrap around empty to highest
  12184. ;; default
  12185. (if org-priority-start-cycle-with-default
  12186. org-default-priority
  12187. (1+ org-default-priority))))))
  12188. (t (user-error "Invalid action")))
  12189. (when (or (< (upcase new) org-highest-priority)
  12190. (> (upcase new) org-lowest-priority))
  12191. (if (and (memq action '(up down))
  12192. (not have) (not (eq last-command this-command)))
  12193. ;; `new' is from default priority
  12194. (error
  12195. "The default can not be set, see `org-default-priority' why")
  12196. ;; normal cycling: `new' is beyond highest/lowest priority
  12197. ;; and is wrapped around to the empty priority
  12198. (setq remove t)))
  12199. (setq news (format "%c" new))
  12200. (if have
  12201. (if remove
  12202. (replace-match "" t t nil 1)
  12203. (replace-match news t t nil 2))
  12204. (if remove
  12205. (user-error "No priority cookie found in line")
  12206. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12207. (if (match-end 2)
  12208. (progn
  12209. (goto-char (match-end 2))
  12210. (insert " [#" news "]"))
  12211. (goto-char (match-beginning 3))
  12212. (insert "[#" news "] "))))
  12213. (org-align-tags))
  12214. (if remove
  12215. (message "Priority removed")
  12216. (message "Priority of current item set to %s" news)))))
  12217. (defun org-show-priority ()
  12218. "Show the priority of the current item.
  12219. This priority is composed of the main priority given with the [#A] cookies,
  12220. and by additional input from the age of a schedules or deadline entry."
  12221. (interactive)
  12222. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12223. (org-get-at-bol 'priority)
  12224. (save-excursion
  12225. (save-match-data
  12226. (beginning-of-line)
  12227. (and (looking-at org-heading-regexp)
  12228. (org-get-priority (match-string 0))))))))
  12229. (message "Priority is %d" (if pri pri -1000))))
  12230. (defun org-get-priority (s)
  12231. "Find priority cookie and return priority."
  12232. (save-match-data
  12233. (if (functionp org-get-priority-function)
  12234. (funcall org-get-priority-function)
  12235. (if (not (string-match org-priority-regexp s))
  12236. (* 1000 (- org-lowest-priority org-default-priority))
  12237. (* 1000 (- org-lowest-priority
  12238. (string-to-char (match-string 2 s))))))))
  12239. ;;;; Tags
  12240. (defvar org-agenda-archives-mode)
  12241. (defvar org-map-continue-from nil
  12242. "Position from where mapping should continue.
  12243. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12244. (defvar org-scanner-tags nil
  12245. "The current tag list while the tags scanner is running.")
  12246. (defvar org-trust-scanner-tags nil
  12247. "Should `org-get-tags' use the tags for the scanner.
  12248. This is for internal dynamical scoping only.
  12249. When this is non-nil, the function `org-get-tags' will return the value
  12250. of `org-scanner-tags' instead of building the list by itself. This
  12251. can lead to large speed-ups when the tags scanner is used in a file with
  12252. many entries, and when the list of tags is retrieved, for example to
  12253. obtain a list of properties. Building the tags list for each entry in such
  12254. a file becomes an N^2 operation - but with this variable set, it scales
  12255. as N.")
  12256. (defvar org--matcher-tags-todo-only nil)
  12257. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12258. "Scan headline tags with inheritance and produce output ACTION.
  12259. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12260. or `agenda' to produce an entry list for an agenda view. It can also be
  12261. a Lisp form or a function that should be called at each matched headline, in
  12262. this case the return value is a list of all return values from these calls.
  12263. MATCHER is a function accepting three arguments, returning
  12264. a non-nil value whenever a given set of tags qualifies a headline
  12265. for inclusion. See `org-make-tags-matcher' for more information.
  12266. As a special case, it can also be set to t (respectively nil) in
  12267. order to match all (respectively none) headline.
  12268. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  12269. included in the output.
  12270. START-LEVEL can be a string with asterisks, reducing the scope to
  12271. headlines matching this string."
  12272. (require 'org-agenda)
  12273. (let* ((re (concat "^"
  12274. (if start-level
  12275. ;; Get the correct level to match
  12276. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12277. org-outline-regexp)
  12278. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  12279. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  12280. (props (list 'face 'default
  12281. 'done-face 'org-agenda-done
  12282. 'undone-face 'default
  12283. 'mouse-face 'highlight
  12284. 'org-not-done-regexp org-not-done-regexp
  12285. 'org-todo-regexp org-todo-regexp
  12286. 'org-complex-heading-regexp org-complex-heading-regexp
  12287. 'help-echo
  12288. (format "mouse-2 or RET jump to Org file %S"
  12289. (abbreviate-file-name
  12290. (or (buffer-file-name (buffer-base-buffer))
  12291. (buffer-name (buffer-base-buffer)))))))
  12292. (org-map-continue-from nil)
  12293. lspos tags tags-list
  12294. (tags-alist (list (cons 0 org-file-tags)))
  12295. (llast 0) rtn rtn1 level category i txt
  12296. todo marker entry priority
  12297. ts-date ts-date-type ts-date-pair)
  12298. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12299. (setq action (list 'lambda nil action)))
  12300. (save-excursion
  12301. (goto-char (point-min))
  12302. (when (eq action 'sparse-tree)
  12303. (org-overview)
  12304. (org-remove-occur-highlights))
  12305. (while (let (case-fold-search)
  12306. (re-search-forward re nil t))
  12307. (setq org-map-continue-from nil)
  12308. (catch :skip
  12309. ;; Ignore closing parts of inline tasks.
  12310. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  12311. (throw :skip t))
  12312. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  12313. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  12314. (goto-char (setq lspos (match-beginning 0)))
  12315. (setq level (org-reduced-level (org-outline-level))
  12316. category (org-get-category))
  12317. (when (eq action 'agenda)
  12318. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12319. ts-date (car ts-date-pair)
  12320. ts-date-type (cdr ts-date-pair)))
  12321. (setq i llast llast level)
  12322. ;; remove tag lists from same and sublevels
  12323. (while (>= i level)
  12324. (when (setq entry (assoc i tags-alist))
  12325. (setq tags-alist (delete entry tags-alist)))
  12326. (setq i (1- i)))
  12327. ;; add the next tags
  12328. (when tags
  12329. (setq tags (org-split-string tags ":")
  12330. tags-alist
  12331. (cons (cons level tags) tags-alist)))
  12332. ;; compile tags for current headline
  12333. (setq tags-list
  12334. (if org-use-tag-inheritance
  12335. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12336. tags)
  12337. org-scanner-tags tags-list)
  12338. (when org-use-tag-inheritance
  12339. (setcdr (car tags-alist)
  12340. (mapcar (lambda (x)
  12341. (setq x (copy-sequence x))
  12342. (org-add-prop-inherited x))
  12343. (cdar tags-alist))))
  12344. (when (and tags org-use-tag-inheritance
  12345. (or (not (eq t org-use-tag-inheritance))
  12346. org-tags-exclude-from-inheritance))
  12347. ;; Selective inheritance, remove uninherited ones.
  12348. (setcdr (car tags-alist)
  12349. (org-remove-uninherited-tags (cdar tags-alist))))
  12350. (when (and
  12351. ;; eval matcher only when the todo condition is OK
  12352. (and (or (not todo-only) (member todo org-todo-keywords-1))
  12353. (if (functionp matcher)
  12354. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12355. (funcall matcher todo tags-list level))
  12356. matcher))
  12357. ;; Call the skipper, but return t if it does not
  12358. ;; skip, so that the `and' form continues evaluating.
  12359. (progn
  12360. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12361. t)
  12362. ;; Check if timestamps are deselecting this entry
  12363. (or (not todo-only)
  12364. (and (member todo org-todo-keywords-1)
  12365. (or (not org-agenda-tags-todo-honor-ignore-options)
  12366. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12367. ;; select this headline
  12368. (cond
  12369. ((eq action 'sparse-tree)
  12370. (and org-highlight-sparse-tree-matches
  12371. (org-get-heading) (match-end 0)
  12372. (org-highlight-new-match
  12373. (match-beginning 1) (match-end 1)))
  12374. (org-show-context 'tags-tree))
  12375. ((eq action 'agenda)
  12376. (setq txt (org-agenda-format-item
  12377. ""
  12378. (concat
  12379. (if (eq org-tags-match-list-sublevels 'indented)
  12380. (make-string (1- level) ?.) "")
  12381. (org-get-heading))
  12382. (make-string level ?\s)
  12383. category
  12384. tags-list)
  12385. priority (org-get-priority txt))
  12386. (goto-char lspos)
  12387. (setq marker (org-agenda-new-marker))
  12388. (org-add-props txt props
  12389. 'org-marker marker 'org-hd-marker marker 'org-category category
  12390. 'todo-state todo
  12391. 'ts-date ts-date
  12392. 'priority priority
  12393. 'type (concat "tagsmatch" ts-date-type))
  12394. (push txt rtn))
  12395. ((functionp action)
  12396. (setq org-map-continue-from nil)
  12397. (save-excursion
  12398. (setq rtn1 (funcall action))
  12399. (push rtn1 rtn)))
  12400. (t (user-error "Invalid action")))
  12401. ;; if we are to skip sublevels, jump to end of subtree
  12402. (unless org-tags-match-list-sublevels
  12403. (org-end-of-subtree t)
  12404. (backward-char 1))))
  12405. ;; Get the correct position from where to continue
  12406. (if org-map-continue-from
  12407. (goto-char org-map-continue-from)
  12408. (and (= (point) lspos) (end-of-line 1)))))
  12409. (when (and (eq action 'sparse-tree)
  12410. (not org-sparse-tree-open-archived-trees))
  12411. (org-hide-archived-subtrees (point-min) (point-max)))
  12412. (nreverse rtn)))
  12413. (defun org-remove-uninherited-tags (tags)
  12414. "Remove all tags that are not inherited from the list TAGS."
  12415. (cond
  12416. ((eq org-use-tag-inheritance t)
  12417. (if org-tags-exclude-from-inheritance
  12418. (org-delete-all org-tags-exclude-from-inheritance tags)
  12419. tags))
  12420. ((not org-use-tag-inheritance) nil)
  12421. ((stringp org-use-tag-inheritance)
  12422. (delq nil (mapcar
  12423. (lambda (x)
  12424. (if (and (string-match org-use-tag-inheritance x)
  12425. (not (member x org-tags-exclude-from-inheritance)))
  12426. x nil))
  12427. tags)))
  12428. ((listp org-use-tag-inheritance)
  12429. (delq nil (mapcar
  12430. (lambda (x)
  12431. (if (member x org-use-tag-inheritance) x nil))
  12432. tags)))))
  12433. (defun org-match-sparse-tree (&optional todo-only match)
  12434. "Create a sparse tree according to tags string MATCH.
  12435. MATCH is a string with match syntax. It can contain a selection
  12436. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  12437. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  12438. those. See the manual for details.
  12439. If optional argument TODO-ONLY is non-nil, only select lines that
  12440. are also TODO tasks."
  12441. (interactive "P")
  12442. (org-agenda-prepare-buffers (list (current-buffer)))
  12443. (let ((org--matcher-tags-todo-only todo-only))
  12444. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  12445. org--matcher-tags-todo-only)))
  12446. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  12447. (defvar org-cached-props nil)
  12448. (defun org-cached-entry-get (pom property)
  12449. (if (or (eq t org-use-property-inheritance)
  12450. (and (stringp org-use-property-inheritance)
  12451. (let ((case-fold-search t))
  12452. (string-match-p org-use-property-inheritance property)))
  12453. (and (listp org-use-property-inheritance)
  12454. (member-ignore-case property org-use-property-inheritance)))
  12455. ;; Caching is not possible, check it directly.
  12456. (org-entry-get pom property 'inherit)
  12457. ;; Get all properties, so we can do complicated checks easily.
  12458. (cdr (assoc-string property
  12459. (or org-cached-props
  12460. (setq org-cached-props (org-entry-properties pom)))
  12461. t))))
  12462. (defun org-global-tags-completion-table (&optional files)
  12463. "Return the list of all tags in all agenda buffer/files.
  12464. Optional FILES argument is a list of files which can be used
  12465. instead of the agenda files."
  12466. (save-excursion
  12467. (org-uniquify
  12468. (delq nil
  12469. (apply #'append
  12470. (mapcar
  12471. (lambda (file)
  12472. (set-buffer (find-file-noselect file))
  12473. (org--tag-add-to-alist
  12474. (org-get-buffer-tags)
  12475. (mapcar (lambda (x)
  12476. (and (stringp (car-safe x))
  12477. (list (car-safe x))))
  12478. org-current-tag-alist)))
  12479. (if (car-safe files) files
  12480. (org-agenda-files))))))))
  12481. (defun org-make-tags-matcher (match)
  12482. "Create the TAGS/TODO matcher form for the selection string MATCH.
  12483. Returns a cons of the selection string MATCH and a function
  12484. implementing the matcher.
  12485. The matcher is to be called at an Org entry, with point on the
  12486. headline, and returns non-nil if the entry matches the selection
  12487. string MATCH. It must be called with three arguments: the TODO
  12488. keyword at the entry (or nil if none), the list of all tags at
  12489. the entry including inherited ones and the reduced level of the
  12490. headline. Additionally, the category of the entry, if any, must
  12491. be specified as the text property `org-category' on the headline.
  12492. This function sets the variable `org--matcher-tags-todo-only' to
  12493. a non-nil value if the matcher restricts matching to TODO
  12494. entries, otherwise it is not touched.
  12495. See also `org-scan-tags'."
  12496. (unless match
  12497. ;; Get a new match request, with completion against the global
  12498. ;; tags table and the local tags in current buffer.
  12499. (let ((org-last-tags-completion-table
  12500. (org--tag-add-to-alist
  12501. (org-get-buffer-tags)
  12502. (org-global-tags-completion-table))))
  12503. (setq match
  12504. (completing-read
  12505. "Match: "
  12506. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  12507. (let ((match0 match)
  12508. (re (concat
  12509. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  12510. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  12511. "\\([<>=]\\{1,2\\}\\)"
  12512. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  12513. "\\|" org-tag-re "\\)"))
  12514. (start 0)
  12515. tagsmatch todomatch tagsmatcher todomatcher)
  12516. ;; Expand group tags.
  12517. (setq match (org-tags-expand match))
  12518. ;; Check if there is a TODO part of this match, which would be the
  12519. ;; part after a "/". To make sure that this slash is not part of
  12520. ;; a property value to be matched against, we also check that
  12521. ;; there is no / after that slash. First, find the last slash.
  12522. (let ((s 0))
  12523. (while (string-match "/+" match s)
  12524. (setq start (match-beginning 0))
  12525. (setq s (match-end 0))))
  12526. (if (and (string-match "/+" match start)
  12527. (not (string-match-p "\"" match start)))
  12528. ;; Match contains also a TODO-matching request.
  12529. (progn
  12530. (setq tagsmatch (substring match 0 (match-beginning 0)))
  12531. (setq todomatch (substring match (match-end 0)))
  12532. (when (string-prefix-p "!" todomatch)
  12533. (setq org--matcher-tags-todo-only t)
  12534. (setq todomatch (substring todomatch 1)))
  12535. (when (string-match "\\`\\s-*\\'" todomatch)
  12536. (setq todomatch nil)))
  12537. ;; Only matching tags.
  12538. (setq tagsmatch match)
  12539. (setq todomatch nil))
  12540. ;; Make the tags matcher.
  12541. (when (org-string-nw-p tagsmatch)
  12542. (let ((orlist nil)
  12543. (orterms (org-split-string tagsmatch "|"))
  12544. term)
  12545. (while (setq term (pop orterms))
  12546. (while (and (equal (substring term -1) "\\") orterms)
  12547. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  12548. (while (string-match re term)
  12549. (let* ((rest (substring term (match-end 0)))
  12550. (minus (and (match-end 1)
  12551. (equal (match-string 1 term) "-")))
  12552. (tag (save-match-data
  12553. (replace-regexp-in-string
  12554. "\\\\-" "-" (match-string 2 term))))
  12555. (regexp (eq (string-to-char tag) ?{))
  12556. (levelp (match-end 4))
  12557. (propp (match-end 5))
  12558. (mm
  12559. (cond
  12560. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  12561. (levelp
  12562. `(,(org-op-to-function (match-string 3 term))
  12563. level
  12564. ,(string-to-number (match-string 4 term))))
  12565. (propp
  12566. (let* ((gv (pcase (upcase (match-string 5 term))
  12567. ("CATEGORY"
  12568. '(get-text-property (point) 'org-category))
  12569. ("TODO" 'todo)
  12570. (p `(org-cached-entry-get nil ,p))))
  12571. (pv (match-string 7 term))
  12572. (regexp (eq (string-to-char pv) ?{))
  12573. (strp (eq (string-to-char pv) ?\"))
  12574. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  12575. (po (org-op-to-function (match-string 6 term)
  12576. (if timep 'time strp))))
  12577. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  12578. (when timep (setq pv (org-matcher-time pv)))
  12579. (cond ((and regexp (eq po '/=))
  12580. `(not (string-match ,pv (or ,gv ""))))
  12581. (regexp `(string-match ,pv (or ,gv "")))
  12582. (strp `(,po (or ,gv "") ,pv))
  12583. (t
  12584. `(,po
  12585. (string-to-number (or ,gv ""))
  12586. ,(string-to-number pv))))))
  12587. (t `(member ,tag tags-list)))))
  12588. (push (if minus `(not ,mm) mm) tagsmatcher)
  12589. (setq term rest)))
  12590. (push `(and ,@tagsmatcher) orlist)
  12591. (setq tagsmatcher nil))
  12592. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  12593. ;; Make the TODO matcher.
  12594. (when (org-string-nw-p todomatch)
  12595. (let ((orlist nil))
  12596. (dolist (term (org-split-string todomatch "|"))
  12597. (while (string-match re term)
  12598. (let* ((minus (and (match-end 1)
  12599. (equal (match-string 1 term) "-")))
  12600. (kwd (match-string 2 term))
  12601. (regexp (eq (string-to-char kwd) ?{))
  12602. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  12603. `(equal todo ,kwd))))
  12604. (push (if minus `(not ,mm) mm) todomatcher))
  12605. (setq term (substring term (match-end 0))))
  12606. (push (if (> (length todomatcher) 1)
  12607. (cons 'and todomatcher)
  12608. (car todomatcher))
  12609. orlist)
  12610. (setq todomatcher nil))
  12611. (setq todomatcher (cons 'or orlist))))
  12612. ;; Return the string and function of the matcher. If no
  12613. ;; tags-specific or todo-specific matcher exists, match
  12614. ;; everything.
  12615. (let ((matcher (if (and tagsmatcher todomatcher)
  12616. `(and ,tagsmatcher ,todomatcher)
  12617. (or tagsmatcher todomatcher t))))
  12618. (when org--matcher-tags-todo-only
  12619. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  12620. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  12621. (defun org--tags-expand-group (group tag-groups expanded)
  12622. "Recursively Expand all tags in GROUP, according to TAG-GROUPS.
  12623. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  12624. an accumulator used in recursive calls."
  12625. (dolist (tag group)
  12626. (unless (member tag expanded)
  12627. (let ((group (assoc tag tag-groups)))
  12628. (push tag expanded)
  12629. (when group
  12630. (setq expanded
  12631. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  12632. expanded)
  12633. (defun org-tags-expand (match &optional single-as-list downcased)
  12634. "Expand group tags in MATCH.
  12635. This replaces every group tag in MATCH with a regexp tag search.
  12636. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  12637. will be replaced like this:
  12638. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12639. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12640. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12641. Replacing by a regexp preserves the structure of the match.
  12642. E.g., this expansion
  12643. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  12644. will match anything tagged with \"Lab\" and \"Home\", or tagged
  12645. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  12646. A group tag in MATCH can contain regular expressions of its own.
  12647. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  12648. will be replaced like this:
  12649. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  12650. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  12651. assumed to be a single group tag, and the function will return
  12652. the list of tags in this group.
  12653. When DOWNCASED is non-nil, expand downcased TAGS."
  12654. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  12655. (let ((tag-groups
  12656. (let ((g (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  12657. (if (not downcased) g
  12658. (mapcar (lambda (s) (mapcar #'downcase s)) g)))))
  12659. (cond
  12660. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  12661. (org-group-tags
  12662. (let* ((case-fold-search t)
  12663. (tag-syntax org-mode-syntax-table)
  12664. (group-keys (mapcar #'car tag-groups))
  12665. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  12666. (return-match (if downcased (downcase match) match)))
  12667. ;; Mark regexp-expressions in the match-expression so that we
  12668. ;; do not replace them later on.
  12669. (let ((s 0))
  12670. (while (string-match "{.+?}" return-match s)
  12671. (setq s (match-end 0))
  12672. (add-text-properties
  12673. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  12674. ;; @ and _ are allowed as word-components in tags.
  12675. (modify-syntax-entry ?@ "w" tag-syntax)
  12676. (modify-syntax-entry ?_ "w" tag-syntax)
  12677. ;; For each tag token found in MATCH, compute a regexp and it
  12678. (with-syntax-table tag-syntax
  12679. (replace-regexp-in-string
  12680. key-regexp
  12681. (lambda (m)
  12682. (if (get-text-property (match-beginning 2) 'regexp m)
  12683. m ;regexp tag: ignore
  12684. (let* ((operator (match-string 1 m))
  12685. (tag-token (let ((tag (match-string 2 m)))
  12686. (list (if downcased (downcase tag) tag))))
  12687. regexp-tags regular-tags)
  12688. ;; Partition tags between regexp and regular tags.
  12689. ;; Remove curly bracket syntax from regexp tags.
  12690. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  12691. (save-match-data
  12692. (if (string-match "{\\(.+?\\)}" tag)
  12693. (push (match-string 1 tag) regexp-tags)
  12694. (push tag regular-tags))))
  12695. ;; Replace tag token by the appropriate regexp.
  12696. ;; Regular tags need to be regexp-quoted, whereas
  12697. ;; regexp-tags are inserted as-is.
  12698. (let ((regular (regexp-opt regular-tags))
  12699. (regexp (mapconcat #'identity regexp-tags "\\|")))
  12700. (concat operator
  12701. (cond
  12702. ((null regular-tags) (format "{%s}" regexp))
  12703. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  12704. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  12705. return-match
  12706. t t))))
  12707. (t match))))
  12708. (defun org-op-to-function (op &optional stringp)
  12709. "Turn an operator into the appropriate function."
  12710. (setq op
  12711. (cond
  12712. ((equal op "<" ) '(< org-string< org-time<))
  12713. ((equal op ">" ) '(> org-string> org-time>))
  12714. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  12715. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  12716. ((member op '("=" "==")) '(= string= org-time=))
  12717. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  12718. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  12719. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  12720. (defvar org-tags-overlay (make-overlay 1 1))
  12721. (delete-overlay org-tags-overlay)
  12722. (defun org-add-prop-inherited (s)
  12723. (add-text-properties 0 (length s) '(inherited t) s)
  12724. s)
  12725. (defun org-toggle-tag (tag &optional onoff)
  12726. "Toggle the tag TAG for the current line.
  12727. If ONOFF is `on' or `off', don't toggle but set to this state."
  12728. (save-excursion
  12729. (org-back-to-heading t)
  12730. (let ((current
  12731. ;; Reverse the tags list so any new tag is appended to the
  12732. ;; current list of tags.
  12733. (nreverse (org-get-tags nil t)))
  12734. res)
  12735. (pcase onoff
  12736. (`off (setq current (delete tag current)))
  12737. ((or `on (guard (not (member tag current))))
  12738. (setq res t)
  12739. (cl-pushnew tag current :test #'equal))
  12740. (_ (setq current (delete tag current))))
  12741. (org-set-tags (nreverse current))
  12742. res)))
  12743. (defun org--align-tags-here (to-col)
  12744. "Align tags on the current headline to TO-COL.
  12745. Assume point is on a headline. Preserve point when aligning
  12746. tags."
  12747. (when (org-match-line org-tag-line-re)
  12748. (let* ((tags-start (match-beginning 1))
  12749. (blank-start (save-excursion
  12750. (goto-char tags-start)
  12751. (skip-chars-backward " \t")
  12752. (point)))
  12753. (new (max (if (>= to-col 0) to-col
  12754. (- (abs to-col) (string-width (match-string 1))))
  12755. ;; Introduce at least one space after the heading
  12756. ;; or the stars.
  12757. (save-excursion
  12758. (goto-char blank-start)
  12759. (1+ (current-column)))))
  12760. (current
  12761. (save-excursion (goto-char tags-start) (current-column)))
  12762. (origin (point-marker))
  12763. (column (current-column))
  12764. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  12765. (when (/= new current)
  12766. (delete-region blank-start tags-start)
  12767. (goto-char blank-start)
  12768. (let ((indent-tabs-mode nil)) (indent-to new))
  12769. ;; Try to move back to original position. If point was in the
  12770. ;; blanks before the tags, ORIGIN marker is of no use because
  12771. ;; it now points to BLANK-START. Use COLUMN instead.
  12772. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  12773. (defun org-set-tags-command (&optional arg)
  12774. "Set the tags for the current visible entry.
  12775. When called with `\\[universal-argument]' prefix argument ARG, \
  12776. realign all tags
  12777. in the current buffer. If a region is active, set tags for
  12778. all headlines in the region.
  12779. This function is for interactive use only;
  12780. in Lisp code use `org-set-tags' instead."
  12781. (interactive "P")
  12782. (cond
  12783. (arg (org-align-tags t))
  12784. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12785. ;; Disable `org-loop-over-headlines-in-active-region' for
  12786. ;; successive calls.
  12787. (let (org-loop-over-headlines-in-active-region)
  12788. (org-map-entries
  12789. #'org-set-tags-command
  12790. nil
  12791. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12792. 'region-start-level
  12793. 'region)
  12794. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  12795. (t
  12796. (save-excursion
  12797. (org-back-to-heading)
  12798. (let* ((all-tags (org-get-tags))
  12799. (table (setq org-last-tags-completion-table
  12800. (org--tag-add-to-alist
  12801. (and org-complete-tags-always-offer-all-agenda-tags
  12802. (org-global-tags-completion-table
  12803. (org-agenda-files)))
  12804. (or org-current-tag-alist (org-get-buffer-tags)))))
  12805. (current-tags
  12806. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  12807. all-tags))
  12808. (inherited-tags
  12809. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  12810. all-tags))
  12811. (tags
  12812. (replace-regexp-in-string
  12813. ;; Ignore all forbidden characters in tags.
  12814. "[^[:alnum:]_@#%]+" ":"
  12815. (if (or (eq t org-use-fast-tag-selection)
  12816. (and org-use-fast-tag-selection
  12817. (delq nil (mapcar #'cdr table))))
  12818. (org-fast-tag-selection
  12819. current-tags
  12820. inherited-tags
  12821. table
  12822. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  12823. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  12824. (org-trim (completing-read
  12825. "Tags: "
  12826. #'org-tags-completion-function
  12827. nil nil (org-make-tag-string current-tags)
  12828. 'org-tags-history)))))))
  12829. (org-set-tags tags))))))
  12830. (defun org-align-tags (&optional all)
  12831. "Align tags in current entry.
  12832. When optional argument ALL is non-nil, align all tags in the
  12833. visible part of the buffer."
  12834. (let ((get-indent-column
  12835. (lambda ()
  12836. (let ((offset (if (bound-and-true-p org-indent-mode)
  12837. (* (1- org-indent-indentation-per-level)
  12838. (1- (org-current-level)))
  12839. 0)))
  12840. (+ org-tags-column
  12841. (if (> org-tags-column 0) (- offset) offset))))))
  12842. (if (and (not all) (org-at-heading-p))
  12843. (org--align-tags-here (funcall get-indent-column))
  12844. (save-excursion
  12845. (if all
  12846. (while (re-search-forward org-tag-line-re nil t)
  12847. (org--align-tags-here (funcall get-indent-column)))
  12848. (org-back-to-heading t)
  12849. (org--align-tags-here (funcall get-indent-column)))))))
  12850. (defun org-set-tags (tags)
  12851. "Set the tags of the current entry to TAGS, replacing current tags.
  12852. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  12853. If TAGS is nil or the empty string, all tags are removed.
  12854. This function assumes point is on a headline."
  12855. (org-with-wide-buffer
  12856. (let ((tags (pcase tags
  12857. ((pred listp) tags)
  12858. ((pred stringp) (split-string (org-trim tags) ":" t))
  12859. (_ (error "Invalid tag specification: %S" tags))))
  12860. (old-tags (org-get-tags nil t))
  12861. (tags-change? nil))
  12862. (when (functionp org-tags-sort-function)
  12863. (setq tags (sort tags org-tags-sort-function)))
  12864. (setq tags-change? (not (equal tags old-tags)))
  12865. (when tags-change?
  12866. ;; Delete previous tags and any trailing white space.
  12867. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  12868. (line-end-position)))
  12869. (skip-chars-backward " \t")
  12870. (delete-region (point) (line-end-position))
  12871. ;; Deleting white spaces may break an otherwise empty headline.
  12872. ;; Re-introduce one space in this case.
  12873. (unless (org-at-heading-p) (insert " "))
  12874. (when tags
  12875. (save-excursion (insert " " (org-make-tag-string tags)))
  12876. ;; When text is being inserted on an invisible region
  12877. ;; boundary, it can be inadvertently sucked into
  12878. ;; invisibility.
  12879. (unless (org-invisible-p (line-beginning-position))
  12880. (org-flag-region (point) (line-end-position) nil 'outline))))
  12881. ;; Align tags, if any.
  12882. (when tags (org-align-tags))
  12883. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  12884. (defun org-change-tag-in-region (beg end tag off)
  12885. "Add or remove TAG for each entry in the region.
  12886. This works in the agenda, and also in an Org buffer."
  12887. (interactive
  12888. (list (region-beginning) (region-end)
  12889. (let ((org-last-tags-completion-table
  12890. (if (derived-mode-p 'org-mode)
  12891. (org--tag-add-to-alist
  12892. (org-get-buffer-tags)
  12893. (org-global-tags-completion-table))
  12894. (org-global-tags-completion-table))))
  12895. (completing-read
  12896. "Tag: " 'org-tags-completion-function nil nil nil
  12897. 'org-tags-history))
  12898. (progn
  12899. (message "[s]et or [r]emove? ")
  12900. (equal (read-char-exclusive) ?r))))
  12901. (when (fboundp 'deactivate-mark) (deactivate-mark))
  12902. (let ((agendap (equal major-mode 'org-agenda-mode))
  12903. l1 l2 m buf pos newhead (cnt 0))
  12904. (goto-char end)
  12905. (setq l2 (1- (org-current-line)))
  12906. (goto-char beg)
  12907. (setq l1 (org-current-line))
  12908. (cl-loop for l from l1 to l2 do
  12909. (org-goto-line l)
  12910. (setq m (get-text-property (point) 'org-hd-marker))
  12911. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  12912. (and agendap m))
  12913. (setq buf (if agendap (marker-buffer m) (current-buffer))
  12914. pos (if agendap m (point)))
  12915. (with-current-buffer buf
  12916. (save-excursion
  12917. (save-restriction
  12918. (goto-char pos)
  12919. (setq cnt (1+ cnt))
  12920. (org-toggle-tag tag (if off 'off 'on))
  12921. (setq newhead (org-get-heading)))))
  12922. (and agendap (org-agenda-change-all-lines newhead m))))
  12923. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  12924. (defun org-tags-completion-function (string _predicate &optional flag)
  12925. "Complete tag STRING.
  12926. FLAG specifies the type of completion operation to perform. This
  12927. function is passed as a collection function to `completing-read',
  12928. which see."
  12929. (let ((completion-ignore-case nil) ;tags are case-sensitive
  12930. (confirm (lambda (x) (stringp (car x))))
  12931. (prefix ""))
  12932. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  12933. (setq prefix (match-string 1 string))
  12934. (setq string (match-string 2 string)))
  12935. (pcase flag
  12936. (`t (all-completions string org-last-tags-completion-table confirm))
  12937. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  12938. (`nil
  12939. (pcase (try-completion string org-last-tags-completion-table confirm)
  12940. ((and completion (pred stringp))
  12941. (concat prefix
  12942. completion
  12943. (if (and org-add-colon-after-tag-completion
  12944. (assoc completion org-last-tags-completion-table))
  12945. ":"
  12946. "")))
  12947. (completion completion)))
  12948. (_ nil))))
  12949. (defun org-fast-tag-insert (kwd tags face &optional end)
  12950. "Insert KWD, and the TAGS, the latter with face FACE.
  12951. Also insert END."
  12952. (insert (format "%-12s" (concat kwd ":"))
  12953. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  12954. (or end "")))
  12955. (defun org-fast-tag-show-exit (flag)
  12956. (save-excursion
  12957. (org-goto-line 3)
  12958. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  12959. (replace-match ""))
  12960. (when flag
  12961. (end-of-line 1)
  12962. (org-move-to-column (- (window-width) 19) t)
  12963. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  12964. (defun org-set-current-tags-overlay (current prefix)
  12965. "Add an overlay to CURRENT tag with PREFIX."
  12966. (let ((s (org-make-tag-string current)))
  12967. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  12968. (org-overlay-display org-tags-overlay (concat prefix s))))
  12969. (defvar org-last-tag-selection-key nil)
  12970. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  12971. "Fast tag selection with single keys.
  12972. CURRENT is the current list of tags in the headline, INHERITED is the
  12973. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  12974. possibly with grouping information. TODO-TABLE is a similar table with
  12975. TODO keywords, should these have keys assigned to them.
  12976. If the keys are nil, a-z are automatically assigned.
  12977. Returns the new tags string, or nil to not change the current settings."
  12978. (let* ((fulltable (append table todo-table))
  12979. (maxlen (if (null fulltable) 0
  12980. (apply #'max
  12981. (mapcar (lambda (x)
  12982. (if (stringp (car x)) (string-width (car x))
  12983. 0))
  12984. fulltable))))
  12985. (buf (current-buffer))
  12986. (expert (eq org-fast-tag-selection-single-key 'expert))
  12987. (buffer-tags nil)
  12988. (fwidth (+ maxlen 3 1 3))
  12989. (ncol (/ (- (window-width) 4) fwidth))
  12990. (i-face 'org-done)
  12991. (c-face 'org-todo)
  12992. tg cnt e c char c1 c2 ntable tbl rtn
  12993. ov-start ov-end ov-prefix
  12994. (exit-after-next org-fast-tag-selection-single-key)
  12995. (done-keywords org-done-keywords)
  12996. groups ingroup intaggroup)
  12997. (save-excursion
  12998. (beginning-of-line)
  12999. (if (looking-at org-tag-line-re)
  13000. (setq ov-start (match-beginning 1)
  13001. ov-end (match-end 1)
  13002. ov-prefix "")
  13003. (setq ov-start (1- (point-at-eol))
  13004. ov-end (1+ ov-start))
  13005. (skip-chars-forward "^\n\r")
  13006. (setq ov-prefix
  13007. (concat
  13008. (buffer-substring (1- (point)) (point))
  13009. (if (> (current-column) org-tags-column)
  13010. " "
  13011. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13012. (move-overlay org-tags-overlay ov-start ov-end)
  13013. (save-window-excursion
  13014. (if expert
  13015. (set-buffer (get-buffer-create " *Org tags*"))
  13016. (delete-other-windows)
  13017. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13018. (org-switch-to-buffer-other-window " *Org tags*"))
  13019. (erase-buffer)
  13020. (setq-local org-done-keywords done-keywords)
  13021. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13022. (org-fast-tag-insert "Current" current c-face "\n\n")
  13023. (org-fast-tag-show-exit exit-after-next)
  13024. (org-set-current-tags-overlay current ov-prefix)
  13025. (setq tbl fulltable char ?a cnt 0)
  13026. (while (setq e (pop tbl))
  13027. (cond
  13028. ((eq (car e) :startgroup)
  13029. (push '() groups) (setq ingroup t)
  13030. (unless (zerop cnt)
  13031. (setq cnt 0)
  13032. (insert "\n"))
  13033. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13034. ((eq (car e) :endgroup)
  13035. (setq ingroup nil cnt 0)
  13036. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13037. ((eq (car e) :startgrouptag)
  13038. (setq intaggroup t)
  13039. (unless (zerop cnt)
  13040. (setq cnt 0)
  13041. (insert "\n"))
  13042. (insert "[ "))
  13043. ((eq (car e) :endgrouptag)
  13044. (setq intaggroup nil cnt 0)
  13045. (insert "]\n"))
  13046. ((equal e '(:newline))
  13047. (unless (zerop cnt)
  13048. (setq cnt 0)
  13049. (insert "\n")
  13050. (setq e (car tbl))
  13051. (while (equal (car tbl) '(:newline))
  13052. (insert "\n")
  13053. (setq tbl (cdr tbl)))))
  13054. ((equal e '(:grouptags)) (insert " : "))
  13055. (t
  13056. (setq tg (copy-sequence (car e)) c2 nil)
  13057. (if (cdr e)
  13058. (setq c (cdr e))
  13059. ;; automatically assign a character.
  13060. (setq c1 (string-to-char
  13061. (downcase (substring
  13062. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13063. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13064. (while (or (rassoc char ntable) (rassoc char table))
  13065. (setq char (1+ char)))
  13066. (setq c2 c1))
  13067. (setq c (or c2 char)))
  13068. (when ingroup (push tg (car groups)))
  13069. (setq tg (org-add-props tg nil 'face
  13070. (cond
  13071. ((not (assoc tg table))
  13072. (org-get-todo-face tg))
  13073. ((member tg current) c-face)
  13074. ((member tg inherited) i-face))))
  13075. (when (equal (caar tbl) :grouptags)
  13076. (org-add-props tg nil 'face 'org-tag-group))
  13077. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13078. (insert "[" c "] " tg (make-string
  13079. (- fwidth 4 (length tg)) ?\ ))
  13080. (push (cons tg c) ntable)
  13081. (when (= (cl-incf cnt) ncol)
  13082. (insert "\n")
  13083. (when (or ingroup intaggroup) (insert " "))
  13084. (setq cnt 0)))))
  13085. (setq ntable (nreverse ntable))
  13086. (insert "\n")
  13087. (goto-char (point-min))
  13088. (unless expert (org-fit-window-to-buffer))
  13089. (setq rtn
  13090. (catch 'exit
  13091. (while t
  13092. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  13093. (if (not groups) "no " "")
  13094. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13095. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13096. (setq org-last-tag-selection-key c)
  13097. (cond
  13098. ((= c ?\r) (throw 'exit t))
  13099. ((= c ?!)
  13100. (setq groups (not groups))
  13101. (goto-char (point-min))
  13102. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13103. ((= c ?\C-c)
  13104. (if (not expert)
  13105. (org-fast-tag-show-exit
  13106. (setq exit-after-next (not exit-after-next)))
  13107. (setq expert nil)
  13108. (delete-other-windows)
  13109. (set-window-buffer (split-window-vertically) " *Org tags*")
  13110. (org-switch-to-buffer-other-window " *Org tags*")
  13111. (org-fit-window-to-buffer)))
  13112. ((or (= c ?\C-g)
  13113. (and (= c ?q) (not (rassoc c ntable))))
  13114. (delete-overlay org-tags-overlay)
  13115. (setq quit-flag t))
  13116. ((= c ?\ )
  13117. (setq current nil)
  13118. (when exit-after-next (setq exit-after-next 'now)))
  13119. ((= c ?\t)
  13120. (condition-case nil
  13121. (setq tg (completing-read
  13122. "Tag: "
  13123. (or buffer-tags
  13124. (with-current-buffer buf
  13125. (setq buffer-tags
  13126. (org-get-buffer-tags))))))
  13127. (quit (setq tg "")))
  13128. (when (string-match "\\S-" tg)
  13129. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13130. (if (member tg current)
  13131. (setq current (delete tg current))
  13132. (push tg current)))
  13133. (when exit-after-next (setq exit-after-next 'now)))
  13134. ((setq e (rassoc c todo-table) tg (car e))
  13135. (with-current-buffer buf
  13136. (save-excursion (org-todo tg)))
  13137. (when exit-after-next (setq exit-after-next 'now)))
  13138. ((setq e (rassoc c ntable) tg (car e))
  13139. (if (member tg current)
  13140. (setq current (delete tg current))
  13141. (cl-loop for g in groups do
  13142. (when (member tg g)
  13143. (dolist (x g) (setq current (delete x current)))))
  13144. (push tg current))
  13145. (when exit-after-next (setq exit-after-next 'now))))
  13146. ;; Create a sorted list
  13147. (setq current
  13148. (sort current
  13149. (lambda (a b)
  13150. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13151. (when (eq exit-after-next 'now) (throw 'exit t))
  13152. (goto-char (point-min))
  13153. (beginning-of-line 2)
  13154. (delete-region (point) (point-at-eol))
  13155. (org-fast-tag-insert "Current" current c-face)
  13156. (org-set-current-tags-overlay current ov-prefix)
  13157. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  13158. (while (re-search-forward tag-re nil t)
  13159. (let ((tag (match-string 1)))
  13160. (add-text-properties
  13161. (match-beginning 1) (match-end 1)
  13162. (list 'face
  13163. (cond
  13164. ((member tag current) c-face)
  13165. ((member tag inherited) i-face)
  13166. (t (get-text-property (match-beginning 1) '
  13167. face))))))))
  13168. (goto-char (point-min)))))
  13169. (delete-overlay org-tags-overlay)
  13170. (if rtn
  13171. (mapconcat 'identity current ":")
  13172. nil))))
  13173. (defun org-make-tag-string (tags)
  13174. "Return string associated to TAGS.
  13175. TAGS is a list of strings."
  13176. (if (null tags) ""
  13177. (format ":%s:" (mapconcat #'identity tags ":"))))
  13178. (defun org--get-local-tags ()
  13179. "Return list of tags for the current headline.
  13180. Assume point is at the beginning of the headline."
  13181. (and (looking-at org-tag-line-re)
  13182. (split-string (match-string-no-properties 2) ":" t)))
  13183. (defun org-get-tags (&optional pos local)
  13184. "Get the list of tags specified in the current headline.
  13185. When argument POS is non-nil, retrieve tags for headline at POS.
  13186. According to `org-use-tags-inheritance', tags may be inherited
  13187. from parent headlines, and from the whole document, through
  13188. `org-file-tags'. However, when optional argument LOCAL is
  13189. non-nil, only return tags specified at the headline.
  13190. Inherited tags have the `inherited' text property."
  13191. (if (and org-trust-scanner-tags
  13192. (or (not pos) (eq pos (point)))
  13193. (not local))
  13194. org-scanner-tags
  13195. (org-with-point-at (or pos (point))
  13196. (unless (org-before-first-heading-p)
  13197. (org-back-to-heading t)
  13198. (let ((ltags (org--get-local-tags)) itags)
  13199. (if (or local (not org-use-tag-inheritance)) ltags
  13200. (setq itags org-file-tags)
  13201. (while (org-up-heading-safe)
  13202. (setq itags (append (mapcar #'org-add-prop-inherited
  13203. (org--get-local-tags))
  13204. itags)))
  13205. (delete-dups
  13206. (append (org-remove-uninherited-tags itags) ltags))))))))
  13207. (defun org-get-buffer-tags ()
  13208. "Get a table of all tags used in the buffer, for completion."
  13209. (org-with-point-at 1
  13210. (let (tags)
  13211. (while (re-search-forward org-tag-line-re nil t)
  13212. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  13213. tags)))
  13214. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  13215. ;;;; The mapping API
  13216. (defvar org-agenda-skip-comment-trees)
  13217. (defvar org-agenda-skip-function)
  13218. (defun org-map-entries (func &optional match scope &rest skip)
  13219. "Call FUNC at each headline selected by MATCH in SCOPE.
  13220. FUNC is a function or a lisp form. The function will be called without
  13221. arguments, with the cursor positioned at the beginning of the headline.
  13222. The return values of all calls to the function will be collected and
  13223. returned as a list.
  13224. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13225. does not need to preserve point. After evaluation, the cursor will be
  13226. moved to the end of the line (presumably of the headline of the
  13227. processed entry) and search continues from there. Under some
  13228. circumstances, this may not produce the wanted results. For example,
  13229. if you have removed (e.g. archived) the current (sub)tree it could
  13230. mean that the next entry will be skipped entirely. In such cases, you
  13231. can specify the position from where search should continue by making
  13232. FUNC set the variable `org-map-continue-from' to the desired buffer
  13233. position.
  13234. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13235. Only headlines that are matched by this query will be considered during
  13236. the iteration. When MATCH is nil or t, all headlines will be
  13237. visited by the iteration.
  13238. SCOPE determines the scope of this command. It can be any of:
  13239. nil The current buffer, respecting the restriction if any
  13240. tree The subtree started with the entry at point
  13241. region The entries within the active region, if any
  13242. region-start-level
  13243. The entries within the active region, but only those at
  13244. the same level than the first one.
  13245. file The current buffer, without restriction
  13246. file-with-archives
  13247. The current buffer, and any archives associated with it
  13248. agenda All agenda files
  13249. agenda-with-archives
  13250. All agenda files with any archive files associated with them
  13251. \(file1 file2 ...)
  13252. If this is a list, all files in the list will be scanned
  13253. The remaining args are treated as settings for the skipping facilities of
  13254. the scanner. The following items can be given here:
  13255. archive skip trees with the archive tag
  13256. comment skip trees with the COMMENT keyword
  13257. function or Emacs Lisp form:
  13258. will be used as value for `org-agenda-skip-function', so
  13259. whenever the function returns a position, FUNC will not be
  13260. called for that entry and search will continue from the
  13261. position returned
  13262. If your function needs to retrieve the tags including inherited tags
  13263. at the *current* entry, you can use the value of the variable
  13264. `org-scanner-tags' which will be much faster than getting the value
  13265. with `org-get-tags'. If your function gets properties with
  13266. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  13267. to t around the call to `org-entry-properties' to get the same speedup.
  13268. Note that if your function moves around to retrieve tags and properties at
  13269. a *different* entry, you cannot use these techniques."
  13270. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  13271. (not (org-region-active-p)))
  13272. (let* ((org-agenda-archives-mode nil) ; just to make sure
  13273. (org-agenda-skip-archived-trees (memq 'archive skip))
  13274. (org-agenda-skip-comment-trees (memq 'comment skip))
  13275. (org-agenda-skip-function
  13276. (car (org-delete-all '(comment archive) skip)))
  13277. (org-tags-match-list-sublevels t)
  13278. (start-level (eq scope 'region-start-level))
  13279. matcher res
  13280. org-todo-keywords-for-agenda
  13281. org-done-keywords-for-agenda
  13282. org-todo-keyword-alist-for-agenda
  13283. org-tag-alist-for-agenda
  13284. org--matcher-tags-todo-only)
  13285. (cond
  13286. ((eq match t) (setq matcher t))
  13287. ((eq match nil) (setq matcher t))
  13288. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  13289. (save-excursion
  13290. (save-restriction
  13291. (cond ((eq scope 'tree)
  13292. (org-back-to-heading t)
  13293. (org-narrow-to-subtree)
  13294. (setq scope nil))
  13295. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  13296. (org-region-active-p))
  13297. ;; If needed, set start-level to a string like "2"
  13298. (when start-level
  13299. (save-excursion
  13300. (goto-char (region-beginning))
  13301. (unless (org-at-heading-p) (outline-next-heading))
  13302. (setq start-level (org-current-level))))
  13303. (narrow-to-region (region-beginning)
  13304. (save-excursion
  13305. (goto-char (region-end))
  13306. (unless (and (bolp) (org-at-heading-p))
  13307. (outline-next-heading))
  13308. (point)))
  13309. (setq scope nil)))
  13310. (if (not scope)
  13311. (progn
  13312. (org-agenda-prepare-buffers
  13313. (and buffer-file-name (list buffer-file-name)))
  13314. (setq res
  13315. (org-scan-tags
  13316. func matcher org--matcher-tags-todo-only start-level)))
  13317. ;; Get the right scope
  13318. (cond
  13319. ((and scope (listp scope) (symbolp (car scope)))
  13320. (setq scope (eval scope)))
  13321. ((eq scope 'agenda)
  13322. (setq scope (org-agenda-files t)))
  13323. ((eq scope 'agenda-with-archives)
  13324. (setq scope (org-agenda-files t))
  13325. (setq scope (org-add-archive-files scope)))
  13326. ((eq scope 'file)
  13327. (setq scope (and buffer-file-name (list buffer-file-name))))
  13328. ((eq scope 'file-with-archives)
  13329. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  13330. (org-agenda-prepare-buffers scope)
  13331. (dolist (file scope)
  13332. (with-current-buffer (org-find-base-buffer-visiting file)
  13333. (org-with-wide-buffer
  13334. (goto-char (point-min))
  13335. (setq res
  13336. (append
  13337. res
  13338. (org-scan-tags
  13339. func matcher org--matcher-tags-todo-only)))))))))
  13340. res)))
  13341. ;;; Properties API
  13342. (defconst org-special-properties
  13343. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  13344. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  13345. "The special properties valid in Org mode.
  13346. These are properties that are not defined in the property drawer,
  13347. but in some other way.")
  13348. (defconst org-default-properties
  13349. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  13350. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  13351. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  13352. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  13353. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  13354. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  13355. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  13356. "Some properties that are used by Org mode for various purposes.
  13357. Being in this list makes sure that they are offered for completion.")
  13358. (defun org--valid-property-p (property)
  13359. "Non nil when string PROPERTY is a valid property name."
  13360. (not
  13361. (or (equal property "")
  13362. (string-match-p "\\s-" property))))
  13363. (defun org--update-property-plist (key val props)
  13364. "Associate KEY to VAL in alist PROPS.
  13365. Modifications are made by side-effect. Return new alist."
  13366. (let* ((appending (string= (substring key -1) "+"))
  13367. (key (if appending (substring key 0 -1) key))
  13368. (old (assoc-string key props t)))
  13369. (if (not old) (cons (cons key val) props)
  13370. (setcdr old (if appending (concat (cdr old) " " val) val))
  13371. props)))
  13372. (defun org-get-property-block (&optional beg force)
  13373. "Return the (beg . end) range of the body of the property drawer.
  13374. BEG is the beginning of the current subtree, or of the part
  13375. before the first headline. If it is not given, it will be found.
  13376. If the drawer does not exist, create it if FORCE is non-nil, or
  13377. return nil."
  13378. (org-with-wide-buffer
  13379. (when beg (goto-char beg))
  13380. (unless (org-before-first-heading-p)
  13381. (let ((beg (cond (beg)
  13382. ((or (not (featurep 'org-inlinetask))
  13383. (org-inlinetask-in-task-p))
  13384. (org-back-to-heading t))
  13385. (t (org-with-limited-levels (org-back-to-heading t))))))
  13386. (forward-line)
  13387. (when (looking-at-p org-planning-line-re) (forward-line))
  13388. (cond ((looking-at org-property-drawer-re)
  13389. (forward-line)
  13390. (cons (point) (progn (goto-char (match-end 0))
  13391. (line-beginning-position))))
  13392. (force
  13393. (goto-char beg)
  13394. (org-insert-property-drawer)
  13395. (let ((pos (save-excursion (search-forward ":END:")
  13396. (line-beginning-position))))
  13397. (cons pos pos))))))))
  13398. (defun org-at-property-p ()
  13399. "Non-nil when point is inside a property drawer.
  13400. See `org-property-re' for match data, if applicable."
  13401. (save-excursion
  13402. (beginning-of-line)
  13403. (and (looking-at org-property-re)
  13404. (let ((property-drawer (save-match-data (org-get-property-block))))
  13405. (and property-drawer
  13406. (>= (point) (car property-drawer))
  13407. (< (point) (cdr property-drawer)))))))
  13408. (defun org-property-action ()
  13409. "Do an action on properties."
  13410. (interactive)
  13411. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  13412. (let ((c (read-char-exclusive)))
  13413. (cl-case c
  13414. (?s (call-interactively #'org-set-property))
  13415. (?d (call-interactively #'org-delete-property))
  13416. (?D (call-interactively #'org-delete-property-globally))
  13417. (?c (call-interactively #'org-compute-property-at-point))
  13418. (otherwise (user-error "No such property action %c" c)))))
  13419. (defun org-inc-effort ()
  13420. "Increment the value of the effort property in the current entry."
  13421. (interactive)
  13422. (org-set-effort t))
  13423. (defvar org-clock-effort) ; Defined in org-clock.el.
  13424. (defvar org-clock-current-task) ; Defined in org-clock.el.
  13425. (defun org-set-effort (&optional increment value)
  13426. "Set the effort property of the current entry.
  13427. If INCREMENT is non-nil, set the property to the next allowed
  13428. value. Otherwise, if optional argument VALUE is provided, use
  13429. it. Eventually, prompt for the new value if none of the previous
  13430. variables is set."
  13431. (interactive "P")
  13432. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  13433. (current (org-entry-get nil org-effort-property))
  13434. (value
  13435. (cond
  13436. (increment
  13437. (unless allowed (user-error "Allowed effort values are not set"))
  13438. (or (cl-caadr (member (list current) allowed))
  13439. (user-error "Unknown value %S among allowed values" current)))
  13440. (value
  13441. (if (stringp value) value
  13442. (error "Invalid effort value: %S" value)))
  13443. (t
  13444. (let ((must-match
  13445. (and allowed
  13446. (not (get-text-property 0 'org-unrestricted
  13447. (caar allowed))))))
  13448. (completing-read "Effort: " allowed nil must-match))))))
  13449. (unless (equal current value)
  13450. (org-entry-put nil org-effort-property value))
  13451. (org-refresh-property '((effort . identity)
  13452. (effort-minutes . org-duration-to-minutes))
  13453. value)
  13454. (when (equal (org-get-heading t t t t)
  13455. (bound-and-true-p org-clock-current-task))
  13456. (setq org-clock-effort value)
  13457. (org-clock-update-mode-line))
  13458. (message "%s is now %s" org-effort-property value)))
  13459. (defun org-entry-properties (&optional pom which)
  13460. "Get all properties of the current entry.
  13461. When POM is a buffer position, get all properties from the entry
  13462. there instead.
  13463. This includes the TODO keyword, the tags, time strings for
  13464. deadline, scheduled, and clocking, and any additional properties
  13465. defined in the entry.
  13466. If WHICH is nil or `all', get all properties. If WHICH is
  13467. `special' or `standard', only get that subclass. If WHICH is
  13468. a string, only get that property.
  13469. Return value is an alist. Keys are properties, as upcased
  13470. strings."
  13471. (org-with-point-at pom
  13472. (when (and (derived-mode-p 'org-mode)
  13473. (ignore-errors (org-back-to-heading t)))
  13474. (catch 'exit
  13475. (let* ((beg (point))
  13476. (specific (and (stringp which) (upcase which)))
  13477. (which (cond ((not specific) which)
  13478. ((member specific org-special-properties) 'special)
  13479. (t 'standard)))
  13480. props)
  13481. ;; Get the special properties, like TODO and TAGS.
  13482. (when (memq which '(nil all special))
  13483. (when (or (not specific) (string= specific "CLOCKSUM"))
  13484. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  13485. (when clocksum
  13486. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  13487. props)))
  13488. (when specific (throw 'exit props)))
  13489. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  13490. (let ((clocksumt (get-text-property (point)
  13491. :org-clock-minutes-today)))
  13492. (when clocksumt
  13493. (push (cons "CLOCKSUM_T"
  13494. (org-duration-from-minutes clocksumt))
  13495. props)))
  13496. (when specific (throw 'exit props)))
  13497. (when (or (not specific) (string= specific "ITEM"))
  13498. (let ((case-fold-search nil))
  13499. (when (looking-at org-complex-heading-regexp)
  13500. (push (cons "ITEM"
  13501. (let ((title (match-string-no-properties 4)))
  13502. (if (org-string-nw-p title)
  13503. (org-remove-tabs title)
  13504. "")))
  13505. props)))
  13506. (when specific (throw 'exit props)))
  13507. (when (or (not specific) (string= specific "TODO"))
  13508. (let ((case-fold-search nil))
  13509. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  13510. (push (cons "TODO" (match-string-no-properties 2)) props)))
  13511. (when specific (throw 'exit props)))
  13512. (when (or (not specific) (string= specific "PRIORITY"))
  13513. (push (cons "PRIORITY"
  13514. (if (looking-at org-priority-regexp)
  13515. (match-string-no-properties 2)
  13516. (char-to-string org-default-priority)))
  13517. props)
  13518. (when specific (throw 'exit props)))
  13519. (when (or (not specific) (string= specific "FILE"))
  13520. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  13521. props)
  13522. (when specific (throw 'exit props)))
  13523. (when (or (not specific) (string= specific "TAGS"))
  13524. (let ((tags (org-get-tags nil t)))
  13525. (when tags
  13526. (push (cons "TAGS" (org-make-tag-string tags))
  13527. props)))
  13528. (when specific (throw 'exit props)))
  13529. (when (or (not specific) (string= specific "ALLTAGS"))
  13530. (let ((tags (org-get-tags)))
  13531. (when tags
  13532. (push (cons "ALLTAGS" (org-make-tag-string tags))
  13533. props)))
  13534. (when specific (throw 'exit props)))
  13535. (when (or (not specific) (string= specific "BLOCKED"))
  13536. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  13537. (when specific (throw 'exit props)))
  13538. (when (or (not specific)
  13539. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  13540. (forward-line)
  13541. (when (looking-at-p org-planning-line-re)
  13542. (end-of-line)
  13543. (let ((bol (line-beginning-position))
  13544. ;; Backward compatibility: time keywords used to
  13545. ;; be configurable (before 8.3). Make sure we
  13546. ;; get the correct keyword.
  13547. (key-assoc `(("CLOSED" . ,org-closed-string)
  13548. ("DEADLINE" . ,org-deadline-string)
  13549. ("SCHEDULED" . ,org-scheduled-string))))
  13550. (dolist (pair (if specific (list (assoc specific key-assoc))
  13551. key-assoc))
  13552. (save-excursion
  13553. (when (search-backward (cdr pair) bol t)
  13554. (goto-char (match-end 0))
  13555. (skip-chars-forward " \t")
  13556. (and (looking-at org-ts-regexp-both)
  13557. (push (cons (car pair)
  13558. (match-string-no-properties 0))
  13559. props)))))))
  13560. (when specific (throw 'exit props)))
  13561. (when (or (not specific)
  13562. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  13563. (let ((find-ts
  13564. (lambda (end ts)
  13565. ;; Fix next time-stamp before END. TS is the
  13566. ;; list of time-stamps found so far.
  13567. (let ((ts ts)
  13568. (regexp (cond
  13569. ((string= specific "TIMESTAMP")
  13570. org-ts-regexp)
  13571. ((string= specific "TIMESTAMP_IA")
  13572. org-ts-regexp-inactive)
  13573. ((assoc "TIMESTAMP_IA" ts)
  13574. org-ts-regexp)
  13575. ((assoc "TIMESTAMP" ts)
  13576. org-ts-regexp-inactive)
  13577. (t org-ts-regexp-both))))
  13578. (catch 'next
  13579. (while (re-search-forward regexp end t)
  13580. (backward-char)
  13581. (let ((object (org-element-context)))
  13582. ;; Accept to match timestamps in node
  13583. ;; properties, too.
  13584. (when (memq (org-element-type object)
  13585. '(node-property timestamp))
  13586. (let ((type
  13587. (org-element-property :type object)))
  13588. (cond
  13589. ((and (memq type '(active active-range))
  13590. (not (equal specific "TIMESTAMP_IA")))
  13591. (unless (assoc "TIMESTAMP" ts)
  13592. (push (cons "TIMESTAMP"
  13593. (org-element-property
  13594. :raw-value object))
  13595. ts)
  13596. (when specific (throw 'exit ts))))
  13597. ((and (memq type '(inactive inactive-range))
  13598. (not (string= specific "TIMESTAMP")))
  13599. (unless (assoc "TIMESTAMP_IA" ts)
  13600. (push (cons "TIMESTAMP_IA"
  13601. (org-element-property
  13602. :raw-value object))
  13603. ts)
  13604. (when specific (throw 'exit ts))))))
  13605. ;; Both timestamp types are found,
  13606. ;; move to next part.
  13607. (when (= (length ts) 2) (throw 'next ts)))))
  13608. ts)))))
  13609. (goto-char beg)
  13610. ;; First look for timestamps within headline.
  13611. (let ((ts (funcall find-ts (line-end-position) nil)))
  13612. (if (= (length ts) 2) (setq props (nconc ts props))
  13613. ;; Then find timestamps in the section, skipping
  13614. ;; planning line.
  13615. (let ((end (save-excursion (outline-next-heading))))
  13616. (forward-line)
  13617. (when (looking-at-p org-planning-line-re) (forward-line))
  13618. (setq props (nconc (funcall find-ts end ts) props))))))))
  13619. ;; Get the standard properties, like :PROP:.
  13620. (when (memq which '(nil all standard))
  13621. ;; If we are looking after a specific property, delegate
  13622. ;; to `org-entry-get', which is faster. However, make an
  13623. ;; exception for "CATEGORY", since it can be also set
  13624. ;; through keywords (i.e. #+CATEGORY).
  13625. (if (and specific (not (equal specific "CATEGORY")))
  13626. (let ((value (org-entry-get beg specific nil t)))
  13627. (throw 'exit (and value (list (cons specific value)))))
  13628. (let ((range (org-get-property-block beg)))
  13629. (when range
  13630. (let ((end (cdr range)) seen-base)
  13631. (goto-char (car range))
  13632. ;; Unlike to `org--update-property-plist', we
  13633. ;; handle the case where base values is found
  13634. ;; after its extension. We also forbid standard
  13635. ;; properties to be named as special properties.
  13636. (while (re-search-forward org-property-re end t)
  13637. (let* ((key (upcase (match-string-no-properties 2)))
  13638. (extendp (string-match-p "\\+\\'" key))
  13639. (key-base (if extendp (substring key 0 -1) key))
  13640. (value (match-string-no-properties 3)))
  13641. (cond
  13642. ((member-ignore-case key-base org-special-properties))
  13643. (extendp
  13644. (setq props
  13645. (org--update-property-plist key value props)))
  13646. ((member key seen-base))
  13647. (t (push key seen-base)
  13648. (let ((p (assoc-string key props t)))
  13649. (if p (setcdr p (concat value " " (cdr p)))
  13650. (push (cons key value) props))))))))))))
  13651. (unless (assoc "CATEGORY" props)
  13652. (push (cons "CATEGORY" (org-get-category beg)) props)
  13653. (when (string= specific "CATEGORY") (throw 'exit props)))
  13654. ;; Return value.
  13655. props)))))
  13656. (defun org--property-local-values (property literal-nil)
  13657. "Return value for PROPERTY in current entry.
  13658. Value is a list whose car is the base value for PROPERTY and cdr
  13659. a list of accumulated values. Return nil if neither is found in
  13660. the entry. Also return nil when PROPERTY is set to \"nil\",
  13661. unless LITERAL-NIL is non-nil."
  13662. (let ((range (org-get-property-block)))
  13663. (when range
  13664. (goto-char (car range))
  13665. (let* ((case-fold-search t)
  13666. (end (cdr range))
  13667. (value
  13668. ;; Base value.
  13669. (save-excursion
  13670. (let ((v (and (re-search-forward
  13671. (org-re-property property nil t) end t)
  13672. (match-string-no-properties 3))))
  13673. (list (if literal-nil v (org-not-nil v)))))))
  13674. ;; Find additional values.
  13675. (let* ((property+ (org-re-property (concat property "+") nil t)))
  13676. (while (re-search-forward property+ end t)
  13677. (push (match-string-no-properties 3) value)))
  13678. ;; Return final values.
  13679. (and (not (equal value '(nil))) (nreverse value))))))
  13680. (defun org--property-global-value (property literal-nil)
  13681. "Return value for PROPERTY in current buffer.
  13682. Return value is a string. Return nil if property is not set
  13683. globally. Also return nil when PROPERTY is set to \"nil\",
  13684. unless LITERAL-NIL is non-nil."
  13685. (let ((global
  13686. (cdr (or (assoc-string property org-file-properties t)
  13687. (assoc-string property org-global-properties t)
  13688. (assoc-string property org-global-properties-fixed t)))))
  13689. (if literal-nil global (org-not-nil global))))
  13690. (defun org-entry-get (pom property &optional inherit literal-nil)
  13691. "Get value of PROPERTY for entry or content at point-or-marker POM.
  13692. If INHERIT is non-nil and the entry does not have the property,
  13693. then also check higher levels of the hierarchy. If INHERIT is
  13694. the symbol `selective', use inheritance only if the setting in
  13695. `org-use-property-inheritance' selects PROPERTY for inheritance.
  13696. If the property is present but empty, the return value is the
  13697. empty string. If the property is not present at all, nil is
  13698. returned. In any other case, return the value as a string.
  13699. Search is case-insensitive.
  13700. If LITERAL-NIL is set, return the string value \"nil\" as
  13701. a string, do not interpret it as the list atom nil. This is used
  13702. for inheritance when a \"nil\" value can supersede a non-nil
  13703. value higher up the hierarchy."
  13704. (org-with-point-at pom
  13705. (cond
  13706. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  13707. ;; We need a special property. Use `org-entry-properties' to
  13708. ;; retrieve it, but specify the wanted property.
  13709. (cdr (assoc-string property (org-entry-properties nil property))))
  13710. ((and inherit
  13711. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  13712. (org-entry-get-with-inheritance property literal-nil))
  13713. (t
  13714. (let* ((local (org--property-local-values property literal-nil))
  13715. (value (and local (mapconcat #'identity (delq nil local) " "))))
  13716. (if literal-nil value (org-not-nil value)))))))
  13717. (defun org-property-or-variable-value (var &optional inherit)
  13718. "Check if there is a property fixing the value of VAR.
  13719. If yes, return this value. If not, return the current value of the variable."
  13720. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  13721. (if (and prop (stringp prop) (string-match "\\S-" prop))
  13722. (read prop)
  13723. (symbol-value var))))
  13724. (defun org-entry-delete (pom property)
  13725. "Delete PROPERTY from entry at point-or-marker POM.
  13726. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  13727. non-nil when a property was removed."
  13728. (org-with-point-at pom
  13729. (pcase (org-get-property-block)
  13730. (`(,begin . ,origin)
  13731. (let* ((end (copy-marker origin))
  13732. (re (org-re-property
  13733. (concat (regexp-quote property) "\\+?") t t)))
  13734. (goto-char begin)
  13735. (while (re-search-forward re end t)
  13736. (delete-region (match-beginning 0) (line-beginning-position 2)))
  13737. ;; If drawer is empty, remove it altogether.
  13738. (when (= begin end)
  13739. (delete-region (line-beginning-position 0)
  13740. (line-beginning-position 2)))
  13741. ;; Return non-nil if some property was removed.
  13742. (prog1 (/= end origin) (set-marker end nil))))
  13743. (_ nil))))
  13744. ;; Multi-values properties are properties that contain multiple values
  13745. ;; These values are assumed to be single words, separated by whitespace.
  13746. (defun org-entry-add-to-multivalued-property (pom property value)
  13747. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  13748. (let* ((old (org-entry-get pom property))
  13749. (values (and old (split-string old))))
  13750. (setq value (org-entry-protect-space value))
  13751. (unless (member value values)
  13752. (setq values (append values (list value)))
  13753. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13754. (defun org-entry-remove-from-multivalued-property (pom property value)
  13755. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  13756. (let* ((old (org-entry-get pom property))
  13757. (values (and old (split-string old))))
  13758. (setq value (org-entry-protect-space value))
  13759. (when (member value values)
  13760. (setq values (delete value values))
  13761. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13762. (defun org-entry-member-in-multivalued-property (pom property value)
  13763. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  13764. (let* ((old (org-entry-get pom property))
  13765. (values (and old (split-string old))))
  13766. (setq value (org-entry-protect-space value))
  13767. (member value values)))
  13768. (defun org-entry-get-multivalued-property (pom property)
  13769. "Return a list of values in a multivalued property."
  13770. (let* ((value (org-entry-get pom property))
  13771. (values (and value (split-string value))))
  13772. (mapcar #'org-entry-restore-space values)))
  13773. (defun org-entry-put-multivalued-property (pom property &rest values)
  13774. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  13775. VALUES should be a list of strings. Spaces will be protected."
  13776. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  13777. (let* ((value (org-entry-get pom property))
  13778. (values (and value (split-string value))))
  13779. (mapcar #'org-entry-restore-space values)))
  13780. (defun org-entry-protect-space (s)
  13781. "Protect spaces and newline in string S."
  13782. (while (string-match " " s)
  13783. (setq s (replace-match "%20" t t s)))
  13784. (while (string-match "\n" s)
  13785. (setq s (replace-match "%0A" t t s)))
  13786. s)
  13787. (defun org-entry-restore-space (s)
  13788. "Restore spaces and newline in string S."
  13789. (while (string-match "%20" s)
  13790. (setq s (replace-match " " t t s)))
  13791. (while (string-match "%0A" s)
  13792. (setq s (replace-match "\n" t t s)))
  13793. s)
  13794. (defvar org-entry-property-inherited-from (make-marker)
  13795. "Marker pointing to the entry from where a property was inherited.
  13796. Each call to `org-entry-get-with-inheritance' will set this marker to the
  13797. location of the entry where the inheritance search matched. If there was
  13798. no match, the marker will point nowhere.
  13799. Note that also `org-entry-get' calls this function, if the INHERIT flag
  13800. is set.")
  13801. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  13802. "Get PROPERTY of entry or content at point, search higher levels if needed.
  13803. The search will stop at the first ancestor which has the property defined.
  13804. If the value found is \"nil\", return nil to show that the property
  13805. should be considered as undefined (this is the meaning of nil here).
  13806. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  13807. (move-marker org-entry-property-inherited-from nil)
  13808. (org-with-wide-buffer
  13809. (let (value)
  13810. (catch 'exit
  13811. (while t
  13812. (let ((v (org--property-local-values property literal-nil)))
  13813. (when v
  13814. (setq value
  13815. (concat (mapconcat #'identity (delq nil v) " ")
  13816. (and value " ")
  13817. value)))
  13818. (cond
  13819. ((car v)
  13820. (org-back-to-heading t)
  13821. (move-marker org-entry-property-inherited-from (point))
  13822. (throw 'exit nil))
  13823. ((org-up-heading-safe))
  13824. (t
  13825. (let ((global (org--property-global-value property literal-nil)))
  13826. (cond ((not global))
  13827. (value (setq value (concat global " " value)))
  13828. (t (setq value global))))
  13829. (throw 'exit nil))))))
  13830. (if literal-nil value (org-not-nil value)))))
  13831. (defvar org-property-changed-functions nil
  13832. "Hook called when the value of a property has changed.
  13833. Each hook function should accept two arguments, the name of the property
  13834. and the new value.")
  13835. (defun org-entry-put (pom property value)
  13836. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  13837. If the value is nil, it is converted to the empty string. If it
  13838. is not a string, an error is raised. Also raise an error on
  13839. invalid property names.
  13840. PROPERTY can be any regular property (see
  13841. `org-special-properties'). It can also be \"TODO\",
  13842. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  13843. For the last two properties, VALUE may have any of the special
  13844. values \"earlier\" and \"later\". The function then increases or
  13845. decreases scheduled or deadline date by one day."
  13846. (cond ((null value) (setq value ""))
  13847. ((not (stringp value)) (error "Properties values should be strings"))
  13848. ((not (org--valid-property-p property))
  13849. (user-error "Invalid property name: \"%s\"" property)))
  13850. (org-with-point-at pom
  13851. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  13852. (org-back-to-heading t)
  13853. (org-with-limited-levels (org-back-to-heading t)))
  13854. (let ((beg (point)))
  13855. (cond
  13856. ((equal property "TODO")
  13857. (cond ((not (org-string-nw-p value)) (setq value 'none))
  13858. ((not (member value org-todo-keywords-1))
  13859. (user-error "\"%s\" is not a valid TODO state" value)))
  13860. (org-todo value)
  13861. (org-align-tags))
  13862. ((equal property "PRIORITY")
  13863. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  13864. (org-align-tags))
  13865. ((equal property "SCHEDULED")
  13866. (forward-line)
  13867. (if (and (looking-at-p org-planning-line-re)
  13868. (re-search-forward
  13869. org-scheduled-time-regexp (line-end-position) t))
  13870. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  13871. ((string= value "later") (org-timestamp-change 1 'day))
  13872. ((string= value "") (org-schedule '(4)))
  13873. (t (org-schedule nil value)))
  13874. (if (member value '("earlier" "later" ""))
  13875. (call-interactively #'org-schedule)
  13876. (org-schedule nil value))))
  13877. ((equal property "DEADLINE")
  13878. (forward-line)
  13879. (if (and (looking-at-p org-planning-line-re)
  13880. (re-search-forward
  13881. org-deadline-time-regexp (line-end-position) t))
  13882. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  13883. ((string= value "later") (org-timestamp-change 1 'day))
  13884. ((string= value "") (org-deadline '(4)))
  13885. (t (org-deadline nil value)))
  13886. (if (member value '("earlier" "later" ""))
  13887. (call-interactively #'org-deadline)
  13888. (org-deadline nil value))))
  13889. ((member property org-special-properties)
  13890. (error "The %s property cannot be set with `org-entry-put'" property))
  13891. (t
  13892. (let* ((range (org-get-property-block beg 'force))
  13893. (end (cdr range))
  13894. (case-fold-search t))
  13895. (goto-char (car range))
  13896. (if (re-search-forward (org-re-property property nil t) end t)
  13897. (progn (delete-region (match-beginning 0) (match-end 0))
  13898. (goto-char (match-beginning 0)))
  13899. (goto-char end)
  13900. (insert "\n")
  13901. (backward-char))
  13902. (insert ":" property ":")
  13903. (when value (insert " " value))
  13904. (org-indent-line)))))
  13905. (run-hook-with-args 'org-property-changed-functions property value)))
  13906. (defun org-buffer-property-keys (&optional specials defaults columns)
  13907. "Get all property keys in the current buffer.
  13908. When SPECIALS is non-nil, also list the special properties that
  13909. reflect things like tags and TODO state.
  13910. When DEFAULTS is non-nil, also include properties that has
  13911. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  13912. DESCRIPTION, LOCATION, and LOGGING and others.
  13913. When COLUMNS in non-nil, also include property names given in
  13914. COLUMN formats in the current buffer."
  13915. (let ((case-fold-search t)
  13916. (props (append
  13917. (and specials org-special-properties)
  13918. (and defaults (cons org-effort-property org-default-properties))
  13919. nil)))
  13920. (org-with-wide-buffer
  13921. (goto-char (point-min))
  13922. (while (re-search-forward org-property-start-re nil t)
  13923. (catch :skip
  13924. (let ((range (org-get-property-block)))
  13925. (unless range (throw :skip nil))
  13926. (goto-char (car range))
  13927. (let ((begin (car range))
  13928. (end (cdr range)))
  13929. ;; Make sure that found property block is not located
  13930. ;; before current point, as it would generate an infloop.
  13931. ;; It can happen, for example, in the following
  13932. ;; situation:
  13933. ;;
  13934. ;; * Headline
  13935. ;; :PROPERTIES:
  13936. ;; ...
  13937. ;; :END:
  13938. ;; *************** Inlinetask
  13939. ;; #+BEGIN_EXAMPLE
  13940. ;; :PROPERTIES:
  13941. ;; #+END_EXAMPLE
  13942. ;;
  13943. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  13944. (while (< (point) end)
  13945. (let ((p (progn (looking-at org-property-re)
  13946. (match-string-no-properties 2))))
  13947. ;; Only add true property name, not extension symbol.
  13948. (push (if (not (string-match-p "\\+\\'" p)) p
  13949. (substring p 0 -1))
  13950. props))
  13951. (forward-line))))
  13952. (outline-next-heading)))
  13953. (when columns
  13954. (goto-char (point-min))
  13955. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  13956. (let ((element (org-element-at-point)))
  13957. (when (memq (org-element-type element) '(keyword node-property))
  13958. (let ((value (org-element-property :value element))
  13959. (start 0))
  13960. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  13961. \\(?:{[^}]+}\\)?"
  13962. value start)
  13963. (setq start (match-end 0))
  13964. (let ((p (match-string-no-properties 1 value)))
  13965. (unless (member-ignore-case p org-special-properties)
  13966. (push p props))))))))))
  13967. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  13968. (defun org-property-values (key)
  13969. "List all non-nil values of property KEY in current buffer."
  13970. (org-with-wide-buffer
  13971. (goto-char (point-min))
  13972. (let ((case-fold-search t)
  13973. (re (org-re-property key))
  13974. values)
  13975. (while (re-search-forward re nil t)
  13976. (push (org-entry-get (point) key) values))
  13977. (delete-dups values))))
  13978. (defun org-insert-property-drawer ()
  13979. "Insert a property drawer into the current entry."
  13980. (org-with-wide-buffer
  13981. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  13982. (org-back-to-heading t)
  13983. (org-with-limited-levels (org-back-to-heading t)))
  13984. (forward-line)
  13985. (when (looking-at-p org-planning-line-re) (forward-line))
  13986. (unless (looking-at-p org-property-drawer-re)
  13987. ;; Make sure we start editing a line from current entry, not from
  13988. ;; next one. It prevents extending text properties or overlays
  13989. ;; belonging to the latter.
  13990. (when (bolp) (backward-char))
  13991. (let ((begin (1+ (point)))
  13992. (inhibit-read-only t))
  13993. (insert "\n:PROPERTIES:\n:END:")
  13994. (when (eobp) (insert "\n"))
  13995. (org-indent-region begin (point))))))
  13996. (defun org-insert-drawer (&optional arg drawer)
  13997. "Insert a drawer at point.
  13998. When optional argument ARG is non-nil, insert a property drawer.
  13999. Optional argument DRAWER, when non-nil, is a string representing
  14000. drawer's name. Otherwise, the user is prompted for a name.
  14001. If a region is active, insert the drawer around that region
  14002. instead.
  14003. Point is left between drawer's boundaries."
  14004. (interactive "P")
  14005. (let* ((drawer (if arg "PROPERTIES"
  14006. (or drawer (read-from-minibuffer "Drawer: ")))))
  14007. (cond
  14008. ;; With C-u, fall back on `org-insert-property-drawer'
  14009. (arg (org-insert-property-drawer))
  14010. ;; Check validity of suggested drawer's name.
  14011. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14012. (user-error "Invalid drawer name"))
  14013. ;; With an active region, insert a drawer at point.
  14014. ((not (org-region-active-p))
  14015. (progn
  14016. (unless (bolp) (insert "\n"))
  14017. (insert (format ":%s:\n\n:END:\n" drawer))
  14018. (forward-line -2)))
  14019. ;; Otherwise, insert the drawer at point
  14020. (t
  14021. (let ((rbeg (region-beginning))
  14022. (rend (copy-marker (region-end))))
  14023. (unwind-protect
  14024. (progn
  14025. (goto-char rbeg)
  14026. (beginning-of-line)
  14027. (when (save-excursion
  14028. (re-search-forward org-outline-regexp-bol rend t))
  14029. (user-error "Drawers cannot contain headlines"))
  14030. ;; Position point at the beginning of the first
  14031. ;; non-blank line in region. Insert drawer's opening
  14032. ;; there, then indent it.
  14033. (org-skip-whitespace)
  14034. (beginning-of-line)
  14035. (insert ":" drawer ":\n")
  14036. (forward-line -1)
  14037. (indent-for-tab-command)
  14038. ;; Move point to the beginning of the first blank line
  14039. ;; after the last non-blank line in region. Insert
  14040. ;; drawer's closing, then indent it.
  14041. (goto-char rend)
  14042. (skip-chars-backward " \r\t\n")
  14043. (insert "\n:END:")
  14044. (deactivate-mark t)
  14045. (indent-for-tab-command)
  14046. (unless (eolp) (insert "\n")))
  14047. ;; Clear marker, whatever the outcome of insertion is.
  14048. (set-marker rend nil)))))))
  14049. (defvar org-property-set-functions-alist nil
  14050. "Property set function alist.
  14051. Each entry should have the following format:
  14052. (PROPERTY . READ-FUNCTION)
  14053. The read function will be called with the same argument as
  14054. `org-completing-read'.")
  14055. (defun org-set-property-function (property)
  14056. "Get the function that should be used to set PROPERTY.
  14057. This is computed according to `org-property-set-functions-alist'."
  14058. (or (cdr (assoc property org-property-set-functions-alist))
  14059. 'org-completing-read))
  14060. (defun org-read-property-value (property &optional pom)
  14061. "Read value for PROPERTY, as a string.
  14062. When optional argument POM is non-nil, completion uses additional
  14063. information, i.e., allowed or existing values at point or marker
  14064. POM."
  14065. (let* ((completion-ignore-case t)
  14066. (allowed
  14067. (or (org-property-get-allowed-values nil property 'table)
  14068. (and pom (org-property-get-allowed-values pom property 'table))))
  14069. (current (org-entry-get nil property))
  14070. (prompt (format "%s value%s: "
  14071. property
  14072. (if (org-string-nw-p current)
  14073. (format " [%s]" current)
  14074. "")))
  14075. (set-function (org-set-property-function property)))
  14076. (org-trim
  14077. (if allowed
  14078. (funcall set-function
  14079. prompt allowed nil
  14080. (not (get-text-property 0 'org-unrestricted (caar allowed))))
  14081. (let ((all (mapcar #'list
  14082. (append (org-property-values property)
  14083. (and pom
  14084. (org-with-point-at pom
  14085. (org-property-values property)))))))
  14086. (funcall set-function prompt all nil nil "" nil current))))))
  14087. (defvar org-last-set-property nil)
  14088. (defvar org-last-set-property-value nil)
  14089. (defun org-read-property-name ()
  14090. "Read a property name."
  14091. (let ((completion-ignore-case t)
  14092. (default-prop (or (and (org-at-property-p)
  14093. (match-string-no-properties 2))
  14094. org-last-set-property)))
  14095. (org-completing-read
  14096. (concat "Property"
  14097. (if default-prop (concat " [" default-prop "]") "")
  14098. ": ")
  14099. (mapcar #'list (org-buffer-property-keys nil t t))
  14100. nil nil nil nil default-prop)))
  14101. (defun org-set-property-and-value (use-last)
  14102. "Allow to set [PROPERTY]: [value] direction from prompt.
  14103. When use-default, don't even ask, just use the last
  14104. \"[PROPERTY]: [value]\" string from the history."
  14105. (interactive "P")
  14106. (let* ((completion-ignore-case t)
  14107. (pv (or (and use-last org-last-set-property-value)
  14108. (org-completing-read
  14109. "Enter a \"[Property]: [value]\" pair: "
  14110. nil nil nil nil nil
  14111. org-last-set-property-value)))
  14112. prop val)
  14113. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14114. (setq prop (match-string 1 pv)
  14115. val (match-string 2 pv))
  14116. (org-set-property prop val))))
  14117. (defun org-set-property (property value)
  14118. "In the current entry, set PROPERTY to VALUE.
  14119. When called interactively, this will prompt for a property name, offering
  14120. completion on existing and default properties. And then it will prompt
  14121. for a value, offering completion either on allowed values (via an inherited
  14122. xxx_ALL property) or on existing values in other instances of this property
  14123. in the current file.
  14124. Throw an error when trying to set a property with an invalid name."
  14125. (interactive (list nil nil))
  14126. (let ((property (or property (org-read-property-name))))
  14127. ;; `org-entry-put' also makes the following check, but this one
  14128. ;; avoids polluting `org-last-set-property' and
  14129. ;; `org-last-set-property-value' needlessly.
  14130. (unless (org--valid-property-p property)
  14131. (user-error "Invalid property name: \"%s\"" property))
  14132. (let ((value (or value (org-read-property-value property)))
  14133. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14134. (setq org-last-set-property property)
  14135. (setq org-last-set-property-value (concat property ": " value))
  14136. ;; Possibly postprocess the inserted value:
  14137. (when fn (setq value (funcall fn value)))
  14138. (unless (equal (org-entry-get nil property) value)
  14139. (org-entry-put nil property value)))))
  14140. (defun org-find-property (property &optional value)
  14141. "Find first entry in buffer that sets PROPERTY.
  14142. When optional argument VALUE is non-nil, only consider an entry
  14143. if it contains PROPERTY set to this value. If PROPERTY should be
  14144. explicitly set to nil, use string \"nil\" for VALUE.
  14145. Return position where the entry begins, or nil if there is no
  14146. such entry. If narrowing is in effect, only search the visible
  14147. part of the buffer."
  14148. (save-excursion
  14149. (goto-char (point-min))
  14150. (let ((case-fold-search t)
  14151. (re (org-re-property property nil (not value) value)))
  14152. (catch 'exit
  14153. (while (re-search-forward re nil t)
  14154. (when (if value (org-at-property-p)
  14155. (org-entry-get (point) property nil t))
  14156. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14157. (defun org-delete-property (property)
  14158. "In the current entry, delete PROPERTY."
  14159. (interactive
  14160. (let* ((completion-ignore-case t)
  14161. (cat (org-entry-get (point) "CATEGORY"))
  14162. (props0 (org-entry-properties nil 'standard))
  14163. (props (if cat props0
  14164. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14165. (prop (if (< 1 (length props))
  14166. (completing-read "Property: " props nil t)
  14167. (caar props))))
  14168. (list prop)))
  14169. (if (not property)
  14170. (message "No property to delete in this entry")
  14171. (org-entry-delete nil property)
  14172. (message "Property \"%s\" deleted" property)))
  14173. (defun org-delete-property-globally (property)
  14174. "Remove PROPERTY globally, from all entries.
  14175. This function ignores narrowing, if any."
  14176. (interactive
  14177. (let* ((completion-ignore-case t)
  14178. (prop (completing-read
  14179. "Globally remove property: "
  14180. (mapcar #'list (org-buffer-property-keys)))))
  14181. (list prop)))
  14182. (org-with-wide-buffer
  14183. (goto-char (point-min))
  14184. (let ((count 0)
  14185. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14186. (while (re-search-forward re nil t)
  14187. (when (org-entry-delete (point) property) (cl-incf count)))
  14188. (message "Property \"%s\" removed from %d entries" property count))))
  14189. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14190. (defun org-compute-property-at-point ()
  14191. "Compute the property at point.
  14192. This looks for an enclosing column format, extracts the operator and
  14193. then applies it to the property in the column format's scope."
  14194. (interactive)
  14195. (unless (org-at-property-p)
  14196. (user-error "Not at a property"))
  14197. (let ((prop (match-string-no-properties 2)))
  14198. (org-columns-get-format-and-top-level)
  14199. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14200. (user-error "No operator defined for property %s" prop))
  14201. (org-columns-compute prop)))
  14202. (defvar org-property-allowed-value-functions nil
  14203. "Hook for functions supplying allowed values for a specific property.
  14204. The functions must take a single argument, the name of the property, and
  14205. return a flat list of allowed values. If \":ETC\" is one of
  14206. the values, this means that these values are intended as defaults for
  14207. completion, but that other values should be allowed too.
  14208. The functions must return nil if they are not responsible for this
  14209. property.")
  14210. (defun org-property-get-allowed-values (pom property &optional table)
  14211. "Get allowed values for the property PROPERTY.
  14212. When TABLE is non-nil, return an alist that can directly be used for
  14213. completion."
  14214. (let (vals)
  14215. (cond
  14216. ((equal property "TODO")
  14217. (setq vals (org-with-point-at pom
  14218. (append org-todo-keywords-1 '("")))))
  14219. ((equal property "PRIORITY")
  14220. (let ((n org-lowest-priority))
  14221. (while (>= n org-highest-priority)
  14222. (push (char-to-string n) vals)
  14223. (setq n (1- n)))))
  14224. ((equal property "CATEGORY"))
  14225. ((member property org-special-properties))
  14226. ((setq vals (run-hook-with-args-until-success
  14227. 'org-property-allowed-value-functions property)))
  14228. (t
  14229. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14230. (when (and vals (string-match "\\S-" vals))
  14231. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14232. (setq vals (mapcar (lambda (x)
  14233. (cond ((stringp x) x)
  14234. ((numberp x) (number-to-string x))
  14235. ((symbolp x) (symbol-name x))
  14236. (t "???")))
  14237. vals)))))
  14238. (when (member ":ETC" vals)
  14239. (setq vals (remove ":ETC" vals))
  14240. (org-add-props (car vals) '(org-unrestricted t)))
  14241. (if table (mapcar 'list vals) vals)))
  14242. (defun org-property-previous-allowed-value (&optional _previous)
  14243. "Switch to the next allowed value for this property."
  14244. (interactive)
  14245. (org-property-next-allowed-value t))
  14246. (defun org-property-next-allowed-value (&optional previous)
  14247. "Switch to the next allowed value for this property."
  14248. (interactive)
  14249. (unless (org-at-property-p)
  14250. (user-error "Not at a property"))
  14251. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  14252. (key (match-string 2))
  14253. (value (match-string 3))
  14254. (allowed (or (org-property-get-allowed-values (point) key)
  14255. (and (member value '("[ ]" "[-]" "[X]"))
  14256. '("[ ]" "[X]"))))
  14257. (heading (save-match-data (nth 4 (org-heading-components))))
  14258. nval)
  14259. (unless allowed
  14260. (user-error "Allowed values for this property have not been defined"))
  14261. (when previous (setq allowed (reverse allowed)))
  14262. (when (member value allowed)
  14263. (setq nval (car (cdr (member value allowed)))))
  14264. (setq nval (or nval (car allowed)))
  14265. (when (equal nval value)
  14266. (user-error "Only one allowed value for this property"))
  14267. (org-at-property-p)
  14268. (replace-match (concat " :" key ": " nval) t t)
  14269. (org-indent-line)
  14270. (beginning-of-line 1)
  14271. (skip-chars-forward " \t")
  14272. (when (equal prop org-effort-property)
  14273. (org-refresh-property
  14274. '((effort . identity)
  14275. (effort-minutes . org-duration-to-minutes))
  14276. nval)
  14277. (when (string= org-clock-current-task heading)
  14278. (setq org-clock-effort nval)
  14279. (org-clock-update-mode-line)))
  14280. (run-hook-with-args 'org-property-changed-functions key nval)))
  14281. (defun org-find-olp (path &optional this-buffer)
  14282. "Return a marker pointing to the entry at outline path OLP.
  14283. If anything goes wrong, throw an error.
  14284. You can wrap this call to catch the error like this:
  14285. (condition-case msg
  14286. (org-mobile-locate-entry (match-string 4))
  14287. (error (nth 1 msg)))
  14288. The return value will then be either a string with the error message,
  14289. or a marker if everything is OK.
  14290. If THIS-BUFFER is set, the outline path does not contain a file,
  14291. only headings."
  14292. (let* ((file (if this-buffer buffer-file-name (pop path)))
  14293. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  14294. (level 1)
  14295. (lmin 1)
  14296. (lmax 1)
  14297. end found flevel)
  14298. (unless buffer (error "File not found :%s" file))
  14299. (with-current-buffer buffer
  14300. (unless (derived-mode-p 'org-mode)
  14301. (error "Buffer %s needs to be in Org mode" buffer))
  14302. (org-with-wide-buffer
  14303. (goto-char (point-min))
  14304. (dolist (heading path)
  14305. (let ((re (format org-complex-heading-regexp-format
  14306. (regexp-quote heading)))
  14307. (cnt 0))
  14308. (while (re-search-forward re end t)
  14309. (setq level (- (match-end 1) (match-beginning 1)))
  14310. (when (and (>= level lmin) (<= level lmax))
  14311. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  14312. (when (= cnt 0)
  14313. (error "Heading not found on level %d: %s" lmax heading))
  14314. (when (> cnt 1)
  14315. (error "Heading not unique on level %d: %s" lmax heading))
  14316. (goto-char found)
  14317. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  14318. (setq end (save-excursion (org-end-of-subtree t t)))))
  14319. (when (org-at-heading-p)
  14320. (point-marker))))))
  14321. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  14322. "Find node HEADING in BUFFER.
  14323. Return a marker to the heading if it was found, or nil if not.
  14324. If POS-ONLY is set, return just the position instead of a marker.
  14325. The heading text must match exact, but it may have a TODO keyword,
  14326. a priority cookie and tags in the standard locations."
  14327. (with-current-buffer (or buffer (current-buffer))
  14328. (org-with-wide-buffer
  14329. (goto-char (point-min))
  14330. (let (case-fold-search)
  14331. (when (re-search-forward
  14332. (format org-complex-heading-regexp-format
  14333. (regexp-quote heading)) nil t)
  14334. (if pos-only
  14335. (match-beginning 0)
  14336. (move-marker (make-marker) (match-beginning 0))))))))
  14337. (defun org-find-exact-heading-in-directory (heading &optional dir)
  14338. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  14339. When the target headline is found, return a marker to this location."
  14340. (let ((files (directory-files (or dir default-directory)
  14341. t "\\`[^.#].*\\.org\\'"))
  14342. visiting m buffer)
  14343. (catch 'found
  14344. (dolist (file files)
  14345. (message "trying %s" file)
  14346. (setq visiting (org-find-base-buffer-visiting file))
  14347. (setq buffer (or visiting (find-file-noselect file)))
  14348. (setq m (org-find-exact-headline-in-buffer
  14349. heading buffer))
  14350. (when (and (not m) (not visiting)) (kill-buffer buffer))
  14351. (and m (throw 'found m))))))
  14352. (defun org-find-entry-with-id (ident)
  14353. "Locate the entry that contains the ID property with exact value IDENT.
  14354. IDENT can be a string, a symbol or a number, this function will search for
  14355. the string representation of it.
  14356. Return the position where this entry starts, or nil if there is no such entry."
  14357. (interactive "sID: ")
  14358. (let ((id (cond
  14359. ((stringp ident) ident)
  14360. ((symbolp ident) (symbol-name ident))
  14361. ((numberp ident) (number-to-string ident))
  14362. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  14363. (org-with-wide-buffer (org-find-property "ID" id))))
  14364. ;;;; Timestamps
  14365. (defvar org-last-changed-timestamp nil)
  14366. (defvar org-last-inserted-timestamp nil
  14367. "The last time stamp inserted with `org-insert-time-stamp'.")
  14368. (defun org-time-stamp (arg &optional inactive)
  14369. "Prompt for a date/time and insert a time stamp.
  14370. If the user specifies a time like HH:MM or if this command is
  14371. called with at least one prefix argument, the time stamp contains
  14372. the date and the time. Otherwise, only the date is included.
  14373. All parts of a date not specified by the user are filled in from
  14374. the timestamp at point, if any, or the current date/time
  14375. otherwise.
  14376. If there is already a timestamp at the cursor, it is replaced.
  14377. With two universal prefix arguments, insert an active timestamp
  14378. with the current time without prompting the user.
  14379. When called from lisp, the timestamp is inactive if INACTIVE is
  14380. non-nil."
  14381. (interactive "P")
  14382. (let* ((ts (cond
  14383. ((org-at-date-range-p t)
  14384. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  14385. ((org-at-timestamp-p 'lax) (match-string 0))))
  14386. ;; Default time is either the timestamp at point or today.
  14387. ;; When entering a range, only the range start is considered.
  14388. (default-time (if (not ts) (current-time)
  14389. (apply #'encode-time (org-parse-time-string ts))))
  14390. (default-input (and ts (org-get-compact-tod ts)))
  14391. (repeater (and ts
  14392. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  14393. (match-string 0 ts)))
  14394. org-time-was-given
  14395. org-end-time-was-given
  14396. (time
  14397. (and (if (equal arg '(16)) (current-time)
  14398. ;; Preserve `this-command' and `last-command'.
  14399. (let ((this-command this-command)
  14400. (last-command last-command))
  14401. (org-read-date
  14402. arg 'totime nil nil default-time default-input
  14403. inactive))))))
  14404. (cond
  14405. ((and ts
  14406. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  14407. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  14408. (insert "--")
  14409. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  14410. (ts
  14411. ;; Make sure we're on a timestamp. When in the middle of a date
  14412. ;; range, move arbitrarily to range end.
  14413. (unless (org-at-timestamp-p 'lax)
  14414. (skip-chars-forward "-")
  14415. (org-at-timestamp-p 'lax))
  14416. (replace-match "")
  14417. (setq org-last-changed-timestamp
  14418. (org-insert-time-stamp
  14419. time (or org-time-was-given arg)
  14420. inactive nil nil (list org-end-time-was-given)))
  14421. (when repeater
  14422. (backward-char)
  14423. (insert " " repeater)
  14424. (setq org-last-changed-timestamp
  14425. (concat (substring org-last-inserted-timestamp 0 -1)
  14426. " " repeater ">")))
  14427. (message "Timestamp updated"))
  14428. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  14429. (t (org-insert-time-stamp
  14430. time (or org-time-was-given arg) inactive nil nil
  14431. (list org-end-time-was-given))))))
  14432. ;; FIXME: can we use this for something else, like computing time differences?
  14433. (defun org-get-compact-tod (s)
  14434. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  14435. (let* ((t1 (match-string 1 s))
  14436. (h1 (string-to-number (match-string 2 s)))
  14437. (m1 (string-to-number (match-string 3 s)))
  14438. (t2 (and (match-end 4) (match-string 5 s)))
  14439. (h2 (and t2 (string-to-number (match-string 6 s))))
  14440. (m2 (and t2 (string-to-number (match-string 7 s))))
  14441. dh dm)
  14442. (if (not t2)
  14443. t1
  14444. (setq dh (- h2 h1) dm (- m2 m1))
  14445. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  14446. (concat t1 "+" (number-to-string dh)
  14447. (and (/= 0 dm) (format ":%02d" dm)))))))
  14448. (defun org-time-stamp-inactive (&optional arg)
  14449. "Insert an inactive time stamp.
  14450. An inactive time stamp is enclosed in square brackets instead of angle
  14451. brackets. It is inactive in the sense that it does not trigger agenda entries,
  14452. does not link to the calendar and cannot be changed with the S-cursor keys.
  14453. So these are more for recording a certain time/date.
  14454. If the user specifies a time like HH:MM or if this command is called with
  14455. at least one prefix argument, the time stamp contains the date and the time.
  14456. Otherwise, only the date is included.
  14457. When called with two universal prefix arguments, insert an active time stamp
  14458. with the current time without prompting the user."
  14459. (interactive "P")
  14460. (org-time-stamp arg 'inactive))
  14461. (defvar org-date-ovl (make-overlay 1 1))
  14462. (overlay-put org-date-ovl 'face 'org-date-selected)
  14463. (delete-overlay org-date-ovl)
  14464. (defvar org-ans1) ; dynamically scoped parameter
  14465. (defvar org-ans2) ; dynamically scoped parameter
  14466. (defvar org-plain-time-of-day-regexp) ; defined below
  14467. (defvar org-overriding-default-time nil) ; dynamically scoped
  14468. (defvar org-read-date-overlay nil)
  14469. (defvar org-dcst nil) ; dynamically scoped
  14470. (defvar org-read-date-history nil)
  14471. (defvar org-read-date-final-answer nil)
  14472. (defvar org-read-date-analyze-futurep nil)
  14473. (defvar org-read-date-analyze-forced-year nil)
  14474. (defvar org-read-date-inactive)
  14475. (defvar org-def)
  14476. (defvar org-defdecode)
  14477. (defvar org-with-time)
  14478. (defvar calendar-setup) ; Dynamically scoped.
  14479. (defun org-read-date (&optional with-time to-time from-string prompt
  14480. default-time default-input inactive)
  14481. "Read a date, possibly a time, and make things smooth for the user.
  14482. The prompt will suggest to enter an ISO date, but you can also enter anything
  14483. which will at least partially be understood by `parse-time-string'.
  14484. Unrecognized parts of the date will default to the current day, month, year,
  14485. hour and minute. If this command is called to replace a timestamp at point,
  14486. or to enter the second timestamp of a range, the default time is taken
  14487. from the existing stamp. Furthermore, the command prefers the future,
  14488. so if you are giving a date where the year is not given, and the day-month
  14489. combination is already past in the current year, it will assume you
  14490. mean next year. For details, see the manual. A few examples:
  14491. 3-2-5 --> 2003-02-05
  14492. feb 15 --> currentyear-02-15
  14493. 2/15 --> currentyear-02-15
  14494. sep 12 9 --> 2009-09-12
  14495. 12:45 --> today 12:45
  14496. 22 sept 0:34 --> currentyear-09-22 0:34
  14497. 12 --> currentyear-currentmonth-12
  14498. Fri --> nearest Friday after today
  14499. -Tue --> last Tuesday
  14500. etc.
  14501. Furthermore you can specify a relative date by giving, as the *first* thing
  14502. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  14503. change in days weeks, months, years.
  14504. With a single plus or minus, the date is relative to today. With a double
  14505. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  14506. +4d --> four days from today
  14507. +4 --> same as above
  14508. +2w --> two weeks from today
  14509. ++5 --> five days from default date
  14510. The function understands only English month and weekday abbreviations.
  14511. While prompting, a calendar is popped up - you can also select the
  14512. date with the mouse (button 1). The calendar shows a period of three
  14513. months. To scroll it to other months, use the keys `>' and `<'.
  14514. If you don't like the calendar, turn it off with
  14515. (setq org-read-date-popup-calendar nil)
  14516. With optional argument TO-TIME, the date will immediately be converted
  14517. to an internal time.
  14518. With an optional argument WITH-TIME, the prompt will suggest to
  14519. also insert a time. Note that when WITH-TIME is not set, you can
  14520. still enter a time, and this function will inform the calling routine
  14521. about this change. The calling routine may then choose to change the
  14522. format used to insert the time stamp into the buffer to include the time.
  14523. With optional argument FROM-STRING, read from this string instead from
  14524. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  14525. the time/date that is used for everything that is not specified by the
  14526. user."
  14527. (require 'parse-time)
  14528. (let* ((org-with-time with-time)
  14529. (org-time-stamp-rounding-minutes
  14530. (if (equal org-with-time '(16))
  14531. '(0 0)
  14532. org-time-stamp-rounding-minutes))
  14533. (org-dcst org-display-custom-times)
  14534. (ct (org-current-time))
  14535. (org-def (or org-overriding-default-time default-time ct))
  14536. (org-defdecode (decode-time org-def))
  14537. (cur-frame (selected-frame))
  14538. (mouse-autoselect-window nil) ; Don't let the mouse jump
  14539. (calendar-setup
  14540. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  14541. (calendar-move-hook nil)
  14542. (calendar-view-diary-initially-flag nil)
  14543. (calendar-view-holidays-initially-flag nil)
  14544. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  14545. ;; Rationalize `org-def' and `org-defdecode', if required.
  14546. (when (< (nth 2 org-defdecode) org-extend-today-until)
  14547. (setf (nth 2 org-defdecode) -1)
  14548. (setf (nth 1 org-defdecode) 59)
  14549. (setq org-def (apply #'encode-time org-defdecode))
  14550. (setq org-defdecode (decode-time org-def)))
  14551. (let* ((timestr (format-time-string
  14552. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  14553. org-def))
  14554. (prompt (concat (if prompt (concat prompt " ") "")
  14555. (format "Date+time [%s]: " timestr))))
  14556. (cond
  14557. (from-string (setq ans from-string))
  14558. (org-read-date-popup-calendar
  14559. (save-excursion
  14560. (save-window-excursion
  14561. (calendar)
  14562. (when (eq calendar-setup 'calendar-only)
  14563. (setq cal-frame
  14564. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  14565. (select-frame cal-frame))
  14566. (org-eval-in-calendar '(setq cursor-type nil) t)
  14567. (unwind-protect
  14568. (progn
  14569. (calendar-forward-day (- (time-to-days org-def)
  14570. (calendar-absolute-from-gregorian
  14571. (calendar-current-date))))
  14572. (org-eval-in-calendar nil t)
  14573. (let* ((old-map (current-local-map))
  14574. (map (copy-keymap calendar-mode-map))
  14575. (minibuffer-local-map
  14576. (copy-keymap org-read-date-minibuffer-local-map)))
  14577. (org-defkey map (kbd "RET") 'org-calendar-select)
  14578. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  14579. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  14580. (unwind-protect
  14581. (progn
  14582. (use-local-map map)
  14583. (setq org-read-date-inactive inactive)
  14584. (add-hook 'post-command-hook 'org-read-date-display)
  14585. (setq org-ans0
  14586. (read-string prompt
  14587. default-input
  14588. 'org-read-date-history
  14589. nil))
  14590. ;; org-ans0: from prompt
  14591. ;; org-ans1: from mouse click
  14592. ;; org-ans2: from calendar motion
  14593. (setq ans
  14594. (concat org-ans0 " " (or org-ans1 org-ans2))))
  14595. (remove-hook 'post-command-hook 'org-read-date-display)
  14596. (use-local-map old-map)
  14597. (when org-read-date-overlay
  14598. (delete-overlay org-read-date-overlay)
  14599. (setq org-read-date-overlay nil)))))
  14600. (bury-buffer "*Calendar*")
  14601. (when cal-frame
  14602. (delete-frame cal-frame)
  14603. (select-frame-set-input-focus cur-frame))))))
  14604. (t ; Naked prompt only
  14605. (unwind-protect
  14606. (setq ans (read-string prompt default-input
  14607. 'org-read-date-history timestr))
  14608. (when org-read-date-overlay
  14609. (delete-overlay org-read-date-overlay)
  14610. (setq org-read-date-overlay nil))))))
  14611. (setq final (org-read-date-analyze ans org-def org-defdecode))
  14612. (when org-read-date-analyze-forced-year
  14613. (message "Year was forced into %s"
  14614. (if org-read-date-force-compatible-dates
  14615. "compatible range (1970-2037)"
  14616. "range representable on this machine"))
  14617. (ding))
  14618. ;; One round trip to get rid of 34th of August and stuff like that....
  14619. (setq final (decode-time (apply 'encode-time final)))
  14620. (setq org-read-date-final-answer ans)
  14621. (if to-time
  14622. (apply 'encode-time final)
  14623. (if (and (boundp 'org-time-was-given) org-time-was-given)
  14624. (format "%04d-%02d-%02d %02d:%02d"
  14625. (nth 5 final) (nth 4 final) (nth 3 final)
  14626. (nth 2 final) (nth 1 final))
  14627. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  14628. (defun org-read-date-display ()
  14629. "Display the current date prompt interpretation in the minibuffer."
  14630. (when org-read-date-display-live
  14631. (when org-read-date-overlay
  14632. (delete-overlay org-read-date-overlay))
  14633. (when (minibufferp (current-buffer))
  14634. (save-excursion
  14635. (end-of-line 1)
  14636. (while (not (equal (buffer-substring
  14637. (max (point-min) (- (point) 4)) (point))
  14638. " "))
  14639. (insert " ")))
  14640. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  14641. " " (or org-ans1 org-ans2)))
  14642. (org-end-time-was-given nil)
  14643. (f (org-read-date-analyze ans org-def org-defdecode))
  14644. (fmts (if org-dcst
  14645. org-time-stamp-custom-formats
  14646. org-time-stamp-formats))
  14647. (fmt (if (or org-with-time
  14648. (and (boundp 'org-time-was-given) org-time-was-given))
  14649. (cdr fmts)
  14650. (car fmts)))
  14651. (txt (format-time-string fmt (apply 'encode-time f)))
  14652. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  14653. (txt (concat "=> " txt)))
  14654. (when (and org-end-time-was-given
  14655. (string-match org-plain-time-of-day-regexp txt))
  14656. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  14657. org-end-time-was-given
  14658. (substring txt (match-end 0)))))
  14659. (when org-read-date-analyze-futurep
  14660. (setq txt (concat txt " (=>F)")))
  14661. (setq org-read-date-overlay
  14662. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  14663. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  14664. (defun org-read-date-analyze (ans def defdecode)
  14665. "Analyze the combined answer of the date prompt."
  14666. ;; FIXME: cleanup and comment
  14667. ;; Pass `current-time' result to `decode-time' (instead of calling
  14668. ;; without arguments) so that only `current-time' has to be
  14669. ;; overridden in tests.
  14670. (let ((org-def def)
  14671. (org-defdecode defdecode)
  14672. (nowdecode (decode-time (current-time)))
  14673. delta deltan deltaw deltadef year month day
  14674. hour minute second wday pm h2 m2 tl wday1
  14675. iso-year iso-weekday iso-week iso-date futurep kill-year)
  14676. (setq org-read-date-analyze-futurep nil
  14677. org-read-date-analyze-forced-year nil)
  14678. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  14679. (setq ans "+0"))
  14680. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  14681. (setq ans (replace-match "" t t ans)
  14682. deltan (car delta)
  14683. deltaw (nth 1 delta)
  14684. deltadef (nth 2 delta)))
  14685. ;; Check if there is an iso week date in there. If yes, store the
  14686. ;; info and postpone interpreting it until the rest of the parsing
  14687. ;; is done.
  14688. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  14689. (setq iso-year (when (match-end 1)
  14690. (org-small-year-to-year
  14691. (string-to-number (match-string 1 ans))))
  14692. iso-weekday (when (match-end 3)
  14693. (string-to-number (match-string 3 ans)))
  14694. iso-week (string-to-number (match-string 2 ans)))
  14695. (setq ans (replace-match "" t t ans)))
  14696. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  14697. (when (string-match
  14698. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  14699. (setq year (if (match-end 2)
  14700. (string-to-number (match-string 2 ans))
  14701. (progn (setq kill-year t)
  14702. (string-to-number (format-time-string "%Y"))))
  14703. month (string-to-number (match-string 3 ans))
  14704. day (string-to-number (match-string 4 ans)))
  14705. (setq year (org-small-year-to-year year))
  14706. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14707. t nil ans)))
  14708. ;; Help matching dotted european dates
  14709. (when (string-match
  14710. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  14711. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  14712. (setq kill-year t)
  14713. (string-to-number (format-time-string "%Y")))
  14714. day (string-to-number (match-string 1 ans))
  14715. month (string-to-number (match-string 2 ans))
  14716. ans (replace-match (format "%04d-%02d-%02d" year month day)
  14717. t nil ans)))
  14718. ;; Help matching american dates, like 5/30 or 5/30/7
  14719. (when (string-match
  14720. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  14721. (setq year (if (match-end 4)
  14722. (string-to-number (match-string 4 ans))
  14723. (progn (setq kill-year t)
  14724. (string-to-number (format-time-string "%Y"))))
  14725. month (string-to-number (match-string 1 ans))
  14726. day (string-to-number (match-string 2 ans)))
  14727. (setq year (org-small-year-to-year year))
  14728. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14729. t nil ans)))
  14730. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  14731. ;; If there is a time with am/pm, and *no* time without it, we convert
  14732. ;; so that matching will be successful.
  14733. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  14734. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  14735. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  14736. (setq hour (string-to-number (match-string 1 ans))
  14737. minute (if (match-end 3)
  14738. (string-to-number (match-string 3 ans))
  14739. 0)
  14740. pm (equal ?p
  14741. (string-to-char (downcase (match-string 4 ans)))))
  14742. (if (and (= hour 12) (not pm))
  14743. (setq hour 0)
  14744. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  14745. (setq ans (replace-match (format "%02d:%02d" hour minute)
  14746. t t ans))))
  14747. ;; Check if a time range is given as a duration
  14748. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  14749. (setq hour (string-to-number (match-string 1 ans))
  14750. h2 (+ hour (string-to-number (match-string 3 ans)))
  14751. minute (string-to-number (match-string 2 ans))
  14752. m2 (+ minute (if (match-end 5) (string-to-number
  14753. (match-string 5 ans))0)))
  14754. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  14755. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  14756. t t ans)))
  14757. ;; Check if there is a time range
  14758. (when (boundp 'org-end-time-was-given)
  14759. (setq org-time-was-given nil)
  14760. (when (and (string-match org-plain-time-of-day-regexp ans)
  14761. (match-end 8))
  14762. (setq org-end-time-was-given (match-string 8 ans))
  14763. (setq ans (concat (substring ans 0 (match-beginning 7))
  14764. (substring ans (match-end 7))))))
  14765. (setq tl (parse-time-string ans)
  14766. day (or (nth 3 tl) (nth 3 org-defdecode))
  14767. month
  14768. (cond ((nth 4 tl))
  14769. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  14770. ;; Day was specified. Make sure DAY+MONTH
  14771. ;; combination happens in the future.
  14772. ((nth 3 tl)
  14773. (setq futurep t)
  14774. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  14775. (nth 4 nowdecode)))
  14776. (t (nth 4 org-defdecode)))
  14777. year
  14778. (cond ((and (not kill-year) (nth 5 tl)))
  14779. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  14780. ;; Month was guessed in the future and is at least
  14781. ;; equal to NOWDECODE's. Fix year accordingly.
  14782. (futurep
  14783. (if (or (> month (nth 4 nowdecode))
  14784. (>= day (nth 3 nowdecode)))
  14785. (nth 5 nowdecode)
  14786. (1+ (nth 5 nowdecode))))
  14787. ;; Month was specified. Make sure MONTH+YEAR
  14788. ;; combination happens in the future.
  14789. ((nth 4 tl)
  14790. (setq futurep t)
  14791. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  14792. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  14793. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  14794. (t (nth 5 nowdecode))))
  14795. (t (nth 5 org-defdecode)))
  14796. hour (or (nth 2 tl) (nth 2 org-defdecode))
  14797. minute (or (nth 1 tl) (nth 1 org-defdecode))
  14798. second (or (nth 0 tl) 0)
  14799. wday (nth 6 tl))
  14800. (when (and (eq org-read-date-prefer-future 'time)
  14801. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  14802. (equal day (nth 3 nowdecode))
  14803. (equal month (nth 4 nowdecode))
  14804. (equal year (nth 5 nowdecode))
  14805. (nth 2 tl)
  14806. (or (< (nth 2 tl) (nth 2 nowdecode))
  14807. (and (= (nth 2 tl) (nth 2 nowdecode))
  14808. (nth 1 tl)
  14809. (< (nth 1 tl) (nth 1 nowdecode)))))
  14810. (setq day (1+ day)
  14811. futurep t))
  14812. ;; Special date definitions below
  14813. (cond
  14814. (iso-week
  14815. ;; There was an iso week
  14816. (require 'cal-iso)
  14817. (setq futurep nil)
  14818. (setq year (or iso-year year)
  14819. day (or iso-weekday wday 1)
  14820. wday nil ; to make sure that the trigger below does not match
  14821. iso-date (calendar-gregorian-from-absolute
  14822. (calendar-iso-to-absolute
  14823. (list iso-week day year))))
  14824. ; FIXME: Should we also push ISO weeks into the future?
  14825. ; (when (and org-read-date-prefer-future
  14826. ; (not iso-year)
  14827. ; (< (calendar-absolute-from-gregorian iso-date)
  14828. ; (time-to-days (current-time))))
  14829. ; (setq year (1+ year)
  14830. ; iso-date (calendar-gregorian-from-absolute
  14831. ; (calendar-iso-to-absolute
  14832. ; (list iso-week day year)))))
  14833. (setq month (car iso-date)
  14834. year (nth 2 iso-date)
  14835. day (nth 1 iso-date)))
  14836. (deltan
  14837. (setq futurep nil)
  14838. (unless deltadef
  14839. ;; Pass `current-time' result to `decode-time' (instead of
  14840. ;; calling without arguments) so that only `current-time' has
  14841. ;; to be overridden in tests.
  14842. (let ((now (decode-time (current-time))))
  14843. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  14844. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  14845. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  14846. ((equal deltaw "m") (setq month (+ month deltan)))
  14847. ((equal deltaw "y") (setq year (+ year deltan)))))
  14848. ((and wday (not (nth 3 tl)))
  14849. ;; Weekday was given, but no day, so pick that day in the week
  14850. ;; on or after the derived date.
  14851. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  14852. (unless (equal wday wday1)
  14853. (setq day (+ day (% (- wday wday1 -7) 7))))))
  14854. (when (and (boundp 'org-time-was-given)
  14855. (nth 2 tl))
  14856. (setq org-time-was-given t))
  14857. (when (< year 100) (setq year (+ 2000 year)))
  14858. ;; Check of the date is representable
  14859. (if org-read-date-force-compatible-dates
  14860. (progn
  14861. (when (< year 1970)
  14862. (setq year 1970 org-read-date-analyze-forced-year t))
  14863. (when (> year 2037)
  14864. (setq year 2037 org-read-date-analyze-forced-year t)))
  14865. (condition-case nil
  14866. (ignore (encode-time second minute hour day month year))
  14867. (error
  14868. (setq year (nth 5 org-defdecode))
  14869. (setq org-read-date-analyze-forced-year t))))
  14870. (setq org-read-date-analyze-futurep futurep)
  14871. (list second minute hour day month year)))
  14872. (defvar parse-time-weekdays)
  14873. (defun org-read-date-get-relative (s today default)
  14874. "Check string S for special relative date string.
  14875. TODAY and DEFAULT are internal times, for today and for a default.
  14876. Return shift list (N what def-flag)
  14877. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  14878. N is the number of WHATs to shift.
  14879. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  14880. the DEFAULT date rather than TODAY."
  14881. (require 'parse-time)
  14882. (when (and
  14883. (string-match
  14884. (concat
  14885. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  14886. "\\([0-9]+\\)?"
  14887. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  14888. "\\([ \t]\\|$\\)") s)
  14889. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  14890. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  14891. (string-to-char (substring (match-string 1 s) -1))
  14892. ?+))
  14893. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  14894. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  14895. (what (if (match-end 3) (match-string 3 s) "d"))
  14896. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  14897. (date (if rel default today))
  14898. (wday (nth 6 (decode-time date)))
  14899. delta)
  14900. (if wday1
  14901. (progn
  14902. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  14903. (when (= delta 0) (setq delta 7))
  14904. (when (= dir ?-)
  14905. (setq delta (- delta 7))
  14906. (when (= delta 0) (setq delta -7)))
  14907. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  14908. (list delta "d" rel))
  14909. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  14910. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  14911. "Turn a user-specified date into the internal representation.
  14912. The internal representation needed by the calendar is (month day year).
  14913. This is a wrapper to handle the brain-dead convention in calendar that
  14914. user function argument order change dependent on argument order."
  14915. (pcase calendar-date-style
  14916. (`american (list arg1 arg2 arg3))
  14917. (`european (list arg2 arg1 arg3))
  14918. (`iso (list arg2 arg3 arg1))))
  14919. (defun org-eval-in-calendar (form &optional keepdate)
  14920. "Eval FORM in the calendar window and return to current window.
  14921. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  14922. (let ((sf (selected-frame))
  14923. (sw (selected-window)))
  14924. (select-window (get-buffer-window "*Calendar*" t))
  14925. (eval form)
  14926. (when (and (not keepdate) (calendar-cursor-to-date))
  14927. (let* ((date (calendar-cursor-to-date))
  14928. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  14929. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  14930. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  14931. (select-window sw)
  14932. (select-frame-set-input-focus sf)))
  14933. (defun org-calendar-select ()
  14934. "Return to `org-read-date' with the date currently selected.
  14935. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  14936. (interactive)
  14937. (when (calendar-cursor-to-date)
  14938. (let* ((date (calendar-cursor-to-date))
  14939. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  14940. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  14941. (when (active-minibuffer-window) (exit-minibuffer))))
  14942. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  14943. "Insert a date stamp for the date given by the internal TIME.
  14944. See `format-time-string' for the format of TIME.
  14945. WITH-HM means use the stamp format that includes the time of the day.
  14946. INACTIVE means use square brackets instead of angular ones, so that the
  14947. stamp will not contribute to the agenda.
  14948. PRE and POST are optional strings to be inserted before and after the
  14949. stamp.
  14950. The command returns the inserted time stamp."
  14951. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  14952. stamp)
  14953. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  14954. (insert-before-markers (or pre ""))
  14955. (when (listp extra)
  14956. (setq extra (car extra))
  14957. (if (and (stringp extra)
  14958. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  14959. (setq extra (format "-%02d:%02d"
  14960. (string-to-number (match-string 1 extra))
  14961. (string-to-number (match-string 2 extra))))
  14962. (setq extra nil)))
  14963. (when extra
  14964. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  14965. (insert-before-markers (setq stamp (format-time-string fmt time)))
  14966. (insert-before-markers (or post ""))
  14967. (setq org-last-inserted-timestamp stamp)))
  14968. (defun org-toggle-time-stamp-overlays ()
  14969. "Toggle the use of custom time stamp formats."
  14970. (interactive)
  14971. (setq org-display-custom-times (not org-display-custom-times))
  14972. (unless org-display-custom-times
  14973. (let ((p (point-min)) (bmp (buffer-modified-p)))
  14974. (while (setq p (next-single-property-change p 'display))
  14975. (when (and (get-text-property p 'display)
  14976. (eq (get-text-property p 'face) 'org-date))
  14977. (remove-text-properties
  14978. p (setq p (next-single-property-change p 'display))
  14979. '(display t))))
  14980. (set-buffer-modified-p bmp)))
  14981. (org-restart-font-lock)
  14982. (setq org-table-may-need-update t)
  14983. (if org-display-custom-times
  14984. (message "Time stamps are overlaid with custom format")
  14985. (message "Time stamp overlays removed")))
  14986. (defun org-display-custom-time (beg end)
  14987. "Overlay modified time stamp format over timestamp between BEG and END."
  14988. (let* ((ts (buffer-substring beg end))
  14989. t1 with-hm tf time str (off 0))
  14990. (save-match-data
  14991. (setq t1 (org-parse-time-string ts t))
  14992. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  14993. (setq off (- (match-end 0) (match-beginning 0)))))
  14994. (setq end (- end off))
  14995. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  14996. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  14997. time (org-fix-decoded-time t1)
  14998. str (org-add-props
  14999. (format-time-string
  15000. (substring tf 1 -1) (apply 'encode-time time))
  15001. nil 'mouse-face 'highlight))
  15002. (put-text-property beg end 'display str)))
  15003. (defun org-fix-decoded-time (time)
  15004. "Set 0 instead of nil for the first 6 elements of time.
  15005. Don't touch the rest."
  15006. (let ((n 0))
  15007. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15008. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15009. "Difference between TIMESTAMP-STRING and now in days.
  15010. If SECONDS is non-nil, return the difference in seconds."
  15011. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15012. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15013. (funcall fdiff (current-time)))))
  15014. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15015. "Is the time in TIMESTAMP-STRING close to the current date?"
  15016. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15017. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15018. (not (org-entry-is-done-p))))
  15019. (defun org-get-wdays (ts &optional delay zero-delay)
  15020. "Get the deadline lead time appropriate for timestring TS.
  15021. When DELAY is non-nil, get the delay time for scheduled items
  15022. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15023. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15024. don't try to find the delay cookie in the scheduled timestamp."
  15025. (let ((tv (if delay org-scheduled-delay-days
  15026. org-deadline-warning-days)))
  15027. (cond
  15028. ((or (and delay (< tv 0))
  15029. (and delay zero-delay (<= tv 0))
  15030. (and (not delay) (<= tv 0)))
  15031. ;; Enforce this value no matter what
  15032. (- tv))
  15033. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15034. ;; lead time is specified.
  15035. (floor (* (string-to-number (match-string 1 ts))
  15036. (cdr (assoc (match-string 2 ts)
  15037. '(("d" . 1) ("w" . 7)
  15038. ("m" . 30.4) ("y" . 365.25)
  15039. ("h" . 0.041667)))))))
  15040. ;; go for the default.
  15041. (t tv))))
  15042. (defun org-calendar-select-mouse (ev)
  15043. "Return to `org-read-date' with the date currently selected.
  15044. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15045. (interactive "e")
  15046. (mouse-set-point ev)
  15047. (when (calendar-cursor-to-date)
  15048. (let* ((date (calendar-cursor-to-date))
  15049. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15050. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15051. (when (active-minibuffer-window) (exit-minibuffer))))
  15052. (defun org-check-deadlines (ndays)
  15053. "Check if there are any deadlines due or past due.
  15054. A deadline is considered due if it happens within `org-deadline-warning-days'
  15055. days from today's date. If the deadline appears in an entry marked DONE,
  15056. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15057. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15058. are shown."
  15059. (interactive "P")
  15060. (let* ((org-warn-days
  15061. (cond
  15062. ((equal ndays '(4)) 100000)
  15063. (ndays (prefix-numeric-value ndays))
  15064. (t (abs org-deadline-warning-days))))
  15065. (case-fold-search nil)
  15066. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15067. (callback
  15068. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15069. (message "%d deadlines past-due or due within %d days"
  15070. (org-occur regexp nil callback)
  15071. org-warn-days)))
  15072. (defsubst org-re-timestamp (type)
  15073. "Return a regexp for timestamp TYPE.
  15074. Allowed values for TYPE are:
  15075. all: all timestamps
  15076. active: only active timestamps (<...>)
  15077. inactive: only inactive timestamps ([...])
  15078. scheduled: only scheduled timestamps
  15079. deadline: only deadline timestamps
  15080. closed: only closed time-stamps
  15081. When TYPE is nil, fall back on returning a regexp that matches
  15082. both scheduled and deadline timestamps."
  15083. (cl-case type
  15084. (all org-ts-regexp-both)
  15085. (active org-ts-regexp)
  15086. (inactive org-ts-regexp-inactive)
  15087. (scheduled org-scheduled-time-regexp)
  15088. (deadline org-deadline-time-regexp)
  15089. (closed org-closed-time-regexp)
  15090. (otherwise
  15091. (concat "\\<"
  15092. (regexp-opt (list org-deadline-string org-scheduled-string))
  15093. " *<\\([^>]+\\)>"))))
  15094. (defun org-check-before-date (d)
  15095. "Check if there are deadlines or scheduled entries before date D."
  15096. (interactive (list (org-read-date)))
  15097. (let* ((case-fold-search nil)
  15098. (regexp (org-re-timestamp org-ts-type))
  15099. (ts-type org-ts-type)
  15100. (callback
  15101. (lambda ()
  15102. (let ((match (match-string 1)))
  15103. (and (if (memq ts-type '(active inactive all))
  15104. (eq (org-element-type (save-excursion
  15105. (backward-char)
  15106. (org-element-context)))
  15107. 'timestamp)
  15108. (org-at-planning-p))
  15109. (time-less-p
  15110. (org-time-string-to-time match)
  15111. (org-time-string-to-time d)))))))
  15112. (message "%d entries before %s"
  15113. (org-occur regexp nil callback)
  15114. d)))
  15115. (defun org-check-after-date (d)
  15116. "Check if there are deadlines or scheduled entries after date D."
  15117. (interactive (list (org-read-date)))
  15118. (let* ((case-fold-search nil)
  15119. (regexp (org-re-timestamp org-ts-type))
  15120. (ts-type org-ts-type)
  15121. (callback
  15122. (lambda ()
  15123. (let ((match (match-string 1)))
  15124. (and (if (memq ts-type '(active inactive all))
  15125. (eq (org-element-type (save-excursion
  15126. (backward-char)
  15127. (org-element-context)))
  15128. 'timestamp)
  15129. (org-at-planning-p))
  15130. (not (time-less-p
  15131. (org-time-string-to-time match)
  15132. (org-time-string-to-time d))))))))
  15133. (message "%d entries after %s"
  15134. (org-occur regexp nil callback)
  15135. d)))
  15136. (defun org-check-dates-range (start-date end-date)
  15137. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15138. (interactive (list (org-read-date nil nil nil "Range starts")
  15139. (org-read-date nil nil nil "Range end")))
  15140. (let ((case-fold-search nil)
  15141. (regexp (org-re-timestamp org-ts-type))
  15142. (callback
  15143. (let ((type org-ts-type))
  15144. (lambda ()
  15145. (let ((match (match-string 1)))
  15146. (and
  15147. (if (memq type '(active inactive all))
  15148. (eq (org-element-type (save-excursion
  15149. (backward-char)
  15150. (org-element-context)))
  15151. 'timestamp)
  15152. (org-at-planning-p))
  15153. (not (time-less-p
  15154. (org-time-string-to-time match)
  15155. (org-time-string-to-time start-date)))
  15156. (time-less-p
  15157. (org-time-string-to-time match)
  15158. (org-time-string-to-time end-date))))))))
  15159. (message "%d entries between %s and %s"
  15160. (org-occur regexp nil callback) start-date end-date)))
  15161. (defun org-evaluate-time-range (&optional to-buffer)
  15162. "Evaluate a time range by computing the difference between start and end.
  15163. Normally the result is just printed in the echo area, but with prefix arg
  15164. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15165. If the time range is actually in a table, the result is inserted into the
  15166. next column.
  15167. For time difference computation, a year is assumed to be exactly 365
  15168. days in order to avoid rounding problems."
  15169. (interactive "P")
  15170. (or
  15171. (org-clock-update-time-maybe)
  15172. (save-excursion
  15173. (unless (org-at-date-range-p t)
  15174. (goto-char (point-at-bol))
  15175. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  15176. (unless (org-at-date-range-p t)
  15177. (user-error "Not at a time-stamp range, and none found in current line")))
  15178. (let* ((ts1 (match-string 1))
  15179. (ts2 (match-string 2))
  15180. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  15181. (match-end (match-end 0))
  15182. (time1 (org-time-string-to-time ts1))
  15183. (time2 (org-time-string-to-time ts2))
  15184. (t1 (float-time time1))
  15185. (t2 (float-time time2))
  15186. (diff (abs (- t2 t1)))
  15187. (negative (< (- t2 t1) 0))
  15188. ;; (ys (floor (* 365 24 60 60)))
  15189. (ds (* 24 60 60))
  15190. (hs (* 60 60))
  15191. (fy "%dy %dd %02d:%02d")
  15192. (fy1 "%dy %dd")
  15193. (fd "%dd %02d:%02d")
  15194. (fd1 "%dd")
  15195. (fh "%02d:%02d")
  15196. y d h m align)
  15197. (if havetime
  15198. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15199. y 0
  15200. d (floor (/ diff ds)) diff (mod diff ds)
  15201. h (floor (/ diff hs)) diff (mod diff hs)
  15202. m (floor (/ diff 60)))
  15203. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15204. y 0
  15205. d (floor (+ (/ diff ds) 0.5))
  15206. h 0 m 0))
  15207. (if (not to-buffer)
  15208. (message "%s" (org-make-tdiff-string y d h m))
  15209. (if (org-at-table-p)
  15210. (progn
  15211. (goto-char match-end)
  15212. (setq align t)
  15213. (and (looking-at " *|") (goto-char (match-end 0))))
  15214. (goto-char match-end))
  15215. (when (looking-at
  15216. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  15217. (replace-match ""))
  15218. (when negative (insert " -"))
  15219. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  15220. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  15221. (insert " " (format fh h m))))
  15222. (when align (org-table-align))
  15223. (message "Time difference inserted")))))
  15224. (defun org-make-tdiff-string (y d h m)
  15225. (let ((fmt "")
  15226. (l nil))
  15227. (when (> y 0)
  15228. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  15229. (push y l))
  15230. (when (> d 0)
  15231. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  15232. (push d l))
  15233. (when (> h 0)
  15234. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  15235. (push h l))
  15236. (when (> m 0)
  15237. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  15238. (push m l))
  15239. (apply 'format fmt (nreverse l))))
  15240. (defun org-time-string-to-time (s)
  15241. "Convert timestamp string S into internal time."
  15242. (apply #'encode-time (org-parse-time-string s)))
  15243. (defun org-time-string-to-seconds (s)
  15244. "Convert a timestamp string S into a number of seconds."
  15245. (float-time (org-time-string-to-time s)))
  15246. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  15247. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  15248. "Convert time stamp S to an absolute day number.
  15249. If DAYNR in non-nil, and there is a specifier for a cyclic time
  15250. stamp, get the closest date to DAYNR. If PREFER is
  15251. `past' (respectively `future') return a date past (respectively
  15252. after) or equal to DAYNR.
  15253. POS is the location of time stamp S, as a buffer position in
  15254. BUFFER.
  15255. Diary sexp timestamps are matched against DAYNR, when non-nil.
  15256. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  15257. signaled."
  15258. (cond
  15259. ((string-match "\\`%%\\((.*)\\)" s)
  15260. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  15261. ;; only able to match individual dates. If it fails, raise an
  15262. ;; error.
  15263. (if (and daynr
  15264. (org-diary-sexp-entry
  15265. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  15266. daynr
  15267. (signal 'org-diary-sexp-no-match (list s))))
  15268. (daynr (org-closest-date s daynr prefer))
  15269. (t (time-to-days
  15270. (condition-case errdata
  15271. (apply #'encode-time (org-parse-time-string s))
  15272. (error (error "Bad timestamp `%s'%s\nError was: %s"
  15273. s
  15274. (if (not (and buffer pos)) ""
  15275. (format-message " at %d in buffer `%s'" pos buffer))
  15276. (cdr errdata))))))))
  15277. (defun org-days-to-iso-week (days)
  15278. "Return the iso week number."
  15279. (require 'cal-iso)
  15280. (car (calendar-iso-from-absolute days)))
  15281. (defun org-small-year-to-year (year)
  15282. "Convert 2-digit years into 4-digit years.
  15283. YEAR is expanded into one of the 30 next years, if possible, or
  15284. into a past one. Any year larger than 99 is returned unchanged."
  15285. (if (>= year 100) year
  15286. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  15287. (century (/ current 100))
  15288. (offset (- year (% current 100))))
  15289. (cond ((> offset 30) (+ (* (1- century) 100) year))
  15290. ((> offset -70) (+ (* century 100) year))
  15291. (t (+ (* (1+ century) 100) year))))))
  15292. (defun org-time-from-absolute (d)
  15293. "Return the time corresponding to date D.
  15294. D may be an absolute day number, or a calendar-type list (month day year)."
  15295. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  15296. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  15297. (defvar org-agenda-current-date)
  15298. (defun org-calendar-holiday ()
  15299. "List of holidays, for Diary display in Org mode."
  15300. (require 'holidays)
  15301. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  15302. (and hl (mapconcat #'identity hl "; "))))
  15303. (defun org-diary-sexp-entry (sexp entry d)
  15304. "Process a SEXP diary ENTRY for date D."
  15305. (require 'diary-lib)
  15306. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  15307. ;; dynamically.
  15308. (let* ((sexp `(let ((entry ,entry)
  15309. (date ',d))
  15310. ,(car (read-from-string sexp))))
  15311. (result (if calendar-debug-sexp (eval sexp)
  15312. (condition-case nil
  15313. (eval sexp)
  15314. (error
  15315. (beep)
  15316. (message "Bad sexp at line %d in %s: %s"
  15317. (org-current-line)
  15318. (buffer-file-name) sexp)
  15319. (sleep-for 2))))))
  15320. (cond ((stringp result) (split-string result "; "))
  15321. ((and (consp result)
  15322. (not (consp (cdr result)))
  15323. (stringp (cdr result))) (cdr result))
  15324. ((and (consp result)
  15325. (stringp (car result))) result)
  15326. (result entry))))
  15327. (defun org-diary-to-ical-string (frombuf)
  15328. "Get iCalendar entries from diary entries in buffer FROMBUF.
  15329. This uses the icalendar.el library."
  15330. (let* ((tmpdir temporary-file-directory)
  15331. (tmpfile (make-temp-name
  15332. (expand-file-name "orgics" tmpdir)))
  15333. buf rtn b e)
  15334. (with-current-buffer frombuf
  15335. (icalendar-export-region (point-min) (point-max) tmpfile)
  15336. (setq buf (find-buffer-visiting tmpfile))
  15337. (set-buffer buf)
  15338. (goto-char (point-min))
  15339. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  15340. (setq b (match-beginning 0)))
  15341. (goto-char (point-max))
  15342. (when (re-search-backward "^END:VEVENT" nil t)
  15343. (setq e (match-end 0)))
  15344. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  15345. (kill-buffer buf)
  15346. (delete-file tmpfile)
  15347. rtn))
  15348. (defun org-closest-date (start current prefer)
  15349. "Return closest date to CURRENT starting from START.
  15350. CURRENT and START are both time stamps.
  15351. When PREFER is `past', return a date that is either CURRENT or
  15352. past. When PREFER is `future', return a date that is either
  15353. CURRENT or future.
  15354. Only time stamps with a repeater are modified. Any other time
  15355. stamp stay unchanged. In any case, return value is an absolute
  15356. day number."
  15357. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  15358. ;; No repeater. Do not shift time stamp.
  15359. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15360. (let ((value (string-to-number (match-string 1 start)))
  15361. (type (match-string 2 start)))
  15362. (if (= 0 value)
  15363. ;; Repeater with a 0-value is considered as void.
  15364. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15365. (let* ((base (org-date-to-gregorian start))
  15366. (target (org-date-to-gregorian current))
  15367. (sday (calendar-absolute-from-gregorian base))
  15368. (cday (calendar-absolute-from-gregorian target))
  15369. n1 n2)
  15370. ;; If START is already past CURRENT, just return START.
  15371. (if (<= cday sday) sday
  15372. ;; Compute closest date before (N1) and closest date past
  15373. ;; (N2) CURRENT.
  15374. (pcase type
  15375. ("h"
  15376. (let ((missing-hours
  15377. (mod (+ (- (* 24 (- cday sday))
  15378. (nth 2 (org-parse-time-string start)))
  15379. org-extend-today-until)
  15380. value)))
  15381. (setf n1 (if (= missing-hours 0) cday
  15382. (- cday (1+ (/ missing-hours 24)))))
  15383. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  15384. ((or "d" "w")
  15385. (let ((value (if (equal type "w") (* 7 value) value)))
  15386. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  15387. (setf n2 (+ n1 value))))
  15388. ("m"
  15389. (let* ((add-months
  15390. (lambda (d n)
  15391. ;; Add N months to gregorian date D, i.e.,
  15392. ;; a list (MONTH DAY YEAR). Return a valid
  15393. ;; gregorian date.
  15394. (let ((m (+ (nth 0 d) n)))
  15395. (list (mod m 12)
  15396. (nth 1 d)
  15397. (+ (/ m 12) (nth 2 d))))))
  15398. (months ; Complete months to TARGET.
  15399. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  15400. (- (nth 0 target) (nth 0 base))
  15401. ;; If START's day is greater than
  15402. ;; TARGET's, remove incomplete month.
  15403. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  15404. value)
  15405. value))
  15406. (before (funcall add-months base months)))
  15407. (setf n1 (calendar-absolute-from-gregorian before))
  15408. (setf n2
  15409. (calendar-absolute-from-gregorian
  15410. (funcall add-months before value)))))
  15411. (_
  15412. (let* ((d (nth 1 base))
  15413. (m (nth 0 base))
  15414. (y (nth 2 base))
  15415. (years ; Complete years to TARGET.
  15416. (* (/ (- (nth 2 target)
  15417. y
  15418. ;; If START's month and day are
  15419. ;; greater than TARGET's, remove
  15420. ;; incomplete year.
  15421. (if (or (> (nth 0 target) m)
  15422. (and (= (nth 0 target) m)
  15423. (> (nth 1 target) d)))
  15424. 0
  15425. 1))
  15426. value)
  15427. value))
  15428. (before (list m d (+ y years))))
  15429. (setf n1 (calendar-absolute-from-gregorian before))
  15430. (setf n2 (calendar-absolute-from-gregorian
  15431. (list m d (+ (nth 2 before) value)))))))
  15432. ;; Handle PREFER parameter, if any.
  15433. (cond
  15434. ((eq prefer 'past) (if (= cday n2) n2 n1))
  15435. ((eq prefer 'future) (if (= cday n1) n1 n2))
  15436. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  15437. (defun org-date-to-gregorian (d)
  15438. "Turn any specification of date D into a Gregorian date for the calendar."
  15439. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  15440. ((and (listp d) (= (length d) 3)) d)
  15441. ((stringp d)
  15442. (let ((d (org-parse-time-string d)))
  15443. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  15444. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  15445. (defun org-timestamp-up (&optional arg)
  15446. "Increase the date item at the cursor by one.
  15447. If the cursor is on the year, change the year. If it is on the month,
  15448. the day or the time, change that. If the cursor is on the enclosing
  15449. bracket, change the timestamp type.
  15450. With prefix ARG, change by that many units."
  15451. (interactive "p")
  15452. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  15453. (defun org-timestamp-down (&optional arg)
  15454. "Decrease the date item at the cursor by one.
  15455. If the cursor is on the year, change the year. If it is on the month,
  15456. the day or the time, change that. If the cursor is on the enclosing
  15457. bracket, change the timestamp type.
  15458. With prefix ARG, change by that many units."
  15459. (interactive "p")
  15460. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  15461. (defun org-timestamp-up-day (&optional arg)
  15462. "Increase the date in the time stamp by one day.
  15463. With prefix ARG, change that many days."
  15464. (interactive "p")
  15465. (if (and (not (org-at-timestamp-p 'lax))
  15466. (org-at-heading-p))
  15467. (org-todo 'up)
  15468. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  15469. (defun org-timestamp-down-day (&optional arg)
  15470. "Decrease the date in the time stamp by one day.
  15471. With prefix ARG, change that many days."
  15472. (interactive "p")
  15473. (if (and (not (org-at-timestamp-p 'lax))
  15474. (org-at-heading-p))
  15475. (org-todo 'down)
  15476. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  15477. (defun org-at-timestamp-p (&optional extended)
  15478. "Non-nil if point is inside a timestamp.
  15479. By default, the function only consider syntactically valid active
  15480. timestamps. However, the caller may have a broader definition
  15481. for timestamps. As a consequence, optional argument EXTENDED can
  15482. be set to the following values
  15483. `inactive'
  15484. Include also syntactically valid inactive timestamps.
  15485. `agenda'
  15486. Include timestamps allowed in Agenda, i.e., those in
  15487. properties drawers, planning lines and clock lines.
  15488. `lax'
  15489. Ignore context. The function matches any part of the
  15490. document looking like a timestamp. This includes comments,
  15491. example blocks...
  15492. For backward-compatibility with Org 9.0, every other non-nil
  15493. value is equivalent to `inactive'.
  15494. When at a timestamp, return the position of the point as a symbol
  15495. among `bracket', `after', `year', `month', `hour', `minute',
  15496. `day' or a number of character from the last know part of the
  15497. time stamp.
  15498. When matching, the match groups are the following:
  15499. group 1: year
  15500. group 2: month
  15501. group 3: day number
  15502. group 4: day name
  15503. group 5: hours, if any
  15504. group 6: minutes, if any"
  15505. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  15506. (pos (point))
  15507. (match?
  15508. (let ((boundaries (org-in-regexp regexp)))
  15509. (save-match-data
  15510. (cond ((null boundaries) nil)
  15511. ((eq extended 'lax) t)
  15512. (t
  15513. (or (and (eq extended 'agenda)
  15514. (or (org-at-planning-p)
  15515. (org-at-property-p)
  15516. (and (bound-and-true-p
  15517. org-agenda-include-inactive-timestamps)
  15518. (org-at-clock-log-p))))
  15519. (eq 'timestamp
  15520. (save-excursion
  15521. (when (= pos (cdr boundaries)) (forward-char -1))
  15522. (org-element-type (org-element-context)))))))))))
  15523. (cond
  15524. ((not match?) nil)
  15525. ((= pos (match-beginning 0)) 'bracket)
  15526. ;; Distinguish location right before the closing bracket from
  15527. ;; right after it.
  15528. ((= pos (1- (match-end 0))) 'bracket)
  15529. ((= pos (match-end 0)) 'after)
  15530. ((org-pos-in-match-range pos 2) 'year)
  15531. ((org-pos-in-match-range pos 3) 'month)
  15532. ((org-pos-in-match-range pos 7) 'hour)
  15533. ((org-pos-in-match-range pos 8) 'minute)
  15534. ((or (org-pos-in-match-range pos 4)
  15535. (org-pos-in-match-range pos 5)) 'day)
  15536. ((and (> pos (or (match-end 8) (match-end 5)))
  15537. (< pos (match-end 0)))
  15538. (- pos (or (match-end 8) (match-end 5))))
  15539. (t 'day))))
  15540. (defun org-toggle-timestamp-type ()
  15541. "Toggle the type (<active> or [inactive]) of a time stamp."
  15542. (interactive)
  15543. (when (org-at-timestamp-p 'lax)
  15544. (let ((beg (match-beginning 0)) (end (match-end 0))
  15545. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  15546. (save-excursion
  15547. (goto-char beg)
  15548. (while (re-search-forward "[][<>]" end t)
  15549. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  15550. t t)))
  15551. (message "Timestamp is now %sactive"
  15552. (if (equal (char-after beg) ?<) "" "in")))))
  15553. (defun org-at-clock-log-p ()
  15554. "Non-nil if point is on a clock log line."
  15555. (and (org-match-line org-clock-line-re)
  15556. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  15557. (defvar org-clock-history) ; defined in org-clock.el
  15558. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  15559. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  15560. "Change the date in the time stamp at point.
  15561. The date will be changed by N times WHAT. WHAT can be `day', `month',
  15562. `year', `minute', `second'. If WHAT is not given, the cursor position
  15563. in the timestamp determines what will be changed.
  15564. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  15565. (let ((origin (point))
  15566. (timestamp? (org-at-timestamp-p 'lax))
  15567. origin-cat
  15568. with-hm inactive
  15569. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  15570. extra rem
  15571. ts time time0 fixnext clrgx)
  15572. (unless timestamp? (user-error "Not at a timestamp"))
  15573. (if (and (not what) (eq timestamp? 'bracket))
  15574. (org-toggle-timestamp-type)
  15575. ;; Point isn't on brackets. Remember the part of the time-stamp
  15576. ;; the point was in. Indeed, size of time-stamps may change,
  15577. ;; but point must be kept in the same category nonetheless.
  15578. (setq origin-cat timestamp?)
  15579. (when (and (not what) (not (eq timestamp? 'day))
  15580. org-display-custom-times
  15581. (get-text-property (point) 'display)
  15582. (not (get-text-property (1- (point)) 'display)))
  15583. (setq timestamp? 'day))
  15584. (setq timestamp? (or what timestamp?)
  15585. inactive (= (char-after (match-beginning 0)) ?\[)
  15586. ts (match-string 0))
  15587. (replace-match "")
  15588. (when (string-match
  15589. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  15590. ts)
  15591. (setq extra (match-string 1 ts))
  15592. (when suppress-tmp-delay
  15593. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  15594. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  15595. (setq with-hm t))
  15596. (setq time0 (org-parse-time-string ts))
  15597. (when (and updown
  15598. (eq timestamp? 'minute)
  15599. (not current-prefix-arg))
  15600. ;; This looks like s-up and s-down. Change by one rounding step.
  15601. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  15602. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  15603. (setcar (cdr time0) (+ (nth 1 time0)
  15604. (if (> n 0) (- rem) (- dm rem))))))
  15605. (setq time
  15606. (apply #'encode-time
  15607. (or (car time0) 0)
  15608. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  15609. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  15610. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  15611. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  15612. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  15613. (nthcdr 6 time0)))
  15614. (when (and (memq timestamp? '(hour minute))
  15615. extra
  15616. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  15617. (setq extra (org-modify-ts-extra
  15618. extra
  15619. (if (eq timestamp? 'hour) 2 5)
  15620. n dm)))
  15621. (when (integerp timestamp?)
  15622. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  15623. (when (eq what 'calendar)
  15624. (let ((cal-date (org-get-date-from-calendar)))
  15625. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  15626. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  15627. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  15628. (setcar time0 (or (car time0) 0))
  15629. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  15630. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  15631. (setq time (apply 'encode-time time0))))
  15632. ;; Insert the new time-stamp, and ensure point stays in the same
  15633. ;; category as before (i.e. not after the last position in that
  15634. ;; category).
  15635. (let ((pos (point)))
  15636. ;; Stay before inserted string. `save-excursion' is of no use.
  15637. (setq org-last-changed-timestamp
  15638. (org-insert-time-stamp time with-hm inactive nil nil extra))
  15639. (goto-char pos))
  15640. (save-match-data
  15641. (looking-at org-ts-regexp3)
  15642. (goto-char
  15643. (pcase origin-cat
  15644. ;; `day' category ends before `hour' if any, or at the end
  15645. ;; of the day name.
  15646. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  15647. (`hour (min (match-end 7) origin))
  15648. (`minute (min (1- (match-end 8)) origin))
  15649. ((pred integerp) (min (1- (match-end 0)) origin))
  15650. ;; Point was right after the time-stamp. However, the
  15651. ;; time-stamp length might have changed, so refer to
  15652. ;; (match-end 0) instead.
  15653. (`after (match-end 0))
  15654. ;; `year' and `month' have both fixed size: point couldn't
  15655. ;; have moved into another part.
  15656. (_ origin))))
  15657. ;; Update clock if on a CLOCK line.
  15658. (org-clock-update-time-maybe)
  15659. ;; Maybe adjust the closest clock in `org-clock-history'
  15660. (when org-clock-adjust-closest
  15661. (if (not (and (org-at-clock-log-p)
  15662. (< 1 (length (delq nil (mapcar 'marker-position
  15663. org-clock-history))))))
  15664. (message "No clock to adjust")
  15665. (cond ((save-excursion ; fix previous clock?
  15666. (re-search-backward org-ts-regexp0 nil t)
  15667. (looking-back (concat org-clock-string " \\[")
  15668. (line-beginning-position)))
  15669. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  15670. ((save-excursion ; fix next clock?
  15671. (re-search-backward org-ts-regexp0 nil t)
  15672. (looking-at (concat org-ts-regexp0 "\\] =>")))
  15673. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  15674. (save-window-excursion
  15675. ;; Find closest clock to point, adjust the previous/next one in history
  15676. (let* ((p (save-excursion (org-back-to-heading t)))
  15677. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  15678. (clfixnth
  15679. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  15680. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  15681. (if (not clfixpos)
  15682. (message "No clock to adjust")
  15683. (save-excursion
  15684. (org-goto-marker-or-bmk clfixpos)
  15685. (org-show-subtree)
  15686. (when (re-search-forward clrgx nil t)
  15687. (goto-char (match-beginning 1))
  15688. (let (org-clock-adjust-closest)
  15689. (org-timestamp-change n timestamp? updown))
  15690. (message "Clock adjusted in %s for heading: %s"
  15691. (file-name-nondirectory (buffer-file-name))
  15692. (org-get-heading t t)))))))))
  15693. ;; Try to recenter the calendar window, if any.
  15694. (when (and org-calendar-follow-timestamp-change
  15695. (get-buffer-window "*Calendar*" t)
  15696. (memq timestamp? '(day month year)))
  15697. (org-recenter-calendar (time-to-days time))))))
  15698. (defun org-modify-ts-extra (s pos n dm)
  15699. "Change the different parts of the lead-time and repeat fields in timestamp."
  15700. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  15701. ng h m new rem)
  15702. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  15703. (cond
  15704. ((or (org-pos-in-match-range pos 2)
  15705. (org-pos-in-match-range pos 3))
  15706. (setq m (string-to-number (match-string 3 s))
  15707. h (string-to-number (match-string 2 s)))
  15708. (if (org-pos-in-match-range pos 2)
  15709. (setq h (+ h n))
  15710. (setq n (* dm (with-no-warnings (cl-signum n))))
  15711. (unless (= 0 (setq rem (% m dm)))
  15712. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  15713. (setq m (+ m n)))
  15714. (when (< m 0) (setq m (+ m 60) h (1- h)))
  15715. (when (> m 59) (setq m (- m 60) h (1+ h)))
  15716. (setq h (mod h 24))
  15717. (setq ng 1 new (format "-%02d:%02d" h m)))
  15718. ((org-pos-in-match-range pos 6)
  15719. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  15720. ((org-pos-in-match-range pos 5)
  15721. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  15722. ((org-pos-in-match-range pos 9)
  15723. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  15724. ((org-pos-in-match-range pos 8)
  15725. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  15726. (when ng
  15727. (setq s (concat
  15728. (substring s 0 (match-beginning ng))
  15729. new
  15730. (substring s (match-end ng))))))
  15731. s))
  15732. (defun org-recenter-calendar (d)
  15733. "If the calendar is visible, recenter it to date D."
  15734. (let ((cwin (get-buffer-window "*Calendar*" t)))
  15735. (when cwin
  15736. (let ((calendar-move-hook nil))
  15737. (with-selected-window cwin
  15738. (calendar-goto-date
  15739. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  15740. (defun org-goto-calendar (&optional arg)
  15741. "Go to the Emacs calendar at the current date.
  15742. If there is a time stamp in the current line, go to that date.
  15743. A prefix ARG can be used to force the current date."
  15744. (interactive "P")
  15745. (let ((calendar-move-hook nil)
  15746. (calendar-view-holidays-initially-flag nil)
  15747. (calendar-view-diary-initially-flag nil)
  15748. diff)
  15749. (when (or (org-at-timestamp-p 'lax)
  15750. (org-match-line (concat ".*" org-ts-regexp)))
  15751. (let ((d1 (time-to-days (current-time)))
  15752. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  15753. (setq diff (- d2 d1))))
  15754. (calendar)
  15755. (calendar-goto-today)
  15756. (when (and diff (not arg)) (calendar-forward-day diff))))
  15757. (defun org-get-date-from-calendar ()
  15758. "Return a list (month day year) of date at point in calendar."
  15759. (with-current-buffer "*Calendar*"
  15760. (save-match-data
  15761. (calendar-cursor-to-date))))
  15762. (defun org-date-from-calendar ()
  15763. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  15764. If there is already a time stamp at the cursor position, update it."
  15765. (interactive)
  15766. (if (org-at-timestamp-p 'lax)
  15767. (org-timestamp-change 0 'calendar)
  15768. (let ((cal-date (org-get-date-from-calendar)))
  15769. (org-insert-time-stamp
  15770. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  15771. (defcustom org-image-actual-width t
  15772. "Should we use the actual width of images when inlining them?
  15773. When set to t, always use the image width.
  15774. When set to a number, use imagemagick (when available) to set
  15775. the image's width to this value.
  15776. When set to a number in a list, try to get the width from any
  15777. #+ATTR.* keyword if it matches a width specification like
  15778. #+ATTR_HTML: :width 300px
  15779. and fall back on that number if none is found.
  15780. When set to nil, try to get the width from an #+ATTR.* keyword
  15781. and fall back on the original width if none is found.
  15782. This requires Emacs >= 24.1, build with imagemagick support."
  15783. :group 'org-appearance
  15784. :version "24.4"
  15785. :package-version '(Org . "8.0")
  15786. :type '(choice
  15787. (const :tag "Use the image width" t)
  15788. (integer :tag "Use a number of pixels")
  15789. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  15790. (const :tag "Use #+ATTR* or don't resize" nil)))
  15791. (defcustom org-agenda-inhibit-startup nil
  15792. "Inhibit startup when preparing agenda buffers.
  15793. When this variable is t, the initialization of the Org agenda
  15794. buffers is inhibited: e.g. the visibility state is not set, the
  15795. tables are not re-aligned, etc."
  15796. :type 'boolean
  15797. :version "24.3"
  15798. :group 'org-agenda)
  15799. (defcustom org-agenda-ignore-properties nil
  15800. "Avoid updating text properties when building the agenda.
  15801. Properties are used to prepare buffers for effort estimates,
  15802. appointments, statistics and subtree-local categories.
  15803. If you don't use these in the agenda, you can add them to this
  15804. list and agenda building will be a bit faster.
  15805. The value is a list, with zero or more of the symbols `effort', `appt',
  15806. `stats' or `category'."
  15807. :type '(set :greedy t
  15808. (const effort)
  15809. (const appt)
  15810. (const stats)
  15811. (const category))
  15812. :version "26.1"
  15813. :package-version '(Org . "8.3")
  15814. :group 'org-agenda)
  15815. ;;;; Files
  15816. (defun org-save-all-org-buffers ()
  15817. "Save all Org buffers without user confirmation."
  15818. (interactive)
  15819. (message "Saving all Org buffers...")
  15820. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  15821. (when (featurep 'org-id) (org-id-locations-save))
  15822. (message "Saving all Org buffers... done"))
  15823. (defun org-revert-all-org-buffers ()
  15824. "Revert all Org buffers.
  15825. Prompt for confirmation when there are unsaved changes.
  15826. Be sure you know what you are doing before letting this function
  15827. overwrite your changes.
  15828. This function is useful in a setup where one tracks Org files
  15829. with a version control system, to revert on one machine after pulling
  15830. changes from another. I believe the procedure must be like this:
  15831. 1. M-x org-save-all-org-buffers
  15832. 2. Pull changes from the other machine, resolve conflicts
  15833. 3. M-x org-revert-all-org-buffers"
  15834. (interactive)
  15835. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  15836. (user-error "Abort"))
  15837. (save-excursion
  15838. (save-window-excursion
  15839. (dolist (b (buffer-list))
  15840. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  15841. (with-current-buffer b buffer-file-name))
  15842. (pop-to-buffer-same-window b)
  15843. (revert-buffer t 'no-confirm)))
  15844. (when (and (featurep 'org-id) org-id-track-globally)
  15845. (org-id-locations-load)))))
  15846. ;;;; Agenda files
  15847. ;;;###autoload
  15848. (defun org-switchb (&optional arg)
  15849. "Switch between Org buffers.
  15850. With `\\[universal-argument]' prefix, restrict available buffers to files.
  15851. With `\\[universal-argument] \\[universal-argument]' \
  15852. prefix, restrict available buffers to agenda files."
  15853. (interactive "P")
  15854. (let ((blist (org-buffer-list
  15855. (cond ((equal arg '(4)) 'files)
  15856. ((equal arg '(16)) 'agenda)))))
  15857. (pop-to-buffer-same-window
  15858. (completing-read "Org buffer: "
  15859. (mapcar #'list (mapcar #'buffer-name blist))
  15860. nil t))))
  15861. (defun org-buffer-list (&optional predicate exclude-tmp)
  15862. "Return a list of Org buffers.
  15863. PREDICATE can be `export', `files' or `agenda'.
  15864. export restrict the list to Export buffers.
  15865. files restrict the list to buffers visiting Org files.
  15866. agenda restrict the list to buffers visiting agenda files.
  15867. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  15868. (let* ((bfn nil)
  15869. (agenda-files (and (eq predicate 'agenda)
  15870. (mapcar 'file-truename (org-agenda-files t))))
  15871. (filter
  15872. (cond
  15873. ((eq predicate 'files)
  15874. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  15875. ((eq predicate 'export)
  15876. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  15877. ((eq predicate 'agenda)
  15878. (lambda (b)
  15879. (with-current-buffer b
  15880. (and (derived-mode-p 'org-mode)
  15881. (setq bfn (buffer-file-name b))
  15882. (member (file-truename bfn) agenda-files)))))
  15883. (t (lambda (b) (with-current-buffer b
  15884. (or (derived-mode-p 'org-mode)
  15885. (string-match "\\*Org .*Export"
  15886. (buffer-name b)))))))))
  15887. (delq nil
  15888. (mapcar
  15889. (lambda(b)
  15890. (if (and (funcall filter b)
  15891. (or (not exclude-tmp)
  15892. (not (string-match "tmp" (buffer-name b)))))
  15893. b
  15894. nil))
  15895. (buffer-list)))))
  15896. (defun org-agenda-files (&optional unrestricted archives)
  15897. "Get the list of agenda files.
  15898. Optional UNRESTRICTED means return the full list even if a restriction
  15899. is currently in place.
  15900. When ARCHIVES is t, include all archive files that are really being
  15901. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  15902. `org-agenda-archives-mode' is t."
  15903. (let ((files
  15904. (cond
  15905. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  15906. ((stringp org-agenda-files) (org-read-agenda-file-list))
  15907. ((listp org-agenda-files) org-agenda-files)
  15908. (t (error "Invalid value of `org-agenda-files'")))))
  15909. (setq files (apply 'append
  15910. (mapcar (lambda (f)
  15911. (if (file-directory-p f)
  15912. (directory-files
  15913. f t org-agenda-file-regexp)
  15914. (list f)))
  15915. files)))
  15916. (when org-agenda-skip-unavailable-files
  15917. (setq files (delq nil
  15918. (mapcar (function
  15919. (lambda (file)
  15920. (and (file-readable-p file) file)))
  15921. files))))
  15922. (when (or (eq archives t)
  15923. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  15924. (setq files (org-add-archive-files files)))
  15925. files))
  15926. (defun org-agenda-file-p (&optional file)
  15927. "Return non-nil, if FILE is an agenda file.
  15928. If FILE is omitted, use the file associated with the current
  15929. buffer."
  15930. (let ((fname (or file (buffer-file-name))))
  15931. (and fname
  15932. (member (file-truename fname)
  15933. (mapcar #'file-truename (org-agenda-files t))))))
  15934. (defun org-edit-agenda-file-list ()
  15935. "Edit the list of agenda files.
  15936. Depending on setup, this either uses customize to edit the variable
  15937. `org-agenda-files', or it visits the file that is holding the list. In the
  15938. latter case, the buffer is set up in a way that saving it automatically kills
  15939. the buffer and restores the previous window configuration."
  15940. (interactive)
  15941. (if (stringp org-agenda-files)
  15942. (let ((cw (current-window-configuration)))
  15943. (find-file org-agenda-files)
  15944. (setq-local org-window-configuration cw)
  15945. (add-hook 'after-save-hook
  15946. (lambda ()
  15947. (set-window-configuration
  15948. (prog1 org-window-configuration
  15949. (kill-buffer (current-buffer))))
  15950. (org-install-agenda-files-menu)
  15951. (message "New agenda file list installed"))
  15952. nil 'local)
  15953. (message "%s" (substitute-command-keys
  15954. "Edit list and finish with \\[save-buffer]")))
  15955. (customize-variable 'org-agenda-files)))
  15956. (defun org-store-new-agenda-file-list (list)
  15957. "Set new value for the agenda file list and save it correctly."
  15958. (if (stringp org-agenda-files)
  15959. (let ((fe (org-read-agenda-file-list t)) b u)
  15960. (while (setq b (find-buffer-visiting org-agenda-files))
  15961. (kill-buffer b))
  15962. (with-temp-file org-agenda-files
  15963. (insert
  15964. (mapconcat
  15965. (lambda (f) ;; Keep un-expanded entries.
  15966. (if (setq u (assoc f fe))
  15967. (cdr u)
  15968. f))
  15969. list "\n")
  15970. "\n")))
  15971. (let ((org-mode-hook nil) (org-inhibit-startup t)
  15972. (org-insert-mode-line-in-empty-file nil))
  15973. (setq org-agenda-files list)
  15974. (customize-save-variable 'org-agenda-files org-agenda-files))))
  15975. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  15976. "Read the list of agenda files from a file.
  15977. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  15978. filenames, used by `org-store-new-agenda-file-list' to write back
  15979. un-expanded file names."
  15980. (when (file-directory-p org-agenda-files)
  15981. (error "`org-agenda-files' cannot be a single directory"))
  15982. (when (stringp org-agenda-files)
  15983. (with-temp-buffer
  15984. (insert-file-contents org-agenda-files)
  15985. (mapcar
  15986. (lambda (f)
  15987. (let ((e (expand-file-name (substitute-in-file-name f)
  15988. org-directory)))
  15989. (if pair-with-expansion
  15990. (cons e f)
  15991. e)))
  15992. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  15993. ;;;###autoload
  15994. (defun org-cycle-agenda-files ()
  15995. "Cycle through the files in `org-agenda-files'.
  15996. If the current buffer visits an agenda file, find the next one in the list.
  15997. If the current buffer does not, find the first agenda file."
  15998. (interactive)
  15999. (let* ((fs (or (org-agenda-files t)
  16000. (user-error "No agenda files")))
  16001. (files (copy-sequence fs))
  16002. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16003. file)
  16004. (when tcf
  16005. (while (and (setq file (pop files))
  16006. (not (equal (file-truename file) tcf)))))
  16007. (find-file (car (or files fs)))
  16008. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16009. (defun org-agenda-file-to-front (&optional to-end)
  16010. "Move/add the current file to the top of the agenda file list.
  16011. If the file is not present in the list, it is added to the front. If it is
  16012. present, it is moved there. With optional argument TO-END, add/move to the
  16013. end of the list."
  16014. (interactive "P")
  16015. (let ((org-agenda-skip-unavailable-files nil)
  16016. (file-alist (mapcar (lambda (x)
  16017. (cons (file-truename x) x))
  16018. (org-agenda-files t)))
  16019. (ctf (file-truename
  16020. (or buffer-file-name
  16021. (user-error "Please save the current buffer to a file"))))
  16022. x had)
  16023. (setq x (assoc ctf file-alist) had x)
  16024. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16025. (if to-end
  16026. (setq file-alist (append (delq x file-alist) (list x)))
  16027. (setq file-alist (cons x (delq x file-alist))))
  16028. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16029. (org-install-agenda-files-menu)
  16030. (message "File %s to %s of agenda file list"
  16031. (if had "moved" "added") (if to-end "end" "front"))))
  16032. (defun org-remove-file (&optional file)
  16033. "Remove current file from the list of files in variable `org-agenda-files'.
  16034. These are the files which are being checked for agenda entries.
  16035. Optional argument FILE means use this file instead of the current."
  16036. (interactive)
  16037. (let* ((org-agenda-skip-unavailable-files nil)
  16038. (file (or file buffer-file-name
  16039. (user-error "Current buffer does not visit a file")))
  16040. (true-file (file-truename file))
  16041. (afile (abbreviate-file-name file))
  16042. (files (delq nil (mapcar
  16043. (lambda (x)
  16044. (unless (equal true-file
  16045. (file-truename x))
  16046. x))
  16047. (org-agenda-files t)))))
  16048. (if (not (= (length files) (length (org-agenda-files t))))
  16049. (progn
  16050. (org-store-new-agenda-file-list files)
  16051. (org-install-agenda-files-menu)
  16052. (message "Removed from Org Agenda list: %s" afile))
  16053. (message "File was not in list: %s (not removed)" afile))))
  16054. (defun org-file-menu-entry (file)
  16055. (vector file (list 'find-file file) t))
  16056. (defun org-check-agenda-file (file)
  16057. "Make sure FILE exists. If not, ask user what to do."
  16058. (unless (file-exists-p file)
  16059. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16060. (abbreviate-file-name file))
  16061. (let ((r (downcase (read-char-exclusive))))
  16062. (cond
  16063. ((equal r ?r)
  16064. (org-remove-file file)
  16065. (throw 'nextfile t))
  16066. (t (user-error "Abort"))))))
  16067. (defun org-get-agenda-file-buffer (file)
  16068. "Get an agenda buffer visiting FILE.
  16069. If the buffer needs to be created, add it to the list of buffers
  16070. which might be released later."
  16071. (let ((buf (org-find-base-buffer-visiting file)))
  16072. (if buf
  16073. buf ; just return it
  16074. ;; Make a new buffer and remember it
  16075. (setq buf (find-file-noselect file))
  16076. (when buf (push buf org-agenda-new-buffers))
  16077. buf)))
  16078. (defun org-release-buffers (blist)
  16079. "Release all buffers in list, asking the user for confirmation when needed.
  16080. When a buffer is unmodified, it is just killed. When modified, it is saved
  16081. \(if the user agrees) and then killed."
  16082. (let (file)
  16083. (dolist (buf blist)
  16084. (setq file (buffer-file-name buf))
  16085. (when (and (buffer-modified-p buf)
  16086. file
  16087. (y-or-n-p (format "Save file %s? " file)))
  16088. (with-current-buffer buf (save-buffer)))
  16089. (kill-buffer buf))))
  16090. (defun org-agenda-prepare-buffers (files)
  16091. "Create buffers for all agenda files, protect archived trees and comments."
  16092. (interactive)
  16093. (let ((pa '(:org-archived t))
  16094. (pc '(:org-comment t))
  16095. (pall '(:org-archived t :org-comment t))
  16096. (inhibit-read-only t)
  16097. (org-inhibit-startup org-agenda-inhibit-startup)
  16098. (rea (org-make-tag-string (list org-archive-tag)))
  16099. re pos)
  16100. (setq org-tag-alist-for-agenda nil
  16101. org-tag-groups-alist-for-agenda nil)
  16102. (save-excursion
  16103. (save-restriction
  16104. (dolist (file files)
  16105. (catch 'nextfile
  16106. (if (bufferp file)
  16107. (set-buffer file)
  16108. (org-check-agenda-file file)
  16109. (set-buffer (org-get-agenda-file-buffer file)))
  16110. (widen)
  16111. (org-set-regexps-and-options 'tags-only)
  16112. (setq pos (point))
  16113. (or (memq 'category org-agenda-ignore-properties)
  16114. (org-refresh-category-properties))
  16115. (or (memq 'stats org-agenda-ignore-properties)
  16116. (org-refresh-stats-properties))
  16117. (or (memq 'effort org-agenda-ignore-properties)
  16118. (org-refresh-effort-properties))
  16119. (or (memq 'appt org-agenda-ignore-properties)
  16120. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16121. (setq org-todo-keywords-for-agenda
  16122. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16123. (setq org-done-keywords-for-agenda
  16124. (append org-done-keywords-for-agenda org-done-keywords))
  16125. (setq org-todo-keyword-alist-for-agenda
  16126. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16127. (setq org-tag-alist-for-agenda
  16128. (org--tag-add-to-alist
  16129. org-tag-alist-for-agenda
  16130. org-current-tag-alist))
  16131. ;; Merge current file's tag groups into global
  16132. ;; `org-tag-groups-alist-for-agenda'.
  16133. (when org-group-tags
  16134. (dolist (alist org-tag-groups-alist)
  16135. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  16136. (if old
  16137. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  16138. (push alist org-tag-groups-alist-for-agenda)))))
  16139. (with-silent-modifications
  16140. (save-excursion
  16141. (remove-text-properties (point-min) (point-max) pall)
  16142. (when org-agenda-skip-archived-trees
  16143. (goto-char (point-min))
  16144. (while (re-search-forward rea nil t)
  16145. (when (org-at-heading-p t)
  16146. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  16147. (goto-char (point-min))
  16148. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  16149. (while (re-search-forward re nil t)
  16150. (when (save-match-data (org-in-commented-heading-p t))
  16151. (add-text-properties
  16152. (match-beginning 0) (org-end-of-subtree t) pc)))))
  16153. (goto-char pos)))))
  16154. (setq org-todo-keywords-for-agenda
  16155. (org-uniquify org-todo-keywords-for-agenda))
  16156. (setq org-todo-keyword-alist-for-agenda
  16157. (org-uniquify org-todo-keyword-alist-for-agenda))))
  16158. ;;;; CDLaTeX minor mode
  16159. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  16160. "Keymap for the minor `org-cdlatex-mode'.")
  16161. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  16162. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  16163. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  16164. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  16165. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  16166. (defvar org-cdlatex-texmathp-advice-is-done nil
  16167. "Flag remembering if we have applied the advice to texmathp already.")
  16168. (define-minor-mode org-cdlatex-mode
  16169. "Toggle the minor `org-cdlatex-mode'.
  16170. This mode supports entering LaTeX environment and math in LaTeX fragments
  16171. in Org mode.
  16172. \\{org-cdlatex-mode-map}"
  16173. nil " OCDL" nil
  16174. (when org-cdlatex-mode
  16175. (require 'cdlatex)
  16176. (run-hooks 'cdlatex-mode-hook)
  16177. (cdlatex-compute-tables))
  16178. (unless org-cdlatex-texmathp-advice-is-done
  16179. (setq org-cdlatex-texmathp-advice-is-done t)
  16180. (defadvice texmathp (around org-math-always-on activate)
  16181. "Always return t in Org buffers.
  16182. This is because we want to insert math symbols without dollars even outside
  16183. the LaTeX math segments. If Org mode thinks that point is actually inside
  16184. an embedded LaTeX fragment, let `texmathp' do its job.
  16185. `\\[org-cdlatex-mode-map]'"
  16186. (interactive)
  16187. (let (p)
  16188. (cond
  16189. ((not (derived-mode-p 'org-mode)) ad-do-it)
  16190. ((eq this-command 'cdlatex-math-symbol)
  16191. (setq ad-return-value t
  16192. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  16193. (t
  16194. (let ((p (org-inside-LaTeX-fragment-p)))
  16195. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  16196. (setq ad-return-value t
  16197. texmathp-why '("Org mode embedded math" . 0))
  16198. (when p ad-do-it)))))))))
  16199. (defun turn-on-org-cdlatex ()
  16200. "Unconditionally turn on `org-cdlatex-mode'."
  16201. (org-cdlatex-mode 1))
  16202. (defun org-try-cdlatex-tab ()
  16203. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  16204. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  16205. - inside a LaTeX fragment, or
  16206. - after the first word in a line, where an abbreviation expansion could
  16207. insert a LaTeX environment."
  16208. (when org-cdlatex-mode
  16209. (cond
  16210. ;; Before any word on the line: No expansion possible.
  16211. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  16212. ;; Just after first word on the line: Expand it. Make sure it
  16213. ;; cannot happen on headlines, though.
  16214. ((save-excursion
  16215. (skip-chars-backward "a-zA-Z0-9*")
  16216. (skip-chars-backward " \t")
  16217. (and (bolp) (not (org-at-heading-p))))
  16218. (cdlatex-tab) t)
  16219. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  16220. (defun org-cdlatex-underscore-caret (&optional _arg)
  16221. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  16222. Revert to the normal definition outside of these fragments."
  16223. (interactive "P")
  16224. (if (org-inside-LaTeX-fragment-p)
  16225. (call-interactively 'cdlatex-sub-superscript)
  16226. (let (org-cdlatex-mode)
  16227. (call-interactively (key-binding (vector last-input-event))))))
  16228. (defun org-cdlatex-math-modify (&optional _arg)
  16229. "Execute `cdlatex-math-modify' in LaTeX fragments.
  16230. Revert to the normal definition outside of these fragments."
  16231. (interactive "P")
  16232. (if (org-inside-LaTeX-fragment-p)
  16233. (call-interactively 'cdlatex-math-modify)
  16234. (let (org-cdlatex-mode)
  16235. (call-interactively (key-binding (vector last-input-event))))))
  16236. (defun org-cdlatex-environment-indent (&optional environment item)
  16237. "Execute `cdlatex-environment' and indent the inserted environment.
  16238. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  16239. The inserted environment is indented to current indentation
  16240. unless point is at the beginning of the line, in which the
  16241. environment remains unintended."
  16242. (interactive)
  16243. ;; cdlatex-environment always return nil. Therefore, capture output
  16244. ;; first and determine if an environment was selected.
  16245. (let* ((beg (point-marker))
  16246. (end (copy-marker (point) t))
  16247. (inserted (progn
  16248. (ignore-errors (cdlatex-environment environment item))
  16249. (< beg end)))
  16250. ;; Figure out how many lines to move forward after the
  16251. ;; environment has been inserted.
  16252. (lines (when inserted
  16253. (save-excursion
  16254. (- (cl-loop while (< beg (point))
  16255. with x = 0
  16256. do (forward-line -1)
  16257. (cl-incf x)
  16258. finally return x)
  16259. (if (progn (goto-char beg)
  16260. (and (progn (skip-chars-forward " \t") (eolp))
  16261. (progn (skip-chars-backward " \t") (bolp))))
  16262. 1 0)))))
  16263. (env (org-trim (delete-and-extract-region beg end))))
  16264. (when inserted
  16265. ;; Get indentation of next line unless at column 0.
  16266. (let ((ind (if (bolp) 0
  16267. (save-excursion
  16268. (org-return-indent)
  16269. (prog1 (current-indentation)
  16270. (when (progn (skip-chars-forward " \t") (eolp))
  16271. (delete-region beg (point)))))))
  16272. (bol (progn (skip-chars-backward " \t") (bolp))))
  16273. ;; Insert a newline before environment unless at column zero
  16274. ;; to "escape" the current line. Insert a newline if
  16275. ;; something is one the same line as \end{ENVIRONMENT}.
  16276. (insert
  16277. (concat (unless bol "\n") env
  16278. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  16279. (unless (zerop ind)
  16280. (save-excursion
  16281. (goto-char beg)
  16282. (while (< (point) end)
  16283. (unless (eolp) (indent-line-to ind))
  16284. (forward-line))))
  16285. (goto-char beg)
  16286. (forward-line lines)
  16287. (indent-line-to ind)))
  16288. (set-marker beg nil)
  16289. (set-marker end nil)))
  16290. ;;;; LaTeX fragments
  16291. (defun org-inside-LaTeX-fragment-p ()
  16292. "Test if point is inside a LaTeX fragment.
  16293. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  16294. sequence appearing also before point.
  16295. Even though the matchers for math are configurable, this function assumes
  16296. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  16297. delimiters are skipped when they have been removed by customization.
  16298. The return value is nil, or a cons cell with the delimiter and the
  16299. position of this delimiter.
  16300. This function does a reasonably good job, but can locally be fooled by
  16301. for example currency specifications. For example it will assume being in
  16302. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  16303. fragments that are properly closed, but during editing, we have to live
  16304. with the uncertainty caused by missing closing delimiters. This function
  16305. looks only before point, not after."
  16306. (catch 'exit
  16307. (let ((pos (point))
  16308. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  16309. (lim (save-excursion (org-backward-paragraph) (point)))
  16310. dd-on str (start 0) m re)
  16311. (goto-char pos)
  16312. (when dodollar
  16313. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  16314. re (nth 1 (assoc "$" org-latex-regexps)))
  16315. (while (string-match re str start)
  16316. (cond
  16317. ((= (match-end 0) (length str))
  16318. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  16319. ((= (match-end 0) (- (length str) 5))
  16320. (throw 'exit nil))
  16321. (t (setq start (match-end 0))))))
  16322. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  16323. (goto-char pos)
  16324. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  16325. (and (match-beginning 2) (throw 'exit nil))
  16326. ;; count $$
  16327. (while (re-search-backward "\\$\\$" lim t)
  16328. (setq dd-on (not dd-on)))
  16329. (goto-char pos)
  16330. (when dd-on (cons "$$" m))))))
  16331. (defun org-inside-latex-macro-p ()
  16332. "Is point inside a LaTeX macro or its arguments?"
  16333. (save-match-data
  16334. (org-in-regexp
  16335. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  16336. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  16337. "Build an overlay between BEG and END using IMAGE file.
  16338. Argument IMAGETYPE is the extension of the displayed image,
  16339. as a string. It defaults to \"png\"."
  16340. (let ((ov (make-overlay beg end))
  16341. (imagetype (or (intern imagetype) 'png)))
  16342. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  16343. (overlay-put ov 'evaporate t)
  16344. (overlay-put ov
  16345. 'modification-hooks
  16346. (list (lambda (o _flag _beg _end &optional _l)
  16347. (delete-overlay o))))
  16348. (overlay-put ov
  16349. 'display
  16350. (list 'image :type imagetype :file image :ascent 'center))))
  16351. (defun org--list-latex-overlays (&optional beg end)
  16352. "List all Org LaTeX overlays in current buffer.
  16353. Limit to overlays between BEG and END when those are provided."
  16354. (cl-remove-if-not
  16355. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  16356. (overlays-in (or beg (point-min)) (or end (point-max)))))
  16357. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  16358. "Remove all overlays with LaTeX fragment images in current buffer.
  16359. When optional arguments BEG and END are non-nil, remove all
  16360. overlays between them instead. Return a non-nil value when some
  16361. overlays were removed, nil otherwise."
  16362. (let ((overlays (org--list-latex-overlays beg end)))
  16363. (mapc #'delete-overlay overlays)
  16364. overlays))
  16365. (defun org-toggle-latex-fragment (&optional arg)
  16366. "Preview the LaTeX fragment at point, or all locally or globally.
  16367. If the cursor is on a LaTeX fragment, create the image and overlay
  16368. it over the source code, if there is none. Remove it otherwise.
  16369. If there is no fragment at point, display all fragments in the
  16370. current section.
  16371. With prefix ARG, preview or clear image for all fragments in the
  16372. current subtree or in the whole buffer when used before the first
  16373. headline. With a prefix ARG `\\[universal-argument] \
  16374. \\[universal-argument]' preview or clear images
  16375. for all fragments in the buffer."
  16376. (interactive "P")
  16377. (when (display-graphic-p)
  16378. (catch 'exit
  16379. (save-excursion
  16380. (let (beg end msg)
  16381. (cond
  16382. ((or (equal arg '(16))
  16383. (and (equal arg '(4))
  16384. (org-with-limited-levels (org-before-first-heading-p))))
  16385. (if (org-remove-latex-fragment-image-overlays)
  16386. (progn (message "LaTeX fragments images removed from buffer")
  16387. (throw 'exit nil))
  16388. (setq msg "Creating images for buffer...")))
  16389. ((equal arg '(4))
  16390. (org-with-limited-levels (org-back-to-heading t))
  16391. (setq beg (point))
  16392. (setq end (progn (org-end-of-subtree t) (point)))
  16393. (if (org-remove-latex-fragment-image-overlays beg end)
  16394. (progn
  16395. (message "LaTeX fragment images removed from subtree")
  16396. (throw 'exit nil))
  16397. (setq msg "Creating images for subtree...")))
  16398. ((let ((datum (org-element-context)))
  16399. (when (memq (org-element-type datum)
  16400. '(latex-environment latex-fragment))
  16401. (setq beg (org-element-property :begin datum))
  16402. (setq end (org-element-property :end datum))
  16403. (if (org-remove-latex-fragment-image-overlays beg end)
  16404. (progn (message "LaTeX fragment image removed")
  16405. (throw 'exit nil))
  16406. (setq msg "Creating image...")))))
  16407. (t
  16408. (org-with-limited-levels
  16409. (setq beg (if (org-at-heading-p) (line-beginning-position)
  16410. (outline-previous-heading)
  16411. (point)))
  16412. (setq end (progn (outline-next-heading) (point)))
  16413. (if (org-remove-latex-fragment-image-overlays beg end)
  16414. (progn
  16415. (message "LaTeX fragment images removed from section")
  16416. (throw 'exit nil))
  16417. (setq msg "Creating images for section...")))))
  16418. (let ((file (buffer-file-name (buffer-base-buffer))))
  16419. (org-format-latex
  16420. (concat org-preview-latex-image-directory "org-ltximg")
  16421. beg end
  16422. ;; Emacs cannot overlay images from remote hosts. Create
  16423. ;; it in `temporary-file-directory' instead.
  16424. (if (or (not file) (file-remote-p file))
  16425. temporary-file-directory
  16426. default-directory)
  16427. 'overlays msg 'forbuffer org-preview-latex-default-process))
  16428. (message (concat msg "done")))))))
  16429. (defun org-format-latex
  16430. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  16431. "Replace LaTeX fragments with links to an image.
  16432. The function takes care of creating the replacement image.
  16433. Only consider fragments between BEG and END when those are
  16434. provided.
  16435. When optional argument OVERLAYS is non-nil, display the image on
  16436. top of the fragment instead of replacing it.
  16437. PROCESSING-TYPE is the conversion method to use, as a symbol.
  16438. Some of the options can be changed using the variable
  16439. `org-format-latex-options', which see."
  16440. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  16441. (unless (eq processing-type 'verbatim)
  16442. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  16443. (cnt 0)
  16444. checkdir-flag)
  16445. (goto-char (or beg (point-min)))
  16446. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  16447. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  16448. (overlay-recenter (or end (point-max))))
  16449. (while (re-search-forward math-regexp end t)
  16450. (unless (and overlays
  16451. (eq (get-char-property (point) 'org-overlay-type)
  16452. 'org-latex-overlay))
  16453. (let* ((context (org-element-context))
  16454. (type (org-element-type context)))
  16455. (when (memq type '(latex-environment latex-fragment))
  16456. (let ((block-type (eq type 'latex-environment))
  16457. (value (org-element-property :value context))
  16458. (beg (org-element-property :begin context))
  16459. (end (save-excursion
  16460. (goto-char (org-element-property :end context))
  16461. (skip-chars-backward " \r\t\n")
  16462. (point))))
  16463. (cond
  16464. ((eq processing-type 'mathjax)
  16465. ;; Prepare for MathJax processing.
  16466. (if (not (string-match "\\`\\$\\$?" value))
  16467. (goto-char end)
  16468. (delete-region beg end)
  16469. (if (string= (match-string 0 value) "$$")
  16470. (insert "\\[" (substring value 2 -2) "\\]")
  16471. (insert "\\(" (substring value 1 -1) "\\)"))))
  16472. ((assq processing-type org-preview-latex-process-alist)
  16473. ;; Process to an image.
  16474. (cl-incf cnt)
  16475. (goto-char beg)
  16476. (let* ((processing-info
  16477. (cdr (assq processing-type org-preview-latex-process-alist)))
  16478. (face (face-at-point))
  16479. ;; Get the colors from the face at point.
  16480. (fg
  16481. (let ((color (plist-get org-format-latex-options
  16482. :foreground)))
  16483. (if (and forbuffer (eq color 'auto))
  16484. (face-attribute face :foreground nil 'default)
  16485. color)))
  16486. (bg
  16487. (let ((color (plist-get org-format-latex-options
  16488. :background)))
  16489. (if (and forbuffer (eq color 'auto))
  16490. (face-attribute face :background nil 'default)
  16491. color)))
  16492. (hash (sha1 (prin1-to-string
  16493. (list org-format-latex-header
  16494. org-latex-default-packages-alist
  16495. org-latex-packages-alist
  16496. org-format-latex-options
  16497. forbuffer value fg bg))))
  16498. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  16499. (absprefix (expand-file-name prefix dir))
  16500. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  16501. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  16502. (sep (and block-type "\n\n"))
  16503. (link (concat sep "[[file:" linkfile "]]" sep))
  16504. (options
  16505. (org-combine-plists
  16506. org-format-latex-options
  16507. `(:foreground ,fg :background ,bg))))
  16508. (when msg (message msg cnt))
  16509. (unless checkdir-flag ; Ensure the directory exists.
  16510. (setq checkdir-flag t)
  16511. (let ((todir (file-name-directory absprefix)))
  16512. (unless (file-directory-p todir)
  16513. (make-directory todir t))))
  16514. (unless (file-exists-p movefile)
  16515. (org-create-formula-image
  16516. value movefile options forbuffer processing-type))
  16517. (if overlays
  16518. (progn
  16519. (dolist (o (overlays-in beg end))
  16520. (when (eq (overlay-get o 'org-overlay-type)
  16521. 'org-latex-overlay)
  16522. (delete-overlay o)))
  16523. (org--format-latex-make-overlay beg end movefile imagetype)
  16524. (goto-char end))
  16525. (delete-region beg end)
  16526. (insert
  16527. (org-add-props link
  16528. (list 'org-latex-src
  16529. (replace-regexp-in-string "\"" "" value)
  16530. 'org-latex-src-embed-type
  16531. (if block-type 'paragraph 'character)))))))
  16532. ((eq processing-type 'mathml)
  16533. ;; Process to MathML.
  16534. (unless (org-format-latex-mathml-available-p)
  16535. (user-error "LaTeX to MathML converter not configured"))
  16536. (cl-incf cnt)
  16537. (when msg (message msg cnt))
  16538. (goto-char beg)
  16539. (delete-region beg end)
  16540. (insert (org-format-latex-as-mathml
  16541. value block-type prefix dir)))
  16542. (t
  16543. (error "Unknown conversion process %s for LaTeX fragments"
  16544. processing-type)))))))))))
  16545. (defun org-create-math-formula (latex-frag &optional mathml-file)
  16546. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  16547. Use `org-latex-to-mathml-convert-command'. If the conversion is
  16548. sucessful, return the portion between \"<math...> </math>\"
  16549. elements otherwise return nil. When MATHML-FILE is specified,
  16550. write the results in to that file. When invoked as an
  16551. interactive command, prompt for LATEX-FRAG, with initial value
  16552. set to the current active region and echo the results for user
  16553. inspection."
  16554. (interactive (list (let ((frag (when (org-region-active-p)
  16555. (buffer-substring-no-properties
  16556. (region-beginning) (region-end)))))
  16557. (read-string "LaTeX Fragment: " frag nil frag))))
  16558. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  16559. (let* ((tmp-in-file
  16560. (let ((file (file-relative-name
  16561. (make-temp-name (expand-file-name "ltxmathml-in")))))
  16562. (write-region latex-frag nil file)
  16563. file))
  16564. (tmp-out-file (file-relative-name
  16565. (make-temp-name (expand-file-name "ltxmathml-out"))))
  16566. (cmd (format-spec
  16567. org-latex-to-mathml-convert-command
  16568. `((?j . ,(and org-latex-to-mathml-jar-file
  16569. (shell-quote-argument
  16570. (expand-file-name
  16571. org-latex-to-mathml-jar-file))))
  16572. (?I . ,(shell-quote-argument tmp-in-file))
  16573. (?i . ,latex-frag)
  16574. (?o . ,(shell-quote-argument tmp-out-file)))))
  16575. mathml shell-command-output)
  16576. (when (called-interactively-p 'any)
  16577. (unless (org-format-latex-mathml-available-p)
  16578. (user-error "LaTeX to MathML converter not configured")))
  16579. (message "Running %s" cmd)
  16580. (setq shell-command-output (shell-command-to-string cmd))
  16581. (setq mathml
  16582. (when (file-readable-p tmp-out-file)
  16583. (with-current-buffer (find-file-noselect tmp-out-file t)
  16584. (goto-char (point-min))
  16585. (when (re-search-forward
  16586. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  16587. (regexp-quote
  16588. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  16589. nil t)
  16590. (prog1 (match-string 0) (kill-buffer))))))
  16591. (cond
  16592. (mathml
  16593. (setq mathml
  16594. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  16595. (when mathml-file
  16596. (write-region mathml nil mathml-file))
  16597. (when (called-interactively-p 'any)
  16598. (message mathml)))
  16599. ((message "LaTeX to MathML conversion failed")
  16600. (message shell-command-output)))
  16601. (delete-file tmp-in-file)
  16602. (when (file-exists-p tmp-out-file)
  16603. (delete-file tmp-out-file))
  16604. mathml))
  16605. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  16606. prefix &optional dir)
  16607. "Use `org-create-math-formula' but check local cache first."
  16608. (let* ((absprefix (expand-file-name prefix dir))
  16609. (print-length nil) (print-level nil)
  16610. (formula-id (concat
  16611. "formula-"
  16612. (sha1
  16613. (prin1-to-string
  16614. (list latex-frag
  16615. org-latex-to-mathml-convert-command)))))
  16616. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  16617. (formula-cache-dir (file-name-directory formula-cache)))
  16618. (unless (file-directory-p formula-cache-dir)
  16619. (make-directory formula-cache-dir t))
  16620. (unless (file-exists-p formula-cache)
  16621. (org-create-math-formula latex-frag formula-cache))
  16622. (if (file-exists-p formula-cache)
  16623. ;; Successful conversion. Return the link to MathML file.
  16624. (org-add-props
  16625. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  16626. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  16627. 'org-latex-src-embed-type (if latex-frag-type
  16628. 'paragraph 'character)))
  16629. ;; Failed conversion. Return the LaTeX fragment verbatim
  16630. latex-frag)))
  16631. (defun org--get-display-dpi ()
  16632. "Get the DPI of the display.
  16633. The function assumes that the display has the same pixel width in
  16634. the horizontal and vertical directions."
  16635. (if (display-graphic-p)
  16636. (round (/ (display-pixel-height)
  16637. (/ (display-mm-height) 25.4)))
  16638. (error "Attempt to calculate the dpi of a non-graphic display")))
  16639. (defun org-create-formula-image
  16640. (string tofile options buffer &optional processing-type)
  16641. "Create an image from LaTeX source using external processes.
  16642. The LaTeX STRING is saved to a temporary LaTeX file, then
  16643. converted to an image file by process PROCESSING-TYPE defined in
  16644. `org-preview-latex-process-alist'. A nil value defaults to
  16645. `org-preview-latex-default-process'.
  16646. The generated image file is eventually moved to TOFILE.
  16647. The OPTIONS argument controls the size, foreground color and
  16648. background color of the generated image.
  16649. When BUFFER non-nil, this function is used for LaTeX previewing.
  16650. Otherwise, it is used to deal with LaTeX snippets showed in
  16651. a HTML file."
  16652. (let* ((processing-type (or processing-type
  16653. org-preview-latex-default-process))
  16654. (processing-info
  16655. (cdr (assq processing-type org-preview-latex-process-alist)))
  16656. (programs (plist-get processing-info :programs))
  16657. (error-message (or (plist-get processing-info :message) ""))
  16658. (use-xcolor (plist-get processing-info :use-xcolor))
  16659. (image-input-type (plist-get processing-info :image-input-type))
  16660. (image-output-type (plist-get processing-info :image-output-type))
  16661. (post-clean (or (plist-get processing-info :post-clean)
  16662. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  16663. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  16664. (latex-header
  16665. (or (plist-get processing-info :latex-header)
  16666. (org-latex-make-preamble
  16667. (org-export-get-environment (org-export-get-backend 'latex))
  16668. org-format-latex-header
  16669. 'snippet)))
  16670. (latex-compiler (plist-get processing-info :latex-compiler))
  16671. (image-converter (plist-get processing-info :image-converter))
  16672. (tmpdir temporary-file-directory)
  16673. (texfilebase (make-temp-name
  16674. (expand-file-name "orgtex" tmpdir)))
  16675. (texfile (concat texfilebase ".tex"))
  16676. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  16677. '(1.0 . 1.0)))
  16678. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  16679. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  16680. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  16681. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  16682. "Black"))
  16683. (bg (or (plist-get options (if buffer :background :html-background))
  16684. "Transparent"))
  16685. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  16686. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  16687. (dolist (program programs)
  16688. (org-check-external-command program error-message))
  16689. (if use-xcolor
  16690. (progn (if (eq fg 'default)
  16691. (setq fg (org-latex-color :foreground))
  16692. (setq fg (org-latex-color-format fg)))
  16693. (if (eq bg 'default)
  16694. (setq bg (org-latex-color :background))
  16695. (setq bg (org-latex-color-format
  16696. (if (string= bg "Transparent") "white" bg))))
  16697. (with-temp-file texfile
  16698. (insert latex-header)
  16699. (insert "\n\\begin{document}\n"
  16700. "\\definecolor{fg}{rgb}{" fg "}\n"
  16701. "\\definecolor{bg}{rgb}{" bg "}\n"
  16702. "\n\\pagecolor{bg}\n"
  16703. "\n{\\color{fg}\n"
  16704. string
  16705. "\n}\n"
  16706. "\n\\end{document}\n")))
  16707. (if (eq fg 'default)
  16708. (setq fg (org-dvipng-color :foreground))
  16709. (unless (string= fg "Transparent")
  16710. (setq fg (org-dvipng-color-format fg))))
  16711. (if (eq bg 'default)
  16712. (setq bg (org-dvipng-color :background))
  16713. (unless (string= bg "Transparent")
  16714. (setq bg (org-dvipng-color-format bg))))
  16715. (with-temp-file texfile
  16716. (insert latex-header)
  16717. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  16718. (let* ((err-msg (format "Please adjust `%s' part of \
  16719. `org-preview-latex-process-alist'."
  16720. processing-type))
  16721. (image-input-file
  16722. (org-compile-file
  16723. texfile latex-compiler image-input-type err-msg log-buf))
  16724. (image-output-file
  16725. (org-compile-file
  16726. image-input-file image-converter image-output-type err-msg log-buf
  16727. `((?F . ,(shell-quote-argument fg))
  16728. (?B . ,(shell-quote-argument bg))
  16729. (?D . ,(shell-quote-argument (format "%s" dpi)))
  16730. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  16731. (copy-file image-output-file tofile 'replace)
  16732. (dolist (e post-clean)
  16733. (when (file-exists-p (concat texfilebase e))
  16734. (delete-file (concat texfilebase e))))
  16735. image-output-file)))
  16736. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  16737. "Fill a LaTeX header template TPL.
  16738. In the template, the following place holders will be recognized:
  16739. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  16740. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  16741. [PACKAGES] \\usepackage statements for PKG
  16742. [NO-PACKAGES] do not include PKG
  16743. [EXTRA] the string EXTRA
  16744. [NO-EXTRA] do not include EXTRA
  16745. For backward compatibility, if both the positive and the negative place
  16746. holder is missing, the positive one (without the \"NO-\") will be
  16747. assumed to be present at the end of the template.
  16748. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  16749. EXTRA is a string.
  16750. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  16751. (let (rpl (end ""))
  16752. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  16753. (setq rpl (if (or (match-end 1) (not def-pkg))
  16754. "" (org-latex-packages-to-string def-pkg snippets-p t))
  16755. tpl (replace-match rpl t t tpl))
  16756. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  16757. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  16758. (setq rpl (if (or (match-end 1) (not pkg))
  16759. "" (org-latex-packages-to-string pkg snippets-p t))
  16760. tpl (replace-match rpl t t tpl))
  16761. (when pkg (setq end
  16762. (concat end "\n"
  16763. (org-latex-packages-to-string pkg snippets-p)))))
  16764. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  16765. (setq rpl (if (or (match-end 1) (not extra))
  16766. "" (concat extra "\n"))
  16767. tpl (replace-match rpl t t tpl))
  16768. (when (and extra (string-match "\\S-" extra))
  16769. (setq end (concat end "\n" extra))))
  16770. (if (string-match "\\S-" end)
  16771. (concat tpl "\n" end)
  16772. tpl)))
  16773. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  16774. "Turn an alist of packages into a string with the \\usepackage macros."
  16775. (setq pkg (mapconcat (lambda(p)
  16776. (cond
  16777. ((stringp p) p)
  16778. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  16779. (format "%% Package %s omitted" (cadr p)))
  16780. ((equal "" (car p))
  16781. (format "\\usepackage{%s}" (cadr p)))
  16782. (t
  16783. (format "\\usepackage[%s]{%s}"
  16784. (car p) (cadr p)))))
  16785. pkg
  16786. "\n"))
  16787. (if newline (concat pkg "\n") pkg))
  16788. (defun org-dvipng-color (attr)
  16789. "Return a RGB color specification for dvipng."
  16790. (org-dvipng-color-format (face-attribute 'default attr nil)))
  16791. (defun org-dvipng-color-format (color-name)
  16792. "Convert COLOR-NAME to a RGB color value for dvipng."
  16793. (apply #'format "rgb %s %s %s"
  16794. (mapcar 'org-normalize-color
  16795. (color-values color-name))))
  16796. (defun org-latex-color (attr)
  16797. "Return a RGB color for the LaTeX color package."
  16798. (org-latex-color-format (face-attribute 'default attr nil)))
  16799. (defun org-latex-color-format (color-name)
  16800. "Convert COLOR-NAME to a RGB color value."
  16801. (apply #'format "%s,%s,%s"
  16802. (mapcar 'org-normalize-color
  16803. (color-values color-name))))
  16804. (defun org-normalize-color (value)
  16805. "Return string to be used as color value for an RGB component."
  16806. (format "%g" (/ value 65535.0)))
  16807. ;; Image display
  16808. (defvar-local org-inline-image-overlays nil)
  16809. (defun org-toggle-inline-images (&optional include-linked)
  16810. "Toggle the display of inline images.
  16811. INCLUDE-LINKED is passed to `org-display-inline-images'."
  16812. (interactive "P")
  16813. (if org-inline-image-overlays
  16814. (progn
  16815. (org-remove-inline-images)
  16816. (when (called-interactively-p 'interactive)
  16817. (message "Inline image display turned off")))
  16818. (org-display-inline-images include-linked)
  16819. (when (called-interactively-p 'interactive)
  16820. (message (if org-inline-image-overlays
  16821. (format "%d images displayed inline"
  16822. (length org-inline-image-overlays))
  16823. "No images to display inline")))))
  16824. (defun org-redisplay-inline-images ()
  16825. "Refresh the display of inline images."
  16826. (interactive)
  16827. (if (not org-inline-image-overlays)
  16828. (org-toggle-inline-images)
  16829. (org-toggle-inline-images)
  16830. (org-toggle-inline-images)))
  16831. (defun org-display-inline-images (&optional include-linked refresh beg end)
  16832. "Display inline images.
  16833. An inline image is a link which follows either of these
  16834. conventions:
  16835. 1. Its path is a file with an extension matching return value
  16836. from `image-file-name-regexp' and it has no contents.
  16837. 2. Its description consists in a single link of the previous
  16838. type.
  16839. When optional argument INCLUDE-LINKED is non-nil, also links with
  16840. a text description part will be inlined. This can be nice for
  16841. a quick look at those images, but it does not reflect what
  16842. exported files will look like.
  16843. When optional argument REFRESH is non-nil, refresh existing
  16844. images between BEG and END. This will create new image displays
  16845. only if necessary. BEG and END default to the buffer
  16846. boundaries."
  16847. (interactive "P")
  16848. (when (display-graphic-p)
  16849. (unless refresh
  16850. (org-remove-inline-images)
  16851. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  16852. (org-with-wide-buffer
  16853. (goto-char (or beg (point-min)))
  16854. (let* ((case-fold-search t)
  16855. (file-extension-re (image-file-name-regexp))
  16856. (link-abbrevs (mapcar #'car
  16857. (append org-link-abbrev-alist-local
  16858. org-link-abbrev-alist)))
  16859. ;; Check absolute, relative file names and explicit
  16860. ;; "file:" links. Also check link abbreviations since
  16861. ;; some might expand to "file" links.
  16862. (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
  16863. (if (not link-abbrevs) ""
  16864. (format "\\|\\(?:%s:\\)"
  16865. (regexp-opt link-abbrevs))))))
  16866. (while (re-search-forward file-types-re end t)
  16867. (let ((link (save-match-data (org-element-context))))
  16868. ;; Check if we're at an inline image, i.e., an image file
  16869. ;; link without a description (unless INCLUDE-LINKED is
  16870. ;; non-nil).
  16871. (when (and (equal "file" (org-element-property :type link))
  16872. (or include-linked
  16873. (null (org-element-contents link)))
  16874. (string-match-p file-extension-re
  16875. (org-element-property :path link)))
  16876. (let ((file (expand-file-name
  16877. (org-link-unescape
  16878. (org-element-property :path link)))))
  16879. (when (file-exists-p file)
  16880. (let ((width
  16881. ;; Apply `org-image-actual-width' specifications.
  16882. (cond
  16883. ((not (image-type-available-p 'imagemagick)) nil)
  16884. ((eq org-image-actual-width t) nil)
  16885. ((listp org-image-actual-width)
  16886. (or
  16887. ;; First try to find a width among
  16888. ;; attributes associated to the paragraph
  16889. ;; containing link.
  16890. (let ((paragraph
  16891. (let ((e link))
  16892. (while (and (setq e (org-element-property
  16893. :parent e))
  16894. (not (eq (org-element-type e)
  16895. 'paragraph))))
  16896. e)))
  16897. (when paragraph
  16898. (save-excursion
  16899. (goto-char (org-element-property :begin paragraph))
  16900. (when
  16901. (re-search-forward
  16902. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  16903. (org-element-property
  16904. :post-affiliated paragraph)
  16905. t)
  16906. (string-to-number (match-string 1))))))
  16907. ;; Otherwise, fall-back to provided number.
  16908. (car org-image-actual-width)))
  16909. ((numberp org-image-actual-width)
  16910. org-image-actual-width)))
  16911. (old (get-char-property-and-overlay
  16912. (org-element-property :begin link)
  16913. 'org-image-overlay)))
  16914. (if (and (car-safe old) refresh)
  16915. (image-refresh (overlay-get (cdr old) 'display))
  16916. (let ((image (create-image file
  16917. (and width 'imagemagick)
  16918. nil
  16919. :width width)))
  16920. (when image
  16921. (let ((ov (make-overlay
  16922. (org-element-property :begin link)
  16923. (progn
  16924. (goto-char
  16925. (org-element-property :end link))
  16926. (skip-chars-backward " \t")
  16927. (point)))))
  16928. (overlay-put ov 'display image)
  16929. (overlay-put ov 'face 'default)
  16930. (overlay-put ov 'org-image-overlay t)
  16931. (overlay-put
  16932. ov 'modification-hooks
  16933. (list 'org-display-inline-remove-overlay))
  16934. (push ov org-inline-image-overlays)))))))))))))))
  16935. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  16936. "Remove inline-display overlay if a corresponding region is modified."
  16937. (let ((inhibit-modification-hooks t))
  16938. (when (and ov after)
  16939. (delete ov org-inline-image-overlays)
  16940. (delete-overlay ov))))
  16941. (defun org-remove-inline-images ()
  16942. "Remove inline display of images."
  16943. (interactive)
  16944. (mapc #'delete-overlay org-inline-image-overlays)
  16945. (setq org-inline-image-overlays nil))
  16946. (defvar org-self-insert-command-undo-counter 0)
  16947. (defvar org-speed-command nil)
  16948. (defun org-self-insert-command (N)
  16949. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  16950. If the cursor is in a table looking at whitespace, the whitespace is
  16951. overwritten, and the table is not marked as requiring realignment."
  16952. (interactive "p")
  16953. (org-check-before-invisible-edit 'insert)
  16954. (cond
  16955. ((and org-use-speed-commands
  16956. (let ((kv (this-command-keys-vector)))
  16957. (setq org-speed-command
  16958. (run-hook-with-args-until-success
  16959. 'org-speed-command-hook
  16960. (make-string 1 (aref kv (1- (length kv))))))))
  16961. (cond
  16962. ((commandp org-speed-command)
  16963. (setq this-command org-speed-command)
  16964. (call-interactively org-speed-command))
  16965. ((functionp org-speed-command)
  16966. (funcall org-speed-command))
  16967. ((and org-speed-command (listp org-speed-command))
  16968. (eval org-speed-command))
  16969. (t (let (org-use-speed-commands)
  16970. (call-interactively 'org-self-insert-command)))))
  16971. ((and
  16972. (= N 1)
  16973. (not (org-region-active-p))
  16974. (org-at-table-p)
  16975. (progn
  16976. ;; Check if we blank the field, and if that triggers align.
  16977. (and (featurep 'org-table)
  16978. org-table-auto-blank-field
  16979. (memq last-command
  16980. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  16981. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  16982. ;; Got extra space, this field does not determine
  16983. ;; column width.
  16984. (let (org-table-may-need-update) (org-table-blank-field))
  16985. ;; No extra space, this field may determine column
  16986. ;; width.
  16987. (org-table-blank-field)))
  16988. t)
  16989. (looking-at "[^|\n]* |"))
  16990. ;; There is room for insertion without re-aligning the table.
  16991. (self-insert-command N)
  16992. (org-table-with-shrunk-field
  16993. (save-excursion
  16994. (skip-chars-forward "^|")
  16995. ;; Do not delete last space, which is
  16996. ;; `org-table-separator-space', but the regular space before
  16997. ;; it.
  16998. (delete-region (- (point) 2) (1- (point))))))
  16999. (t
  17000. (setq org-table-may-need-update t)
  17001. (self-insert-command N)
  17002. (org-fix-tags-on-the-fly)
  17003. (when org-self-insert-cluster-for-undo
  17004. (if (not (eq last-command 'org-self-insert-command))
  17005. (setq org-self-insert-command-undo-counter 1)
  17006. (if (>= org-self-insert-command-undo-counter 20)
  17007. (setq org-self-insert-command-undo-counter 1)
  17008. (and (> org-self-insert-command-undo-counter 0)
  17009. buffer-undo-list (listp buffer-undo-list)
  17010. (not (cadr buffer-undo-list)) ; remove nil entry
  17011. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  17012. (setq org-self-insert-command-undo-counter
  17013. (1+ org-self-insert-command-undo-counter))))))))
  17014. (defun org-check-before-invisible-edit (kind)
  17015. "Check is editing if kind KIND would be dangerous with invisible text around.
  17016. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  17017. ;; First, try to get out of here as quickly as possible, to reduce overhead
  17018. (when (and org-catch-invisible-edits
  17019. (or (not (boundp 'visible-mode)) (not visible-mode))
  17020. (or (get-char-property (point) 'invisible)
  17021. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  17022. ;; OK, we need to take a closer look. Do not consider
  17023. ;; invisibility obtained through text properties (e.g., link
  17024. ;; fontification), as it cannot be toggled.
  17025. (let* ((invisible-at-point
  17026. (pcase (get-char-property-and-overlay (point) 'invisible)
  17027. (`(,_ . ,(and (pred overlayp) o)) o)))
  17028. ;; Assume that point cannot land in the middle of an
  17029. ;; overlay, or between two overlays.
  17030. (invisible-before-point
  17031. (and (not invisible-at-point)
  17032. (not (bobp))
  17033. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  17034. (`(,_ . ,(and (pred overlayp) o)) o))))
  17035. (border-and-ok-direction
  17036. (or
  17037. ;; Check if we are acting predictably before invisible
  17038. ;; text.
  17039. (and invisible-at-point
  17040. (memq kind '(insert delete-backward)))
  17041. ;; Check if we are acting predictably after invisible text
  17042. ;; This works not well, and I have turned it off. It seems
  17043. ;; better to always show and stop after invisible text.
  17044. ;; (and (not invisible-at-point) invisible-before-point
  17045. ;; (memq kind '(insert delete)))
  17046. )))
  17047. (when (or invisible-at-point invisible-before-point)
  17048. (when (eq org-catch-invisible-edits 'error)
  17049. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  17050. (if (and org-custom-properties-overlays
  17051. (y-or-n-p "Display invisible properties in this buffer? "))
  17052. (org-toggle-custom-properties-visibility)
  17053. ;; Make the area visible
  17054. (save-excursion
  17055. (when invisible-before-point
  17056. (goto-char
  17057. (previous-single-char-property-change (point) 'invisible)))
  17058. ;; Remove whatever overlay is currently making yet-to-be
  17059. ;; edited text invisible. Also remove nested invisibility
  17060. ;; related overlays.
  17061. (delete-overlay (or invisible-at-point invisible-before-point))
  17062. (let ((origin (if invisible-at-point (point) (1- (point)))))
  17063. (while (pcase (get-char-property-and-overlay origin 'invisible)
  17064. (`(,_ . ,(and (pred overlayp) o))
  17065. (delete-overlay o)
  17066. t)))))
  17067. (cond
  17068. ((eq org-catch-invisible-edits 'show)
  17069. ;; That's it, we do the edit after showing
  17070. (message
  17071. "Unfolding invisible region around point before editing")
  17072. (sit-for 1))
  17073. ((and (eq org-catch-invisible-edits 'smart)
  17074. border-and-ok-direction)
  17075. (message "Unfolding invisible region around point before editing"))
  17076. (t
  17077. ;; Don't do the edit, make the user repeat it in full visibility
  17078. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  17079. (defun org-fix-tags-on-the-fly ()
  17080. "Align tags in headline at point.
  17081. Unlike `org-align-tags', this function does nothing if point is
  17082. either not currently on a tagged headline or on a tag."
  17083. (when (and (org-match-line org-tag-line-re)
  17084. (< (point) (match-beginning 1)))
  17085. (org-align-tags)))
  17086. (defun org-delete-backward-char (N)
  17087. "Like `delete-backward-char', insert whitespace at field end in tables.
  17088. When deleting backwards, in tables this function will insert whitespace in
  17089. front of the next \"|\" separator, to keep the table aligned. The table will
  17090. still be marked for re-alignment if the field did fill the entire column,
  17091. because, in this case the deletion might narrow the column."
  17092. (interactive "p")
  17093. (save-match-data
  17094. (org-check-before-invisible-edit 'delete-backward)
  17095. (if (and (= N 1)
  17096. (not overwrite-mode)
  17097. (not (org-region-active-p))
  17098. (not (eq (char-before) ?|))
  17099. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  17100. (looking-at-p ".*?|")
  17101. (org-at-table-p))
  17102. (progn (forward-char -1) (org-delete-char 1))
  17103. (backward-delete-char N)
  17104. (org-fix-tags-on-the-fly))))
  17105. (defun org-delete-char (N)
  17106. "Like `delete-char', but insert whitespace at field end in tables.
  17107. When deleting characters, in tables this function will insert whitespace in
  17108. front of the next \"|\" separator, to keep the table aligned. The table will
  17109. still be marked for re-alignment if the field did fill the entire column,
  17110. because, in this case the deletion might narrow the column."
  17111. (interactive "p")
  17112. (save-match-data
  17113. (org-check-before-invisible-edit 'delete)
  17114. (cond
  17115. ((or (/= N 1)
  17116. (eq (char-after) ?|)
  17117. (save-excursion (skip-chars-backward " \t") (bolp))
  17118. (not (org-at-table-p)))
  17119. (delete-char N)
  17120. (org-fix-tags-on-the-fly))
  17121. ((looking-at ".\\(.*?\\)|")
  17122. (let* ((update? org-table-may-need-update)
  17123. (noalign (looking-at-p ".*? |")))
  17124. (delete-char 1)
  17125. (org-table-with-shrunk-field
  17126. (save-excursion
  17127. ;; Last space is `org-table-separator-space', so insert
  17128. ;; a regular one before it instead.
  17129. (goto-char (- (match-end 0) 2))
  17130. (insert " ")))
  17131. ;; If there were two spaces at the end, this field does not
  17132. ;; determine the width of the column.
  17133. (when noalign (setq org-table-may-need-update update?))))
  17134. (t
  17135. (delete-char N)))))
  17136. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  17137. (put 'org-self-insert-command 'delete-selection
  17138. (lambda ()
  17139. (not (run-hook-with-args-until-success
  17140. 'self-insert-uses-region-functions))))
  17141. (put 'orgtbl-self-insert-command 'delete-selection
  17142. (lambda ()
  17143. (not (run-hook-with-args-until-success
  17144. 'self-insert-uses-region-functions))))
  17145. (put 'org-delete-char 'delete-selection 'supersede)
  17146. (put 'org-delete-backward-char 'delete-selection 'supersede)
  17147. (put 'org-yank 'delete-selection 'yank)
  17148. ;; Make `flyspell-mode' delay after some commands
  17149. (put 'org-self-insert-command 'flyspell-delayed t)
  17150. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  17151. (put 'org-delete-char 'flyspell-delayed t)
  17152. (put 'org-delete-backward-char 'flyspell-delayed t)
  17153. ;; Make pabbrev-mode expand after Org mode commands
  17154. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  17155. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  17156. (defun org-transpose-words ()
  17157. "Transpose words for Org.
  17158. This uses the `org-mode-transpose-word-syntax-table' syntax
  17159. table, which interprets characters in `org-emphasis-alist' as
  17160. word constituents."
  17161. (interactive)
  17162. (with-syntax-table org-mode-transpose-word-syntax-table
  17163. (call-interactively 'transpose-words)))
  17164. (defvar org-ctrl-c-ctrl-c-hook nil
  17165. "Hook for functions attaching themselves to `C-c C-c'.
  17166. This can be used to add additional functionality to the C-c C-c
  17167. key which executes context-dependent commands. This hook is run
  17168. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  17169. run after the last test.
  17170. Each function will be called with no arguments. The function
  17171. must check if the context is appropriate for it to act. If yes,
  17172. it should do its thing and then return a non-nil value. If the
  17173. context is wrong, just do nothing and return nil.")
  17174. (defvar org-ctrl-c-ctrl-c-final-hook nil
  17175. "Hook for functions attaching themselves to `C-c C-c'.
  17176. This can be used to add additional functionality to the C-c C-c
  17177. key which executes context-dependent commands. This hook is run
  17178. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  17179. before the first test.
  17180. Each function will be called with no arguments. The function
  17181. must check if the context is appropriate for it to act. If yes,
  17182. it should do its thing and then return a non-nil value. If the
  17183. context is wrong, just do nothing and return nil.")
  17184. (defvar org-tab-first-hook nil
  17185. "Hook for functions to attach themselves to TAB.
  17186. See `org-ctrl-c-ctrl-c-hook' for more information.
  17187. This hook runs as the first action when TAB is pressed, even before
  17188. `org-cycle' messes around with the `outline-regexp' to cater for
  17189. inline tasks and plain list item folding.
  17190. If any function in this hook returns t, any other actions that
  17191. would have been caused by TAB (such as table field motion or visibility
  17192. cycling) will not occur.")
  17193. (defvar org-tab-after-check-for-table-hook nil
  17194. "Hook for functions to attach themselves to TAB.
  17195. See `org-ctrl-c-ctrl-c-hook' for more information.
  17196. This hook runs after it has been established that the cursor is not in a
  17197. table, but before checking if the cursor is in a headline or if global cycling
  17198. should be done.
  17199. If any function in this hook returns t, not other actions like visibility
  17200. cycling will be done.")
  17201. (defvar org-tab-after-check-for-cycling-hook nil
  17202. "Hook for functions to attach themselves to TAB.
  17203. See `org-ctrl-c-ctrl-c-hook' for more information.
  17204. This hook runs after it has been established that not table field motion and
  17205. not visibility should be done because of current context. This is probably
  17206. the place where a package like yasnippets can hook in.")
  17207. (defvar org-tab-before-tab-emulation-hook nil
  17208. "Hook for functions to attach themselves to TAB.
  17209. See `org-ctrl-c-ctrl-c-hook' for more information.
  17210. This hook runs after every other options for TAB have been exhausted, but
  17211. before indentation and \t insertion takes place.")
  17212. (defvar org-metaleft-hook nil
  17213. "Hook for functions attaching themselves to `M-left'.
  17214. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17215. (defvar org-metaright-hook nil
  17216. "Hook for functions attaching themselves to `M-right'.
  17217. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17218. (defvar org-metaup-hook nil
  17219. "Hook for functions attaching themselves to `M-up'.
  17220. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17221. (defvar org-metadown-hook nil
  17222. "Hook for functions attaching themselves to `M-down'.
  17223. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17224. (defvar org-shiftmetaleft-hook nil
  17225. "Hook for functions attaching themselves to `M-S-left'.
  17226. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17227. (defvar org-shiftmetaright-hook nil
  17228. "Hook for functions attaching themselves to `M-S-right'.
  17229. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17230. (defvar org-shiftmetaup-hook nil
  17231. "Hook for functions attaching themselves to `M-S-up'.
  17232. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17233. (defvar org-shiftmetadown-hook nil
  17234. "Hook for functions attaching themselves to `M-S-down'.
  17235. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17236. (defvar org-metareturn-hook nil
  17237. "Hook for functions attaching themselves to `M-RET'.
  17238. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17239. (defvar org-shiftup-hook nil
  17240. "Hook for functions attaching themselves to `S-up'.
  17241. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17242. (defvar org-shiftup-final-hook nil
  17243. "Hook for functions attaching themselves to `S-up'.
  17244. This one runs after all other options except shift-select have been excluded.
  17245. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17246. (defvar org-shiftdown-hook nil
  17247. "Hook for functions attaching themselves to `S-down'.
  17248. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17249. (defvar org-shiftdown-final-hook nil
  17250. "Hook for functions attaching themselves to `S-down'.
  17251. This one runs after all other options except shift-select have been excluded.
  17252. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17253. (defvar org-shiftleft-hook nil
  17254. "Hook for functions attaching themselves to `S-left'.
  17255. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17256. (defvar org-shiftleft-final-hook nil
  17257. "Hook for functions attaching themselves to `S-left'.
  17258. This one runs after all other options except shift-select have been excluded.
  17259. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17260. (defvar org-shiftright-hook nil
  17261. "Hook for functions attaching themselves to `S-right'.
  17262. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17263. (defvar org-shiftright-final-hook nil
  17264. "Hook for functions attaching themselves to `S-right'.
  17265. This one runs after all other options except shift-select have been excluded.
  17266. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17267. (defun org-modifier-cursor-error ()
  17268. "Throw an error, a modified cursor command was applied in wrong context."
  17269. (user-error "This command is active in special context like tables, headlines or items"))
  17270. (defun org-shiftselect-error ()
  17271. "Throw an error because Shift-Cursor command was applied in wrong context."
  17272. (if (and (boundp 'shift-select-mode) shift-select-mode)
  17273. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  17274. (user-error "This command works only in special context like headlines or timestamps")))
  17275. (defun org-call-for-shift-select (cmd)
  17276. (let ((this-command-keys-shift-translated t))
  17277. (call-interactively cmd)))
  17278. (defun org-shifttab (&optional arg)
  17279. "Global visibility cycling or move to previous table field.
  17280. Call `org-table-previous-field' within a table.
  17281. When ARG is nil, cycle globally through visibility states.
  17282. When ARG is a numeric prefix, show contents of this level."
  17283. (interactive "P")
  17284. (cond
  17285. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  17286. ((integerp arg)
  17287. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  17288. (message "Content view to level: %d" arg)
  17289. (org-content (prefix-numeric-value arg2))
  17290. (org-cycle-show-empty-lines t)
  17291. (setq org-cycle-global-status 'overview)))
  17292. (t (call-interactively 'org-global-cycle))))
  17293. (defun org-shiftmetaleft ()
  17294. "Promote subtree or delete table column.
  17295. Calls `org-promote-subtree', `org-outdent-item-tree', or
  17296. `org-table-delete-column', depending on context. See the
  17297. individual commands for more information."
  17298. (interactive)
  17299. (cond
  17300. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  17301. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  17302. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  17303. ((if (not (org-region-active-p)) (org-at-item-p)
  17304. (save-excursion (goto-char (region-beginning))
  17305. (org-at-item-p)))
  17306. (call-interactively 'org-outdent-item-tree))
  17307. (t (org-modifier-cursor-error))))
  17308. (defun org-shiftmetaright ()
  17309. "Demote subtree or insert table column.
  17310. Calls `org-demote-subtree', `org-indent-item-tree', or
  17311. `org-table-insert-column', depending on context. See the
  17312. individual commands for more information."
  17313. (interactive)
  17314. (cond
  17315. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  17316. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  17317. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  17318. ((if (not (org-region-active-p)) (org-at-item-p)
  17319. (save-excursion (goto-char (region-beginning))
  17320. (org-at-item-p)))
  17321. (call-interactively 'org-indent-item-tree))
  17322. (t (org-modifier-cursor-error))))
  17323. (defun org-shiftmetaup (&optional _arg)
  17324. "Drag the line at point up.
  17325. In a table, kill the current row.
  17326. On a clock timestamp, update the value of the timestamp like `S-<up>'
  17327. but also adjust the previous clocked item in the clock history.
  17328. Everywhere else, drag the line at point up."
  17329. (interactive "P")
  17330. (cond
  17331. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  17332. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  17333. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17334. (call-interactively 'org-timestamp-up)))
  17335. (t (call-interactively 'org-drag-line-backward))))
  17336. (defun org-shiftmetadown (&optional _arg)
  17337. "Drag the line at point down.
  17338. In a table, insert an empty row at the current line.
  17339. On a clock timestamp, update the value of the timestamp like `S-<down>'
  17340. but also adjust the previous clocked item in the clock history.
  17341. Everywhere else, drag the line at point down."
  17342. (interactive "P")
  17343. (cond
  17344. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  17345. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  17346. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17347. (call-interactively 'org-timestamp-down)))
  17348. (t (call-interactively 'org-drag-line-forward))))
  17349. (defsubst org-hidden-tree-error ()
  17350. (user-error
  17351. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  17352. (defun org-metaleft (&optional _arg)
  17353. "Promote heading, list item at point or move table column left.
  17354. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  17355. depending on context. With no specific context, calls the Emacs
  17356. default `backward-word'. See the individual commands for more
  17357. information.
  17358. This function runs the hook `org-metaleft-hook' as a first step,
  17359. and returns at first non-nil value."
  17360. (interactive "P")
  17361. (cond
  17362. ((run-hook-with-args-until-success 'org-metaleft-hook))
  17363. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  17364. ((org-with-limited-levels
  17365. (or (org-at-heading-p)
  17366. (and (org-region-active-p)
  17367. (save-excursion
  17368. (goto-char (region-beginning))
  17369. (org-at-heading-p)))))
  17370. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  17371. (call-interactively 'org-do-promote))
  17372. ;; At an inline task.
  17373. ((org-at-heading-p)
  17374. (call-interactively 'org-inlinetask-promote))
  17375. ((or (org-at-item-p)
  17376. (and (org-region-active-p)
  17377. (save-excursion
  17378. (goto-char (region-beginning))
  17379. (org-at-item-p))))
  17380. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  17381. (call-interactively 'org-outdent-item))
  17382. (t (call-interactively 'backward-word))))
  17383. (defun org-metaright (&optional _arg)
  17384. "Demote heading, list item at point or move table column right.
  17385. In front of a drawer or a block keyword, indent it correctly.
  17386. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  17387. `org-indent-drawer' or `org-indent-block' depending on context.
  17388. With no specific context, calls the Emacs default `forward-word'.
  17389. See the individual commands for more information.
  17390. This function runs the hook `org-metaright-hook' as a first step,
  17391. and returns at first non-nil value."
  17392. (interactive "P")
  17393. (cond
  17394. ((run-hook-with-args-until-success 'org-metaright-hook))
  17395. ((org-at-table-p) (call-interactively 'org-table-move-column))
  17396. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  17397. ((org-at-block-p) (call-interactively 'org-indent-block))
  17398. ((org-with-limited-levels
  17399. (or (org-at-heading-p)
  17400. (and (org-region-active-p)
  17401. (save-excursion
  17402. (goto-char (region-beginning))
  17403. (org-at-heading-p)))))
  17404. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  17405. (call-interactively 'org-do-demote))
  17406. ;; At an inline task.
  17407. ((org-at-heading-p)
  17408. (call-interactively 'org-inlinetask-demote))
  17409. ((or (org-at-item-p)
  17410. (and (org-region-active-p)
  17411. (save-excursion
  17412. (goto-char (region-beginning))
  17413. (org-at-item-p))))
  17414. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  17415. (call-interactively 'org-indent-item))
  17416. (t (call-interactively 'forward-word))))
  17417. (defun org-check-for-hidden (what)
  17418. "Check if there are hidden headlines/items in the current visual line.
  17419. WHAT can be either `headlines' or `items'. If the current line is
  17420. an outline or item heading and it has a folded subtree below it,
  17421. this function returns t, nil otherwise."
  17422. (let ((re (cond
  17423. ((eq what 'headlines) org-outline-regexp-bol)
  17424. ((eq what 'items) (org-item-beginning-re))
  17425. (t (error "This should not happen"))))
  17426. beg end)
  17427. (save-excursion
  17428. (catch 'exit
  17429. (unless (org-region-active-p)
  17430. (setq beg (point-at-bol))
  17431. (beginning-of-line 2)
  17432. (while (and (not (eobp)) ;; this is like `next-line'
  17433. (get-char-property (1- (point)) 'invisible))
  17434. (beginning-of-line 2))
  17435. (setq end (point))
  17436. (goto-char beg)
  17437. (goto-char (point-at-eol))
  17438. (setq end (max end (point)))
  17439. (while (re-search-forward re end t)
  17440. (when (get-char-property (match-beginning 0) 'invisible)
  17441. (throw 'exit t))))
  17442. nil))))
  17443. (defun org-metaup (&optional _arg)
  17444. "Move subtree up or move table row up.
  17445. Calls `org-move-subtree-up' or `org-table-move-row' or
  17446. `org-move-item-up', depending on context. See the individual commands
  17447. for more information."
  17448. (interactive "P")
  17449. (cond
  17450. ((run-hook-with-args-until-success 'org-metaup-hook))
  17451. ((org-region-active-p)
  17452. (let* ((a (save-excursion
  17453. (goto-char (min (region-beginning) (region-end)))
  17454. (line-beginning-position)))
  17455. (b (save-excursion
  17456. (goto-char (max (region-beginning) (region-end)))
  17457. (if (bolp) (1- (point)) (line-end-position))))
  17458. (c (save-excursion
  17459. (goto-char a)
  17460. (move-beginning-of-line 0)
  17461. (point)))
  17462. (d (save-excursion
  17463. (goto-char a)
  17464. (move-end-of-line 0)
  17465. (point))))
  17466. (transpose-regions a b c d)
  17467. (goto-char c)))
  17468. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  17469. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  17470. ((org-at-item-p) (call-interactively 'org-move-item-up))
  17471. (t (org-drag-element-backward))))
  17472. (defun org-metadown (&optional _arg)
  17473. "Move subtree down or move table row down.
  17474. Calls `org-move-subtree-down' or `org-table-move-row' or
  17475. `org-move-item-down', depending on context. See the individual
  17476. commands for more information."
  17477. (interactive "P")
  17478. (cond
  17479. ((run-hook-with-args-until-success 'org-metadown-hook))
  17480. ((org-region-active-p)
  17481. (let* ((a (save-excursion
  17482. (goto-char (min (region-beginning) (region-end)))
  17483. (line-beginning-position)))
  17484. (b (save-excursion
  17485. (goto-char (max (region-beginning) (region-end)))
  17486. (if (bolp) (1- (point)) (line-end-position))))
  17487. (c (save-excursion
  17488. (goto-char b)
  17489. (move-beginning-of-line (if (bolp) 1 2))
  17490. (point)))
  17491. (d (save-excursion
  17492. (goto-char b)
  17493. (move-end-of-line (if (bolp) 1 2))
  17494. (point))))
  17495. (transpose-regions a b c d)
  17496. (goto-char d)))
  17497. ((org-at-table-p) (call-interactively 'org-table-move-row))
  17498. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  17499. ((org-at-item-p) (call-interactively 'org-move-item-down))
  17500. (t (org-drag-element-forward))))
  17501. (defun org-shiftup (&optional arg)
  17502. "Act on current element according to context.
  17503. Call `org-timestamp-up' or `org-priority-up', or
  17504. `org-previous-item', or `org-table-move-cell-up'. See the
  17505. individual commands for more information."
  17506. (interactive "P")
  17507. (cond
  17508. ((run-hook-with-args-until-success 'org-shiftup-hook))
  17509. ((and org-support-shift-select (org-region-active-p))
  17510. (org-call-for-shift-select 'previous-line))
  17511. ((org-at-timestamp-p 'lax)
  17512. (call-interactively (if org-edit-timestamp-down-means-later
  17513. 'org-timestamp-down 'org-timestamp-up)))
  17514. ((and (not (eq org-support-shift-select 'always))
  17515. org-enable-priority-commands
  17516. (org-at-heading-p))
  17517. (call-interactively 'org-priority-up))
  17518. ((and (not org-support-shift-select) (org-at-item-p))
  17519. (call-interactively 'org-previous-item))
  17520. ((org-clocktable-try-shift 'up arg))
  17521. ((org-at-table-p) (org-table-move-cell-up))
  17522. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  17523. (org-support-shift-select
  17524. (org-call-for-shift-select 'previous-line))
  17525. (t (org-shiftselect-error))))
  17526. (defun org-shiftdown (&optional arg)
  17527. "Act on current element according to context.
  17528. Call `org-timestamp-down' or `org-priority-down', or
  17529. `org-next-item', or `org-table-move-cell-down'. See the
  17530. individual commands for more information."
  17531. (interactive "P")
  17532. (cond
  17533. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  17534. ((and org-support-shift-select (org-region-active-p))
  17535. (org-call-for-shift-select 'next-line))
  17536. ((org-at-timestamp-p 'lax)
  17537. (call-interactively (if org-edit-timestamp-down-means-later
  17538. 'org-timestamp-up 'org-timestamp-down)))
  17539. ((and (not (eq org-support-shift-select 'always))
  17540. org-enable-priority-commands
  17541. (org-at-heading-p))
  17542. (call-interactively 'org-priority-down))
  17543. ((and (not org-support-shift-select) (org-at-item-p))
  17544. (call-interactively 'org-next-item))
  17545. ((org-clocktable-try-shift 'down arg))
  17546. ((org-at-table-p) (org-table-move-cell-down))
  17547. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  17548. (org-support-shift-select
  17549. (org-call-for-shift-select 'next-line))
  17550. (t (org-shiftselect-error))))
  17551. (defun org-shiftright (&optional arg)
  17552. "Act on the current element according to context.
  17553. This does one of the following:
  17554. - switch a timestamp at point one day into the future
  17555. - on a headline, switch to the next TODO keyword.
  17556. - on an item, switch entire list to the next bullet type
  17557. - on a property line, switch to the next allowed value
  17558. - on a clocktable definition line, move time block into the future
  17559. - in a table, move a single cell right"
  17560. (interactive "P")
  17561. (cond
  17562. ((run-hook-with-args-until-success 'org-shiftright-hook))
  17563. ((and org-support-shift-select (org-region-active-p))
  17564. (org-call-for-shift-select 'forward-char))
  17565. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  17566. ((and (not (eq org-support-shift-select 'always))
  17567. (org-at-heading-p))
  17568. (let ((org-inhibit-logging
  17569. (not org-treat-S-cursor-todo-selection-as-state-change))
  17570. (org-inhibit-blocking
  17571. (not org-treat-S-cursor-todo-selection-as-state-change)))
  17572. (org-call-with-arg 'org-todo 'right)))
  17573. ((or (and org-support-shift-select
  17574. (not (eq org-support-shift-select 'always))
  17575. (org-at-item-bullet-p))
  17576. (and (not org-support-shift-select) (org-at-item-p)))
  17577. (org-call-with-arg 'org-cycle-list-bullet nil))
  17578. ((and (not (eq org-support-shift-select 'always))
  17579. (org-at-property-p))
  17580. (call-interactively 'org-property-next-allowed-value))
  17581. ((org-clocktable-try-shift 'right arg))
  17582. ((org-at-table-p) (org-table-move-cell-right))
  17583. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  17584. (org-support-shift-select
  17585. (org-call-for-shift-select 'forward-char))
  17586. (t (org-shiftselect-error))))
  17587. (defun org-shiftleft (&optional arg)
  17588. "Act on current element according to context.
  17589. This does one of the following:
  17590. - switch a timestamp at point one day into the past
  17591. - on a headline, switch to the previous TODO keyword.
  17592. - on an item, switch entire list to the previous bullet type
  17593. - on a property line, switch to the previous allowed value
  17594. - on a clocktable definition line, move time block into the past
  17595. - in a table, move a single cell left"
  17596. (interactive "P")
  17597. (cond
  17598. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  17599. ((and org-support-shift-select (org-region-active-p))
  17600. (org-call-for-shift-select 'backward-char))
  17601. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  17602. ((and (not (eq org-support-shift-select 'always))
  17603. (org-at-heading-p))
  17604. (let ((org-inhibit-logging
  17605. (not org-treat-S-cursor-todo-selection-as-state-change))
  17606. (org-inhibit-blocking
  17607. (not org-treat-S-cursor-todo-selection-as-state-change)))
  17608. (org-call-with-arg 'org-todo 'left)))
  17609. ((or (and org-support-shift-select
  17610. (not (eq org-support-shift-select 'always))
  17611. (org-at-item-bullet-p))
  17612. (and (not org-support-shift-select) (org-at-item-p)))
  17613. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  17614. ((and (not (eq org-support-shift-select 'always))
  17615. (org-at-property-p))
  17616. (call-interactively 'org-property-previous-allowed-value))
  17617. ((org-clocktable-try-shift 'left arg))
  17618. ((org-at-table-p) (org-table-move-cell-left))
  17619. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  17620. (org-support-shift-select
  17621. (org-call-for-shift-select 'backward-char))
  17622. (t (org-shiftselect-error))))
  17623. (defun org-shiftcontrolright ()
  17624. "Switch to next TODO set."
  17625. (interactive)
  17626. (cond
  17627. ((and org-support-shift-select (org-region-active-p))
  17628. (org-call-for-shift-select 'forward-word))
  17629. ((and (not (eq org-support-shift-select 'always))
  17630. (org-at-heading-p))
  17631. (org-call-with-arg 'org-todo 'nextset))
  17632. (org-support-shift-select
  17633. (org-call-for-shift-select 'forward-word))
  17634. (t (org-shiftselect-error))))
  17635. (defun org-shiftcontrolleft ()
  17636. "Switch to previous TODO set."
  17637. (interactive)
  17638. (cond
  17639. ((and org-support-shift-select (org-region-active-p))
  17640. (org-call-for-shift-select 'backward-word))
  17641. ((and (not (eq org-support-shift-select 'always))
  17642. (org-at-heading-p))
  17643. (org-call-with-arg 'org-todo 'previousset))
  17644. (org-support-shift-select
  17645. (org-call-for-shift-select 'backward-word))
  17646. (t (org-shiftselect-error))))
  17647. (defun org-shiftcontrolup (&optional n)
  17648. "Change timestamps synchronously up in CLOCK log lines.
  17649. Optional argument N tells to change by that many units."
  17650. (interactive "P")
  17651. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  17652. (let (org-support-shift-select)
  17653. (org-clock-timestamps-up n))
  17654. (user-error "Not at a clock log")))
  17655. (defun org-shiftcontroldown (&optional n)
  17656. "Change timestamps synchronously down in CLOCK log lines.
  17657. Optional argument N tells to change by that many units."
  17658. (interactive "P")
  17659. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  17660. (let (org-support-shift-select)
  17661. (org-clock-timestamps-down n))
  17662. (user-error "Not at a clock log")))
  17663. (defun org-increase-number-at-point (&optional inc)
  17664. "Increment the number at point.
  17665. With an optional prefix numeric argument INC, increment using
  17666. this numeric value."
  17667. (interactive "p")
  17668. (if (not (number-at-point))
  17669. (user-error "Not on a number")
  17670. (unless inc (setq inc 1))
  17671. (let ((pos (point))
  17672. (beg (skip-chars-backward "-+^/*0-9eE."))
  17673. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  17674. (setq nap (buffer-substring-no-properties
  17675. (+ pos beg) (+ pos beg end)))
  17676. (delete-region (+ pos beg) (+ pos beg end))
  17677. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  17678. (when (org-at-table-p)
  17679. (org-table-align)
  17680. (org-table-end-of-field 1))))
  17681. (defun org-decrease-number-at-point (&optional inc)
  17682. "Decrement the number at point.
  17683. With an optional prefix numeric argument INC, decrement using
  17684. this numeric value."
  17685. (interactive "p")
  17686. (org-increase-number-at-point (- (or inc 1))))
  17687. (defun org-ctrl-c-ret ()
  17688. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  17689. (interactive)
  17690. (cond
  17691. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  17692. (t (call-interactively 'org-insert-heading))))
  17693. (defun org-find-visible ()
  17694. (let ((s (point)))
  17695. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  17696. (get-char-property s 'invisible)))
  17697. s))
  17698. (defun org-find-invisible ()
  17699. (let ((s (point)))
  17700. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  17701. (not (get-char-property s 'invisible))))
  17702. s))
  17703. (defun org-copy-visible (beg end)
  17704. "Copy the visible parts of the region."
  17705. (interactive "r")
  17706. (let ((result ""))
  17707. (while (/= beg end)
  17708. (when (get-char-property beg 'invisible)
  17709. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  17710. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  17711. (setq result (concat result (buffer-substring beg next)))
  17712. (setq beg next)))
  17713. (setq deactivate-mark t)
  17714. (kill-new result)
  17715. (message "Visible strings have been copied to the kill ring.")))
  17716. (defun org-copy-special ()
  17717. "Copy region in table or copy current subtree.
  17718. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  17719. context. See the individual commands for more information."
  17720. (interactive)
  17721. (call-interactively
  17722. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  17723. (defun org-cut-special ()
  17724. "Cut region in table or cut current subtree.
  17725. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  17726. context. See the individual commands for more information."
  17727. (interactive)
  17728. (call-interactively
  17729. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  17730. (defun org-paste-special (arg)
  17731. "Paste rectangular region into table, or past subtree relative to level.
  17732. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  17733. See the individual commands for more information."
  17734. (interactive "P")
  17735. (if (org-at-table-p)
  17736. (org-table-paste-rectangle)
  17737. (org-paste-subtree arg)))
  17738. (defun org-edit-special (&optional arg)
  17739. "Call a special editor for the element at point.
  17740. When at a table, call the formula editor with `org-table-edit-formulas'.
  17741. When in a source code block, call `org-edit-src-code'.
  17742. When in a fixed-width region, call `org-edit-fixed-width-region'.
  17743. When in an export block, call `org-edit-export-block'.
  17744. When in a LaTeX environment, call `org-edit-latex-environment'.
  17745. When at an #+INCLUDE keyword, visit the included file.
  17746. When at a footnote reference, call `org-edit-footnote-reference'.
  17747. When at a planning line call, `org-deadline' and/or `org-schedule'.
  17748. When at an active timestamp, call `org-time-stamp'.
  17749. When at an inactive timestamp, call `org-time-stamp-inactive'.
  17750. On a link, call `ffap' to visit the link at point.
  17751. Otherwise, return a user error."
  17752. (interactive "P")
  17753. (let ((element (org-element-at-point)))
  17754. (barf-if-buffer-read-only)
  17755. (pcase (org-element-type element)
  17756. (`src-block
  17757. (if (not arg) (org-edit-src-code)
  17758. (let* ((info (org-babel-get-src-block-info))
  17759. (lang (nth 0 info))
  17760. (params (nth 2 info))
  17761. (session (cdr (assq :session params))))
  17762. (if (not session) (org-edit-src-code)
  17763. ;; At a source block with a session and function called
  17764. ;; with an ARG: switch to the buffer related to the
  17765. ;; inferior process.
  17766. (switch-to-buffer
  17767. (funcall (intern (concat "org-babel-prep-session:" lang))
  17768. session params))))))
  17769. (`keyword
  17770. (unless (member (org-element-property :key element)
  17771. '("INCLUDE" "SETUPFILE"))
  17772. (user-error "No special environment to edit here"))
  17773. (org-open-link-from-string
  17774. (format "[[%s]]"
  17775. (expand-file-name
  17776. (let ((value (org-strip-quotes
  17777. (org-element-property :value element))))
  17778. (cond
  17779. ((not (org-string-nw-p value))
  17780. (user-error "No file to edit"))
  17781. ((org-file-url-p value)
  17782. (user-error "Files located with a URL cannot be edited"))
  17783. (t value)))))))
  17784. (`table
  17785. (if (eq (org-element-property :type element) 'table.el)
  17786. (org-edit-table.el)
  17787. (call-interactively 'org-table-edit-formulas)))
  17788. ;; Only Org tables contain `table-row' type elements.
  17789. (`table-row (call-interactively 'org-table-edit-formulas))
  17790. (`example-block (org-edit-src-code))
  17791. (`export-block (org-edit-export-block))
  17792. (`fixed-width (org-edit-fixed-width-region))
  17793. (`latex-environment (org-edit-latex-environment))
  17794. (`planning
  17795. (let ((proplist (cadr element)))
  17796. (mapc #'call-interactively
  17797. (remq nil
  17798. (list
  17799. (when (plist-get proplist :deadline) #'org-deadline)
  17800. (when (plist-get proplist :scheduled) #'org-schedule))))))
  17801. (_
  17802. ;; No notable element at point. Though, we may be at a link or
  17803. ;; a footnote reference, which are objects. Thus, scan deeper.
  17804. (let ((context (org-element-context element)))
  17805. (pcase (org-element-type context)
  17806. (`footnote-reference (org-edit-footnote-reference))
  17807. (`inline-src-block (org-edit-inline-src-code))
  17808. (`timestamp (if (eq 'inactive (org-element-property :type context))
  17809. (call-interactively #'org-time-stamp-inactive)
  17810. (call-interactively #'org-time-stamp)))
  17811. (`link (call-interactively #'ffap))
  17812. (_ (user-error "No special environment to edit here"))))))))
  17813. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  17814. (defun org-ctrl-c-ctrl-c (&optional arg)
  17815. "Set tags in headline, or update according to changed information at point.
  17816. This command does many different things, depending on context:
  17817. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  17818. this is what we do.
  17819. - If the cursor is on a statistics cookie, update it.
  17820. - If the cursor is in a headline, prompt for tags and insert them
  17821. into the current line, aligned to `org-tags-column'. When called
  17822. with prefix arg, realign all tags in the current buffer.
  17823. - If the cursor is in one of the special #+KEYWORD lines, this
  17824. triggers scanning the buffer for these lines and updating the
  17825. information.
  17826. - If the cursor is inside a table, realign the table. This command
  17827. works even if the automatic table editor has been turned off.
  17828. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  17829. the entire table.
  17830. - If the cursor is at a footnote reference or definition, jump to
  17831. the corresponding definition or references, respectively.
  17832. - If the cursor is a the beginning of a dynamic block, update it.
  17833. - If the current buffer is a capture buffer, close note and file it.
  17834. - If the cursor is on a <<<target>>>, update radio targets and
  17835. corresponding links in this buffer.
  17836. - If the cursor is on a numbered item in a plain list, renumber the
  17837. ordered list.
  17838. - If the cursor is on a checkbox, toggle it.
  17839. - If the cursor is on a code block, evaluate it. The variable
  17840. `org-confirm-babel-evaluate' can be used to control prompting
  17841. before code block evaluation, by default every code block
  17842. evaluation requires confirmation. Code block evaluation can be
  17843. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  17844. (interactive "P")
  17845. (cond
  17846. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  17847. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  17848. (org-remove-occur-highlights)
  17849. (message "Temporary highlights/overlays removed from current buffer"))
  17850. ((and (local-variable-p 'org-finish-function)
  17851. (fboundp org-finish-function))
  17852. (funcall org-finish-function))
  17853. ((org-babel-hash-at-point))
  17854. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  17855. (t
  17856. (let* ((context
  17857. (org-element-lineage
  17858. (org-element-context)
  17859. ;; Limit to supported contexts.
  17860. '(babel-call clock dynamic-block footnote-definition
  17861. footnote-reference inline-babel-call inline-src-block
  17862. inlinetask item keyword node-property paragraph
  17863. plain-list planning property-drawer radio-target
  17864. src-block statistics-cookie table table-cell table-row
  17865. timestamp)
  17866. t))
  17867. (type (org-element-type context)))
  17868. ;; For convenience: at the first line of a paragraph on the same
  17869. ;; line as an item, apply function on that item instead.
  17870. (when (eq type 'paragraph)
  17871. (let ((parent (org-element-property :parent context)))
  17872. (when (and (eq (org-element-type parent) 'item)
  17873. (= (line-beginning-position)
  17874. (org-element-property :begin parent)))
  17875. (setq context parent)
  17876. (setq type 'item))))
  17877. ;; Act according to type of element or object at point.
  17878. ;;
  17879. ;; Do nothing on a blank line, except if it is contained in
  17880. ;; a source block. Hence, we first check if point is in such
  17881. ;; a block and then if it is at a blank line.
  17882. (pcase type
  17883. ((or `inline-src-block `src-block)
  17884. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  17885. (org-babel-eval-wipe-error-buffer)
  17886. (org-babel-execute-src-block
  17887. current-prefix-arg (org-babel-get-src-block-info nil context))))
  17888. ((guard (org-match-line "[ \t]*$"))
  17889. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  17890. (user-error
  17891. (substitute-command-keys
  17892. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  17893. ((or `babel-call `inline-babel-call)
  17894. (let ((info (org-babel-lob-get-info context)))
  17895. (when info (org-babel-execute-src-block nil info))))
  17896. (`clock (org-clock-update-time-maybe))
  17897. (`dynamic-block
  17898. (save-excursion
  17899. (goto-char (org-element-property :post-affiliated context))
  17900. (org-update-dblock)))
  17901. (`footnote-definition
  17902. (goto-char (org-element-property :post-affiliated context))
  17903. (call-interactively 'org-footnote-action))
  17904. (`footnote-reference (call-interactively #'org-footnote-action))
  17905. ((or `headline `inlinetask)
  17906. (save-excursion (goto-char (org-element-property :begin context))
  17907. (call-interactively #'org-set-tags-command)))
  17908. (`item
  17909. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  17910. ;; unconditionally, whereas `C-u' will toggle its presence.
  17911. ;; Without a universal argument, if the item has a checkbox,
  17912. ;; toggle it. Otherwise repair the list.
  17913. (let* ((box (org-element-property :checkbox context))
  17914. (struct (org-element-property :structure context))
  17915. (old-struct (copy-tree struct))
  17916. (parents (org-list-parents-alist struct))
  17917. (prevs (org-list-prevs-alist struct))
  17918. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  17919. (org-list-set-checkbox
  17920. (org-element-property :begin context) struct
  17921. (cond ((equal arg '(16)) "[-]")
  17922. ((and (not box) (equal arg '(4))) "[ ]")
  17923. ((or (not box) (equal arg '(4))) nil)
  17924. ((eq box 'on) "[ ]")
  17925. (t "[X]")))
  17926. ;; Mimic `org-list-write-struct' but with grabbing a return
  17927. ;; value from `org-list-struct-fix-box'.
  17928. (org-list-struct-fix-ind struct parents 2)
  17929. (org-list-struct-fix-item-end struct)
  17930. (org-list-struct-fix-bul struct prevs)
  17931. (org-list-struct-fix-ind struct parents)
  17932. (let ((block-item
  17933. (org-list-struct-fix-box struct parents prevs orderedp)))
  17934. (if (and box (equal struct old-struct))
  17935. (if (equal arg '(16))
  17936. (message "Checkboxes already reset")
  17937. (user-error "Cannot toggle this checkbox: %s"
  17938. (if (eq box 'on)
  17939. "all subitems checked"
  17940. "unchecked subitems")))
  17941. (org-list-struct-apply-struct struct old-struct)
  17942. (org-update-checkbox-count-maybe))
  17943. (when block-item
  17944. (message "Checkboxes were removed due to empty box at line %d"
  17945. (org-current-line block-item))))))
  17946. (`keyword
  17947. (let ((org-inhibit-startup-visibility-stuff t)
  17948. (org-startup-align-all-tables nil))
  17949. (when (boundp 'org-table-coordinate-overlays)
  17950. (mapc #'delete-overlay org-table-coordinate-overlays)
  17951. (setq org-table-coordinate-overlays nil))
  17952. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  17953. (message "Local setup has been refreshed"))
  17954. (`plain-list
  17955. ;; At a plain list, with a double C-u argument, set
  17956. ;; checkboxes of each item to "[-]", whereas a single one
  17957. ;; will toggle their presence according to the state of the
  17958. ;; first item in the list. Without an argument, repair the
  17959. ;; list.
  17960. (let* ((begin (org-element-property :contents-begin context))
  17961. (struct (org-element-property :structure context))
  17962. (old-struct (copy-tree struct))
  17963. (first-box (save-excursion
  17964. (goto-char begin)
  17965. (looking-at org-list-full-item-re)
  17966. (match-string-no-properties 3)))
  17967. (new-box (cond ((equal arg '(16)) "[-]")
  17968. ((equal arg '(4)) (unless first-box "[ ]"))
  17969. ((equal first-box "[X]") "[ ]")
  17970. (t "[X]"))))
  17971. (cond
  17972. (arg
  17973. (dolist (pos
  17974. (org-list-get-all-items
  17975. begin struct (org-list-prevs-alist struct)))
  17976. (org-list-set-checkbox pos struct new-box)))
  17977. ((and first-box (eq (point) begin))
  17978. ;; For convenience, when point is at bol on the first
  17979. ;; item of the list and no argument is provided, simply
  17980. ;; toggle checkbox of that item, if any.
  17981. (org-list-set-checkbox begin struct new-box)))
  17982. (when (equal
  17983. (org-list-write-struct
  17984. struct (org-list-parents-alist struct) old-struct)
  17985. old-struct)
  17986. (message "Cannot update this checkbox"))
  17987. (org-update-checkbox-count-maybe)))
  17988. ((or `property-drawer `node-property)
  17989. (call-interactively #'org-property-action))
  17990. (`radio-target
  17991. (call-interactively #'org-update-radio-target-regexp))
  17992. (`statistics-cookie
  17993. (call-interactively #'org-update-statistics-cookies))
  17994. ((or `table `table-cell `table-row)
  17995. ;; At a table, recalculate every field and align it. Also
  17996. ;; send the table if necessary. If the table has
  17997. ;; a `table.el' type, just give up. At a table row or cell,
  17998. ;; maybe recalculate line but always align table.
  17999. (if (eq (org-element-property :type context) 'table.el)
  18000. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  18001. Use `\\[org-edit-special]' to edit table.el tables"))
  18002. (if (or (eq type 'table)
  18003. ;; Check if point is at a TBLFM line.
  18004. (and (eq type 'table-row)
  18005. (= (point) (org-element-property :end context))))
  18006. (save-excursion
  18007. (if (org-at-TBLFM-p)
  18008. (progn (require 'org-table)
  18009. (org-table-calc-current-TBLFM))
  18010. (goto-char (org-element-property :contents-begin context))
  18011. (org-call-with-arg 'org-table-recalculate (or arg t))
  18012. (orgtbl-send-table 'maybe)))
  18013. (org-table-maybe-eval-formula)
  18014. (cond (arg (call-interactively #'org-table-recalculate))
  18015. ((org-table-maybe-recalculate-line))
  18016. (t (org-table-align))))))
  18017. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  18018. (org-timestamp-change 0 'day))
  18019. ((and `nil (guard (org-at-heading-p)))
  18020. ;; When point is on an unsupported object type, we can miss
  18021. ;; the fact that it also is at a heading. Handle it here.
  18022. (call-interactively #'org-set-tags-command))
  18023. ((guard
  18024. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  18025. (_
  18026. (user-error
  18027. (substitute-command-keys
  18028. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  18029. (defun org-mode-restart ()
  18030. (interactive)
  18031. (let ((indent-status (bound-and-true-p org-indent-mode)))
  18032. (funcall major-mode)
  18033. (hack-local-variables)
  18034. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  18035. (org-indent-mode -1))
  18036. (org-reset-file-cache))
  18037. (message "%s restarted" major-mode))
  18038. (defun org-kill-note-or-show-branches ()
  18039. "Abort storing current note, or call `outline-show-branches'."
  18040. (interactive)
  18041. (if (not org-finish-function)
  18042. (save-excursion
  18043. (save-restriction
  18044. (org-narrow-to-subtree)
  18045. (org-flag-subtree t)
  18046. (call-interactively 'outline-show-branches)
  18047. (org-hide-archived-subtrees (point-min) (point-max))))
  18048. (let ((org-note-abort t))
  18049. (funcall org-finish-function))))
  18050. (defun org-delete-indentation (&optional arg)
  18051. "Join current line to previous and fix whitespace at join.
  18052. If previous line is a headline add to headline title. Otherwise
  18053. the function calls `delete-indentation'.
  18054. With a non-nil optional argument, join it to the following one."
  18055. (interactive "*P")
  18056. (if (save-excursion
  18057. (beginning-of-line (if arg 1 0))
  18058. (let ((case-fold-search nil))
  18059. (looking-at org-complex-heading-regexp)))
  18060. ;; At headline.
  18061. (let ((tags-column (when (match-beginning 5)
  18062. (save-excursion (goto-char (match-beginning 5))
  18063. (current-column))))
  18064. (string (concat " " (progn (when arg (forward-line 1))
  18065. (org-trim (delete-and-extract-region
  18066. (line-beginning-position)
  18067. (line-end-position)))))))
  18068. (unless (bobp) (delete-region (point) (1- (point))))
  18069. (goto-char (or (match-end 4)
  18070. (match-beginning 5)
  18071. (match-end 0)))
  18072. (skip-chars-backward " \t")
  18073. (save-excursion (insert string))
  18074. ;; Adjust alignment of tags.
  18075. (cond
  18076. ((not tags-column)) ;no tags
  18077. (org-auto-align-tags (org-align-tags))
  18078. (t (org--align-tags-here tags-column)))) ;preserve tags column
  18079. (delete-indentation arg)))
  18080. (defun org-open-line (n)
  18081. "Insert a new row in tables, call `open-line' elsewhere.
  18082. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  18083. As a special case, when a document starts with a table, allow to
  18084. call `open-line' on the very first character."
  18085. (interactive "*p")
  18086. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  18087. (org-table-insert-row)
  18088. (open-line n)))
  18089. (defun org-return (&optional indent)
  18090. "Goto next table row or insert a newline.
  18091. Calls `org-table-next-row' or `newline', depending on context.
  18092. When optional INDENT argument is non-nil, call
  18093. `newline-and-indent' instead of `newline'.
  18094. When `org-return-follows-link' is non-nil and point is on
  18095. a timestamp or a link, call `org-open-at-point'. However, it
  18096. will not happen if point is in a table or on a \"dead\"
  18097. object (e.g., within a comment). In these case, you need to use
  18098. `org-open-at-point' directly."
  18099. (interactive)
  18100. (let ((context (if org-return-follows-link (org-element-context)
  18101. (org-element-at-point))))
  18102. (cond
  18103. ;; In a table, call `org-table-next-row'. However, before first
  18104. ;; column or after last one, split the table.
  18105. ((or (and (eq 'table (org-element-type context))
  18106. (not (eq 'table.el (org-element-property :type context)))
  18107. (>= (point) (org-element-property :contents-begin context))
  18108. (< (point) (org-element-property :contents-end context)))
  18109. (org-element-lineage context '(table-row table-cell) t))
  18110. (if (or (looking-at-p "[ \t]*$")
  18111. (save-excursion (skip-chars-backward " \t") (bolp)))
  18112. (insert "\n")
  18113. (org-table-justify-field-maybe)
  18114. (call-interactively #'org-table-next-row)))
  18115. ;; On a link or a timestamp, call `org-open-at-point' if
  18116. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  18117. ;; locations, e.g., in a comment, as `org-open-at-point'.
  18118. ((and org-return-follows-link
  18119. (or (and (eq 'link (org-element-type context))
  18120. ;; Ensure point is not on the white spaces after
  18121. ;; the link.
  18122. (let ((origin (point)))
  18123. (org-with-point-at (org-element-property :end context)
  18124. (skip-chars-backward " \t")
  18125. (> (point) origin))))
  18126. (org-in-regexp org-ts-regexp-both nil t)
  18127. (org-in-regexp org-tsr-regexp-both nil t)
  18128. (org-in-regexp org-any-link-re nil t)))
  18129. (call-interactively #'org-open-at-point))
  18130. ;; Insert newline in heading, but preserve tags.
  18131. ((and (not (bolp))
  18132. (let ((case-fold-search nil))
  18133. (org-match-line org-complex-heading-regexp)))
  18134. ;; At headline. Split line. However, if point is on keyword,
  18135. ;; priority cookie or tags, do not break any of them: add
  18136. ;; a newline after the headline instead.
  18137. (let ((tags-column (and (match-beginning 5)
  18138. (save-excursion (goto-char (match-beginning 5))
  18139. (current-column))))
  18140. (string
  18141. (when (and (match-end 4) (org-point-in-group (point) 4))
  18142. (delete-and-extract-region (point) (match-end 4)))))
  18143. ;; Adjust tag alignment.
  18144. (cond
  18145. ((not (and tags-column string)))
  18146. (org-auto-align-tags (org-align-tags))
  18147. (t (org--align-tags-here tags-column))) ;preserve tags column
  18148. (end-of-line)
  18149. (org-show-entry)
  18150. (if indent (newline-and-indent) (newline))
  18151. (when string (save-excursion (insert (org-trim string))))))
  18152. ;; In a list, make sure indenting keeps trailing text within.
  18153. ((and indent
  18154. (not (eolp))
  18155. (org-element-lineage context '(item)))
  18156. (let ((trailing-data
  18157. (delete-and-extract-region (point) (line-end-position))))
  18158. (newline-and-indent)
  18159. (save-excursion (insert trailing-data))))
  18160. (t
  18161. ;; Do not auto-fill when point is in an Org property drawer.
  18162. (let ((auto-fill-function (and (not (org-at-property-p))
  18163. auto-fill-function)))
  18164. (if indent
  18165. (newline-and-indent)
  18166. (newline)))))))
  18167. (defun org-return-indent ()
  18168. "Goto next table row or insert a newline and indent.
  18169. Calls `org-table-next-row' or `newline-and-indent', depending on
  18170. context. See the individual commands for more information."
  18171. (interactive)
  18172. (org-return t))
  18173. (defun org-ctrl-c-tab (&optional _arg)
  18174. "Toggle columns width in a table, or show children.
  18175. Call `org-table-toggle-column-width' if point is in a table.
  18176. Otherwise, call `org-show-children'."
  18177. (interactive "p")
  18178. (call-interactively
  18179. (if (org-at-table-p) #'org-table-toggle-column-width
  18180. #'org-show-children)))
  18181. (defun org-ctrl-c-star ()
  18182. "Compute table, or change heading status of lines.
  18183. Calls `org-table-recalculate' or `org-toggle-heading',
  18184. depending on context."
  18185. (interactive)
  18186. (cond
  18187. ((org-at-table-p)
  18188. (call-interactively 'org-table-recalculate))
  18189. (t
  18190. ;; Convert all lines in region to list items
  18191. (call-interactively 'org-toggle-heading))))
  18192. (defun org-ctrl-c-minus ()
  18193. "Insert separator line in table or modify bullet status of line.
  18194. Also turns a plain line or a region of lines into list items.
  18195. Calls `org-table-insert-hline', `org-toggle-item', or
  18196. `org-cycle-list-bullet', depending on context."
  18197. (interactive)
  18198. (cond
  18199. ((org-at-table-p)
  18200. (call-interactively 'org-table-insert-hline))
  18201. ((org-region-active-p)
  18202. (call-interactively 'org-toggle-item))
  18203. ((org-in-item-p)
  18204. (call-interactively 'org-cycle-list-bullet))
  18205. (t
  18206. (call-interactively 'org-toggle-item))))
  18207. (defun org-toggle-heading (&optional nstars)
  18208. "Convert headings to normal text, or items or text to headings.
  18209. If there is no active region, only convert the current line.
  18210. With a `\\[universal-argument]' prefix, convert the whole list at
  18211. point into heading.
  18212. In a region:
  18213. - If the first non blank line is a headline, remove the stars
  18214. from all headlines in the region.
  18215. - If it is a normal line, turn each and every normal line (i.e.,
  18216. not an heading or an item) in the region into headings. If you
  18217. want to convert only the first line of this region, use one
  18218. universal prefix argument.
  18219. - If it is a plain list item, turn all plain list items into headings.
  18220. When converting a line into a heading, the number of stars is chosen
  18221. such that the lines become children of the current entry. However,
  18222. when a numeric prefix argument is given, its value determines the
  18223. number of stars to add."
  18224. (interactive "P")
  18225. (let ((skip-blanks
  18226. (function
  18227. ;; Return beginning of first non-blank line, starting from
  18228. ;; line at POS.
  18229. (lambda (pos)
  18230. (save-excursion
  18231. (goto-char pos)
  18232. (while (org-at-comment-p) (forward-line))
  18233. (skip-chars-forward " \r\t\n")
  18234. (point-at-bol)))))
  18235. beg end toggled)
  18236. ;; Determine boundaries of changes. If a universal prefix has
  18237. ;; been given, put the list in a region. If region ends at a bol,
  18238. ;; do not consider the last line to be in the region.
  18239. (when (and current-prefix-arg (org-at-item-p))
  18240. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  18241. (org-mark-element))
  18242. (if (org-region-active-p)
  18243. (setq beg (funcall skip-blanks (region-beginning))
  18244. end (copy-marker (save-excursion
  18245. (goto-char (region-end))
  18246. (if (bolp) (point) (point-at-eol)))))
  18247. (setq beg (funcall skip-blanks (point-at-bol))
  18248. end (copy-marker (point-at-eol))))
  18249. ;; Ensure inline tasks don't count as headings.
  18250. (org-with-limited-levels
  18251. (save-excursion
  18252. (goto-char beg)
  18253. (cond
  18254. ;; Case 1. Started at an heading: de-star headings.
  18255. ((org-at-heading-p)
  18256. (while (< (point) end)
  18257. (when (org-at-heading-p t)
  18258. (looking-at org-outline-regexp) (replace-match "")
  18259. (setq toggled t))
  18260. (forward-line)))
  18261. ;; Case 2. Started at an item: change items into headlines.
  18262. ;; One star will be added by `org-list-to-subtree'.
  18263. ((org-at-item-p)
  18264. (while (< (point) end)
  18265. (when (org-at-item-p)
  18266. ;; Pay attention to cases when region ends before list.
  18267. (let* ((struct (org-list-struct))
  18268. (list-end
  18269. (min (org-list-get-bottom-point struct) (1+ end))))
  18270. (save-restriction
  18271. (narrow-to-region (point) list-end)
  18272. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  18273. (setq toggled t))
  18274. (forward-line)))
  18275. ;; Case 3. Started at normal text: make every line an heading,
  18276. ;; skipping headlines and items.
  18277. (t (let* ((stars
  18278. (make-string
  18279. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  18280. (add-stars
  18281. (cond (nstars "") ; stars from prefix only
  18282. ((equal stars "") "*") ; before first heading
  18283. (org-odd-levels-only "**") ; inside heading, odd
  18284. (t "*"))) ; inside heading, oddeven
  18285. (rpl (concat stars add-stars " "))
  18286. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  18287. (while (< (point) (if (equal nstars '(4)) lend end))
  18288. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  18289. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  18290. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  18291. (forward-line)))))))
  18292. (unless toggled (message "Cannot toggle heading from here"))))
  18293. (defun org-meta-return (&optional arg)
  18294. "Insert a new heading or wrap a region in a table.
  18295. Calls `org-insert-heading', `org-insert-item' or
  18296. `org-table-wrap-region', depending on context. When called with
  18297. an argument, unconditionally call `org-insert-heading'."
  18298. (interactive "P")
  18299. (org-check-before-invisible-edit 'insert)
  18300. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  18301. (call-interactively (cond (arg #'org-insert-heading)
  18302. ((org-at-table-p) #'org-table-wrap-region)
  18303. ((org-in-item-p) #'org-insert-item)
  18304. (t #'org-insert-heading)))))
  18305. ;;; Menu entries
  18306. (defsubst org-in-subtree-not-table-p ()
  18307. "Are we in a subtree and not in a table?"
  18308. (and (not (org-before-first-heading-p))
  18309. (not (org-at-table-p))))
  18310. ;; Define the Org mode menus
  18311. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  18312. '("Tbl"
  18313. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  18314. ["Next Field" org-cycle (org-at-table-p)]
  18315. ["Previous Field" org-shifttab (org-at-table-p)]
  18316. ["Next Row" org-return (org-at-table-p)]
  18317. "--"
  18318. ["Blank Field" org-table-blank-field (org-at-table-p)]
  18319. ["Edit Field" org-table-edit-field (org-at-table-p)]
  18320. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  18321. "--"
  18322. ("Column"
  18323. ["Move Column Left" org-metaleft (org-at-table-p)]
  18324. ["Move Column Right" org-metaright (org-at-table-p)]
  18325. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  18326. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  18327. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  18328. ("Row"
  18329. ["Move Row Up" org-metaup (org-at-table-p)]
  18330. ["Move Row Down" org-metadown (org-at-table-p)]
  18331. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  18332. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  18333. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  18334. "--"
  18335. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  18336. ("Rectangle"
  18337. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  18338. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  18339. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  18340. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  18341. "--"
  18342. ("Calculate"
  18343. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  18344. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  18345. ["Edit Formulas" org-edit-special (org-at-table-p)]
  18346. "--"
  18347. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  18348. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  18349. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  18350. "--"
  18351. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  18352. "--"
  18353. ["Sum Column/Rectangle" org-table-sum
  18354. (or (org-at-table-p) (org-region-active-p))]
  18355. ["Which Column?" org-table-current-column (org-at-table-p)])
  18356. ["Debug Formulas"
  18357. org-table-toggle-formula-debugger
  18358. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  18359. ["Show Col/Row Numbers"
  18360. org-table-toggle-coordinate-overlays
  18361. :style toggle
  18362. :selected (bound-and-true-p org-table-overlay-coordinates)]
  18363. "--"
  18364. ["Create" org-table-create (not (org-at-table-p))]
  18365. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  18366. ["Import from File" org-table-import (not (org-at-table-p))]
  18367. ["Export to File" org-table-export (org-at-table-p)]
  18368. "--"
  18369. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  18370. "--"
  18371. ("Plot"
  18372. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  18373. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  18374. (easy-menu-define org-org-menu org-mode-map "Org menu"
  18375. '("Org"
  18376. ("Show/Hide"
  18377. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  18378. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  18379. ["Sparse Tree..." org-sparse-tree t]
  18380. ["Reveal Context" org-reveal t]
  18381. ["Show All" org-show-all t]
  18382. "--"
  18383. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  18384. "--"
  18385. ["New Heading" org-insert-heading t]
  18386. ("Navigate Headings"
  18387. ["Up" outline-up-heading t]
  18388. ["Next" outline-next-visible-heading t]
  18389. ["Previous" outline-previous-visible-heading t]
  18390. ["Next Same Level" outline-forward-same-level t]
  18391. ["Previous Same Level" outline-backward-same-level t]
  18392. "--"
  18393. ["Jump" org-goto t])
  18394. ("Edit Structure"
  18395. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  18396. "--"
  18397. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  18398. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  18399. "--"
  18400. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  18401. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  18402. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  18403. "--"
  18404. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  18405. "--"
  18406. ["Copy visible text" org-copy-visible t]
  18407. "--"
  18408. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  18409. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  18410. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  18411. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  18412. "--"
  18413. ["Sort Region/Children" org-sort t]
  18414. "--"
  18415. ["Convert to odd levels" org-convert-to-odd-levels t]
  18416. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  18417. ("Editing"
  18418. ["Emphasis..." org-emphasize t]
  18419. ["Edit Source Example" org-edit-special t]
  18420. "--"
  18421. ["Footnote new/jump" org-footnote-action t]
  18422. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  18423. ("Archive"
  18424. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  18425. "--"
  18426. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  18427. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  18428. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  18429. )
  18430. "--"
  18431. ("Hyperlinks"
  18432. ["Store Link (Global)" org-store-link t]
  18433. ["Find existing link to here" org-occur-link-in-agenda-files t]
  18434. ["Insert Link" org-insert-link t]
  18435. ["Follow Link" org-open-at-point t]
  18436. "--"
  18437. ["Next link" org-next-link t]
  18438. ["Previous link" org-previous-link t]
  18439. "--"
  18440. ["Descriptive Links"
  18441. org-toggle-link-display
  18442. :style radio
  18443. :selected org-descriptive-links
  18444. ]
  18445. ["Literal Links"
  18446. org-toggle-link-display
  18447. :style radio
  18448. :selected (not org-descriptive-links)])
  18449. "--"
  18450. ("TODO Lists"
  18451. ["TODO/DONE/-" org-todo t]
  18452. ("Select keyword"
  18453. ["Next keyword" org-shiftright (org-at-heading-p)]
  18454. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  18455. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  18456. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  18457. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  18458. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  18459. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  18460. "--"
  18461. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  18462. :selected org-enforce-todo-dependencies :style toggle :active t]
  18463. "Settings for tree at point"
  18464. ["Do Children sequentially" org-toggle-ordered-property :style radio
  18465. :selected (org-entry-get nil "ORDERED")
  18466. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  18467. ["Do Children parallel" org-toggle-ordered-property :style radio
  18468. :selected (not (org-entry-get nil "ORDERED"))
  18469. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  18470. "--"
  18471. ["Set Priority" org-priority t]
  18472. ["Priority Up" org-shiftup t]
  18473. ["Priority Down" org-shiftdown t]
  18474. "--"
  18475. ["Get news from all feeds" org-feed-update-all t]
  18476. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  18477. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  18478. ("TAGS and Properties"
  18479. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  18480. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  18481. "--"
  18482. ["Set property" org-set-property (not (org-before-first-heading-p))]
  18483. ["Column view of properties" org-columns t]
  18484. ["Insert Column View DBlock" org-columns-insert-dblock t])
  18485. ("Dates and Scheduling"
  18486. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  18487. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  18488. ("Change Date"
  18489. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  18490. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  18491. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  18492. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  18493. ["Compute Time Range" org-evaluate-time-range t]
  18494. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  18495. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  18496. "--"
  18497. ["Custom time format" org-toggle-time-stamp-overlays
  18498. :style radio :selected org-display-custom-times]
  18499. "--"
  18500. ["Goto Calendar" org-goto-calendar t]
  18501. ["Date from Calendar" org-date-from-calendar t]
  18502. "--"
  18503. ["Start/Restart Timer" org-timer-start t]
  18504. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  18505. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  18506. ["Insert Timer String" org-timer t]
  18507. ["Insert Timer Item" org-timer-item t])
  18508. ("Logging work"
  18509. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  18510. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  18511. ["Clock out" org-clock-out t]
  18512. ["Clock cancel" org-clock-cancel t]
  18513. "--"
  18514. ["Mark as default task" org-clock-mark-default-task t]
  18515. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  18516. ["Goto running clock" org-clock-goto t]
  18517. "--"
  18518. ["Display times" org-clock-display t]
  18519. ["Create clock table" org-clock-report t]
  18520. "--"
  18521. ["Record DONE time"
  18522. (progn (setq org-log-done (not org-log-done))
  18523. (message "Switching to %s will %s record a timestamp"
  18524. (car org-done-keywords)
  18525. (if org-log-done "automatically" "not")))
  18526. :style toggle :selected org-log-done])
  18527. "--"
  18528. ["Agenda Command..." org-agenda t]
  18529. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  18530. ("File List for Agenda")
  18531. ("Special views current file"
  18532. ["TODO Tree" org-show-todo-tree t]
  18533. ["Check Deadlines" org-check-deadlines t]
  18534. ["Tags/Property tree" org-match-sparse-tree t])
  18535. "--"
  18536. ["Export/Publish..." org-export-dispatch t]
  18537. ("LaTeX"
  18538. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  18539. :style toggle :selected org-cdlatex-mode]
  18540. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  18541. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  18542. ["Modify math symbol" org-cdlatex-math-modify
  18543. (org-inside-LaTeX-fragment-p)]
  18544. ["Insert citation" org-reftex-citation t])
  18545. "--"
  18546. ("MobileOrg"
  18547. ["Push Files and Views" org-mobile-push t]
  18548. ["Get Captured and Flagged" org-mobile-pull t]
  18549. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
  18550. "--"
  18551. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  18552. "--"
  18553. ("Documentation"
  18554. ["Show Version" org-version t]
  18555. ["Info Documentation" org-info t]
  18556. ["Browse Org News" org-browse-news t])
  18557. ("Customize"
  18558. ["Browse Org Group" org-customize t]
  18559. "--"
  18560. ["Expand This Menu" org-create-customize-menu
  18561. (fboundp 'customize-menu-create)])
  18562. ["Send bug report" org-submit-bug-report t]
  18563. "--"
  18564. ("Refresh/Reload"
  18565. ["Refresh setup current buffer" org-mode-restart t]
  18566. ["Reload Org (after update)" org-reload t]
  18567. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  18568. (defun org-info (&optional node)
  18569. "Read documentation for Org in the info system.
  18570. With optional NODE, go directly to that node."
  18571. (interactive)
  18572. (info (format "(org)%s" (or node ""))))
  18573. (defun org-browse-news ()
  18574. "Browse the news for the latest major release."
  18575. (interactive)
  18576. (browse-url "https://orgmode.org/Changes.html"))
  18577. ;;;###autoload
  18578. (defun org-submit-bug-report ()
  18579. "Submit a bug report on Org via mail.
  18580. Don't hesitate to report any problems or inaccurate documentation.
  18581. If you don't have setup sending mail from (X)Emacs, please copy the
  18582. output buffer into your mail program, as it gives us important
  18583. information about your Org version and configuration."
  18584. (interactive)
  18585. (require 'reporter)
  18586. (defvar reporter-prompt-for-summary-p)
  18587. (org-load-modules-maybe)
  18588. (org-require-autoloaded-modules)
  18589. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  18590. (reporter-submit-bug-report
  18591. "emacs-orgmode@gnu.org"
  18592. (org-version nil 'full)
  18593. (let (list)
  18594. (save-window-excursion
  18595. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  18596. (delete-other-windows)
  18597. (erase-buffer)
  18598. (insert "You are about to submit a bug report to the Org mailing list.
  18599. We would like to add your full Org and Outline configuration to the
  18600. bug report. This greatly simplifies the work of the maintainer and
  18601. other experts on the mailing list.
  18602. HOWEVER, some variables you have customized may contain private
  18603. information. The names of customers, colleagues, or friends, might
  18604. appear in the form of file names, tags, todo states, or search strings.
  18605. If you answer yes to the prompt, you might want to check and remove
  18606. such private information before sending the email.")
  18607. (add-text-properties (point-min) (point-max) '(face org-warning))
  18608. (when (yes-or-no-p "Include your Org configuration ")
  18609. (mapatoms
  18610. (lambda (v)
  18611. (and (boundp v)
  18612. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  18613. (or (and (symbol-value v)
  18614. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  18615. (and
  18616. (get v 'custom-type) (get v 'standard-value)
  18617. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  18618. (push v list)))))
  18619. (kill-buffer (get-buffer "*Warn about privacy*"))
  18620. list))
  18621. nil nil
  18622. "Remember to cover the basics, that is, what you expected to happen and
  18623. what in fact did happen. You don't know how to make a good report? See
  18624. https://orgmode.org/manual/Feedback.html#Feedback
  18625. Your bug report will be posted to the Org mailing list.
  18626. ------------------------------------------------------------------------")
  18627. (save-excursion
  18628. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  18629. (replace-match "\\1Bug: \\3 [\\2]")))))
  18630. (defun org-install-agenda-files-menu ()
  18631. (let ((bl (buffer-list)))
  18632. (save-excursion
  18633. (while bl
  18634. (set-buffer (pop bl))
  18635. (when (derived-mode-p 'org-mode) (setq bl nil)))
  18636. (when (derived-mode-p 'org-mode)
  18637. (easy-menu-change
  18638. '("Org") "File List for Agenda"
  18639. (append
  18640. (list
  18641. ["Edit File List" (org-edit-agenda-file-list) t]
  18642. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  18643. ["Remove Current File from List" org-remove-file t]
  18644. ["Cycle through agenda files" org-cycle-agenda-files t]
  18645. ["Occur in all agenda files" org-occur-in-agenda-files t]
  18646. "--")
  18647. (mapcar 'org-file-menu-entry
  18648. ;; Prevent initialization from failing.
  18649. (ignore-errors (org-agenda-files t)))))))))
  18650. ;;;; Documentation
  18651. (defun org-require-autoloaded-modules ()
  18652. (interactive)
  18653. (mapc #'require
  18654. '(org-agenda org-archive org-attach org-clock org-colview org-id
  18655. org-table org-timer)))
  18656. ;;;###autoload
  18657. (defun org-reload (&optional uncompiled)
  18658. "Reload all Org Lisp files.
  18659. With prefix arg UNCOMPILED, load the uncompiled versions."
  18660. (interactive "P")
  18661. (require 'loadhist)
  18662. (let* ((org-dir (org-find-library-dir "org"))
  18663. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  18664. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  18665. (remove-re (format "\\`%s\\'"
  18666. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  18667. (feats (delete-dups
  18668. (mapcar 'file-name-sans-extension
  18669. (mapcar 'file-name-nondirectory
  18670. (delq nil
  18671. (mapcar 'feature-file
  18672. features))))))
  18673. (lfeat (append
  18674. (sort
  18675. (setq feats
  18676. (delq nil (mapcar
  18677. (lambda (f)
  18678. (if (and (string-match feature-re f)
  18679. (not (string-match remove-re f)))
  18680. f nil))
  18681. feats)))
  18682. 'string-lessp)
  18683. (list "org-version" "org")))
  18684. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  18685. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  18686. load-uncore load-misses)
  18687. (setq load-misses
  18688. (delq 't
  18689. (mapcar (lambda (f)
  18690. (or (org-load-noerror-mustsuffix (concat org-dir f))
  18691. (and (string= org-dir contrib-dir)
  18692. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  18693. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  18694. (add-to-list 'load-uncore f 'append)
  18695. 't)
  18696. f))
  18697. lfeat)))
  18698. (when load-uncore
  18699. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  18700. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  18701. (if load-misses
  18702. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  18703. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  18704. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  18705. ;;;###autoload
  18706. (defun org-customize ()
  18707. "Call the customize function with org as argument."
  18708. (interactive)
  18709. (org-load-modules-maybe)
  18710. (org-require-autoloaded-modules)
  18711. (customize-browse 'org))
  18712. (defun org-create-customize-menu ()
  18713. "Create a full customization menu for Org mode, insert it into the menu."
  18714. (interactive)
  18715. (org-load-modules-maybe)
  18716. (org-require-autoloaded-modules)
  18717. (if (fboundp 'customize-menu-create)
  18718. (progn
  18719. (easy-menu-change
  18720. '("Org") "Customize"
  18721. `(["Browse Org group" org-customize t]
  18722. "--"
  18723. ,(customize-menu-create 'org)
  18724. ["Set" Custom-set t]
  18725. ["Save" Custom-save t]
  18726. ["Reset to Current" Custom-reset-current t]
  18727. ["Reset to Saved" Custom-reset-saved t]
  18728. ["Reset to Standard Settings" Custom-reset-standard t]))
  18729. (message "\"Org\"-menu now contains full customization menu"))
  18730. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  18731. ;;;; Miscellaneous stuff
  18732. ;;; Generally useful functions
  18733. (defun org-link-display-format (s)
  18734. "Replace links in string S with their description.
  18735. If there is no description, use the link target."
  18736. (save-match-data
  18737. (replace-regexp-in-string
  18738. org-bracket-link-analytic-regexp
  18739. (lambda (m)
  18740. (if (match-end 5) (match-string 5 m)
  18741. (concat (match-string 1 m) (match-string 3 m))))
  18742. s nil t)))
  18743. (defun org-toggle-link-display ()
  18744. "Toggle the literal or descriptive display of links."
  18745. (interactive)
  18746. (if org-descriptive-links
  18747. (remove-from-invisibility-spec '(org-link))
  18748. (add-to-invisibility-spec '(org-link)))
  18749. (org-restart-font-lock)
  18750. (setq org-descriptive-links (not org-descriptive-links)))
  18751. (defun org-in-clocktable-p ()
  18752. "Check if the cursor is in a clocktable."
  18753. (let ((pos (point)) start)
  18754. (save-excursion
  18755. (end-of-line 1)
  18756. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  18757. (setq start (match-beginning 0))
  18758. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  18759. (>= (match-end 0) pos)
  18760. start))))
  18761. (defun org-in-verbatim-emphasis ()
  18762. (save-match-data
  18763. (and (org-in-regexp org-verbatim-re 2)
  18764. (>= (point) (match-beginning 3))
  18765. (<= (point) (match-end 4)))))
  18766. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  18767. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  18768. (if (and marker (marker-buffer marker)
  18769. (buffer-live-p (marker-buffer marker)))
  18770. (progn
  18771. (pop-to-buffer-same-window (marker-buffer marker))
  18772. (when (or (> marker (point-max)) (< marker (point-min)))
  18773. (widen))
  18774. (goto-char marker)
  18775. (org-show-context 'org-goto))
  18776. (if bookmark
  18777. (bookmark-jump bookmark)
  18778. (error "Cannot find location"))))
  18779. (defun org-quote-csv-field (s)
  18780. "Quote field for inclusion in CSV material."
  18781. (if (string-match "[\",]" s)
  18782. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  18783. s))
  18784. (defun org-force-self-insert (N)
  18785. "Needed to enforce self-insert under remapping."
  18786. (interactive "p")
  18787. (self-insert-command N))
  18788. (defun org-fill-template (template alist)
  18789. "Find each %key of ALIST in TEMPLATE and replace it."
  18790. (let ((case-fold-search nil))
  18791. (dolist (entry (sort (copy-sequence alist)
  18792. (lambda (a b) (< (length (car a)) (length (car b))))))
  18793. (setq template
  18794. (replace-regexp-in-string
  18795. (concat "%" (regexp-quote (car entry)))
  18796. (or (cdr entry) "") template t t)))
  18797. template))
  18798. (defun org-quote-vert (s)
  18799. "Replace \"|\" with \"\\vert\"."
  18800. (while (string-match "|" s)
  18801. (setq s (replace-match "\\vert" t t s)))
  18802. s)
  18803. (defun org-uuidgen-p (s)
  18804. "Is S an ID created by UUIDGEN?"
  18805. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  18806. (defun org-in-src-block-p (&optional inside)
  18807. "Whether point is in a code source block.
  18808. When INSIDE is non-nil, don't consider we are within a source
  18809. block when point is at #+BEGIN_SRC or #+END_SRC."
  18810. (let ((case-fold-search t))
  18811. (or (and (eq (get-char-property (point) 'src-block) t))
  18812. (and (not inside)
  18813. (save-match-data
  18814. (save-excursion
  18815. (beginning-of-line)
  18816. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  18817. (defun org-context ()
  18818. "Return a list of contexts of the current cursor position.
  18819. If several contexts apply, all are returned.
  18820. Each context entry is a list with a symbol naming the context, and
  18821. two positions indicating start and end of the context. Possible
  18822. contexts are:
  18823. :headline anywhere in a headline
  18824. :headline-stars on the leading stars in a headline
  18825. :todo-keyword on a TODO keyword (including DONE) in a headline
  18826. :tags on the TAGS in a headline
  18827. :priority on the priority cookie in a headline
  18828. :item on the first line of a plain list item
  18829. :item-bullet on the bullet/number of a plain list item
  18830. :checkbox on the checkbox in a plain list item
  18831. :table in an Org table
  18832. :table-special on a special filed in a table
  18833. :table-table in a table.el table
  18834. :clocktable in a clocktable
  18835. :src-block in a source block
  18836. :link on a hyperlink
  18837. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  18838. :target on a <<target>>
  18839. :radio-target on a <<<radio-target>>>
  18840. :latex-fragment on a LaTeX fragment
  18841. :latex-preview on a LaTeX fragment with overlaid preview image
  18842. This function expects the position to be visible because it uses font-lock
  18843. faces as a help to recognize the following contexts: :table-special, :link,
  18844. and :keyword."
  18845. (let* ((f (get-text-property (point) 'face))
  18846. (faces (if (listp f) f (list f)))
  18847. (case-fold-search t)
  18848. (p (point)) clist o)
  18849. ;; First the large context
  18850. (cond
  18851. ((org-at-heading-p t)
  18852. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  18853. (when (progn
  18854. (beginning-of-line 1)
  18855. (looking-at org-todo-line-tags-regexp))
  18856. (push (org-point-in-group p 1 :headline-stars) clist)
  18857. (push (org-point-in-group p 2 :todo-keyword) clist)
  18858. (push (org-point-in-group p 4 :tags) clist))
  18859. (goto-char p)
  18860. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  18861. (when (looking-at "\\[#[A-Z0-9]\\]")
  18862. (push (org-point-in-group p 0 :priority) clist)))
  18863. ((org-at-item-p)
  18864. (push (org-point-in-group p 2 :item-bullet) clist)
  18865. (push (list :item (point-at-bol)
  18866. (save-excursion (org-end-of-item) (point)))
  18867. clist)
  18868. (and (org-at-item-checkbox-p)
  18869. (push (org-point-in-group p 0 :checkbox) clist)))
  18870. ((org-at-table-p)
  18871. (push (list :table (org-table-begin) (org-table-end)) clist)
  18872. (when (memq 'org-formula faces)
  18873. (push (list :table-special
  18874. (previous-single-property-change p 'face)
  18875. (next-single-property-change p 'face)) clist)))
  18876. ((org-at-table-p 'any)
  18877. (push (list :table-table) clist)))
  18878. (goto-char p)
  18879. (let ((case-fold-search t))
  18880. ;; New the "medium" contexts: clocktables, source blocks
  18881. (cond ((org-in-clocktable-p)
  18882. (push (list :clocktable
  18883. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  18884. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  18885. (match-beginning 1))
  18886. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  18887. (match-end 0))) clist))
  18888. ((org-in-src-block-p)
  18889. (push (list :src-block
  18890. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  18891. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  18892. (match-beginning 1))
  18893. (and (search-forward "#+END_SRC" nil t)
  18894. (match-beginning 0))) clist))))
  18895. (goto-char p)
  18896. ;; Now the small context
  18897. (cond
  18898. ((org-at-timestamp-p)
  18899. (push (org-point-in-group p 0 :timestamp) clist))
  18900. ((memq 'org-link faces)
  18901. (push (list :link
  18902. (previous-single-property-change p 'face)
  18903. (next-single-property-change p 'face)) clist))
  18904. ((memq 'org-special-keyword faces)
  18905. (push (list :keyword
  18906. (previous-single-property-change p 'face)
  18907. (next-single-property-change p 'face)) clist))
  18908. ((org-at-target-p)
  18909. (push (org-point-in-group p 0 :target) clist)
  18910. (goto-char (1- (match-beginning 0)))
  18911. (when (looking-at org-radio-target-regexp)
  18912. (push (org-point-in-group p 0 :radio-target) clist))
  18913. (goto-char p))
  18914. ((setq o (cl-some
  18915. (lambda (o)
  18916. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  18917. o))
  18918. (overlays-at (point))))
  18919. (push (list :latex-fragment
  18920. (overlay-start o) (overlay-end o)) clist)
  18921. (push (list :latex-preview
  18922. (overlay-start o) (overlay-end o)) clist))
  18923. ((org-inside-LaTeX-fragment-p)
  18924. ;; FIXME: positions wrong.
  18925. (push (list :latex-fragment (point) (point)) clist)))
  18926. (setq clist (nreverse (delq nil clist)))
  18927. clist))
  18928. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  18929. "Non-nil when point is between matches of START-RE and END-RE.
  18930. Also return a non-nil value when point is on one of the matches.
  18931. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  18932. buffer positions. Default values are the positions of headlines
  18933. surrounding the point.
  18934. The functions returns a cons cell whose car (resp. cdr) is the
  18935. position before START-RE (resp. after END-RE)."
  18936. (save-match-data
  18937. (let ((pos (point))
  18938. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  18939. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  18940. beg end)
  18941. (save-excursion
  18942. ;; Point is on a block when on START-RE or if START-RE can be
  18943. ;; found before it...
  18944. (and (or (org-in-regexp start-re)
  18945. (re-search-backward start-re limit-up t))
  18946. (setq beg (match-beginning 0))
  18947. ;; ... and END-RE after it...
  18948. (goto-char (match-end 0))
  18949. (re-search-forward end-re limit-down t)
  18950. (> (setq end (match-end 0)) pos)
  18951. ;; ... without another START-RE in-between.
  18952. (goto-char (match-beginning 0))
  18953. (not (re-search-backward start-re (1+ beg) t))
  18954. ;; Return value.
  18955. (cons beg end))))))
  18956. (defun org-in-block-p (names)
  18957. "Non-nil when point belongs to a block whose name belongs to NAMES.
  18958. NAMES is a list of strings containing names of blocks.
  18959. Return first block name matched, or nil. Beware that in case of
  18960. nested blocks, the returned name may not belong to the closest
  18961. block from point."
  18962. (save-match-data
  18963. (catch 'exit
  18964. (let ((case-fold-search t)
  18965. (lim-up (save-excursion (outline-previous-heading)))
  18966. (lim-down (save-excursion (outline-next-heading))))
  18967. (dolist (name names)
  18968. (let ((n (regexp-quote name)))
  18969. (when (org-between-regexps-p
  18970. (concat "^[ \t]*#\\+begin_" n)
  18971. (concat "^[ \t]*#\\+end_" n)
  18972. lim-up lim-down)
  18973. (throw 'exit n)))))
  18974. nil)))
  18975. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  18976. "Call `multi-occur' with buffers for all agenda files."
  18977. (interactive "sOrg-files matching: ")
  18978. (let* ((files (org-agenda-files))
  18979. (tnames (mapcar #'file-truename files))
  18980. (extra org-agenda-text-search-extra-files))
  18981. (when (eq (car extra) 'agenda-archives)
  18982. (setq extra (cdr extra))
  18983. (setq files (org-add-archive-files files)))
  18984. (dolist (f extra)
  18985. (unless (member (file-truename f) tnames)
  18986. (unless (member f files) (setq files (append files (list f))))
  18987. (setq tnames (append tnames (list (file-truename f))))))
  18988. (multi-occur
  18989. (mapcar (lambda (x)
  18990. (with-current-buffer
  18991. ;; FIXME: Why not just (find-file-noselect x)?
  18992. ;; Is it to avoid the "revert buffer" prompt?
  18993. (or (get-file-buffer x) (find-file-noselect x))
  18994. (widen)
  18995. (current-buffer)))
  18996. files)
  18997. regexp)))
  18998. (add-hook 'occur-mode-find-occurrence-hook
  18999. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  19000. (defun org-occur-link-in-agenda-files ()
  19001. "Create a link and search for it in the agendas.
  19002. The link is not stored in `org-stored-links', it is just created
  19003. for the search purpose."
  19004. (interactive)
  19005. (let ((link (condition-case nil
  19006. (org-store-link nil)
  19007. (error "Unable to create a link to here"))))
  19008. (org-occur-in-agenda-files (regexp-quote link))))
  19009. (defun org-back-over-empty-lines ()
  19010. "Move backwards over whitespace, to the beginning of the first empty line.
  19011. Returns the number of empty lines passed."
  19012. (let ((pos (point)))
  19013. (if (cdr (assq 'heading org-blank-before-new-entry))
  19014. (skip-chars-backward " \t\n\r")
  19015. (unless (eobp)
  19016. (forward-line -1)))
  19017. (beginning-of-line 2)
  19018. (goto-char (min (point) pos))
  19019. (count-lines (point) pos)))
  19020. (defun org-replace-escapes (string table)
  19021. "Replace %-escapes in STRING with values in TABLE.
  19022. TABLE is an association list with keys like \"%a\" and string values.
  19023. The sequences in STRING may contain normal field width and padding information,
  19024. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  19025. so values can contain further %-escapes if they are define later in TABLE."
  19026. (let ((tbl (copy-alist table))
  19027. (case-fold-search nil)
  19028. (pchg 0)
  19029. re rpl)
  19030. (dolist (e tbl)
  19031. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  19032. (when (and (cdr e) (string-match re (cdr e)))
  19033. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  19034. (safe "SREF"))
  19035. (add-text-properties 0 3 (list 'sref sref) safe)
  19036. (setcdr e (replace-match safe t t (cdr e)))))
  19037. (while (string-match re string)
  19038. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  19039. (cdr e)))
  19040. (setq string (replace-match rpl t t string))))
  19041. (while (setq pchg (next-property-change pchg string))
  19042. (let ((sref (get-text-property pchg 'sref string)))
  19043. (when (and sref (string-match "SREF" string pchg))
  19044. (setq string (replace-match sref t t string)))))
  19045. string))
  19046. ;;; TODO: Only called once, from ox-odt which should probably use
  19047. ;;; org-export-inline-image-p or something.
  19048. (defun org-file-image-p (file)
  19049. "Return non-nil if FILE is an image."
  19050. (save-match-data
  19051. (string-match (image-file-name-regexp) file)))
  19052. (defun org-get-cursor-date (&optional with-time)
  19053. "Return the date at cursor in as a time.
  19054. This works in the calendar and in the agenda, anywhere else it just
  19055. returns the current time.
  19056. If WITH-TIME is non-nil, returns the time of the event at point (in
  19057. the agenda) or the current time of the day."
  19058. (let (date day defd tp hod mod)
  19059. (when with-time
  19060. (setq tp (get-text-property (point) 'time))
  19061. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  19062. (setq hod (string-to-number (match-string 1 tp))
  19063. mod (string-to-number (match-string 2 tp))))
  19064. (or tp (let ((now (decode-time)))
  19065. (setq hod (nth 2 now)
  19066. mod (nth 1 now)))))
  19067. (cond
  19068. ((eq major-mode 'calendar-mode)
  19069. (setq date (calendar-cursor-to-date)
  19070. defd (encode-time 0 (or mod 0) (or hod 0)
  19071. (nth 1 date) (nth 0 date) (nth 2 date))))
  19072. ((eq major-mode 'org-agenda-mode)
  19073. (setq day (get-text-property (point) 'day))
  19074. (when day
  19075. (setq date (calendar-gregorian-from-absolute day)
  19076. defd (encode-time 0 (or mod 0) (or hod 0)
  19077. (nth 1 date) (nth 0 date) (nth 2 date))))))
  19078. (or defd (current-time))))
  19079. (defun org-mark-subtree (&optional up)
  19080. "Mark the current subtree.
  19081. This puts point at the start of the current subtree, and mark at
  19082. the end. If a numeric prefix UP is given, move up into the
  19083. hierarchy of headlines by UP levels before marking the subtree."
  19084. (interactive "P")
  19085. (org-with-limited-levels
  19086. (cond ((org-at-heading-p) (beginning-of-line))
  19087. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  19088. (t (outline-previous-visible-heading 1))))
  19089. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  19090. (if (called-interactively-p 'any)
  19091. (call-interactively 'org-mark-element)
  19092. (org-mark-element)))
  19093. ;;; Indentation
  19094. (defvar org-element-greater-elements)
  19095. (defun org--get-expected-indentation (element contentsp)
  19096. "Expected indentation column for current line, according to ELEMENT.
  19097. ELEMENT is an element containing point. CONTENTSP is non-nil
  19098. when indentation is to be computed according to contents of
  19099. ELEMENT."
  19100. (let ((type (org-element-type element))
  19101. (start (org-element-property :begin element))
  19102. (post-affiliated (org-element-property :post-affiliated element)))
  19103. (org-with-wide-buffer
  19104. (cond
  19105. (contentsp
  19106. (cl-case type
  19107. ((diary-sexp footnote-definition) 0)
  19108. ((headline inlinetask nil)
  19109. (if (not org-adapt-indentation) 0
  19110. (let ((level (org-current-level)))
  19111. (if level (1+ level) 0))))
  19112. ((item plain-list) (org-list-item-body-column post-affiliated))
  19113. (t
  19114. (goto-char start)
  19115. (current-indentation))))
  19116. ((memq type '(headline inlinetask nil))
  19117. (if (org-match-line "[ \t]*$")
  19118. (org--get-expected-indentation element t)
  19119. 0))
  19120. ((memq type '(diary-sexp footnote-definition)) 0)
  19121. ;; First paragraph of a footnote definition or an item.
  19122. ;; Indent like parent.
  19123. ((< (line-beginning-position) start)
  19124. (org--get-expected-indentation
  19125. (org-element-property :parent element) t))
  19126. ;; At first line: indent according to previous sibling, if any,
  19127. ;; ignoring footnote definitions and inline tasks, or parent's
  19128. ;; contents.
  19129. ((= (line-beginning-position) start)
  19130. (catch 'exit
  19131. (while t
  19132. (if (= (point-min) start) (throw 'exit 0)
  19133. (goto-char (1- start))
  19134. (let* ((previous (org-element-at-point))
  19135. (parent previous))
  19136. (while (and parent (<= (org-element-property :end parent) start))
  19137. (setq previous parent
  19138. parent (org-element-property :parent parent)))
  19139. (cond
  19140. ((not previous) (throw 'exit 0))
  19141. ((> (org-element-property :end previous) start)
  19142. (throw 'exit (org--get-expected-indentation previous t)))
  19143. ((memq (org-element-type previous)
  19144. '(footnote-definition inlinetask))
  19145. (setq start (org-element-property :begin previous)))
  19146. (t (goto-char (org-element-property :begin previous))
  19147. (throw 'exit
  19148. (if (bolp) (current-indentation)
  19149. ;; At first paragraph in an item or
  19150. ;; a footnote definition.
  19151. (org--get-expected-indentation
  19152. (org-element-property :parent previous) t))))))))))
  19153. ;; Otherwise, move to the first non-blank line above.
  19154. (t
  19155. (beginning-of-line)
  19156. (let ((pos (point)))
  19157. (skip-chars-backward " \r\t\n")
  19158. (cond
  19159. ;; Two blank lines end a footnote definition or a plain
  19160. ;; list. When we indent an empty line after them, the
  19161. ;; containing list or footnote definition is over, so it
  19162. ;; qualifies as a previous sibling. Therefore, we indent
  19163. ;; like its first line.
  19164. ((and (memq type '(footnote-definition plain-list))
  19165. (> (count-lines (point) pos) 2))
  19166. (goto-char start)
  19167. (current-indentation))
  19168. ;; Line above is the first one of a paragraph at the
  19169. ;; beginning of an item or a footnote definition. Indent
  19170. ;; like parent.
  19171. ((< (line-beginning-position) start)
  19172. (org--get-expected-indentation
  19173. (org-element-property :parent element) t))
  19174. ;; Line above is the beginning of an element, i.e., point
  19175. ;; was originally on the blank lines between element's start
  19176. ;; and contents.
  19177. ((= (line-beginning-position) post-affiliated)
  19178. (org--get-expected-indentation element t))
  19179. ;; POS is after contents in a greater element. Indent like
  19180. ;; the beginning of the element.
  19181. ((and (memq type org-element-greater-elements)
  19182. (let ((cend (org-element-property :contents-end element)))
  19183. (and cend (<= cend pos))))
  19184. ;; As a special case, if point is at the end of a footnote
  19185. ;; definition or an item, indent like the very last element
  19186. ;; within. If that last element is an item, indent like
  19187. ;; its contents.
  19188. (if (memq type '(footnote-definition item plain-list))
  19189. (let ((last (org-element-at-point)))
  19190. (goto-char pos)
  19191. (org--get-expected-indentation
  19192. last (eq (org-element-type last) 'item)))
  19193. (goto-char start)
  19194. (current-indentation)))
  19195. ;; In any other case, indent like the current line.
  19196. (t (current-indentation)))))))))
  19197. (defun org--align-node-property ()
  19198. "Align node property at point.
  19199. Alignment is done according to `org-property-format', which see."
  19200. (when (save-excursion
  19201. (beginning-of-line)
  19202. (looking-at org-property-re))
  19203. (replace-match
  19204. (concat (match-string 4)
  19205. (org-trim
  19206. (format org-property-format (match-string 1) (match-string 3))))
  19207. t t)))
  19208. (defun org-indent-line ()
  19209. "Indent line depending on context.
  19210. Indentation is done according to the following rules:
  19211. - Footnote definitions, diary sexps, headlines and inline tasks
  19212. have to start at column 0.
  19213. - On the very first line of an element, consider, in order, the
  19214. next rules until one matches:
  19215. 1. If there's a sibling element before, ignoring footnote
  19216. definitions and inline tasks, indent like its first line.
  19217. 2. If element has a parent, indent like its contents. More
  19218. precisely, if parent is an item, indent after the
  19219. description part, if any, or the bullet (see
  19220. `org-list-description-max-indent'). Else, indent like
  19221. parent's first line.
  19222. 3. Otherwise, indent relatively to current level, if
  19223. `org-adapt-indentation' is non-nil, or to left margin.
  19224. - On a blank line at the end of an element, indent according to
  19225. the type of the element. More precisely
  19226. 1. If element is a plain list, an item, or a footnote
  19227. definition, indent like the very last element within.
  19228. 2. If element is a paragraph, indent like its last non blank
  19229. line.
  19230. 3. Otherwise, indent like its very first line.
  19231. - In the code part of a source block, use language major mode
  19232. to indent current line if `org-src-tab-acts-natively' is
  19233. non-nil. If it is nil, do nothing.
  19234. - Otherwise, indent like the first non-blank line above.
  19235. The function doesn't indent an item as it could break the whole
  19236. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  19237. `\\[org-shiftmetaright]'.
  19238. Also align node properties according to `org-property-format'."
  19239. (interactive)
  19240. (cond
  19241. ((org-at-heading-p) 'noindent)
  19242. (t
  19243. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  19244. (type (org-element-type element)))
  19245. (cond ((and (memq type '(plain-list item))
  19246. (= (line-beginning-position)
  19247. (org-element-property :post-affiliated element)))
  19248. 'noindent)
  19249. ((and (eq type 'latex-environment)
  19250. (>= (point) (org-element-property :post-affiliated element))
  19251. (< (point) (org-with-wide-buffer
  19252. (goto-char (org-element-property :end element))
  19253. (skip-chars-backward " \r\t\n")
  19254. (line-beginning-position 2))))
  19255. 'noindent)
  19256. ((and (eq type 'src-block)
  19257. org-src-tab-acts-natively
  19258. (> (line-beginning-position)
  19259. (org-element-property :post-affiliated element))
  19260. (< (line-beginning-position)
  19261. (org-with-wide-buffer
  19262. (goto-char (org-element-property :end element))
  19263. (skip-chars-backward " \r\t\n")
  19264. (line-beginning-position))))
  19265. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  19266. (t
  19267. (let ((column (org--get-expected-indentation element nil)))
  19268. ;; Preserve current column.
  19269. (if (<= (current-column) (current-indentation))
  19270. (indent-line-to column)
  19271. (save-excursion (indent-line-to column))))
  19272. ;; Align node property. Also preserve current column.
  19273. (when (eq type 'node-property)
  19274. (let ((column (current-column)))
  19275. (org--align-node-property)
  19276. (org-move-to-column column)))))))))
  19277. (defun org-indent-region (start end)
  19278. "Indent each non-blank line in the region.
  19279. Called from a program, START and END specify the region to
  19280. indent. The function will not indent contents of example blocks,
  19281. verse blocks and export blocks as leading white spaces are
  19282. assumed to be significant there."
  19283. (interactive "r")
  19284. (save-excursion
  19285. (goto-char start)
  19286. (skip-chars-forward " \r\t\n")
  19287. (unless (eobp) (beginning-of-line))
  19288. (let ((indent-to
  19289. (lambda (ind pos)
  19290. ;; Set IND as indentation for all lines between point and
  19291. ;; POS. Blank lines are ignored. Leave point after POS
  19292. ;; once done.
  19293. (let ((limit (copy-marker pos)))
  19294. (while (< (point) limit)
  19295. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  19296. (forward-line))
  19297. (set-marker limit nil))))
  19298. (end (copy-marker end)))
  19299. (while (< (point) end)
  19300. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  19301. (let* ((element (org-element-at-point))
  19302. (type (org-element-type element))
  19303. (element-end (copy-marker (org-element-property :end element)))
  19304. (ind (org--get-expected-indentation element nil)))
  19305. (cond
  19306. ;; Element indented as a single block. Example blocks
  19307. ;; preserving indentation are a special case since the
  19308. ;; "contents" must not be indented whereas the block
  19309. ;; boundaries can.
  19310. ((or (memq type '(export-block latex-environment))
  19311. (and (eq type 'example-block)
  19312. (not
  19313. (or org-src-preserve-indentation
  19314. (org-element-property :preserve-indent element)))))
  19315. (let ((offset (- ind (current-indentation))))
  19316. (unless (zerop offset)
  19317. (indent-rigidly (org-element-property :begin element)
  19318. (org-element-property :end element)
  19319. offset)))
  19320. (goto-char element-end))
  19321. ;; Elements indented line wise. Be sure to exclude
  19322. ;; example blocks (preserving indentation) and source
  19323. ;; blocks from this category as they are treated
  19324. ;; specially later.
  19325. ((or (memq type '(paragraph table table-row))
  19326. (not (or (org-element-property :contents-begin element)
  19327. (memq type '(example-block src-block)))))
  19328. (when (eq type 'node-property)
  19329. (org--align-node-property)
  19330. (beginning-of-line))
  19331. (funcall indent-to ind (min element-end end)))
  19332. ;; Elements consisting of three parts: before the
  19333. ;; contents, the contents, and after the contents. The
  19334. ;; contents are treated specially, according to the
  19335. ;; element type, or not indented at all. Other parts are
  19336. ;; indented as a single block.
  19337. (t
  19338. (let* ((post (copy-marker
  19339. (org-element-property :post-affiliated element)))
  19340. (cbeg
  19341. (copy-marker
  19342. (cond
  19343. ((not (org-element-property :contents-begin element))
  19344. ;; Fake contents for source blocks.
  19345. (org-with-wide-buffer
  19346. (goto-char post)
  19347. (line-beginning-position 2)))
  19348. ((memq type '(footnote-definition item plain-list))
  19349. ;; Contents in these elements could start on
  19350. ;; the same line as the beginning of the
  19351. ;; element. Make sure we start indenting
  19352. ;; from the second line.
  19353. (org-with-wide-buffer
  19354. (goto-char post)
  19355. (end-of-line)
  19356. (skip-chars-forward " \r\t\n")
  19357. (if (eobp) (point) (line-beginning-position))))
  19358. (t (org-element-property :contents-begin element)))))
  19359. (cend (copy-marker
  19360. (or (org-element-property :contents-end element)
  19361. ;; Fake contents for source blocks.
  19362. (org-with-wide-buffer
  19363. (goto-char element-end)
  19364. (skip-chars-backward " \r\t\n")
  19365. (line-beginning-position)))
  19366. t)))
  19367. ;; Do not change items indentation individually as it
  19368. ;; might break the list as a whole. On the other
  19369. ;; hand, when at a plain list, indent it as a whole.
  19370. (cond ((eq type 'plain-list)
  19371. (let ((offset (- ind (current-indentation))))
  19372. (unless (zerop offset)
  19373. (indent-rigidly (org-element-property :begin element)
  19374. (org-element-property :end element)
  19375. offset))
  19376. (goto-char cbeg)))
  19377. ((eq type 'item) (goto-char cbeg))
  19378. (t (funcall indent-to ind (min cbeg end))))
  19379. (when (< (point) end)
  19380. (cl-case type
  19381. ((example-block verse-block))
  19382. (src-block
  19383. ;; In a source block, indent source code
  19384. ;; according to language major mode, but only if
  19385. ;; `org-src-tab-acts-natively' is non-nil.
  19386. (when (and (< (point) end) org-src-tab-acts-natively)
  19387. (ignore-errors
  19388. (org-babel-do-in-edit-buffer
  19389. (indent-region (point-min) (point-max))))))
  19390. (t (org-indent-region (point) (min cend end))))
  19391. (goto-char (min cend end))
  19392. (when (< (point) end)
  19393. (funcall indent-to ind (min element-end end))))
  19394. (set-marker post nil)
  19395. (set-marker cbeg nil)
  19396. (set-marker cend nil))))
  19397. (set-marker element-end nil))))
  19398. (set-marker end nil))))
  19399. (defun org-indent-drawer ()
  19400. "Indent the drawer at point."
  19401. (interactive)
  19402. (unless (save-excursion
  19403. (beginning-of-line)
  19404. (looking-at-p org-drawer-regexp))
  19405. (user-error "Not at a drawer"))
  19406. (let ((element (org-element-at-point)))
  19407. (unless (memq (org-element-type element) '(drawer property-drawer))
  19408. (user-error "Not at a drawer"))
  19409. (org-with-wide-buffer
  19410. (org-indent-region (org-element-property :begin element)
  19411. (org-element-property :end element))))
  19412. (message "Drawer at point indented"))
  19413. (defun org-indent-block ()
  19414. "Indent the block at point."
  19415. (interactive)
  19416. (unless (save-excursion
  19417. (beginning-of-line)
  19418. (let ((case-fold-search t))
  19419. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  19420. (user-error "Not at a block"))
  19421. (let ((element (org-element-at-point)))
  19422. (unless (memq (org-element-type element)
  19423. '(comment-block center-block dynamic-block example-block
  19424. export-block quote-block special-block
  19425. src-block verse-block))
  19426. (user-error "Not at a block"))
  19427. (org-with-wide-buffer
  19428. (org-indent-region (org-element-property :begin element)
  19429. (org-element-property :end element))))
  19430. (message "Block at point indented"))
  19431. ;;; Filling
  19432. ;; We use our own fill-paragraph and auto-fill functions.
  19433. ;; `org-fill-paragraph' relies on adaptive filling and context
  19434. ;; checking. Appropriate `fill-prefix' is computed with
  19435. ;; `org-adaptive-fill-function'.
  19436. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  19437. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  19438. ;; `org-adaptive-fill-function' value. Internally,
  19439. ;; `org-comment-line-break-function' breaks the line.
  19440. ;; `org-setup-filling' installs filling and auto-filling related
  19441. ;; variables during `org-mode' initialization.
  19442. (defun org-setup-filling ()
  19443. (require 'org-element)
  19444. ;; Prevent auto-fill from inserting unwanted new items.
  19445. (when (boundp 'fill-nobreak-predicate)
  19446. (setq-local
  19447. fill-nobreak-predicate
  19448. (org-uniquify
  19449. (append fill-nobreak-predicate
  19450. '(org-fill-line-break-nobreak-p
  19451. org-fill-n-macro-as-item-nobreak-p
  19452. org-fill-paragraph-with-timestamp-nobreak-p)))))
  19453. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  19454. (setq-local paragraph-start paragraph-ending)
  19455. (setq-local paragraph-separate paragraph-ending))
  19456. (setq-local fill-paragraph-function 'org-fill-paragraph)
  19457. (setq-local auto-fill-inhibit-regexp nil)
  19458. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  19459. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  19460. (setq-local comment-line-break-function 'org-comment-line-break-function))
  19461. (defun org-fill-line-break-nobreak-p ()
  19462. "Non-nil when a new line at point would create an Org line break."
  19463. (save-excursion
  19464. (skip-chars-backward "[ \t]")
  19465. (skip-chars-backward "\\\\")
  19466. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  19467. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  19468. "Non-nil when a new line at point would split a timestamp."
  19469. (and (org-at-timestamp-p 'lax)
  19470. (not (looking-at org-ts-regexp-both))))
  19471. (defun org-fill-n-macro-as-item-nobreak-p ()
  19472. "Non-nil when a new line at point would create a new list."
  19473. ;; During export, a "n" macro followed by a dot or a closing
  19474. ;; parenthesis can end up being parsed as a new list item.
  19475. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  19476. (defvar orgtbl-line-start-regexp) ; From org-table.el
  19477. (defun org-adaptive-fill-function ()
  19478. "Compute a fill prefix for the current line.
  19479. Return fill prefix, as a string, or nil if current line isn't
  19480. meant to be filled. For convenience, if `adaptive-fill-regexp'
  19481. matches in paragraphs or comments, use it."
  19482. (org-with-wide-buffer
  19483. (unless (org-at-heading-p)
  19484. (let* ((p (line-beginning-position))
  19485. (element (save-excursion
  19486. (beginning-of-line)
  19487. (org-element-at-point)))
  19488. (type (org-element-type element))
  19489. (post-affiliated (org-element-property :post-affiliated element)))
  19490. (unless (< p post-affiliated)
  19491. (cl-case type
  19492. (comment
  19493. (save-excursion
  19494. (beginning-of-line)
  19495. (looking-at "[ \t]*")
  19496. (concat (match-string 0) "# ")))
  19497. (footnote-definition "")
  19498. ((item plain-list)
  19499. (make-string (org-list-item-body-column post-affiliated) ?\s))
  19500. (paragraph
  19501. ;; Fill prefix is usually the same as the current line,
  19502. ;; unless the paragraph is at the beginning of an item.
  19503. (let ((parent (org-element-property :parent element)))
  19504. (save-excursion
  19505. (beginning-of-line)
  19506. (cond ((eq (org-element-type parent) 'item)
  19507. (make-string (org-list-item-body-column
  19508. (org-element-property :begin parent))
  19509. ?\s))
  19510. ((and adaptive-fill-regexp
  19511. ;; Locally disable
  19512. ;; `adaptive-fill-function' to let
  19513. ;; `fill-context-prefix' handle
  19514. ;; `adaptive-fill-regexp' variable.
  19515. (let (adaptive-fill-function)
  19516. (fill-context-prefix
  19517. post-affiliated
  19518. (org-element-property :end element)))))
  19519. ((looking-at "[ \t]+") (match-string 0))
  19520. (t "")))))
  19521. (comment-block
  19522. ;; Only fill contents if P is within block boundaries.
  19523. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  19524. (forward-line)
  19525. (point)))
  19526. (cend (save-excursion
  19527. (goto-char (org-element-property :end element))
  19528. (skip-chars-backward " \r\t\n")
  19529. (line-beginning-position))))
  19530. (when (and (>= p cbeg) (< p cend))
  19531. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  19532. (match-string 0)
  19533. ""))))))))))
  19534. (defun org-fill-element (&optional justify)
  19535. "Fill element at point, when applicable.
  19536. This function only applies to comment blocks, comments, example
  19537. blocks and paragraphs. Also, as a special case, re-align table
  19538. when point is at one.
  19539. If JUSTIFY is non-nil (interactively, with prefix argument),
  19540. justify as well. If `sentence-end-double-space' is non-nil, then
  19541. period followed by one space does not end a sentence, so don't
  19542. break a line there. The variable `fill-column' controls the
  19543. width for filling.
  19544. For convenience, when point is at a plain list, an item or
  19545. a footnote definition, try to fill the first paragraph within."
  19546. (with-syntax-table org-mode-transpose-word-syntax-table
  19547. ;; Move to end of line in order to get the first paragraph within
  19548. ;; a plain list or a footnote definition.
  19549. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  19550. ;; First check if point is in a blank line at the beginning of
  19551. ;; the buffer. In that case, ignore filling.
  19552. (cl-case (org-element-type element)
  19553. ;; Use major mode filling function is source blocks.
  19554. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  19555. ;; Align Org tables, leave table.el tables as-is.
  19556. (table-row (org-table-align) t)
  19557. (table
  19558. (when (eq (org-element-property :type element) 'org)
  19559. (save-excursion
  19560. (goto-char (org-element-property :post-affiliated element))
  19561. (org-table-align)))
  19562. t)
  19563. (paragraph
  19564. ;; Paragraphs may contain `line-break' type objects.
  19565. (let ((beg (max (point-min)
  19566. (org-element-property :contents-begin element)))
  19567. (end (min (point-max)
  19568. (org-element-property :contents-end element))))
  19569. ;; Do nothing if point is at an affiliated keyword.
  19570. (if (< (line-end-position) beg) t
  19571. ;; Fill paragraph, taking line breaks into account.
  19572. (save-excursion
  19573. (goto-char beg)
  19574. (let ((cuts (list beg)))
  19575. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  19576. (when (eq 'line-break
  19577. (org-element-type
  19578. (save-excursion (backward-char)
  19579. (org-element-context))))
  19580. (push (point) cuts)))
  19581. (dolist (c (delq end cuts))
  19582. (fill-region-as-paragraph c end justify)
  19583. (setq end c))))
  19584. t)))
  19585. ;; Contents of `comment-block' type elements should be
  19586. ;; filled as plain text, but only if point is within block
  19587. ;; markers.
  19588. (comment-block
  19589. (let* ((case-fold-search t)
  19590. (beg (save-excursion
  19591. (goto-char (org-element-property :begin element))
  19592. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  19593. (forward-line)
  19594. (point)))
  19595. (end (save-excursion
  19596. (goto-char (org-element-property :end element))
  19597. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  19598. (line-beginning-position))))
  19599. (if (or (< (point) beg) (> (point) end)) t
  19600. (fill-region-as-paragraph
  19601. (save-excursion (end-of-line)
  19602. (re-search-backward "^[ \t]*$" beg 'move)
  19603. (line-beginning-position))
  19604. (save-excursion (beginning-of-line)
  19605. (re-search-forward "^[ \t]*$" end 'move)
  19606. (line-beginning-position))
  19607. justify))))
  19608. ;; Fill comments.
  19609. (comment
  19610. (let ((begin (org-element-property :post-affiliated element))
  19611. (end (org-element-property :end element)))
  19612. (when (and (>= (point) begin) (<= (point) end))
  19613. (let ((begin (save-excursion
  19614. (end-of-line)
  19615. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  19616. (progn (forward-line) (point))
  19617. begin)))
  19618. (end (save-excursion
  19619. (end-of-line)
  19620. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  19621. (1- (line-beginning-position))
  19622. (skip-chars-backward " \r\t\n")
  19623. (line-end-position)))))
  19624. ;; Do not fill comments when at a blank line.
  19625. (when (> end begin)
  19626. (let ((fill-prefix
  19627. (save-excursion
  19628. (beginning-of-line)
  19629. (looking-at "[ \t]*#")
  19630. (let ((comment-prefix (match-string 0)))
  19631. (goto-char (match-end 0))
  19632. (if (looking-at adaptive-fill-regexp)
  19633. (concat comment-prefix (match-string 0))
  19634. (concat comment-prefix " "))))))
  19635. (save-excursion
  19636. (fill-region-as-paragraph begin end justify))))))
  19637. t))
  19638. ;; Ignore every other element.
  19639. (otherwise t)))))
  19640. (defun org-fill-paragraph (&optional justify region)
  19641. "Fill element at point, when applicable.
  19642. This function only applies to comment blocks, comments, example
  19643. blocks and paragraphs. Also, as a special case, re-align table
  19644. when point is at one.
  19645. For convenience, when point is at a plain list, an item or
  19646. a footnote definition, try to fill the first paragraph within.
  19647. If JUSTIFY is non-nil (interactively, with prefix argument),
  19648. justify as well. If `sentence-end-double-space' is non-nil, then
  19649. period followed by one space does not end a sentence, so don't
  19650. break a line there. The variable `fill-column' controls the
  19651. width for filling.
  19652. The REGION argument is non-nil if called interactively; in that
  19653. case, if Transient Mark mode is enabled and the mark is active,
  19654. fill each of the elements in the active region, instead of just
  19655. filling the current element."
  19656. (interactive (progn
  19657. (barf-if-buffer-read-only)
  19658. (list (when current-prefix-arg 'full) t)))
  19659. (let ((hash (and (not (buffer-modified-p))
  19660. (org-buffer-hash))))
  19661. (cond
  19662. ((and region transient-mark-mode mark-active
  19663. (not (eq (region-beginning) (region-end))))
  19664. (let ((origin (point-marker))
  19665. (start (region-beginning)))
  19666. (unwind-protect
  19667. (progn
  19668. (goto-char (region-end))
  19669. (while (> (point) start)
  19670. (org-backward-paragraph)
  19671. (org-fill-element justify)))
  19672. (goto-char origin)
  19673. (set-marker origin nil))))
  19674. (t (org-fill-element justify)))
  19675. ;; If we didn't change anything in the buffer (and the buffer was
  19676. ;; previously unmodified), then flip the modification status back
  19677. ;; to "unchanged".
  19678. (when (and hash (equal hash (org-buffer-hash)))
  19679. (set-buffer-modified-p nil))))
  19680. (defun org-auto-fill-function ()
  19681. "Auto-fill function."
  19682. ;; Check if auto-filling is meaningful.
  19683. (let ((fc (current-fill-column)))
  19684. (when (and fc (> (current-column) fc))
  19685. (let* ((fill-prefix (org-adaptive-fill-function))
  19686. ;; Enforce empty fill prefix, if required. Otherwise, it
  19687. ;; will be computed again.
  19688. (adaptive-fill-mode (not (equal fill-prefix ""))))
  19689. (when fill-prefix (do-auto-fill))))))
  19690. (defun org-comment-line-break-function (&optional soft)
  19691. "Break line at point and indent, continuing comment if within one.
  19692. The inserted newline is marked hard if variable
  19693. `use-hard-newlines' is true, unless optional argument SOFT is
  19694. non-nil."
  19695. (if soft (insert-and-inherit ?\n) (newline 1))
  19696. (save-excursion (forward-char -1) (delete-horizontal-space))
  19697. (delete-horizontal-space)
  19698. (indent-to-left-margin)
  19699. (insert-before-markers-and-inherit fill-prefix))
  19700. ;;; Fixed Width Areas
  19701. (defun org-toggle-fixed-width ()
  19702. "Toggle fixed-width markup.
  19703. Add or remove fixed-width markup on current line, whenever it
  19704. makes sense. Return an error otherwise.
  19705. If a region is active and if it contains only fixed-width areas
  19706. or blank lines, remove all fixed-width markup in it. If the
  19707. region contains anything else, convert all non-fixed-width lines
  19708. to fixed-width ones.
  19709. Blank lines at the end of the region are ignored unless the
  19710. region only contains such lines."
  19711. (interactive)
  19712. (if (not (org-region-active-p))
  19713. ;; No region:
  19714. ;;
  19715. ;; Remove fixed width marker only in a fixed-with element.
  19716. ;;
  19717. ;; Add fixed width maker in paragraphs, in blank lines after
  19718. ;; elements or at the beginning of a headline or an inlinetask,
  19719. ;; and before any one-line elements (e.g., a clock).
  19720. (progn
  19721. (beginning-of-line)
  19722. (let* ((element (org-element-at-point))
  19723. (type (org-element-type element)))
  19724. (cond
  19725. ((and (eq type 'fixed-width)
  19726. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  19727. (replace-match
  19728. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  19729. ((and (memq type '(babel-call clock comment diary-sexp headline
  19730. horizontal-rule keyword paragraph
  19731. planning))
  19732. (<= (org-element-property :post-affiliated element) (point)))
  19733. (skip-chars-forward " \t")
  19734. (insert ": "))
  19735. ((and (looking-at-p "[ \t]*$")
  19736. (or (eq type 'inlinetask)
  19737. (save-excursion
  19738. (skip-chars-forward " \r\t\n")
  19739. (<= (org-element-property :end element) (point)))))
  19740. (delete-region (point) (line-end-position))
  19741. (org-indent-line)
  19742. (insert ": "))
  19743. (t (user-error "Cannot insert a fixed-width line here")))))
  19744. ;; Region active.
  19745. (let* ((begin (save-excursion
  19746. (goto-char (region-beginning))
  19747. (line-beginning-position)))
  19748. (end (copy-marker
  19749. (save-excursion
  19750. (goto-char (region-end))
  19751. (unless (eolp) (beginning-of-line))
  19752. (if (save-excursion (re-search-backward "\\S-" begin t))
  19753. (progn (skip-chars-backward " \r\t\n") (point))
  19754. (point)))))
  19755. (all-fixed-width-p
  19756. (catch 'not-all-p
  19757. (save-excursion
  19758. (goto-char begin)
  19759. (skip-chars-forward " \r\t\n")
  19760. (when (eobp) (throw 'not-all-p nil))
  19761. (while (< (point) end)
  19762. (let ((element (org-element-at-point)))
  19763. (if (eq (org-element-type element) 'fixed-width)
  19764. (goto-char (org-element-property :end element))
  19765. (throw 'not-all-p nil))))
  19766. t))))
  19767. (if all-fixed-width-p
  19768. (save-excursion
  19769. (goto-char begin)
  19770. (while (< (point) end)
  19771. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  19772. (replace-match
  19773. "" nil nil nil
  19774. (if (= (line-end-position) (match-end 0)) 0 1)))
  19775. (forward-line)))
  19776. (let ((min-ind (point-max)))
  19777. ;; Find minimum indentation across all lines.
  19778. (save-excursion
  19779. (goto-char begin)
  19780. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  19781. (setq min-ind 0)
  19782. (catch 'zerop
  19783. (while (< (point) end)
  19784. (unless (looking-at-p "[ \t]*$")
  19785. (let ((ind (current-indentation)))
  19786. (setq min-ind (min min-ind ind))
  19787. (when (zerop ind) (throw 'zerop t))))
  19788. (forward-line)))))
  19789. ;; Loop over all lines and add fixed-width markup everywhere
  19790. ;; but in fixed-width lines.
  19791. (save-excursion
  19792. (goto-char begin)
  19793. (while (< (point) end)
  19794. (cond
  19795. ((org-at-heading-p)
  19796. (insert ": ")
  19797. (forward-line)
  19798. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  19799. (insert ":")
  19800. (forward-line)))
  19801. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  19802. (let* ((element (org-element-at-point))
  19803. (element-end (org-element-property :end element)))
  19804. (if (eq (org-element-type element) 'fixed-width)
  19805. (progn (goto-char element-end)
  19806. (skip-chars-backward " \r\t\n")
  19807. (forward-line))
  19808. (let ((limit (min end element-end)))
  19809. (while (< (point) limit)
  19810. (org-move-to-column min-ind t)
  19811. (insert ": ")
  19812. (forward-line))))))
  19813. (t
  19814. (org-move-to-column min-ind t)
  19815. (insert ": ")
  19816. (forward-line)))))))
  19817. (set-marker end nil))))
  19818. ;;; Blocks
  19819. (defun org-block-map (function &optional start end)
  19820. "Call FUNCTION at the head of all source blocks in the current buffer.
  19821. Optional arguments START and END can be used to limit the range."
  19822. (let ((start (or start (point-min)))
  19823. (end (or end (point-max))))
  19824. (save-excursion
  19825. (goto-char start)
  19826. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  19827. (save-excursion
  19828. (save-match-data
  19829. (goto-char (match-beginning 0))
  19830. (funcall function)))))))
  19831. (defun org-next-block (arg &optional backward block-regexp)
  19832. "Jump to the next block.
  19833. With a prefix argument ARG, jump forward ARG many blocks.
  19834. When BACKWARD is non-nil, jump to the previous block.
  19835. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  19836. Match data is set according to this regexp when the function
  19837. returns.
  19838. Return point at beginning of the opening line of found block.
  19839. Throw an error if no block is found."
  19840. (interactive "p")
  19841. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  19842. (case-fold-search t)
  19843. (search-fn (if backward #'re-search-backward #'re-search-forward))
  19844. (count (or arg 1))
  19845. (origin (point))
  19846. last-element)
  19847. (if backward (beginning-of-line) (end-of-line))
  19848. (while (and (> count 0) (funcall search-fn re nil t))
  19849. (let ((element (save-excursion
  19850. (goto-char (match-beginning 0))
  19851. (save-match-data (org-element-at-point)))))
  19852. (when (and (memq (org-element-type element)
  19853. '(center-block comment-block dynamic-block
  19854. example-block export-block quote-block
  19855. special-block src-block verse-block))
  19856. (<= (match-beginning 0)
  19857. (org-element-property :post-affiliated element)))
  19858. (setq last-element element)
  19859. (cl-decf count))))
  19860. (if (= count 0)
  19861. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  19862. (save-match-data (org-show-context)))
  19863. (goto-char origin)
  19864. (user-error "No %s code blocks" (if backward "previous" "further")))))
  19865. (defun org-previous-block (arg &optional block-regexp)
  19866. "Jump to the previous block.
  19867. With a prefix argument ARG, jump backward ARG many source blocks.
  19868. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  19869. (interactive "p")
  19870. (org-next-block arg t block-regexp))
  19871. ;;; Comments
  19872. ;; Org comments syntax is quite complex. It requires the entire line
  19873. ;; to be just a comment. Also, even with the right syntax at the
  19874. ;; beginning of line, some elements (e.g., verse-block or
  19875. ;; example-block) don't accept comments. Usual Emacs comment commands
  19876. ;; cannot cope with those requirements. Therefore, Org replaces them.
  19877. ;; Org still relies on `comment-dwim', but cannot trust
  19878. ;; `comment-only-p'. So, `comment-region-function' and
  19879. ;; `uncomment-region-function' both point
  19880. ;; to`org-comment-or-uncomment-region'. Eventually,
  19881. ;; `org-insert-comment' takes care of insertion of comments at the
  19882. ;; beginning of line.
  19883. ;; `org-setup-comments-handling' install comments related variables
  19884. ;; during `org-mode' initialization.
  19885. (defun org-setup-comments-handling ()
  19886. (interactive)
  19887. (setq-local comment-use-syntax nil)
  19888. (setq-local comment-start "# ")
  19889. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  19890. (setq-local comment-insert-comment-function 'org-insert-comment)
  19891. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  19892. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  19893. (defun org-insert-comment ()
  19894. "Insert an empty comment above current line.
  19895. If the line is empty, insert comment at its beginning. When
  19896. point is within a source block, comment according to the related
  19897. major mode."
  19898. (if (let ((element (org-element-at-point)))
  19899. (and (eq (org-element-type element) 'src-block)
  19900. (< (save-excursion
  19901. (goto-char (org-element-property :post-affiliated element))
  19902. (line-end-position))
  19903. (point))
  19904. (> (save-excursion
  19905. (goto-char (org-element-property :end element))
  19906. (skip-chars-backward " \r\t\n")
  19907. (line-beginning-position))
  19908. (point))))
  19909. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  19910. (beginning-of-line)
  19911. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  19912. (open-line 1))
  19913. (org-indent-line)
  19914. (insert "# ")))
  19915. (defvar comment-empty-lines) ; From newcomment.el.
  19916. (defun org-comment-or-uncomment-region (beg end &rest _)
  19917. "Comment or uncomment each non-blank line in the region.
  19918. Uncomment each non-blank line between BEG and END if it only
  19919. contains commented lines. Otherwise, comment them. If region is
  19920. strictly within a source block, use appropriate comment syntax."
  19921. (if (let ((element (org-element-at-point)))
  19922. (and (eq (org-element-type element) 'src-block)
  19923. (< (save-excursion
  19924. (goto-char (org-element-property :post-affiliated element))
  19925. (line-end-position))
  19926. beg)
  19927. (>= (save-excursion
  19928. (goto-char (org-element-property :end element))
  19929. (skip-chars-backward " \r\t\n")
  19930. (line-beginning-position))
  19931. end)))
  19932. ;; Translate region boundaries for the Org buffer to the source
  19933. ;; buffer.
  19934. (let ((offset (- end beg)))
  19935. (save-excursion
  19936. (goto-char beg)
  19937. (org-babel-do-in-edit-buffer
  19938. (comment-or-uncomment-region (point) (+ offset (point))))))
  19939. (save-restriction
  19940. ;; Restrict region
  19941. (narrow-to-region (save-excursion (goto-char beg)
  19942. (skip-chars-forward " \r\t\n" end)
  19943. (line-beginning-position))
  19944. (save-excursion (goto-char end)
  19945. (skip-chars-backward " \r\t\n" beg)
  19946. (line-end-position)))
  19947. (let ((uncommentp
  19948. ;; UNCOMMENTP is non-nil when every non blank line between
  19949. ;; BEG and END is a comment.
  19950. (save-excursion
  19951. (goto-char (point-min))
  19952. (while (and (not (eobp))
  19953. (let ((element (org-element-at-point)))
  19954. (and (eq (org-element-type element) 'comment)
  19955. (goto-char (min (point-max)
  19956. (org-element-property
  19957. :end element)))))))
  19958. (eobp))))
  19959. (if uncommentp
  19960. ;; Only blank lines and comments in region: uncomment it.
  19961. (save-excursion
  19962. (goto-char (point-min))
  19963. (while (not (eobp))
  19964. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  19965. (replace-match "" nil nil nil 1))
  19966. (forward-line)))
  19967. ;; Comment each line in region.
  19968. (let ((min-indent (point-max)))
  19969. ;; First find the minimum indentation across all lines.
  19970. (save-excursion
  19971. (goto-char (point-min))
  19972. (while (and (not (eobp)) (not (zerop min-indent)))
  19973. (unless (looking-at "[ \t]*$")
  19974. (setq min-indent (min min-indent (current-indentation))))
  19975. (forward-line)))
  19976. ;; Then loop over all lines.
  19977. (save-excursion
  19978. (goto-char (point-min))
  19979. (while (not (eobp))
  19980. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  19981. ;; Don't get fooled by invisible text (e.g. link path)
  19982. ;; when moving to column MIN-INDENT.
  19983. (let ((buffer-invisibility-spec nil))
  19984. (org-move-to-column min-indent t))
  19985. (insert comment-start))
  19986. (forward-line)))))))))
  19987. (defun org-comment-dwim (_arg)
  19988. "Call the comment command you mean.
  19989. Call `org-toggle-comment' if on a heading, otherwise call
  19990. `comment-dwim', within a source edit buffer if needed."
  19991. (interactive "*P")
  19992. (cond ((org-at-heading-p)
  19993. (call-interactively #'org-toggle-comment))
  19994. ((org-in-src-block-p)
  19995. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  19996. (t (call-interactively #'comment-dwim))))
  19997. ;;; Timestamps API
  19998. ;; This section contains tools to operate on, or create, timestamp
  19999. ;; objects, as returned by, e.g. `org-element-context'.
  20000. (defun org-timestamp-from-string (s)
  20001. "Convert Org timestamp S, as a string, into a timestamp object.
  20002. Return nil if S is not a valid timestamp string."
  20003. (when (org-string-nw-p s)
  20004. (with-temp-buffer
  20005. (save-excursion (insert s))
  20006. (org-element-timestamp-parser))))
  20007. (defun org-timestamp-from-time (time &optional with-time inactive)
  20008. "Convert a time value into a timestamp object.
  20009. TIME is an Emacs internal time representation, as returned, e.g.,
  20010. by `current-time'.
  20011. When optional argument WITH-TIME is non-nil, return a timestamp
  20012. object with a time part, i.e., with hours and minutes.
  20013. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  20014. return an active timestamp."
  20015. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  20016. (org-element-create 'timestamp
  20017. (list :type (if inactive 'inactive 'active)
  20018. :year-start year
  20019. :month-start month
  20020. :day-start day
  20021. :hour-start (and with-time hour)
  20022. :minute-start (and with-time minute)))))
  20023. (defun org-timestamp-to-time (timestamp &optional end)
  20024. "Convert TIMESTAMP object into an Emacs internal time value.
  20025. Use end of date range or time range when END is non-nil.
  20026. Otherwise, use its start."
  20027. (apply #'encode-time
  20028. (cons 0
  20029. (mapcar
  20030. (lambda (prop) (or (org-element-property prop timestamp) 0))
  20031. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  20032. '(:minute-start :hour-start :day-start :month-start
  20033. :year-start))))))
  20034. (defun org-timestamp-has-time-p (timestamp)
  20035. "Non-nil when TIMESTAMP has a time specified."
  20036. (org-element-property :hour-start timestamp))
  20037. (defun org-timestamp-format (timestamp format &optional end utc)
  20038. "Format a TIMESTAMP object into a string.
  20039. FORMAT is a format specifier to be passed to
  20040. `format-time-string'.
  20041. When optional argument END is non-nil, use end of date-range or
  20042. time-range, if possible.
  20043. When optional argument UTC is non-nil, time is be expressed as
  20044. Universal Time."
  20045. (format-time-string format (org-timestamp-to-time timestamp end)
  20046. (and utc t)))
  20047. (defun org-timestamp-split-range (timestamp &optional end)
  20048. "Extract a TIMESTAMP object from a date or time range.
  20049. END, when non-nil, means extract the end of the range.
  20050. Otherwise, extract its start.
  20051. Return a new timestamp object."
  20052. (let ((type (org-element-property :type timestamp)))
  20053. (if (memq type '(active inactive diary)) timestamp
  20054. (let ((split-ts (org-element-copy timestamp)))
  20055. ;; Set new type.
  20056. (org-element-put-property
  20057. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  20058. ;; Copy start properties over end properties if END is
  20059. ;; non-nil. Otherwise, copy end properties over `start' ones.
  20060. (let ((p-alist '((:minute-start . :minute-end)
  20061. (:hour-start . :hour-end)
  20062. (:day-start . :day-end)
  20063. (:month-start . :month-end)
  20064. (:year-start . :year-end))))
  20065. (dolist (p-cell p-alist)
  20066. (org-element-put-property
  20067. split-ts
  20068. (funcall (if end #'car #'cdr) p-cell)
  20069. (org-element-property
  20070. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  20071. ;; Eventually refresh `:raw-value'.
  20072. (org-element-put-property split-ts :raw-value nil)
  20073. (org-element-put-property
  20074. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  20075. (defun org-timestamp-translate (timestamp &optional boundary)
  20076. "Translate TIMESTAMP object to custom format.
  20077. Format string is defined in `org-time-stamp-custom-formats',
  20078. which see.
  20079. When optional argument BOUNDARY is non-nil, it is either the
  20080. symbol `start' or `end'. In this case, only translate the
  20081. starting or ending part of TIMESTAMP if it is a date or time
  20082. range. Otherwise, translate both parts.
  20083. Return timestamp as-is if `org-display-custom-times' is nil or if
  20084. it has a `diary' type."
  20085. (let ((type (org-element-property :type timestamp)))
  20086. (if (or (not org-display-custom-times) (eq type 'diary))
  20087. (org-element-interpret-data timestamp)
  20088. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  20089. org-time-stamp-custom-formats)))
  20090. (if (and (not boundary) (memq type '(active-range inactive-range)))
  20091. (concat (org-timestamp-format timestamp fmt)
  20092. "--"
  20093. (org-timestamp-format timestamp fmt t))
  20094. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  20095. ;;; Other stuff
  20096. (defvar reftex-docstruct-symbol)
  20097. (defvar org--rds)
  20098. (defun org-reftex-citation ()
  20099. "Use reftex-citation to insert a citation into the buffer.
  20100. This looks for a line like
  20101. #+BIBLIOGRAPHY: foo plain option:-d
  20102. and derives from it that foo.bib is the bibliography file relevant
  20103. for this document. It then installs the necessary environment for RefTeX
  20104. to work in this buffer and calls `reftex-citation' to insert a citation
  20105. into the buffer.
  20106. Export of such citations to both LaTeX and HTML is handled by the contributed
  20107. package ox-bibtex by Taru Karttunen."
  20108. (interactive)
  20109. (let ((reftex-docstruct-symbol 'org--rds)
  20110. org--rds bib)
  20111. (org-with-wide-buffer
  20112. (let ((case-fold-search t)
  20113. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  20114. (if (not (save-excursion
  20115. (or (re-search-forward re nil t)
  20116. (re-search-backward re nil t))))
  20117. (user-error "No bibliography defined in file")
  20118. (setq bib (concat (match-string 1) ".bib")
  20119. org--rds (list (list 'bib bib))))))
  20120. (call-interactively 'reftex-citation)))
  20121. ;;;; Functions extending outline functionality
  20122. (defun org-beginning-of-line (&optional n)
  20123. "Go to the beginning of the current visible line.
  20124. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  20125. symbol `reversed', on the first attempt move to where the
  20126. headline text starts, and only move to beginning of line when the
  20127. cursor is already before the start of the text of the headline.
  20128. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  20129. start of the text on the second attempt.
  20130. With argument N not nil or 1, move forward N - 1 lines first."
  20131. (interactive "^p")
  20132. (let ((origin (point))
  20133. (special (pcase org-special-ctrl-a/e
  20134. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  20135. deactivate-mark)
  20136. ;; First move to a visible line.
  20137. (if (bound-and-true-p visual-line-mode)
  20138. (beginning-of-visual-line n)
  20139. (move-beginning-of-line n)
  20140. ;; `move-beginning-of-line' may leave point after invisible
  20141. ;; characters if line starts with such of these (e.g., with
  20142. ;; a link at column 0). Really move to the beginning of the
  20143. ;; current visible line.
  20144. (beginning-of-line))
  20145. (cond
  20146. ;; No special behavior. Point is already at the beginning of
  20147. ;; a line, logical or visual.
  20148. ((not special))
  20149. ;; `beginning-of-visual-line' left point before logical beginning
  20150. ;; of line: point is at the beginning of a visual line. Bail
  20151. ;; out.
  20152. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  20153. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  20154. ;; At a headline, special position is before the title, but
  20155. ;; after any TODO keyword or priority cookie.
  20156. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  20157. (line-end-position)))
  20158. (bol (point)))
  20159. (if (eq special 'reversed)
  20160. (when (and (= origin bol) (eq last-command this-command))
  20161. (goto-char refpos))
  20162. (when (or (> origin refpos) (= origin bol))
  20163. (goto-char refpos)))))
  20164. ((and (looking-at org-list-full-item-re)
  20165. (memq (org-element-type (save-match-data (org-element-at-point)))
  20166. '(item plain-list)))
  20167. ;; Set special position at first white space character after
  20168. ;; bullet, and check-box, if any.
  20169. (let ((after-bullet
  20170. (let ((box (match-end 3)))
  20171. (cond ((not box) (match-end 1))
  20172. ((eq (char-after box) ?\s) (1+ box))
  20173. (t box)))))
  20174. (if (eq special 'reversed)
  20175. (when (and (= (point) origin) (eq last-command this-command))
  20176. (goto-char after-bullet))
  20177. (when (or (> origin after-bullet) (= (point) origin))
  20178. (goto-char after-bullet)))))
  20179. ;; No special context. Point is already at beginning of line.
  20180. (t nil))))
  20181. (defun org-end-of-line (&optional n)
  20182. "Go to the end of the line, but before ellipsis, if any.
  20183. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  20184. symbol `reversed', ignore tags on the first attempt, and only
  20185. move to after the tags when the cursor is already beyond the end
  20186. of the headline.
  20187. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  20188. on the second attempt.
  20189. With argument N not nil or 1, move forward N - 1 lines first."
  20190. (interactive "^p")
  20191. (let ((origin (point))
  20192. (special (pcase org-special-ctrl-a/e
  20193. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  20194. deactivate-mark)
  20195. ;; First move to a visible line.
  20196. (if (bound-and-true-p visual-line-mode)
  20197. (beginning-of-visual-line n)
  20198. (move-beginning-of-line n))
  20199. (cond
  20200. ;; At a headline, with tags.
  20201. ((and special
  20202. (save-excursion
  20203. (beginning-of-line)
  20204. (let ((case-fold-search nil))
  20205. (looking-at org-complex-heading-regexp)))
  20206. (match-end 5))
  20207. (let ((tags (save-excursion
  20208. (goto-char (match-beginning 5))
  20209. (skip-chars-backward " \t")
  20210. (point)))
  20211. (visual-end (and (bound-and-true-p visual-line-mode)
  20212. (save-excursion
  20213. (end-of-visual-line)
  20214. (point)))))
  20215. ;; If `end-of-visual-line' brings us before end of line or
  20216. ;; even tags, i.e., the headline spans over multiple visual
  20217. ;; lines, move there.
  20218. (cond ((and visual-end
  20219. (< visual-end tags)
  20220. (<= origin visual-end))
  20221. (goto-char visual-end))
  20222. ((eq special 'reversed)
  20223. (if (and (= origin (line-end-position))
  20224. (eq this-command last-command))
  20225. (goto-char tags)
  20226. (end-of-line)))
  20227. (t
  20228. (if (or (< origin tags) (= origin (line-end-position)))
  20229. (goto-char tags)
  20230. (end-of-line))))))
  20231. ((bound-and-true-p visual-line-mode)
  20232. (let ((bol (line-beginning-position)))
  20233. (end-of-visual-line)
  20234. ;; If `end-of-visual-line' gets us past the ellipsis at the
  20235. ;; end of a line, backtrack and use `end-of-line' instead.
  20236. (when (/= bol (line-beginning-position))
  20237. (goto-char bol)
  20238. (end-of-line))))
  20239. (t (end-of-line)))))
  20240. (defun org-backward-sentence (&optional _arg)
  20241. "Go to beginning of sentence, or beginning of table field.
  20242. This will call `backward-sentence' or `org-table-beginning-of-field',
  20243. depending on context."
  20244. (interactive)
  20245. (let* ((element (org-element-at-point))
  20246. (contents-begin (org-element-property :contents-begin element))
  20247. (table (org-element-lineage element '(table) t)))
  20248. (if (and table
  20249. (> (point) contents-begin)
  20250. (<= (point) (org-element-property :contents-end table)))
  20251. (call-interactively #'org-table-beginning-of-field)
  20252. (save-restriction
  20253. (when (and contents-begin
  20254. (< (point-min) contents-begin)
  20255. (> (point) contents-begin))
  20256. (narrow-to-region contents-begin
  20257. (org-element-property :contents-end element)))
  20258. (call-interactively #'backward-sentence)))))
  20259. (defun org-forward-sentence (&optional _arg)
  20260. "Go to end of sentence, or end of table field.
  20261. This will call `forward-sentence' or `org-table-end-of-field',
  20262. depending on context."
  20263. (interactive)
  20264. (if (and (org-at-heading-p)
  20265. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  20266. (save-restriction
  20267. (narrow-to-region (line-beginning-position) (line-end-position))
  20268. (call-interactively #'forward-sentence))
  20269. (let* ((element (org-element-at-point))
  20270. (contents-end (org-element-property :contents-end element))
  20271. (table (org-element-lineage element '(table) t)))
  20272. (if (and table
  20273. (>= (point) (org-element-property :contents-begin table))
  20274. (< (point) contents-end))
  20275. (call-interactively #'org-table-end-of-field)
  20276. (save-restriction
  20277. (when (and contents-end
  20278. (> (point-max) contents-end)
  20279. ;; Skip blank lines between elements.
  20280. (< (org-element-property :end element)
  20281. (save-excursion (goto-char contents-end)
  20282. (skip-chars-forward " \r\t\n"))))
  20283. (narrow-to-region (org-element-property :contents-begin element)
  20284. contents-end))
  20285. ;; End of heading is considered as the end of a sentence.
  20286. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  20287. (call-interactively #'forward-sentence)))))))
  20288. (defun org-kill-line (&optional _arg)
  20289. "Kill line, to tags or end of line."
  20290. (interactive)
  20291. (cond
  20292. ((or (not org-special-ctrl-k)
  20293. (bolp)
  20294. (not (org-at-heading-p)))
  20295. (when (and (get-char-property (line-end-position) 'invisible)
  20296. org-ctrl-k-protect-subtree
  20297. (or (eq org-ctrl-k-protect-subtree 'error)
  20298. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  20299. (user-error
  20300. (substitute-command-keys
  20301. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  20302. (call-interactively
  20303. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  20304. ((org-match-line org-tag-line-re)
  20305. (let ((end (save-excursion
  20306. (goto-char (match-beginning 1))
  20307. (skip-chars-backward " \t")
  20308. (point))))
  20309. (if (<= end (point)) ;on tags part
  20310. (kill-region (point) (line-end-position))
  20311. (kill-region (point) end)))
  20312. (org-align-tags))
  20313. (t (kill-region (point) (line-end-position)))))
  20314. (defun org-yank (&optional arg)
  20315. "Yank. If the kill is a subtree, treat it specially.
  20316. This command will look at the current kill and check if is a single
  20317. subtree, or a series of subtrees[1]. If it passes the test, and if the
  20318. cursor is at the beginning of a line or after the stars of a currently
  20319. empty headline, then the yank is handled specially. How exactly depends
  20320. on the value of the following variables.
  20321. `org-yank-folded-subtrees'
  20322. By default, this variable is non-nil, which results in
  20323. subtree(s) being folded after insertion, except if doing so
  20324. would swallow text after the yanked text.
  20325. `org-yank-adjusted-subtrees'
  20326. When non-nil (the default value is nil), the subtree will be
  20327. promoted or demoted in order to fit into the local outline tree
  20328. structure, which means that the level will be adjusted so that it
  20329. becomes the smaller one of the two *visible* surrounding headings.
  20330. Any prefix to this command will cause `yank' to be called directly with
  20331. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  20332. will just
  20333. plainly yank the text as it is.
  20334. \[1] The test checks if the first non-white line is a heading
  20335. and if there are no other headings with fewer stars."
  20336. (interactive "P")
  20337. (org-yank-generic 'yank arg))
  20338. (defun org-yank-generic (command arg)
  20339. "Perform some yank-like command.
  20340. This function implements the behavior described in the `org-yank'
  20341. documentation. However, it has been generalized to work for any
  20342. interactive command with similar behavior."
  20343. ;; pretend to be command COMMAND
  20344. (setq this-command command)
  20345. (if arg
  20346. (call-interactively command)
  20347. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  20348. (and (org-kill-is-subtree-p)
  20349. (or (bolp)
  20350. (and (looking-at "[ \t]*$")
  20351. (string-match
  20352. "\\`\\*+\\'"
  20353. (buffer-substring (point-at-bol) (point)))))))
  20354. swallowp)
  20355. (cond
  20356. ((and subtreep org-yank-folded-subtrees)
  20357. (let ((beg (point))
  20358. end)
  20359. (if (and subtreep org-yank-adjusted-subtrees)
  20360. (org-paste-subtree nil nil 'for-yank)
  20361. (call-interactively command))
  20362. (setq end (point))
  20363. (goto-char beg)
  20364. (when (and (bolp) subtreep
  20365. (not (setq swallowp
  20366. (org-yank-folding-would-swallow-text beg end))))
  20367. (org-with-limited-levels
  20368. (or (looking-at org-outline-regexp)
  20369. (re-search-forward org-outline-regexp-bol end t))
  20370. (while (and (< (point) end) (looking-at org-outline-regexp))
  20371. (outline-hide-subtree)
  20372. (org-cycle-show-empty-lines 'folded)
  20373. (condition-case nil
  20374. (outline-forward-same-level 1)
  20375. (error (goto-char end))))))
  20376. (when swallowp
  20377. (message
  20378. "Inserted text not folded because that would swallow text"))
  20379. (goto-char end)
  20380. (skip-chars-forward " \t\n\r")
  20381. (beginning-of-line 1)
  20382. (push-mark beg 'nomsg)))
  20383. ((and subtreep org-yank-adjusted-subtrees)
  20384. (let ((beg (point-at-bol)))
  20385. (org-paste-subtree nil nil 'for-yank)
  20386. (push-mark beg 'nomsg)))
  20387. (t
  20388. (call-interactively command))))))
  20389. (defun org-yank-folding-would-swallow-text (beg end)
  20390. "Would hide-subtree at BEG swallow any text after END?"
  20391. (let (level)
  20392. (org-with-limited-levels
  20393. (save-excursion
  20394. (goto-char beg)
  20395. (when (or (looking-at org-outline-regexp)
  20396. (re-search-forward org-outline-regexp-bol end t))
  20397. (setq level (org-outline-level)))
  20398. (goto-char end)
  20399. (skip-chars-forward " \t\r\n\v\f")
  20400. (not (or (eobp)
  20401. (and (bolp) (looking-at-p org-outline-regexp)
  20402. (<= (org-outline-level) level))))))))
  20403. (defun org-back-to-heading (&optional invisible-ok)
  20404. "Call `outline-back-to-heading', but provide a better error message."
  20405. (condition-case nil
  20406. (outline-back-to-heading invisible-ok)
  20407. (error (error "Before first headline at position %d in buffer %s"
  20408. (point) (current-buffer)))))
  20409. (defun org-before-first-heading-p ()
  20410. "Before first heading?"
  20411. (org-with-limited-levels
  20412. (save-excursion
  20413. (end-of-line)
  20414. (null (re-search-backward org-outline-regexp-bol nil t)))))
  20415. (defun org-at-heading-p (&optional _)
  20416. "Non-nil when on a headline."
  20417. (outline-on-heading-p t))
  20418. (defun org-in-commented-heading-p (&optional no-inheritance)
  20419. "Non-nil if point is under a commented heading.
  20420. This function also checks ancestors of the current headline,
  20421. unless optional argument NO-INHERITANCE is non-nil."
  20422. (cond
  20423. ((org-before-first-heading-p) nil)
  20424. ((let ((headline (nth 4 (org-heading-components))))
  20425. (and headline
  20426. (let ((case-fold-search nil))
  20427. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  20428. headline)))))
  20429. (no-inheritance nil)
  20430. (t
  20431. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  20432. (defun org-at-comment-p nil
  20433. "Is cursor in a commented line?"
  20434. (save-excursion
  20435. (save-match-data
  20436. (beginning-of-line)
  20437. (looking-at "^[ \t]*# "))))
  20438. (defun org-at-drawer-p nil
  20439. "Is cursor at a drawer keyword?"
  20440. (save-excursion
  20441. (move-beginning-of-line 1)
  20442. (looking-at org-drawer-regexp)))
  20443. (defun org-at-block-p nil
  20444. "Is cursor at a block keyword?"
  20445. (save-excursion
  20446. (move-beginning-of-line 1)
  20447. (looking-at org-block-regexp)))
  20448. (defun org-point-at-end-of-empty-headline ()
  20449. "If point is at the end of an empty headline, return t, else nil.
  20450. If the heading only contains a TODO keyword, it is still still considered
  20451. empty."
  20452. (let ((case-fold-search nil))
  20453. (and (looking-at "[ \t]*$")
  20454. org-todo-line-regexp
  20455. (save-excursion
  20456. (beginning-of-line)
  20457. (looking-at org-todo-line-regexp)
  20458. (string= (match-string 3) "")))))
  20459. (defun org-at-heading-or-item-p ()
  20460. (or (org-at-heading-p) (org-at-item-p)))
  20461. (defun org-at-target-p ()
  20462. (or (org-in-regexp org-radio-target-regexp)
  20463. (org-in-regexp org-target-regexp)))
  20464. (defun org-up-heading-all (arg)
  20465. "Move to the heading line of which the present line is a subheading.
  20466. This function considers both visible and invisible heading lines.
  20467. With argument, move up ARG levels."
  20468. (outline-up-heading arg t))
  20469. (defun org-up-heading-safe ()
  20470. "Move to the heading line of which the present line is a subheading.
  20471. This version will not throw an error. It will return the level of the
  20472. headline found, or nil if no higher level is found.
  20473. Also, this function will be a lot faster than `outline-up-heading',
  20474. because it relies on stars being the outline starters. This can really
  20475. make a significant difference in outlines with very many siblings."
  20476. (when (ignore-errors (org-back-to-heading t))
  20477. (let ((level-up (1- (funcall outline-level))))
  20478. (and (> level-up 0)
  20479. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  20480. (funcall outline-level)))))
  20481. (defun org-first-sibling-p ()
  20482. "Is this heading the first child of its parents?"
  20483. (interactive)
  20484. (let ((re org-outline-regexp-bol)
  20485. level l)
  20486. (unless (org-at-heading-p t)
  20487. (user-error "Not at a heading"))
  20488. (setq level (funcall outline-level))
  20489. (save-excursion
  20490. (if (not (re-search-backward re nil t))
  20491. t
  20492. (setq l (funcall outline-level))
  20493. (< l level)))))
  20494. (defun org-goto-sibling (&optional previous)
  20495. "Goto the next sibling, even if it is invisible.
  20496. When PREVIOUS is set, go to the previous sibling instead. Returns t
  20497. when a sibling was found. When none is found, return nil and don't
  20498. move point."
  20499. (let ((fun (if previous 're-search-backward 're-search-forward))
  20500. (pos (point))
  20501. (re org-outline-regexp-bol)
  20502. level l)
  20503. (when (ignore-errors (org-back-to-heading t))
  20504. (setq level (funcall outline-level))
  20505. (catch 'exit
  20506. (or previous (forward-char 1))
  20507. (while (funcall fun re nil t)
  20508. (setq l (funcall outline-level))
  20509. (when (< l level) (goto-char pos) (throw 'exit nil))
  20510. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  20511. (goto-char pos)
  20512. nil))))
  20513. (defun org-show-siblings ()
  20514. "Show all siblings of the current headline."
  20515. (save-excursion
  20516. (while (org-goto-sibling) (org-flag-heading nil)))
  20517. (save-excursion
  20518. (while (org-goto-sibling 'previous)
  20519. (org-flag-heading nil))))
  20520. (defun org-goto-first-child ()
  20521. "Goto the first child, even if it is invisible.
  20522. Return t when a child was found. Otherwise don't move point and
  20523. return nil."
  20524. (let (level (pos (point)) (re org-outline-regexp-bol))
  20525. (when (ignore-errors (org-back-to-heading t))
  20526. (setq level (outline-level))
  20527. (forward-char 1)
  20528. (if (and (re-search-forward re nil t) (> (outline-level) level))
  20529. (progn (goto-char (match-beginning 0)) t)
  20530. (goto-char pos) nil))))
  20531. (defun org-show-hidden-entry ()
  20532. "Show an entry where even the heading is hidden."
  20533. (save-excursion
  20534. (org-show-entry)))
  20535. (defun org-flag-heading (flag &optional entry)
  20536. "Flag the current heading. FLAG non-nil means make invisible.
  20537. When ENTRY is non-nil, show the entire entry."
  20538. (save-excursion
  20539. (org-back-to-heading t)
  20540. ;; Check if we should show the entire entry
  20541. (if (not entry)
  20542. (org-flag-region
  20543. (line-end-position 0) (line-end-position) flag 'outline)
  20544. (org-show-entry)
  20545. (save-excursion
  20546. (and (outline-next-heading)
  20547. (org-flag-heading nil))))))
  20548. (defun org-get-next-sibling ()
  20549. "Move to next heading of the same level, and return point.
  20550. If there is no such heading, return nil.
  20551. This is like outline-next-sibling, but invisible headings are ok."
  20552. (let ((level (funcall outline-level)))
  20553. (outline-next-heading)
  20554. (while (and (not (eobp)) (> (funcall outline-level) level))
  20555. (outline-next-heading))
  20556. (unless (or (eobp) (< (funcall outline-level) level))
  20557. (point))))
  20558. (defun org-get-last-sibling ()
  20559. "Move to previous heading of the same level, and return point.
  20560. If there is no such heading, return nil."
  20561. (let ((opoint (point))
  20562. (level (funcall outline-level)))
  20563. (outline-previous-heading)
  20564. (when (and (/= (point) opoint) (outline-on-heading-p t))
  20565. (while (and (> (funcall outline-level) level)
  20566. (not (bobp)))
  20567. (outline-previous-heading))
  20568. (unless (< (funcall outline-level) level)
  20569. (point)))))
  20570. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  20571. "Goto to the end of a subtree."
  20572. ;; This contains an exact copy of the original function, but it uses
  20573. ;; `org-back-to-heading', to make it work also in invisible
  20574. ;; trees. And is uses an invisible-ok argument.
  20575. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  20576. ;; Furthermore, when used inside Org, finding the end of a large subtree
  20577. ;; with many children and grandchildren etc, this can be much faster
  20578. ;; than the outline version.
  20579. (org-back-to-heading invisible-ok)
  20580. (let ((first t)
  20581. (level (funcall outline-level)))
  20582. (if (and (derived-mode-p 'org-mode) (< level 1000))
  20583. ;; A true heading (not a plain list item), in Org
  20584. ;; This means we can easily find the end by looking
  20585. ;; only for the right number of stars. Using a regexp to do
  20586. ;; this is so much faster than using a Lisp loop.
  20587. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  20588. (forward-char 1)
  20589. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  20590. ;; something else, do it the slow way
  20591. (while (and (not (eobp))
  20592. (or first (> (funcall outline-level) level)))
  20593. (setq first nil)
  20594. (outline-next-heading)))
  20595. (unless to-heading
  20596. (when (memq (preceding-char) '(?\n ?\^M))
  20597. ;; Go to end of line before heading
  20598. (forward-char -1)
  20599. (when (memq (preceding-char) '(?\n ?\^M))
  20600. ;; leave blank line before heading
  20601. (forward-char -1)))))
  20602. (point))
  20603. (defun org-end-of-meta-data (&optional full)
  20604. "Skip planning line and properties drawer in current entry.
  20605. When optional argument FULL is non-nil, also skip empty lines,
  20606. clocking lines and regular drawers at the beginning of the
  20607. entry."
  20608. (org-back-to-heading t)
  20609. (forward-line)
  20610. (when (looking-at-p org-planning-line-re) (forward-line))
  20611. (when (looking-at org-property-drawer-re)
  20612. (goto-char (match-end 0))
  20613. (forward-line))
  20614. (when (and full (not (org-at-heading-p)))
  20615. (catch 'exit
  20616. (let ((end (save-excursion (outline-next-heading) (point)))
  20617. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  20618. (while (not (eobp))
  20619. (cond ((looking-at-p org-drawer-regexp)
  20620. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  20621. (forward-line)
  20622. (throw 'exit t)))
  20623. ((looking-at-p re) (forward-line))
  20624. (t (throw 'exit t))))))))
  20625. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  20626. "Move forward to the ARG'th subheading at same level as this one.
  20627. Stop at the first and last subheadings of a superior heading.
  20628. Normally this only looks at visible headings, but when INVISIBLE-OK is
  20629. non-nil it will also look at invisible ones."
  20630. (interactive "p")
  20631. (let ((backward? (and arg (< arg 0))))
  20632. (if (org-before-first-heading-p)
  20633. (if backward? (goto-char (point-min)) (outline-next-heading))
  20634. (org-back-to-heading invisible-ok)
  20635. (unless backward? (end-of-line)) ;do not match current headline
  20636. (let ((level (- (match-end 0) (match-beginning 0) 1))
  20637. (f (if backward? #'re-search-backward #'re-search-forward))
  20638. (count (if arg (abs arg) 1))
  20639. (result (point)))
  20640. (while (and (> count 0)
  20641. (funcall f org-outline-regexp-bol nil 'move))
  20642. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  20643. (cond ((< l level) (setq count 0))
  20644. ((and (= l level)
  20645. (or invisible-ok
  20646. (not (org-invisible-p
  20647. (line-beginning-position)))))
  20648. (cl-decf count)
  20649. (when (= l level) (setq result (point)))))))
  20650. (goto-char result))
  20651. (beginning-of-line))))
  20652. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  20653. "Move backward to the ARG'th subheading at same level as this one.
  20654. Stop at the first and last subheadings of a superior heading."
  20655. (interactive "p")
  20656. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  20657. (defun org-next-visible-heading (arg)
  20658. "Move to the next visible heading.
  20659. This function wraps `outline-next-visible-heading' with
  20660. `org-with-limited-levels' in order to skip over inline tasks and
  20661. respect customization of `org-odd-levels-only'."
  20662. (interactive "p")
  20663. (org-with-limited-levels
  20664. (outline-next-visible-heading arg)))
  20665. (defun org-previous-visible-heading (arg)
  20666. "Move to the previous visible heading.
  20667. This function wraps `outline-previous-visible-heading' with
  20668. `org-with-limited-levels' in order to skip over inline tasks and
  20669. respect customization of `org-odd-levels-only'."
  20670. (interactive "p")
  20671. (org-with-limited-levels
  20672. (outline-previous-visible-heading arg)))
  20673. (defun org-forward-paragraph ()
  20674. "Move forward to beginning of next paragraph or equivalent.
  20675. The function moves point to the beginning of the next visible
  20676. structural element, which can be a paragraph, a table, a list
  20677. item, etc. It also provides some special moves for convenience:
  20678. - On an affiliated keyword, jump to the beginning of the
  20679. relative element.
  20680. - On an item or a footnote definition, move to the second
  20681. element inside, if any.
  20682. - On a table or a property drawer, jump after it.
  20683. - On a verse or source block, stop after blank lines."
  20684. (interactive)
  20685. (unless (eobp)
  20686. (let* ((deactivate-mark nil)
  20687. (element (org-element-at-point))
  20688. (type (org-element-type element))
  20689. (post-affiliated (org-element-property :post-affiliated element))
  20690. (contents-begin (org-element-property :contents-begin element))
  20691. (contents-end (org-element-property :contents-end element))
  20692. (end (let ((end (org-element-property :end element)) (parent element))
  20693. (while (and (setq parent (org-element-property :parent parent))
  20694. (= (org-element-property :contents-end parent) end))
  20695. (setq end (org-element-property :end parent)))
  20696. end)))
  20697. (cond ((not element)
  20698. (skip-chars-forward " \r\t\n")
  20699. (or (eobp) (beginning-of-line)))
  20700. ;; On affiliated keywords, move to element's beginning.
  20701. ((< (point) post-affiliated)
  20702. (goto-char post-affiliated))
  20703. ;; At a table row, move to the end of the table. Similarly,
  20704. ;; at a node property, move to the end of the property
  20705. ;; drawer.
  20706. ((memq type '(node-property table-row))
  20707. (goto-char (org-element-property
  20708. :end (org-element-property :parent element))))
  20709. ((memq type '(property-drawer table)) (goto-char end))
  20710. ;; Consider blank lines as separators in verse and source
  20711. ;; blocks to ease editing.
  20712. ((memq type '(src-block verse-block))
  20713. (when (eq type 'src-block)
  20714. (setq contents-end
  20715. (save-excursion (goto-char end)
  20716. (skip-chars-backward " \r\t\n")
  20717. (line-beginning-position))))
  20718. (beginning-of-line)
  20719. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  20720. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  20721. (goto-char end)
  20722. (skip-chars-forward " \r\t\n")
  20723. (if (= (point) contents-end) (goto-char end)
  20724. (beginning-of-line))))
  20725. ;; With no contents, just skip element.
  20726. ((not contents-begin) (goto-char end))
  20727. ;; If contents are invisible, skip the element altogether.
  20728. ((org-invisible-p (line-end-position))
  20729. (cl-case type
  20730. (headline
  20731. (org-with-limited-levels (outline-next-visible-heading 1)))
  20732. ;; At a plain list, make sure we move to the next item
  20733. ;; instead of skipping the whole list.
  20734. (plain-list (forward-char)
  20735. (org-forward-paragraph))
  20736. (otherwise (goto-char end))))
  20737. ((>= (point) contents-end) (goto-char end))
  20738. ((>= (point) contents-begin)
  20739. ;; This can only happen on paragraphs and plain lists.
  20740. (cl-case type
  20741. (paragraph (goto-char end))
  20742. ;; At a plain list, try to move to second element in
  20743. ;; first item, if possible.
  20744. (plain-list (end-of-line)
  20745. (org-forward-paragraph))))
  20746. ;; When contents start on the middle of a line (e.g. in
  20747. ;; items and footnote definitions), try to reach first
  20748. ;; element starting after current line.
  20749. ((> (line-end-position) contents-begin)
  20750. (end-of-line)
  20751. (org-forward-paragraph))
  20752. (t (goto-char contents-begin))))))
  20753. (defun org-backward-paragraph ()
  20754. "Move backward to start of previous paragraph or equivalent.
  20755. The function moves point to the beginning of the current
  20756. structural element, which can be a paragraph, a table, a list
  20757. item, etc., or to the beginning of the previous visible one if
  20758. point is already there. It also provides some special moves for
  20759. convenience:
  20760. - On an affiliated keyword, jump to the first one.
  20761. - On a table or a property drawer, move to its beginning.
  20762. - On comment, example, export, src and verse blocks, stop
  20763. before blank lines."
  20764. (interactive)
  20765. (unless (bobp)
  20766. (let* ((deactivate-mark nil)
  20767. (element (org-element-at-point))
  20768. (type (org-element-type element))
  20769. (contents-end (org-element-property :contents-end element))
  20770. (post-affiliated (org-element-property :post-affiliated element))
  20771. (begin (org-element-property :begin element))
  20772. (special? ;blocks handled specially
  20773. (memq type '(comment-block example-block export-block src-block
  20774. verse-block)))
  20775. (contents-begin
  20776. (if special?
  20777. ;; These types have no proper contents. Fake line
  20778. ;; below the block opening line as contents beginning.
  20779. (save-excursion (goto-char begin) (line-beginning-position 2))
  20780. (org-element-property :contents-begin element))))
  20781. (cond
  20782. ((not element) (goto-char (point-min)))
  20783. ((= (point) begin)
  20784. (backward-char)
  20785. (org-backward-paragraph))
  20786. ((<= (point) post-affiliated) (goto-char begin))
  20787. ;; Special behavior: on a table or a property drawer, move to
  20788. ;; its beginning.
  20789. ((memq type '(node-property table-row))
  20790. (goto-char (org-element-property
  20791. :post-affiliated (org-element-property :parent element))))
  20792. (special?
  20793. (if (<= (point) contents-begin) (goto-char post-affiliated)
  20794. ;; Inside a verse block, see blank lines as paragraph
  20795. ;; separators.
  20796. (let ((origin (point)))
  20797. (skip-chars-backward " \r\t\n" contents-begin)
  20798. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  20799. (skip-chars-forward " \r\t\n" origin)
  20800. (if (= (point) origin) (goto-char contents-begin)
  20801. (beginning-of-line))))))
  20802. ((eq type 'paragraph) (goto-char contents-begin)
  20803. ;; When at first paragraph in an item or a footnote definition,
  20804. ;; move directly to beginning of line.
  20805. (let ((parent-contents
  20806. (org-element-property
  20807. :contents-begin (org-element-property :parent element))))
  20808. (when (and parent-contents (= parent-contents contents-begin))
  20809. (beginning-of-line))))
  20810. ;; At the end of a greater element, move to the beginning of
  20811. ;; the last element within.
  20812. ((and contents-end (>= (point) contents-end))
  20813. (goto-char (1- contents-end))
  20814. (org-backward-paragraph))
  20815. (t (goto-char (or post-affiliated begin))))
  20816. ;; Ensure we never leave point invisible.
  20817. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  20818. (defun org-forward-element ()
  20819. "Move forward by one element.
  20820. Move to the next element at the same level, when possible."
  20821. (interactive)
  20822. (cond ((eobp) (user-error "Cannot move further down"))
  20823. ((org-with-limited-levels (org-at-heading-p))
  20824. (let ((origin (point)))
  20825. (goto-char (org-end-of-subtree nil t))
  20826. (unless (org-with-limited-levels (org-at-heading-p))
  20827. (goto-char origin)
  20828. (user-error "Cannot move further down"))))
  20829. (t
  20830. (let* ((elem (org-element-at-point))
  20831. (end (org-element-property :end elem))
  20832. (parent (org-element-property :parent elem)))
  20833. (cond ((and parent (= (org-element-property :contents-end parent) end))
  20834. (goto-char (org-element-property :end parent)))
  20835. ((integer-or-marker-p end) (goto-char end))
  20836. (t (message "No element at point")))))))
  20837. (defun org-backward-element ()
  20838. "Move backward by one element.
  20839. Move to the previous element at the same level, when possible."
  20840. (interactive)
  20841. (cond ((bobp) (user-error "Cannot move further up"))
  20842. ((org-with-limited-levels (org-at-heading-p))
  20843. ;; At a headline, move to the previous one, if any, or stay
  20844. ;; here.
  20845. (let ((origin (point)))
  20846. (org-with-limited-levels (org-backward-heading-same-level 1))
  20847. ;; When current headline has no sibling above, move to its
  20848. ;; parent.
  20849. (when (= (point) origin)
  20850. (or (org-with-limited-levels (org-up-heading-safe))
  20851. (progn (goto-char origin)
  20852. (user-error "Cannot move further up"))))))
  20853. (t
  20854. (let* ((elem (org-element-at-point))
  20855. (beg (org-element-property :begin elem)))
  20856. (cond
  20857. ;; Move to beginning of current element if point isn't
  20858. ;; there already.
  20859. ((null beg) (message "No element at point"))
  20860. ((/= (point) beg) (goto-char beg))
  20861. (t (goto-char beg)
  20862. (skip-chars-backward " \r\t\n")
  20863. (unless (bobp)
  20864. (let ((prev (org-element-at-point)))
  20865. (goto-char (org-element-property :begin prev))
  20866. (while (and (setq prev (org-element-property :parent prev))
  20867. (<= (org-element-property :end prev) beg))
  20868. (goto-char (org-element-property :begin prev)))))))))))
  20869. (defun org-up-element ()
  20870. "Move to upper element."
  20871. (interactive)
  20872. (if (org-with-limited-levels (org-at-heading-p))
  20873. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  20874. (let* ((elem (org-element-at-point))
  20875. (parent (org-element-property :parent elem)))
  20876. (if parent (goto-char (org-element-property :begin parent))
  20877. (if (org-with-limited-levels (org-before-first-heading-p))
  20878. (user-error "No surrounding element")
  20879. (org-with-limited-levels (org-back-to-heading)))))))
  20880. (defun org-down-element ()
  20881. "Move to inner element."
  20882. (interactive)
  20883. (let ((element (org-element-at-point)))
  20884. (cond
  20885. ((memq (org-element-type element) '(plain-list table))
  20886. (goto-char (org-element-property :contents-begin element))
  20887. (forward-char))
  20888. ((memq (org-element-type element) org-element-greater-elements)
  20889. ;; If contents are hidden, first disclose them.
  20890. (when (org-invisible-p (line-end-position)) (org-cycle))
  20891. (goto-char (or (org-element-property :contents-begin element)
  20892. (user-error "No content for this element"))))
  20893. (t (user-error "No inner element")))))
  20894. (defun org-drag-element-backward ()
  20895. "Move backward element at point."
  20896. (interactive)
  20897. (let ((elem (or (org-element-at-point)
  20898. (user-error "No element at point"))))
  20899. (if (eq (org-element-type elem) 'headline)
  20900. ;; Preserve point when moving a whole tree, even if point was
  20901. ;; on blank lines below the headline.
  20902. (let ((offset (skip-chars-backward " \t\n")))
  20903. (unwind-protect (org-move-subtree-up)
  20904. (forward-char (- offset))))
  20905. (let ((prev-elem
  20906. (save-excursion
  20907. (goto-char (org-element-property :begin elem))
  20908. (skip-chars-backward " \r\t\n")
  20909. (unless (bobp)
  20910. (let* ((beg (org-element-property :begin elem))
  20911. (prev (org-element-at-point))
  20912. (up prev))
  20913. (while (and (setq up (org-element-property :parent up))
  20914. (<= (org-element-property :end up) beg))
  20915. (setq prev up))
  20916. prev)))))
  20917. ;; Error out if no previous element or previous element is
  20918. ;; a parent of the current one.
  20919. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  20920. (user-error "Cannot drag element backward")
  20921. (let ((pos (point)))
  20922. (org-element-swap-A-B prev-elem elem)
  20923. (goto-char (+ (org-element-property :begin prev-elem)
  20924. (- pos (org-element-property :begin elem))))))))))
  20925. (defun org-drag-element-forward ()
  20926. "Move forward element at point."
  20927. (interactive)
  20928. (let* ((pos (point))
  20929. (elem (or (org-element-at-point)
  20930. (user-error "No element at point"))))
  20931. (when (= (point-max) (org-element-property :end elem))
  20932. (user-error "Cannot drag element forward"))
  20933. (goto-char (org-element-property :end elem))
  20934. (let ((next-elem (org-element-at-point)))
  20935. (when (or (org-element-nested-p elem next-elem)
  20936. (and (eq (org-element-type next-elem) 'headline)
  20937. (not (eq (org-element-type elem) 'headline))))
  20938. (goto-char pos)
  20939. (user-error "Cannot drag element forward"))
  20940. ;; Compute new position of point: it's shifted by NEXT-ELEM
  20941. ;; body's length (without final blanks) and by the length of
  20942. ;; blanks between ELEM and NEXT-ELEM.
  20943. (let ((size-next (- (save-excursion
  20944. (goto-char (org-element-property :end next-elem))
  20945. (skip-chars-backward " \r\t\n")
  20946. (forward-line)
  20947. ;; Small correction if buffer doesn't end
  20948. ;; with a newline character.
  20949. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  20950. (org-element-property :begin next-elem)))
  20951. (size-blank (- (org-element-property :end elem)
  20952. (save-excursion
  20953. (goto-char (org-element-property :end elem))
  20954. (skip-chars-backward " \r\t\n")
  20955. (forward-line)
  20956. (point)))))
  20957. (org-element-swap-A-B elem next-elem)
  20958. (goto-char (+ pos size-next size-blank))))))
  20959. (defun org-drag-line-forward (arg)
  20960. "Drag the line at point ARG lines forward."
  20961. (interactive "p")
  20962. (dotimes (_ (abs arg))
  20963. (let ((c (current-column)))
  20964. (if (< 0 arg)
  20965. (progn
  20966. (beginning-of-line 2)
  20967. (transpose-lines 1)
  20968. (beginning-of-line 0))
  20969. (transpose-lines 1)
  20970. (beginning-of-line -1))
  20971. (org-move-to-column c))))
  20972. (defun org-drag-line-backward (arg)
  20973. "Drag the line at point ARG lines backward."
  20974. (interactive "p")
  20975. (org-drag-line-forward (- arg)))
  20976. (defun org-mark-element ()
  20977. "Put point at beginning of this element, mark at end.
  20978. Interactively, if this command is repeated or (in Transient Mark
  20979. mode) if the mark is active, it marks the next element after the
  20980. ones already marked."
  20981. (interactive)
  20982. (let (deactivate-mark)
  20983. (if (and (called-interactively-p 'any)
  20984. (or (and (eq last-command this-command) (mark t))
  20985. (and transient-mark-mode mark-active)))
  20986. (set-mark
  20987. (save-excursion
  20988. (goto-char (mark))
  20989. (goto-char (org-element-property :end (org-element-at-point)))))
  20990. (let ((element (org-element-at-point)))
  20991. (end-of-line)
  20992. (push-mark (org-element-property :end element) t t)
  20993. (goto-char (org-element-property :begin element))))))
  20994. (defun org-narrow-to-element ()
  20995. "Narrow buffer to current element."
  20996. (interactive)
  20997. (let ((elem (org-element-at-point)))
  20998. (cond
  20999. ((eq (car elem) 'headline)
  21000. (narrow-to-region
  21001. (org-element-property :begin elem)
  21002. (org-element-property :end elem)))
  21003. ((memq (car elem) org-element-greater-elements)
  21004. (narrow-to-region
  21005. (org-element-property :contents-begin elem)
  21006. (org-element-property :contents-end elem)))
  21007. (t
  21008. (narrow-to-region
  21009. (org-element-property :begin elem)
  21010. (org-element-property :end elem))))))
  21011. (defun org-transpose-element ()
  21012. "Transpose current and previous elements, keeping blank lines between.
  21013. Point is moved after both elements."
  21014. (interactive)
  21015. (org-skip-whitespace)
  21016. (let ((end (org-element-property :end (org-element-at-point))))
  21017. (org-drag-element-backward)
  21018. (goto-char end)))
  21019. (defun org-unindent-buffer ()
  21020. "Un-indent the visible part of the buffer.
  21021. Relative indentation (between items, inside blocks, etc.) isn't
  21022. modified."
  21023. (interactive)
  21024. (unless (eq major-mode 'org-mode)
  21025. (user-error "Cannot un-indent a buffer not in Org mode"))
  21026. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  21027. (unindent-tree
  21028. (lambda (contents)
  21029. (dolist (element (reverse contents))
  21030. (if (memq (org-element-type element) '(headline section))
  21031. (funcall unindent-tree (org-element-contents element))
  21032. (save-excursion
  21033. (save-restriction
  21034. (narrow-to-region
  21035. (org-element-property :begin element)
  21036. (org-element-property :end element))
  21037. (org-do-remove-indentation))))))))
  21038. (funcall unindent-tree (org-element-contents parse-tree))))
  21039. (defun org-make-options-regexp (kwds &optional extra)
  21040. "Make a regular expression for keyword lines.
  21041. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  21042. when non-nil, is a regexp matching keywords names."
  21043. (concat "^[ \t]*#\\+\\("
  21044. (regexp-opt kwds)
  21045. (and extra (concat (and kwds "\\|") extra))
  21046. "\\):[ \t]*\\(.*\\)"))
  21047. ;;; Conveniently switch to Info nodes
  21048. (defun org-info-find-node (&optional nodename)
  21049. "Find Info documentation NODENAME or Org documentation according context.
  21050. Started from `gnus-info-find-node'."
  21051. (interactive)
  21052. (Info-goto-node
  21053. (or nodename
  21054. (let ((default-org-info-node "(org) Top"))
  21055. (cond
  21056. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  21057. ((eq 'org-mode major-mode)
  21058. (let* ((context (org-element-at-point))
  21059. (element-info-nodes ; compare to `org-element-all-elements'.
  21060. `((babel-call . "(org) Evaluating Code Blocks")
  21061. (center-block . "(org) Paragraphs")
  21062. (clock . ,default-org-info-node)
  21063. (comment . "(org) Comment Lines")
  21064. (comment-block . "(org) Comment Lines")
  21065. (diary-sexp . ,default-org-info-node)
  21066. (drawer . "(org) Drawers")
  21067. (dynamic-block . "(org) Dynamic Blocks")
  21068. (example-block . "(org) Literal Examples")
  21069. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  21070. (fixed-width . ,default-org-info-node)
  21071. (footnote-definition . "(org) Creating Footnotes")
  21072. (headline . "(org) Document Structure")
  21073. (horizontal-rule . "(org) Built-in Table Editor")
  21074. (inlinetask . ,default-org-info-node)
  21075. (item . "(org) Plain Lists")
  21076. (keyword . "(org) Per-file keywords")
  21077. (latex-environment . "(org) LaTeX Export")
  21078. (node-property . "(org) Properties and Columns")
  21079. (paragraph . "(org) Paragraphs")
  21080. (plain-list . "(org) Plain Lists")
  21081. (planning . "(org) Deadlines and Scheduling")
  21082. (property-drawer . "(org) Properties and Columns")
  21083. (quote-block . "(org) Paragraphs")
  21084. (section . ,default-org-info-node)
  21085. (special-block . ,default-org-info-node)
  21086. (src-block . "(org) Working with Source Code")
  21087. (table . "(org) Tables")
  21088. (table-row . "(org) Tables")
  21089. (verse-block . "(org) Paragraphs"))))
  21090. (or (cdr (assoc (car context) element-info-nodes))
  21091. default-org-info-node)))
  21092. (t default-org-info-node))))))
  21093. ;;; Finish up
  21094. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  21095. (lambda () (add-hook 'change-major-mode-hook
  21096. 'org-show-all 'append 'local)))
  21097. (provide 'org)
  21098. (run-hooks 'org-load-hook)
  21099. ;;; org.el ends here