org.el 896 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628
  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.1.13
  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. (require 'org-macs)
  84. (require 'org-compat)
  85. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  86. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  87. (defvar org-outline-regexp "\\*+ "
  88. "Regexp to match Org headlines.")
  89. (defvar org-outline-regexp-bol "^\\*+ "
  90. "Regexp to match Org headlines.
  91. This is similar to `org-outline-regexp' but additionally makes
  92. sure that we are at the beginning of the line.")
  93. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  94. "Matches a headline, putting stars and text into groups.
  95. Stars are put in group 1 and the trimmed body in group 2.")
  96. (declare-function calendar-check-holidays "holidays" (date))
  97. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  98. (declare-function cdlatex-math-symbol "ext:cdlatex")
  99. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  100. (declare-function org-add-archive-files "org-archive" (files))
  101. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  102. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  103. (declare-function org-agenda-redo "org-agenda" (&optional all))
  104. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  105. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  106. (declare-function org-archive-subtree-default "org-archive" ())
  107. (declare-function org-archive-to-archive-sibling "org-archive" ())
  108. (declare-function org-attach "org-attach" ())
  109. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  110. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  111. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  112. (declare-function org-clock-cancel "org-clock" ())
  113. (declare-function org-clock-display "org-clock" (&optional arg))
  114. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  115. (declare-function org-clock-goto "org-clock" (&optional select))
  116. (declare-function org-clock-in "org-clock" (&optional select start-time))
  117. (declare-function org-clock-in-last "org-clock" (&optional arg))
  118. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  119. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  120. (declare-function org-clock-report "org-clock" (&optional arg))
  121. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  122. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  123. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  124. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  125. (declare-function org-clock-update-time-maybe "org-clock" ())
  126. (declare-function org-clocking-buffer "org-clock" ())
  127. (declare-function org-clocktable-shift "org-clock" (dir n))
  128. (declare-function org-columns-insert-dblock "org-colview" ())
  129. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  130. (declare-function org-element-at-point "org-element" ())
  131. (declare-function org-element-cache-refresh "org-element" (pos))
  132. (declare-function org-element-cache-reset "org-element" (&optional all))
  133. (declare-function org-element-contents "org-element" (element))
  134. (declare-function org-element-context "org-element" (&optional element))
  135. (declare-function org-element-copy "org-element" (datum))
  136. (declare-function org-element-create "org-element" (type &optional props &rest children))
  137. (declare-function org-element-interpret-data "org-element" (data))
  138. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  139. (declare-function org-element-link-parser "org-element" ())
  140. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  141. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  142. (declare-function org-element-property "org-element" (property element))
  143. (declare-function org-element-put-property "org-element" (element property value))
  144. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  145. (declare-function org-element-timestamp-parser "org-element" ())
  146. (declare-function org-element-type "org-element" (element))
  147. (declare-function org-element-update-syntax "org-element" ())
  148. (declare-function org-export-dispatch "ox" (&optional arg))
  149. (declare-function org-export-get-backend "ox" (name))
  150. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  151. (declare-function org-feed-goto-inbox "org-feed" (feed))
  152. (declare-function org-feed-update-all "org-feed" ())
  153. (declare-function org-goto "org-goto" (&optional alternative-interface))
  154. (declare-function org-id-find-id-file "org-id" (id))
  155. (declare-function org-id-get-create "org-id" (&optional force))
  156. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  157. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  158. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  159. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  160. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  161. (declare-function org-table-align "org-table" ())
  162. (declare-function org-table-begin "org-table" (&optional table-type))
  163. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  164. (declare-function org-table-blank-field "org-table" ())
  165. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  166. (declare-function org-table-copy-down "org-table" (N))
  167. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  168. (declare-function org-table-create-or-convert-from-region "org-table" (arg))
  169. (declare-function org-table-create-with-table.el "org-table" ())
  170. (declare-function org-table-cut-region "org-table" (beg end))
  171. (declare-function org-table-edit-field "org-table" (arg))
  172. (declare-function org-table-end "org-table" (&optional table-type))
  173. (declare-function org-table-end-of-field "org-table" (&optional n))
  174. (declare-function org-table-eval-formula "org-table" (&optional arg equation suppress-align suppress-const suppress-store suppress-analysis))
  175. (declare-function org-table-field-info "org-table" (arg))
  176. (declare-function org-table-insert-row "org-table" (&optional arg))
  177. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  178. (declare-function org-table-maybe-eval-formula "org-table" ())
  179. (declare-function org-table-maybe-recalculate-line "org-table" ())
  180. (declare-function org-table-next-row "org-table" ())
  181. (declare-function org-table-paste-rectangle "org-table" ())
  182. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  183. (declare-function org-table-rotate-recalc-marks "org-table" (&optional newchar))
  184. (declare-function org-table-shrink "org-table" (&optional begin end))
  185. (declare-function org-table-sort-lines "org-table" (&optional with-case sorting-type getkey-func compare-func interactive?))
  186. (declare-function org-table-sum "org-table" (&optional beg end nlast))
  187. (declare-function org-table-toggle-column-width "org-table" (&optional arg))
  188. (declare-function org-table-toggle-coordinate-overlays "org-table" ())
  189. (declare-function org-table-toggle-formula-debugger "org-table" ())
  190. (declare-function org-table-with-shrunk-field "org-table" (&rest body))
  191. (declare-function org-table-wrap-region "org-table" (arg))
  192. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  193. (declare-function org-timer "org-timer" (&optional restart no-insert))
  194. (declare-function org-timer-item "org-timer" (&optional arg))
  195. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  196. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  197. (declare-function org-timer-start "org-timer" (&optional offset))
  198. (declare-function org-timer-stop "org-timer" ())
  199. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  200. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  201. (declare-function orgtbl-mode "org-table" (&optional arg))
  202. (defvar ffap-url-regexp)
  203. (defvar org-element-paragraph-separate)
  204. (defvar org-indent-indentation-per-level)
  205. ;; load languages based on value of `org-babel-load-languages'
  206. (defvar org-babel-load-languages)
  207. ;;;###autoload
  208. (defun org-babel-do-load-languages (sym value)
  209. "Load the languages defined in `org-babel-load-languages'."
  210. (set-default sym value)
  211. (dolist (pair org-babel-load-languages)
  212. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  213. (if active
  214. (require (intern (concat "ob-" lang)))
  215. (funcall 'fmakunbound
  216. (intern (concat "org-babel-execute:" lang)))
  217. (funcall 'fmakunbound
  218. (intern (concat "org-babel-expand-body:" lang)))))))
  219. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  220. ;;;###autoload
  221. (defun org-babel-load-file (file &optional compile)
  222. "Load Emacs Lisp source code blocks in the Org FILE.
  223. This function exports the source code using `org-babel-tangle'
  224. and then loads the resulting file using `load-file'. With prefix
  225. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  226. file to byte-code before it is loaded."
  227. (interactive "fFile to load: \nP")
  228. (let* ((age (lambda (file)
  229. (float-time
  230. (time-subtract (current-time)
  231. (nth 5 (or (file-attributes (file-truename file))
  232. (file-attributes file)))))))
  233. (base-name (file-name-sans-extension file))
  234. (exported-file (concat base-name ".el")))
  235. ;; tangle if the Org file is newer than the elisp file
  236. (unless (and (file-exists-p exported-file)
  237. (> (funcall age file) (funcall age exported-file)))
  238. ;; Tangle-file traversal returns reversed list of tangled files
  239. ;; and we want to evaluate the first target.
  240. (setq exported-file
  241. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  242. (message "%s %s"
  243. (if compile
  244. (progn (byte-compile-file exported-file 'load)
  245. "Compiled and loaded")
  246. (progn (load-file exported-file) "Loaded"))
  247. exported-file)))
  248. (defcustom org-babel-load-languages '((emacs-lisp . t))
  249. "Languages which can be evaluated in Org buffers.
  250. \\<org-mode-map>
  251. This list can be used to load support for any of the languages
  252. below. Each language will depend on a different set of system
  253. executables and/or Emacs modes.
  254. When a language is \"loaded\", code blocks in that language can
  255. be evaluated with `org-babel-execute-src-block', which is bound
  256. by default to \\[org-ctrl-c-ctrl-c].
  257. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  258. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  259. default, only Emacs Lisp is loaded, since it has no specific
  260. requirement."
  261. :group 'org-babel
  262. :set 'org-babel-do-load-languages
  263. :version "24.1"
  264. :type '(alist :tag "Babel Languages"
  265. :key-type
  266. (choice
  267. (const :tag "Awk" awk)
  268. (const :tag "C" C)
  269. (const :tag "R" R)
  270. (const :tag "Asymptote" asymptote)
  271. (const :tag "Calc" calc)
  272. (const :tag "Clojure" clojure)
  273. (const :tag "CSS" css)
  274. (const :tag "Ditaa" ditaa)
  275. (const :tag "Dot" dot)
  276. (const :tag "Ebnf2ps" ebnf2ps)
  277. (const :tag "Emacs Lisp" emacs-lisp)
  278. (const :tag "Forth" forth)
  279. (const :tag "Fortran" fortran)
  280. (const :tag "Gnuplot" gnuplot)
  281. (const :tag "Haskell" haskell)
  282. (const :tag "hledger" hledger)
  283. (const :tag "IO" io)
  284. (const :tag "J" J)
  285. (const :tag "Java" java)
  286. (const :tag "Javascript" js)
  287. (const :tag "LaTeX" latex)
  288. (const :tag "Ledger" ledger)
  289. (const :tag "Lilypond" lilypond)
  290. (const :tag "Lisp" lisp)
  291. (const :tag "Makefile" makefile)
  292. (const :tag "Maxima" maxima)
  293. (const :tag "Matlab" matlab)
  294. (const :tag "Mscgen" mscgen)
  295. (const :tag "Ocaml" ocaml)
  296. (const :tag "Octave" octave)
  297. (const :tag "Org" org)
  298. (const :tag "Perl" perl)
  299. (const :tag "Pico Lisp" picolisp)
  300. (const :tag "PlantUML" plantuml)
  301. (const :tag "Python" python)
  302. (const :tag "Ruby" ruby)
  303. (const :tag "Sass" sass)
  304. (const :tag "Scala" scala)
  305. (const :tag "Scheme" scheme)
  306. (const :tag "Screen" screen)
  307. (const :tag "Shell Script" shell)
  308. (const :tag "Shen" shen)
  309. (const :tag "Sql" sql)
  310. (const :tag "Sqlite" sqlite)
  311. (const :tag "Stan" stan)
  312. (const :tag "Vala" vala))
  313. :value-type (boolean :tag "Activate" :value t)))
  314. ;;;; Customization variables
  315. (defcustom org-clone-delete-id nil
  316. "Remove ID property of clones of a subtree.
  317. When non-nil, clones of a subtree don't inherit the ID property.
  318. Otherwise they inherit the ID property with a new unique
  319. identifier."
  320. :type 'boolean
  321. :version "24.1"
  322. :group 'org-id)
  323. ;;; Version
  324. (org-check-version)
  325. ;;;###autoload
  326. (defun org-version (&optional here full message)
  327. "Show the Org version.
  328. Interactively, or when MESSAGE is non-nil, show it in echo area.
  329. With prefix argument, or when HERE is non-nil, insert it at point.
  330. In non-interactive uses, a reduced version string is output unless
  331. FULL is given."
  332. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  333. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  334. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  335. (load-suffixes (list ".el"))
  336. (org-install-dir
  337. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  338. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  339. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  340. (let* ((load-suffixes save-load-suffixes)
  341. (release (org-release))
  342. (git-version (org-git-version))
  343. (version (format "Org mode version %s (%s @ %s)"
  344. release
  345. git-version
  346. (if org-install-dir
  347. (if (string= org-dir org-install-dir)
  348. org-install-dir
  349. (concat "mixed installation! "
  350. org-install-dir
  351. " and "
  352. org-dir))
  353. "org-loaddefs.el can not be found!")))
  354. (version1 (if full version release)))
  355. (when here (insert version1))
  356. (when message (message "%s" version1))
  357. version1)))
  358. (defconst org-version (org-version))
  359. ;;; Syntax Constants
  360. ;;;; Block
  361. (defconst org-block-regexp
  362. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  363. "Regular expression for hiding blocks.")
  364. (defconst org-dblock-start-re
  365. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  366. "Matches the start line of a dynamic block, with parameters.")
  367. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  368. "Matches the end of a dynamic block.")
  369. ;;;; Clock and Planning
  370. (defconst org-clock-string "CLOCK:"
  371. "String used as prefix for timestamps clocking work hours on an item.")
  372. (defvar org-closed-string "CLOSED:"
  373. "String used as the prefix for timestamps logging closing a TODO entry.")
  374. (defvar org-deadline-string "DEADLINE:"
  375. "String to mark deadline entries.
  376. \\<org-mode-map>
  377. A deadline is this string, followed by a time stamp. It must be
  378. a word, terminated by a colon. You can insert a schedule keyword
  379. and a timestamp with `\\[org-deadline]'.")
  380. (defvar org-scheduled-string "SCHEDULED:"
  381. "String to mark scheduled TODO entries.
  382. \\<org-mode-map>
  383. A schedule is this string, followed by a time stamp. It must be
  384. a word, terminated by a colon. You can insert a schedule keyword
  385. and a timestamp with `\\[org-schedule]'.")
  386. (defconst org-ds-keyword-length
  387. (+ 2
  388. (apply #'max
  389. (mapcar #'length
  390. (list org-deadline-string org-scheduled-string
  391. org-clock-string org-closed-string))))
  392. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  393. (defconst org-planning-line-re
  394. (concat "^[ \t]*"
  395. (regexp-opt
  396. (list org-closed-string org-deadline-string org-scheduled-string)
  397. t))
  398. "Matches a line with planning info.
  399. Matched keyword is in group 1.")
  400. (defconst org-clock-line-re
  401. (concat "^[ \t]*" org-clock-string)
  402. "Matches a line with clock info.")
  403. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  404. "Matches the DEADLINE keyword.")
  405. (defconst org-deadline-time-regexp
  406. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  407. "Matches the DEADLINE keyword together with a time stamp.")
  408. (defconst org-deadline-time-hour-regexp
  409. (concat "\\<" org-deadline-string
  410. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  411. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  412. (defconst org-deadline-line-regexp
  413. (concat "\\<\\(" org-deadline-string "\\).*")
  414. "Matches the DEADLINE keyword and the rest of the line.")
  415. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  416. "Matches the SCHEDULED keyword.")
  417. (defconst org-scheduled-time-regexp
  418. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  419. "Matches the SCHEDULED keyword together with a time stamp.")
  420. (defconst org-scheduled-time-hour-regexp
  421. (concat "\\<" org-scheduled-string
  422. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  423. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  424. (defconst org-closed-time-regexp
  425. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  426. "Matches the CLOSED keyword together with a time stamp.")
  427. (defconst org-keyword-time-regexp
  428. (concat "\\<"
  429. (regexp-opt
  430. (list org-scheduled-string org-deadline-string org-closed-string
  431. org-clock-string)
  432. t)
  433. " *[[<]\\([^]>]+\\)[]>]")
  434. "Matches any of the 4 keywords, together with the time stamp.")
  435. (defconst org-keyword-time-not-clock-regexp
  436. (concat
  437. "\\<"
  438. (regexp-opt
  439. (list org-scheduled-string org-deadline-string org-closed-string) t)
  440. " *[[<]\\([^]>]+\\)[]>]")
  441. "Matches any of the 3 keywords, together with the time stamp.")
  442. (defconst org-maybe-keyword-time-regexp
  443. (concat "\\(\\<"
  444. (regexp-opt
  445. (list org-scheduled-string org-deadline-string org-closed-string
  446. org-clock-string)
  447. t)
  448. "\\)?"
  449. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  450. "\\|"
  451. "<%%([^\r\n>]*>\\)")
  452. "Matches a timestamp, possibly preceded by a keyword.")
  453. (defconst org-all-time-keywords
  454. (mapcar (lambda (w) (substring w 0 -1))
  455. (list org-scheduled-string org-deadline-string
  456. org-clock-string org-closed-string))
  457. "List of time keywords.")
  458. ;;;; Drawer
  459. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  460. "Matches first or last line of a hidden block.
  461. Group 1 contains drawer's name or \"END\".")
  462. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  463. "Regular expression matching the first line of a property drawer.")
  464. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  465. "Regular expression matching the last line of a property drawer.")
  466. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  467. "Regular expression matching the first line of a clock drawer.")
  468. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  469. "Regular expression matching the last line of a clock drawer.")
  470. (defconst org-property-drawer-re
  471. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  472. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  473. "[ \t]*:END:[ \t]*$")
  474. "Matches an entire property drawer.")
  475. (defconst org-clock-drawer-re
  476. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  477. org-clock-drawer-end-re "\\)\n?")
  478. "Matches an entire clock drawer.")
  479. ;;;; Headline
  480. (defconst org-heading-keyword-regexp-format
  481. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  482. "Printf format for a regexp matching a headline with some keyword.
  483. This regexp will match the headline of any node which has the
  484. exact keyword that is put into the format. The keyword isn't in
  485. any group by default, but the stars and the body are.")
  486. (defconst org-heading-keyword-maybe-regexp-format
  487. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  488. "Printf format for a regexp matching a headline, possibly with some keyword.
  489. This regexp can match any headline with the specified keyword, or
  490. without a keyword. The keyword isn't in any group by default,
  491. but the stars and the body are.")
  492. (defconst org-archive-tag "ARCHIVE"
  493. "The tag that marks a subtree as archived.
  494. An archived subtree does not open during visibility cycling, and does
  495. not contribute to the agenda listings.")
  496. (defconst org-tag-re "[[:alnum:]_@#%]+"
  497. "Regexp matching a single tag.")
  498. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  499. "Regexp matching the tag group at the end of a line, with leading spaces.
  500. Tags are stored in match group 1. Match group 2 stores the tags
  501. without the enclosing colons.")
  502. (defconst org-tag-line-re
  503. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  504. "Regexp matching tags in a headline.
  505. Tags are stored in match group 1. Match group 2 stores the tags
  506. without the enclosing colons.")
  507. (eval-and-compile
  508. (defconst org-comment-string "COMMENT"
  509. "Entries starting with this keyword will never be exported.
  510. \\<org-mode-map>
  511. An entry can be toggled between COMMENT and normal with
  512. `\\[org-toggle-comment]'."))
  513. ;;;; LaTeX Environments and Fragments
  514. (defconst org-latex-regexps
  515. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  516. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  517. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  518. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  519. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  520. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  521. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  522. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  523. "Regular expressions for matching embedded LaTeX.")
  524. ;;;; Node Property
  525. (defconst org-effort-property "Effort"
  526. "The property that is being used to keep track of effort estimates.
  527. Effort estimates given in this property need to have the format H:MM.")
  528. ;;;; Table
  529. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  530. "Detect an org-type or table-type table.")
  531. (defconst org-table-line-regexp "^[ \t]*|"
  532. "Detect an org-type table line.")
  533. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  534. "Detect an org-type table line.")
  535. (defconst org-table-hline-regexp "^[ \t]*|-"
  536. "Detect an org-type table hline.")
  537. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  538. "Detect a table-type table hline.")
  539. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  540. "Detect the first line outside a table when searching from within it.
  541. This works for both table types.")
  542. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  543. "Detect a #+TBLFM line.")
  544. ;;;; Timestamp
  545. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  546. "Regular expression for fast time stamp matching.")
  547. (defconst org-ts-regexp-inactive
  548. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  549. "Regular expression for fast inactive time stamp matching.")
  550. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  551. "Regular expression for fast time stamp matching.")
  552. (defconst org-ts-regexp0
  553. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  554. "Regular expression matching time strings for analysis.
  555. This one does not require the space after the date, so it can be used
  556. on a string that terminates immediately after the date.")
  557. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  558. "Regular expression matching time strings for analysis.")
  559. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  560. "Regular expression matching time stamps, with groups.")
  561. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  562. "Regular expression matching time stamps (also [..]), with groups.")
  563. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  564. "Regular expression matching a time stamp range.")
  565. (defconst org-tr-regexp-both
  566. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  567. "Regular expression matching a time stamp range.")
  568. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  569. org-ts-regexp "\\)?")
  570. "Regular expression matching a time stamp or time stamp range.")
  571. (defconst org-tsr-regexp-both
  572. (concat org-ts-regexp-both "\\(--?-?"
  573. org-ts-regexp-both "\\)?")
  574. "Regular expression matching a time stamp or time stamp range.
  575. The time stamps may be either active or inactive.")
  576. (defconst org-repeat-re
  577. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  578. "Regular expression for specifying repeated events.
  579. After a match, group 1 contains the repeat expression.")
  580. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  581. "Formats for `format-time-string' which are used for time stamps.")
  582. ;;; The custom variables
  583. (defgroup org nil
  584. "Outline-based notes management and organizer."
  585. :tag "Org"
  586. :group 'outlines
  587. :group 'calendar)
  588. (defcustom org-mode-hook nil
  589. "Mode hook for Org mode, run after the mode was turned on."
  590. :group 'org
  591. :type 'hook)
  592. (defcustom org-load-hook nil
  593. "Hook that is run after org.el has been loaded."
  594. :group 'org
  595. :type 'hook)
  596. (defcustom org-log-buffer-setup-hook nil
  597. "Hook that is run after an Org log buffer is created."
  598. :group 'org
  599. :version "24.1"
  600. :type 'hook)
  601. (defvar org-modules) ; defined below
  602. (defvar org-modules-loaded nil
  603. "Have the modules been loaded already?")
  604. (defun org-load-modules-maybe (&optional force)
  605. "Load all extensions listed in `org-modules'."
  606. (when (or force (not org-modules-loaded))
  607. (dolist (ext org-modules)
  608. (condition-case nil (require ext)
  609. (error (message "Problems while trying to load feature `%s'" ext))))
  610. (setq org-modules-loaded t)))
  611. (defun org-set-modules (var value)
  612. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  613. (set var value)
  614. (when (featurep 'org)
  615. (org-load-modules-maybe 'force)
  616. (org-element-cache-reset 'all)))
  617. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail org-eww)
  618. "Modules that should always be loaded together with org.el.
  619. If a description starts with <C>, the file is not part of Emacs
  620. and loading it will require that you have downloaded and properly
  621. installed the Org mode distribution.
  622. You can also use this system to load external packages (i.e. neither Org
  623. core modules, nor modules from the CONTRIB directory). Just add symbols
  624. to the end of the list. If the package is called org-xyz.el, then you need
  625. to add the symbol `xyz', and the package must have a call to:
  626. (provide \\='org-xyz)
  627. For export specific modules, see also `org-export-backends'."
  628. :group 'org
  629. :set 'org-set-modules
  630. :version "26.1"
  631. :package-version '(Org . "9.2")
  632. :type
  633. '(set :greedy t
  634. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  635. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  636. (const :tag " crypt: Encryption of subtrees" org-crypt)
  637. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  638. (const :tag " docview: Links to doc-view buffers" org-docview)
  639. (const :tag " eww: Store link to url of eww" org-eww)
  640. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  641. (const :tag " habit: Track your consistency with habits" org-habit)
  642. (const :tag " id: Global IDs for identifying entries" org-id)
  643. (const :tag " info: Links to Info nodes" org-info)
  644. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  645. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  646. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  647. (const :tag " mouse: Additional mouse support" org-mouse)
  648. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  649. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  650. (const :tag " tempo: Fast completion for structures" org-tempo)
  651. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  652. (const :tag " eshell: Support for links to working directories in eshell" org-eshell)
  653. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  654. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  655. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  656. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  657. (const :tag "C collector: Collect properties into tables" org-collector)
  658. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  659. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  660. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  661. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  662. (const :tag "C eval: Include command output as text" org-eval)
  663. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  664. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  665. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  666. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  667. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  668. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  669. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  670. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  671. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  672. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  673. (const :tag "C notify: Notifications for Org-mode" org-notify)
  674. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  675. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  676. (const :tag "C registry: A registry for Org links" org-registry)
  677. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  678. (const :tag "C screenshot: Take and manage screenshots in Org-mode files" org-screenshot)
  679. (const :tag "C secretary: Team management with Org" org-secretary)
  680. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  681. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  682. (const :tag "C track: Keep up with Org mode development" org-track)
  683. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  684. (const :tag "C vm: Links to VM folders/messages" org-vm)
  685. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  686. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  687. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  688. (defvar org-export-registered-backends) ; From ox.el.
  689. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  690. (declare-function org-export-backend-name "ox" (backend) t)
  691. (defcustom org-export-backends '(ascii html icalendar latex odt)
  692. "List of export back-ends that should be always available.
  693. If a description starts with <C>, the file is not part of Emacs
  694. and loading it will require that you have downloaded and properly
  695. installed the Org mode distribution.
  696. Unlike to `org-modules', libraries in this list will not be
  697. loaded along with Org, but only once the export framework is
  698. needed.
  699. This variable needs to be set before org.el is loaded. If you
  700. need to make a change while Emacs is running, use the customize
  701. interface or run the following code, where VAL stands for the new
  702. value of the variable, after updating it:
  703. (progn
  704. (setq org-export-registered-backends
  705. (cl-remove-if-not
  706. (lambda (backend)
  707. (let ((name (org-export-backend-name backend)))
  708. (or (memq name val)
  709. (catch \\='parentp
  710. (dolist (b val)
  711. (and (org-export-derived-backend-p b name)
  712. (throw \\='parentp t)))))))
  713. org-export-registered-backends))
  714. (let ((new-list (mapcar #\\='org-export-backend-name
  715. org-export-registered-backends)))
  716. (dolist (backend val)
  717. (cond
  718. ((not (load (format \"ox-%s\" backend) t t))
  719. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  720. backend))
  721. ((not (memq backend new-list)) (push backend new-list))))
  722. (set-default \\='org-export-backends new-list)))
  723. Adding a back-end to this list will also pull the back-end it
  724. depends on, if any."
  725. :group 'org
  726. :group 'org-export
  727. :version "26.1"
  728. :package-version '(Org . "9.0")
  729. :initialize 'custom-initialize-set
  730. :set (lambda (var val)
  731. (if (not (featurep 'ox)) (set-default var val)
  732. ;; Any back-end not required anymore (not present in VAL and not
  733. ;; a parent of any back-end in the new value) is removed from the
  734. ;; list of registered back-ends.
  735. (setq org-export-registered-backends
  736. (cl-remove-if-not
  737. (lambda (backend)
  738. (let ((name (org-export-backend-name backend)))
  739. (or (memq name val)
  740. (catch 'parentp
  741. (dolist (b val)
  742. (and (org-export-derived-backend-p b name)
  743. (throw 'parentp t)))))))
  744. org-export-registered-backends))
  745. ;; Now build NEW-LIST of both new back-ends and required
  746. ;; parents.
  747. (let ((new-list (mapcar #'org-export-backend-name
  748. org-export-registered-backends)))
  749. (dolist (backend val)
  750. (cond
  751. ((not (load (format "ox-%s" backend) t t))
  752. (message "Problems while trying to load export back-end `%s'"
  753. backend))
  754. ((not (memq backend new-list)) (push backend new-list))))
  755. ;; Set VAR to that list with fixed dependencies.
  756. (set-default var new-list))))
  757. :type '(set :greedy t
  758. (const :tag " ascii Export buffer to ASCII format" ascii)
  759. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  760. (const :tag " html Export buffer to HTML format" html)
  761. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  762. (const :tag " latex Export buffer to LaTeX format" latex)
  763. (const :tag " man Export buffer to MAN format" man)
  764. (const :tag " md Export buffer to Markdown format" md)
  765. (const :tag " odt Export buffer to ODT format" odt)
  766. (const :tag " org Export buffer to Org format" org)
  767. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  768. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  769. (const :tag "C deck Export buffer to deck.js presentations" deck)
  770. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  771. (const :tag "C groff Export buffer to Groff format" groff)
  772. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  773. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  774. (const :tag "C s5 Export buffer to s5 presentations" s5)
  775. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  776. (eval-after-load 'ox
  777. '(dolist (backend org-export-backends)
  778. (condition-case nil (require (intern (format "ox-%s" backend)))
  779. (error (message "Problems while trying to load export back-end `%s'"
  780. backend)))))
  781. (defcustom org-support-shift-select nil
  782. "Non-nil means make shift-cursor commands select text when possible.
  783. \\<org-mode-map>\
  784. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  785. start selecting a region, or enlarge regions started in this way.
  786. In Org mode, in special contexts, these same keys are used for
  787. other purposes, important enough to compete with shift selection.
  788. Org tries to balance these needs by supporting `shift-select-mode'
  789. outside these special contexts, under control of this variable.
  790. The default of this variable is nil, to avoid confusing behavior. Shifted
  791. cursor keys will then execute Org commands in the following contexts:
  792. - on a headline, changing TODO state (left/right) and priority (up/down)
  793. - on a time stamp, changing the time
  794. - in a plain list item, changing the bullet type
  795. - in a property definition line, switching between allowed values
  796. - in the BEGIN line of a clock table (changing the time block).
  797. Outside these contexts, the commands will throw an error.
  798. When this variable is t and the cursor is not in a special
  799. context, Org mode will support shift-selection for making and
  800. enlarging regions. To make this more effective, the bullet
  801. cycling will no longer happen anywhere in an item line, but only
  802. if the cursor is exactly on the bullet.
  803. If you set this variable to the symbol `always', then the keys
  804. will not be special in headlines, property lines, and item lines,
  805. to make shift selection work there as well. If this is what you
  806. want, you can use the following alternative commands:
  807. `\\[org-todo]' and `\\[org-priority]' \
  808. to change TODO state and priority,
  809. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  810. can be used to switch TODO sets,
  811. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  812. and properties can be edited by hand or in column view.
  813. However, when the cursor is on a timestamp, shift-cursor commands
  814. will still edit the time stamp - this is just too good to give up."
  815. :group 'org
  816. :type '(choice
  817. (const :tag "Never" nil)
  818. (const :tag "When outside special context" t)
  819. (const :tag "Everywhere except timestamps" always)))
  820. (defcustom org-loop-over-headlines-in-active-region nil
  821. "Shall some commands act upon headlines in the active region?
  822. When set to t, some commands will be performed in all headlines
  823. within the active region.
  824. When set to `start-level', some commands will be performed in all
  825. headlines within the active region, provided that these headlines
  826. are of the same level than the first one.
  827. When set to a string, those commands will be performed on the
  828. matching headlines within the active region. Such string must be
  829. a tags/property/todo match as it is used in the agenda tags view.
  830. The list of commands is: `org-schedule', `org-deadline',
  831. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  832. `org-archive-to-archive-sibling'. The archiving commands skip
  833. already archived entries."
  834. :type '(choice (const :tag "Don't loop" nil)
  835. (const :tag "All headlines in active region" t)
  836. (const :tag "In active region, headlines at the same level than the first one" start-level)
  837. (string :tag "Tags/Property/Todo matcher"))
  838. :version "24.1"
  839. :group 'org-todo
  840. :group 'org-archive)
  841. (defcustom org-startup-folded t
  842. "Non-nil means entering Org mode will switch to OVERVIEW.
  843. This can also be configured on a per-file basis by adding one of
  844. the following lines anywhere in the buffer:
  845. #+STARTUP: fold (or `overview', this is equivalent)
  846. #+STARTUP: nofold (or `showall', this is equivalent)
  847. #+STARTUP: content
  848. #+STARTUP: showeverything
  849. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  850. to ignore this option when Org opens agenda files for the first
  851. time."
  852. :group 'org-startup
  853. :type '(choice
  854. (const :tag "nofold: show all" nil)
  855. (const :tag "fold: overview" t)
  856. (const :tag "content: all headlines" content)
  857. (const :tag "show everything, even drawers" showeverything)))
  858. (defcustom org-startup-truncated t
  859. "Non-nil means entering Org mode will set `truncate-lines'.
  860. This is useful since some lines containing links can be very long and
  861. uninteresting. Also tables look terrible when wrapped.
  862. The variable `org-startup-truncated' allows to configure
  863. truncation for Org mode different to the other modes that use the
  864. variable `truncate-lines' and as a shortcut instead of putting
  865. the variable `truncate-lines' into the `org-mode-hook'. If one
  866. wants to configure truncation for Org mode not statically but
  867. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  868. the variable `truncate-lines' has to be used because in such a
  869. case it is too late to set the variable `org-startup-truncated'."
  870. :group 'org-startup
  871. :type 'boolean)
  872. (defcustom org-startup-indented nil
  873. "Non-nil means turn on `org-indent-mode' on startup.
  874. This can also be configured on a per-file basis by adding one of
  875. the following lines anywhere in the buffer:
  876. #+STARTUP: indent
  877. #+STARTUP: noindent"
  878. :group 'org-structure
  879. :type '(choice
  880. (const :tag "Not" nil)
  881. (const :tag "Globally (slow on startup in large files)" t)))
  882. (defcustom org-use-sub-superscripts t
  883. "Non-nil means interpret \"_\" and \"^\" for display.
  884. If you want to control how Org exports those characters, see
  885. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  886. used to be an alias for `org-export-with-sub-superscripts' in
  887. Org <8.0, it is not anymore.
  888. When this option is turned on, you can use TeX-like syntax for
  889. sub- and superscripts within the buffer. Several characters after
  890. \"_\" or \"^\" will be considered as a single item - so grouping
  891. with {} is normally not needed. For example, the following things
  892. will be parsed as single sub- or superscripts:
  893. 10^24 or 10^tau several digits will be considered 1 item.
  894. 10^-12 or 10^-tau a leading sign with digits or a word
  895. x^2-y^3 will be read as x^2 - y^3, because items are
  896. terminated by almost any nonword/nondigit char.
  897. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  898. Still, ambiguity is possible. So when in doubt, use {} to enclose
  899. the sub/superscript. If you set this variable to the symbol `{}',
  900. the braces are *required* in order to trigger interpretations as
  901. sub/superscript. This can be helpful in documents that need \"_\"
  902. frequently in plain text."
  903. :group 'org-startup
  904. :version "24.4"
  905. :package-version '(Org . "8.0")
  906. :type '(choice
  907. (const :tag "Always interpret" t)
  908. (const :tag "Only with braces" {})
  909. (const :tag "Never interpret" nil)))
  910. (defcustom org-startup-with-beamer-mode nil
  911. "Non-nil means turn on `org-beamer-mode' on startup.
  912. This can also be configured on a per-file basis by adding one of
  913. the following lines anywhere in the buffer:
  914. #+STARTUP: beamer"
  915. :group 'org-startup
  916. :version "24.1"
  917. :type 'boolean)
  918. (defcustom org-startup-align-all-tables nil
  919. "Non-nil means align all tables when visiting a file.
  920. This can also be configured on a per-file basis by adding one of
  921. the following lines anywhere in the buffer:
  922. #+STARTUP: align
  923. #+STARTUP: noalign"
  924. :group 'org-startup
  925. :type 'boolean)
  926. (defcustom org-startup-shrink-all-tables nil
  927. "Non-nil means shrink all table columns with a width cookie.
  928. This can also be configured on a per-file basis by adding one of
  929. the following lines anywhere in the buffer:
  930. #+STARTUP: shrink"
  931. :group 'org-startup
  932. :type 'boolean
  933. :version "27.1"
  934. :package-version '(Org . "9.2")
  935. :safe #'booleanp)
  936. (defcustom org-startup-with-inline-images nil
  937. "Non-nil means show inline images when loading a new Org file.
  938. This can also be configured on a per-file basis by adding one of
  939. the following lines anywhere in the buffer:
  940. #+STARTUP: inlineimages
  941. #+STARTUP: noinlineimages"
  942. :group 'org-startup
  943. :version "24.1"
  944. :type 'boolean)
  945. (defcustom org-startup-with-latex-preview nil
  946. "Non-nil means preview LaTeX fragments when loading a new Org file.
  947. This can also be configured on a per-file basis by adding one of
  948. the following lines anywhere in the buffer:
  949. #+STARTUP: latexpreview
  950. #+STARTUP: nolatexpreview"
  951. :group 'org-startup
  952. :version "24.4"
  953. :package-version '(Org . "8.0")
  954. :type 'boolean)
  955. (defcustom org-insert-mode-line-in-empty-file nil
  956. "Non-nil means insert the first line setting Org mode in empty files.
  957. When the function `org-mode' is called interactively in an empty file, this
  958. normally means that the file name does not automatically trigger Org mode.
  959. To ensure that the file will always be in Org mode in the future, a
  960. line enforcing Org mode will be inserted into the buffer, if this option
  961. has been set."
  962. :group 'org-startup
  963. :type 'boolean)
  964. (defcustom org-replace-disputed-keys nil
  965. "Non-nil means use alternative key bindings for some keys.
  966. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  967. These keys are also used by other packages like Shift Select mode,
  968. CUA mode or Windmove. If you want to use Org mode together with
  969. one of these other modes, or more generally if you would like to
  970. move some Org mode commands to other keys, set this variable and
  971. configure the keys with the variable `org-disputed-keys'.
  972. This option is only relevant at load-time of Org mode, and must be set
  973. *before* org.el is loaded. Changing it requires a restart of Emacs to
  974. become effective."
  975. :group 'org-startup
  976. :type 'boolean)
  977. (defcustom org-use-extra-keys nil
  978. "Non-nil means use extra key sequence definitions for certain commands.
  979. This happens automatically if `window-system' is nil. This
  980. variable lets you do the same manually. You must set it before
  981. loading Org."
  982. :group 'org-startup
  983. :type 'boolean)
  984. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  985. (defcustom org-disputed-keys
  986. '(([(shift up)] . [(meta p)])
  987. ([(shift down)] . [(meta n)])
  988. ([(shift left)] . [(meta -)])
  989. ([(shift right)] . [(meta +)])
  990. ([(control shift right)] . [(meta shift +)])
  991. ([(control shift left)] . [(meta shift -)]))
  992. "Keys for which Org mode and other modes compete.
  993. This is an alist, cars are the default keys, second element specifies
  994. the alternative to use when `org-replace-disputed-keys' is t.
  995. Keys can be specified in any syntax supported by `define-key'.
  996. The value of this option takes effect only at Org mode startup,
  997. therefore you'll have to restart Emacs to apply it after changing."
  998. :group 'org-startup
  999. :type 'alist)
  1000. (defun org-key (key)
  1001. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  1002. Or return the original if not disputed."
  1003. (when org-replace-disputed-keys
  1004. (let* ((nkey (key-description key))
  1005. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  1006. org-disputed-keys)))
  1007. (setq key (if x (cdr x) key))))
  1008. key)
  1009. (defun org-defkey (keymap key def)
  1010. "Define a key, possibly translated, as returned by `org-key'."
  1011. (define-key keymap (org-key key) def))
  1012. (defcustom org-ellipsis nil
  1013. "The ellipsis to use in the Org mode outline.
  1014. When nil, just use the standard three dots. When a non-empty string,
  1015. use that string instead.
  1016. The change affects only Org mode (which will then use its own display table).
  1017. Changing this requires executing `\\[org-mode]' in a buffer to become
  1018. effective."
  1019. :group 'org-startup
  1020. :type '(choice (const :tag "Default" nil)
  1021. (string :tag "String" :value "...#"))
  1022. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  1023. (defvar org-display-table nil
  1024. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  1025. (defgroup org-keywords nil
  1026. "Keywords in Org mode."
  1027. :tag "Org Keywords"
  1028. :group 'org)
  1029. (defcustom org-closed-keep-when-no-todo nil
  1030. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  1031. :group 'org-todo
  1032. :group 'org-keywords
  1033. :version "24.4"
  1034. :package-version '(Org . "8.0")
  1035. :type 'boolean)
  1036. (defgroup org-structure nil
  1037. "Options concerning the general structure of Org files."
  1038. :tag "Org Structure"
  1039. :group 'org)
  1040. (defgroup org-reveal-location nil
  1041. "Options about how to make context of a location visible."
  1042. :tag "Org Reveal Location"
  1043. :group 'org-structure)
  1044. (defcustom org-show-context-detail '((agenda . local)
  1045. (bookmark-jump . lineage)
  1046. (isearch . lineage)
  1047. (default . ancestors))
  1048. "Alist between context and visibility span when revealing a location.
  1049. \\<org-mode-map>Some actions may move point into invisible
  1050. locations. As a consequence, Org always expose a neighborhood
  1051. around point. How much is shown depends on the initial action,
  1052. or context. Valid contexts are
  1053. agenda when exposing an entry from the agenda
  1054. org-goto when using the command `org-goto' (`\\[org-goto]')
  1055. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1056. tags-tree when constructing a sparse tree based on tags matches
  1057. link-search when exposing search matches associated with a link
  1058. mark-goto when exposing the jump goal of a mark
  1059. bookmark-jump when exposing a bookmark location
  1060. isearch when exiting from an incremental search
  1061. default default for all contexts not set explicitly
  1062. Allowed visibility spans are
  1063. minimal show current headline; if point is not on headline,
  1064. also show entry
  1065. local show current headline, entry and next headline
  1066. ancestors show current headline and its direct ancestors; if
  1067. point is not on headline, also show entry
  1068. lineage show current headline, its direct ancestors and all
  1069. their children; if point is not on headline, also show
  1070. entry and first child
  1071. tree show current headline, its direct ancestors and all
  1072. their children; if point is not on headline, also show
  1073. entry and all children
  1074. canonical show current headline, its direct ancestors along with
  1075. their entries and children; if point is not located on
  1076. the headline, also show current entry and all children
  1077. As special cases, a nil or t value means show all contexts in
  1078. `minimal' or `canonical' view, respectively.
  1079. Some views can make displayed information very compact, but also
  1080. make it harder to edit the location of the match. In such
  1081. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1082. more context."
  1083. :group 'org-reveal-location
  1084. :version "26.1"
  1085. :package-version '(Org . "9.0")
  1086. :type '(choice
  1087. (const :tag "Canonical" t)
  1088. (const :tag "Minimal" nil)
  1089. (repeat :greedy t :tag "Individual contexts"
  1090. (cons
  1091. (choice :tag "Context"
  1092. (const agenda)
  1093. (const org-goto)
  1094. (const occur-tree)
  1095. (const tags-tree)
  1096. (const link-search)
  1097. (const mark-goto)
  1098. (const bookmark-jump)
  1099. (const isearch)
  1100. (const default))
  1101. (choice :tag "Detail level"
  1102. (const minimal)
  1103. (const local)
  1104. (const ancestors)
  1105. (const lineage)
  1106. (const tree)
  1107. (const canonical))))))
  1108. (defcustom org-indirect-buffer-display 'other-window
  1109. "How should indirect tree buffers be displayed?
  1110. This applies to indirect buffers created with the commands
  1111. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1112. Valid values are:
  1113. current-window Display in the current window
  1114. other-window Just display in another window.
  1115. dedicated-frame Create one new frame, and re-use it each time.
  1116. new-frame Make a new frame each time. Note that in this case
  1117. previously-made indirect buffers are kept, and you need to
  1118. kill these buffers yourself."
  1119. :group 'org-structure
  1120. :group 'org-agenda-windows
  1121. :type '(choice
  1122. (const :tag "In current window" current-window)
  1123. (const :tag "In current frame, other window" other-window)
  1124. (const :tag "Each time a new frame" new-frame)
  1125. (const :tag "One dedicated frame" dedicated-frame)))
  1126. (defcustom org-use-speed-commands nil
  1127. "Non-nil means activate single letter commands at beginning of a headline.
  1128. This may also be a function to test for appropriate locations where speed
  1129. commands should be active.
  1130. For example, to activate speed commands when the point is on any
  1131. star at the beginning of the headline, you can do this:
  1132. (setq org-use-speed-commands
  1133. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1134. :group 'org-structure
  1135. :type '(choice
  1136. (const :tag "Never" nil)
  1137. (const :tag "At beginning of headline stars" t)
  1138. (function)))
  1139. (defcustom org-speed-commands-user nil
  1140. "Alist of additional speed commands.
  1141. This list will be checked before `org-speed-commands-default'
  1142. when the variable `org-use-speed-commands' is non-nil
  1143. and when the cursor is at the beginning of a headline.
  1144. The car of each entry is a string with a single letter, which must
  1145. be assigned to `self-insert-command' in the global map.
  1146. The cdr is either a command to be called interactively, a function
  1147. to be called, or a form to be evaluated.
  1148. An entry that is just a list with a single string will be interpreted
  1149. as a descriptive headline that will be added when listing the speed
  1150. commands in the Help buffer using the `?' speed command."
  1151. :group 'org-structure
  1152. :type '(repeat :value ("k" . ignore)
  1153. (choice :value ("k" . ignore)
  1154. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1155. (cons :tag "Letter and Command"
  1156. (string :tag "Command letter")
  1157. (choice
  1158. (function)
  1159. (sexp))))))
  1160. (defcustom org-bookmark-names-plist
  1161. '(:last-capture "org-capture-last-stored"
  1162. :last-refile "org-refile-last-stored"
  1163. :last-capture-marker "org-capture-last-stored-marker")
  1164. "Names for bookmarks automatically set by some Org commands.
  1165. This can provide strings as names for a number of bookmarks Org sets
  1166. automatically. The following keys are currently implemented:
  1167. :last-capture
  1168. :last-capture-marker
  1169. :last-refile
  1170. When a key does not show up in the property list, the corresponding bookmark
  1171. is not set."
  1172. :group 'org-structure
  1173. :type 'plist)
  1174. (defgroup org-cycle nil
  1175. "Options concerning visibility cycling in Org mode."
  1176. :tag "Org Cycle"
  1177. :group 'org-structure)
  1178. (defcustom org-cycle-skip-children-state-if-no-children t
  1179. "Non-nil means skip CHILDREN state in entries that don't have any."
  1180. :group 'org-cycle
  1181. :type 'boolean)
  1182. (defcustom org-cycle-max-level nil
  1183. "Maximum level which should still be subject to visibility cycling.
  1184. Levels higher than this will, for cycling, be treated as text, not a headline.
  1185. When `org-odd-levels-only' is set, a value of N in this variable actually
  1186. means 2N-1 stars as the limiting headline.
  1187. When nil, cycle all levels.
  1188. Note that the limiting level of cycling is also influenced by
  1189. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1190. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1191. than its value."
  1192. :group 'org-cycle
  1193. :type '(choice
  1194. (const :tag "No limit" nil)
  1195. (integer :tag "Maximum level")))
  1196. (defcustom org-hide-block-startup nil
  1197. "Non-nil means entering Org mode will fold all blocks.
  1198. This can also be set in on a per-file basis with
  1199. #+STARTUP: hideblocks
  1200. #+STARTUP: showblocks"
  1201. :group 'org-startup
  1202. :group 'org-cycle
  1203. :type 'boolean)
  1204. (defcustom org-cycle-global-at-bob nil
  1205. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1206. This makes it possible to do global cycling without having to use `S-TAB'
  1207. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1208. line of the buffer
  1209. must not be a headline -- it may be empty or some other text.
  1210. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1211. sure the cursor stays at the beginning of the buffer.
  1212. When this option is nil, don't do anything special at the beginning of
  1213. the buffer."
  1214. :group 'org-cycle
  1215. :type 'boolean)
  1216. (defcustom org-cycle-level-after-item/entry-creation t
  1217. "Non-nil means cycle entry level or item indentation in new empty entries.
  1218. When the cursor is at the end of an empty headline, i.e., with only stars
  1219. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1220. and then all possible ancestor states, before returning to the original state.
  1221. This makes data entry extremely fast: M-RET to create a new headline,
  1222. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1223. When the cursor is at the end of an empty plain list item, one TAB will
  1224. make it a subitem, two or more tabs will back up to make this an item
  1225. higher up in the item hierarchy."
  1226. :group 'org-cycle
  1227. :type 'boolean)
  1228. (defcustom org-cycle-emulate-tab t
  1229. "Where should `org-cycle' emulate TAB.
  1230. nil Never
  1231. white Only in completely white lines
  1232. whitestart Only at the beginning of lines, before the first non-white char
  1233. t Everywhere except in headlines
  1234. exc-hl-bol Everywhere except at the start of a headline
  1235. If TAB is used in a place where it does not emulate TAB, the current subtree
  1236. visibility is cycled."
  1237. :group 'org-cycle
  1238. :type '(choice (const :tag "Never" nil)
  1239. (const :tag "Only in completely white lines" white)
  1240. (const :tag "Before first char in a line" whitestart)
  1241. (const :tag "Everywhere except in headlines" t)
  1242. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1243. (defcustom org-cycle-separator-lines 2
  1244. "Number of empty lines needed to keep an empty line between collapsed trees.
  1245. If you leave an empty line between the end of a subtree and the following
  1246. headline, this empty line is hidden when the subtree is folded.
  1247. Org mode will leave (exactly) one empty line visible if the number of
  1248. empty lines is equal or larger to the number given in this variable.
  1249. So the default 2 means at least 2 empty lines after the end of a subtree
  1250. are needed to produce free space between a collapsed subtree and the
  1251. following headline.
  1252. If the number is negative, and the number of empty lines is at least -N,
  1253. all empty lines are shown.
  1254. Special case: when 0, never leave empty lines in collapsed view."
  1255. :group 'org-cycle
  1256. :type 'integer)
  1257. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1258. (defcustom org-pre-cycle-hook nil
  1259. "Hook that is run before visibility cycling is happening.
  1260. The function(s) in this hook must accept a single argument which indicates
  1261. the new state that will be set right after running this hook. The
  1262. argument is a symbol. Before a global state change, it can have the values
  1263. `overview', `content', or `all'. Before a local state change, it can have
  1264. the values `folded', `children', or `subtree'."
  1265. :group 'org-cycle
  1266. :type 'hook)
  1267. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1268. org-cycle-show-empty-lines
  1269. org-optimize-window-after-visibility-change)
  1270. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1271. The function(s) in this hook must accept a single argument which indicates
  1272. the new state that was set by the most recent `org-cycle' command. The
  1273. argument is a symbol. After a global state change, it can have the values
  1274. `overview', `contents', or `all'. After a local state change, it can have
  1275. the values `folded', `children', or `subtree'."
  1276. :group 'org-cycle
  1277. :type 'hook
  1278. :version "26.1"
  1279. :package-version '(Org . "8.3"))
  1280. (defgroup org-edit-structure nil
  1281. "Options concerning structure editing in Org mode."
  1282. :tag "Org Edit Structure"
  1283. :group 'org-structure)
  1284. (defcustom org-odd-levels-only nil
  1285. "Non-nil means skip even levels and only use odd levels for the outline.
  1286. This has the effect that two stars are being added/taken away in
  1287. promotion/demotion commands. It also influences how levels are
  1288. handled by the exporters.
  1289. Changing it requires restart of `font-lock-mode' to become effective
  1290. for fontification also in regions already fontified.
  1291. You may also set this on a per-file basis by adding one of the following
  1292. lines to the buffer:
  1293. #+STARTUP: odd
  1294. #+STARTUP: oddeven"
  1295. :group 'org-edit-structure
  1296. :group 'org-appearance
  1297. :type 'boolean)
  1298. (defcustom org-adapt-indentation t
  1299. "Non-nil means adapt indentation to outline node level.
  1300. When this variable is set, Org assumes that you write outlines by
  1301. indenting text in each node to align with the headline (after the
  1302. stars). The following issues are influenced by this variable:
  1303. - The indentation is increased by one space in a demotion
  1304. command, and decreased by one in a promotion command. However,
  1305. in the latter case, if shifting some line in the entry body
  1306. would alter document structure (e.g., insert a new headline),
  1307. indentation is not changed at all.
  1308. - Property drawers and planning information is inserted indented
  1309. when this variable is set. When nil, they will not be indented.
  1310. - TAB indents a line relative to current level. The lines below
  1311. a headline will be indented when this variable is set.
  1312. Note that this is all about true indentation, by adding and
  1313. removing space characters. See also \"org-indent.el\" which does
  1314. level-dependent indentation in a virtual way, i.e. at display
  1315. time in Emacs."
  1316. :group 'org-edit-structure
  1317. :type 'boolean
  1318. :safe #'booleanp)
  1319. (defcustom org-special-ctrl-a/e nil
  1320. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1321. When t, `C-a' will bring back the cursor to the beginning of the
  1322. headline text, i.e. after the stars and after a possible TODO
  1323. keyword. In an item, this will be the position after bullet and
  1324. check-box, if any. When the cursor is already at that position,
  1325. another `C-a' will bring it to the beginning of the line.
  1326. `C-e' will jump to the end of the headline, ignoring the presence
  1327. of tags in the headline. A second `C-e' will then jump to the
  1328. true end of the line, after any tags. This also means that, when
  1329. this variable is non-nil, `C-e' also will never jump beyond the
  1330. end of the heading of a folded section, i.e. not after the
  1331. ellipses.
  1332. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1333. normally, going to the true line boundary first. Only a directly
  1334. following, identical keypress will bring the cursor to the
  1335. special positions.
  1336. This may also be a cons cell where the behavior for `C-a' and
  1337. `C-e' is set separately."
  1338. :group 'org-edit-structure
  1339. :type '(choice
  1340. (const :tag "off" nil)
  1341. (const :tag "on: after stars/bullet and before tags first" t)
  1342. (const :tag "reversed: true line boundary first" reversed)
  1343. (cons :tag "Set C-a and C-e separately"
  1344. (choice :tag "Special C-a"
  1345. (const :tag "off" nil)
  1346. (const :tag "on: after stars/bullet first" t)
  1347. (const :tag "reversed: before stars/bullet first" reversed))
  1348. (choice :tag "Special C-e"
  1349. (const :tag "off" nil)
  1350. (const :tag "on: before tags first" t)
  1351. (const :tag "reversed: after tags first" reversed)))))
  1352. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1353. (defcustom org-special-ctrl-k nil
  1354. "Non-nil means `C-k' will behave specially in headlines.
  1355. When nil, `C-k' will call the default `kill-line' command.
  1356. When t, the following will happen while the cursor is in the headline:
  1357. - When the cursor is at the beginning of a headline, kill the entire
  1358. line and possible the folded subtree below the line.
  1359. - When in the middle of the headline text, kill the headline up to the tags.
  1360. - When after the headline text, kill the tags."
  1361. :group 'org-edit-structure
  1362. :type 'boolean)
  1363. (defcustom org-ctrl-k-protect-subtree nil
  1364. "Non-nil means, do not delete a hidden subtree with C-k.
  1365. When set to the symbol `error', simply throw an error when C-k is
  1366. used to kill (part-of) a headline that has hidden text behind it.
  1367. Any other non-nil value will result in a query to the user, if it is
  1368. OK to kill that hidden subtree. When nil, kill without remorse."
  1369. :group 'org-edit-structure
  1370. :version "24.1"
  1371. :type '(choice
  1372. (const :tag "Do not protect hidden subtrees" nil)
  1373. (const :tag "Protect hidden subtrees with a security query" t)
  1374. (const :tag "Never kill a hidden subtree with C-k" error)))
  1375. (defcustom org-special-ctrl-o t
  1376. "Non-nil means, make `C-o' insert a row in tables."
  1377. :group 'org-edit-structure
  1378. :type 'boolean)
  1379. (defcustom org-catch-invisible-edits nil
  1380. "Check if in invisible region before inserting or deleting a character.
  1381. Valid values are:
  1382. nil Do not check, so just do invisible edits.
  1383. error Throw an error and do nothing.
  1384. show Make point visible, and do the requested edit.
  1385. show-and-error Make point visible, then throw an error and abort the edit.
  1386. smart Make point visible, and do insertion/deletion if it is
  1387. adjacent to visible text and the change feels predictable.
  1388. Never delete a previously invisible character or add in the
  1389. middle or right after an invisible region. Basically, this
  1390. allows insertion and backward-delete right before ellipses.
  1391. FIXME: maybe in this case we should not even show?"
  1392. :group 'org-edit-structure
  1393. :version "24.1"
  1394. :type '(choice
  1395. (const :tag "Do not check" nil)
  1396. (const :tag "Throw error when trying to edit" error)
  1397. (const :tag "Unhide, but do not do the edit" show-and-error)
  1398. (const :tag "Show invisible part and do the edit" show)
  1399. (const :tag "Be smart and do the right thing" smart)))
  1400. (defcustom org-yank-folded-subtrees t
  1401. "Non-nil means when yanking subtrees, fold them.
  1402. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1403. it starts with a heading and all other headings in it are either children
  1404. or siblings, then fold all the subtrees. However, do this only if no
  1405. text after the yank would be swallowed into a folded tree by this action."
  1406. :group 'org-edit-structure
  1407. :type 'boolean)
  1408. (defcustom org-yank-adjusted-subtrees nil
  1409. "Non-nil means when yanking subtrees, adjust the level.
  1410. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1411. this function for details."
  1412. :group 'org-edit-structure
  1413. :type 'boolean)
  1414. (defcustom org-M-RET-may-split-line '((default . t))
  1415. "Non-nil means M-RET will split the line at the cursor position.
  1416. When nil, it will go to the end of the line before making a
  1417. new line.
  1418. You may also set this option in a different way for different
  1419. contexts. Valid contexts are:
  1420. headline when creating a new headline
  1421. item when creating a new item
  1422. table in a table field
  1423. default the value to be used for all contexts not explicitly
  1424. customized"
  1425. :group 'org-structure
  1426. :group 'org-table
  1427. :type '(choice
  1428. (const :tag "Always" t)
  1429. (const :tag "Never" nil)
  1430. (repeat :greedy t :tag "Individual contexts"
  1431. (cons
  1432. (choice :tag "Context"
  1433. (const headline)
  1434. (const item)
  1435. (const table)
  1436. (const default))
  1437. (boolean)))))
  1438. (defcustom org-insert-heading-respect-content nil
  1439. "Non-nil means insert new headings after the current subtree.
  1440. \\<org-mode-map>
  1441. When nil, the new heading is created directly after the current line.
  1442. The commands `\\[org-insert-heading-respect-content]' and \
  1443. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1444. for the duration of the command."
  1445. :group 'org-structure
  1446. :type 'boolean)
  1447. (defcustom org-blank-before-new-entry '((heading . auto)
  1448. (plain-list-item . auto))
  1449. "Should `org-insert-heading' leave a blank line before new heading/item?
  1450. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1451. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1452. which case Org will look at the surrounding headings/items and try to
  1453. make an intelligent decision whether to insert a blank line or not."
  1454. :group 'org-edit-structure
  1455. :type '(list
  1456. (cons (const heading)
  1457. (choice (const :tag "Never" nil)
  1458. (const :tag "Always" t)
  1459. (const :tag "Auto" auto)))
  1460. (cons (const plain-list-item)
  1461. (choice (const :tag "Never" nil)
  1462. (const :tag "Always" t)
  1463. (const :tag "Auto" auto)))))
  1464. (defcustom org-insert-heading-hook nil
  1465. "Hook being run after inserting a new heading."
  1466. :group 'org-edit-structure
  1467. :type 'hook)
  1468. (defcustom org-enable-fixed-width-editor t
  1469. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1470. This currently only means they are never auto-wrapped.
  1471. When nil, such lines will be treated like ordinary lines."
  1472. :group 'org-edit-structure
  1473. :type 'boolean)
  1474. (defgroup org-sparse-trees nil
  1475. "Options concerning sparse trees in Org mode."
  1476. :tag "Org Sparse Trees"
  1477. :group 'org-structure)
  1478. (defcustom org-highlight-sparse-tree-matches t
  1479. "Non-nil means highlight all matches that define a sparse tree.
  1480. The highlights will automatically disappear the next time the buffer is
  1481. changed by an edit command."
  1482. :group 'org-sparse-trees
  1483. :type 'boolean)
  1484. (defcustom org-remove-highlights-with-change t
  1485. "Non-nil means any change to the buffer will remove temporary highlights.
  1486. \\<org-mode-map>\
  1487. Such highlights are created by `org-occur' and `org-clock-display'.
  1488. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1489. to get rid of the highlights.
  1490. The highlights created by `org-toggle-latex-fragment' always need
  1491. `\\[org-toggle-latex-fragment]' to be removed."
  1492. :group 'org-sparse-trees
  1493. :group 'org-time
  1494. :type 'boolean)
  1495. (defcustom org-occur-case-fold-search t
  1496. "Non-nil means `org-occur' should be case-insensitive.
  1497. If set to `smart' the search will be case-insensitive only if it
  1498. doesn't specify any upper case character."
  1499. :group 'org-sparse-trees
  1500. :version "26.1"
  1501. :type '(choice
  1502. (const :tag "Case-sensitive" nil)
  1503. (const :tag "Case-insensitive" t)
  1504. (const :tag "Case-insensitive for lower case searches only" smart)))
  1505. (defcustom org-occur-hook '(org-first-headline-recenter)
  1506. "Hook that is run after `org-occur' has constructed a sparse tree.
  1507. This can be used to recenter the window to show as much of the structure
  1508. as possible."
  1509. :group 'org-sparse-trees
  1510. :type 'hook)
  1511. (defgroup org-table nil
  1512. "Options concerning tables in Org mode."
  1513. :tag "Org Table"
  1514. :group 'org)
  1515. (defcustom org-self-insert-cluster-for-undo nil
  1516. "Non-nil means cluster self-insert commands for undo when possible.
  1517. If this is set, then, like in the Emacs command loop, 20 consecutive
  1518. characters will be undone together.
  1519. This is configurable, because there is some impact on typing performance."
  1520. :group 'org-table
  1521. :type 'boolean)
  1522. (defcustom org-table-tab-recognizes-table.el t
  1523. "Non-nil means TAB will automatically notice a table.el table.
  1524. When it sees such a table, it moves point into it and - if necessary -
  1525. calls `table-recognize-table'."
  1526. :group 'org-table-editing
  1527. :type 'boolean)
  1528. (defgroup org-link nil
  1529. "Options concerning links in Org mode."
  1530. :tag "Org Link"
  1531. :group 'org)
  1532. (defvar-local org-link-abbrev-alist-local nil
  1533. "Buffer-local version of `org-link-abbrev-alist', which see.
  1534. The value of this is taken from the #+LINK lines.")
  1535. (defcustom org-link-parameters
  1536. '(("doi" :follow org--open-doi-link)
  1537. ("elisp" :follow org--open-elisp-link)
  1538. ("file" :complete org-file-complete-link)
  1539. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1540. ("help" :follow org--open-help-link)
  1541. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1542. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1543. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1544. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1545. ("shell" :follow org--open-shell-link))
  1546. "An alist of properties that defines all the links in Org mode.
  1547. The key in each association is a string of the link type.
  1548. Subsequent optional elements make up a p-list of link properties.
  1549. :follow - A function that takes the link path as an argument.
  1550. :export - A function that takes the link path, description and
  1551. export-backend as arguments.
  1552. :store - A function responsible for storing the link. See the
  1553. function `org-store-link-functions'.
  1554. :complete - A function that inserts a link with completion. The
  1555. function takes one optional prefix arg.
  1556. :face - A face for the link, or a function that returns a face.
  1557. The function takes one argument which is the link path. The
  1558. default face is `org-link'.
  1559. :mouse-face - The mouse-face. The default is `highlight'.
  1560. :display - `full' will not fold the link in descriptive
  1561. display. Default is `org-link'.
  1562. :help-echo - A string or function that takes (window object position)
  1563. as arguments and returns a string.
  1564. :keymap - A keymap that is active on the link. The default is
  1565. `org-mouse-map'.
  1566. :htmlize-link - A function for the htmlize-link. Defaults
  1567. to (list :uri \"type:path\")
  1568. :activate-func - A function to run at the end of font-lock
  1569. activation. The function must accept (link-start link-end path bracketp)
  1570. as arguments."
  1571. :group 'org-link
  1572. :type '(alist :tag "Link display parameters"
  1573. :value-type plist)
  1574. :version "26.1"
  1575. :package-version '(Org . "9.1"))
  1576. (defun org-link-get-parameter (type key)
  1577. "Get TYPE link property for KEY.
  1578. TYPE is a string and KEY is a plist keyword."
  1579. (plist-get
  1580. (cdr (assoc type org-link-parameters))
  1581. key))
  1582. (defun org-link-set-parameters (type &rest parameters)
  1583. "Set link TYPE properties to PARAMETERS.
  1584. PARAMETERS should be :key val pairs."
  1585. (let ((data (assoc type org-link-parameters)))
  1586. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1587. (push (cons type parameters) org-link-parameters)
  1588. (org-make-link-regexps)
  1589. (org-element-update-syntax))))
  1590. (defun org-link-types ()
  1591. "Return a list of known link types."
  1592. (mapcar #'car org-link-parameters))
  1593. (defcustom org-link-abbrev-alist nil
  1594. "Alist of link abbreviations.
  1595. The car of each element is a string, to be replaced at the start of a link.
  1596. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1597. links in Org buffers can have an optional tag after a double colon, e.g.,
  1598. [[linkkey:tag][description]]
  1599. The `linkkey' must be a single word, starting with a letter, followed
  1600. by letters, numbers, `-' or `_'.
  1601. If REPLACE is a string, the tag will simply be appended to create the link.
  1602. If the string contains \"%s\", the tag will be inserted there. If the string
  1603. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1604. at that point (see the function `url-hexify-string'). If the string contains
  1605. the specifier \"%(my-function)\", then the custom function `my-function' will
  1606. be invoked: this function takes the tag as its only argument and must return
  1607. a string.
  1608. REPLACE may also be a function that will be called with the tag as the
  1609. only argument to create the link, which should be returned as a string.
  1610. See the manual for examples."
  1611. :group 'org-link
  1612. :type '(repeat
  1613. (cons
  1614. (string :tag "Protocol")
  1615. (choice
  1616. (string :tag "Format")
  1617. (function)))))
  1618. (defcustom org-descriptive-links t
  1619. "Non-nil means Org will display descriptive links.
  1620. E.g. [[https://orgmode.org][Org website]] will be displayed as
  1621. \"Org Website\", hiding the link itself and just displaying its
  1622. description. When set to nil, Org will display the full links
  1623. literally.
  1624. You can interactively set the value of this variable by calling
  1625. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1626. :group 'org-link
  1627. :type 'boolean)
  1628. (defcustom org-link-file-path-type 'adaptive
  1629. "How the path name in file links should be stored.
  1630. Valid values are:
  1631. relative Relative to the current directory, i.e. the directory of the file
  1632. into which the link is being inserted.
  1633. absolute Absolute path, if possible with ~ for home directory.
  1634. noabbrev Absolute path, no abbreviation of home directory.
  1635. adaptive Use relative path for files in the current directory and sub-
  1636. directories of it. For other files, use an absolute path."
  1637. :group 'org-link
  1638. :type '(choice
  1639. (const relative)
  1640. (const absolute)
  1641. (const noabbrev)
  1642. (const adaptive)))
  1643. (defvaralias 'org-activate-links 'org-highlight-links)
  1644. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1645. "Types of links that should be highlighted in Org files.
  1646. This is a list of symbols, each one of them leading to the
  1647. highlighting of a certain link type.
  1648. You can still open links that are not highlighted.
  1649. In principle, it does not hurt to turn on highlighting for all
  1650. link types. There may be a small gain when turning off unused
  1651. link types. The types are:
  1652. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1653. angle Links in angular brackets that may contain whitespace like
  1654. <bbdb:Carsten Dominik>.
  1655. plain Plain links in normal text, no whitespace, like http://google.com.
  1656. radio Text that is matched by a radio target, see manual for details.
  1657. tag Tag settings in a headline (link to tag search).
  1658. date Time stamps (link to calendar).
  1659. footnote Footnote labels.
  1660. If you set this variable during an Emacs session, use `org-mode-restart'
  1661. in the Org buffer so that the change takes effect."
  1662. :group 'org-link
  1663. :group 'org-appearance
  1664. :type '(set :greedy t
  1665. (const :tag "Double bracket links" bracket)
  1666. (const :tag "Angular bracket links" angle)
  1667. (const :tag "Plain text links" plain)
  1668. (const :tag "Radio target matches" radio)
  1669. (const :tag "Tags" tag)
  1670. (const :tag "Timestamps" date)
  1671. (const :tag "Footnotes" footnote)))
  1672. (defcustom org-make-link-description-function nil
  1673. "Function to use for generating link descriptions from links.
  1674. This function must take two parameters: the first one is the
  1675. link, the second one is the description generated by
  1676. `org-insert-link'. The function should return the description to
  1677. use."
  1678. :group 'org-link
  1679. :type '(choice (const nil) (function)))
  1680. (defgroup org-link-store nil
  1681. "Options concerning storing links in Org mode."
  1682. :tag "Org Store Link"
  1683. :group 'org-link)
  1684. (defcustom org-url-hexify-p t
  1685. "When non-nil, hexify URL when creating a link."
  1686. :type 'boolean
  1687. :version "24.3"
  1688. :group 'org-link-store)
  1689. (defcustom org-email-link-description-format "Email %c: %.30s"
  1690. "Format of the description part of a link to an email or usenet message.
  1691. The following %-escapes will be replaced by corresponding information:
  1692. %F full \"From\" field
  1693. %f name, taken from \"From\" field, address if no name
  1694. %T full \"To\" field
  1695. %t first name in \"To\" field, address if no name
  1696. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1697. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1698. %s subject
  1699. %d date
  1700. %m message-id.
  1701. You may use normal field width specification between the % and the letter.
  1702. This is for example useful to limit the length of the subject.
  1703. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1704. :group 'org-link-store
  1705. :type 'string)
  1706. (defcustom org-from-is-user-regexp
  1707. (let (r1 r2)
  1708. (when (and user-mail-address (not (string= user-mail-address "")))
  1709. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1710. (when (and user-full-name (not (string= user-full-name "")))
  1711. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1712. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1713. "Regexp matched against the \"From:\" header of an email or usenet message.
  1714. It should match if the message is from the user him/herself."
  1715. :group 'org-link-store
  1716. :type 'regexp)
  1717. (defcustom org-context-in-file-links t
  1718. "Non-nil means file links from `org-store-link' contain context.
  1719. \\<org-mode-map>
  1720. A search string will be added to the file name with :: as separator
  1721. and used to find the context when the link is activated by the command
  1722. `org-open-at-point'. When this option is t, the entire active region
  1723. will be placed in the search string of the file link. If set to a
  1724. positive integer, only the first n lines of context will be stored.
  1725. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1726. \\[org-store-link]')
  1727. negates this setting for the duration of the command."
  1728. :group 'org-link-store
  1729. :type '(choice boolean integer))
  1730. (defcustom org-keep-stored-link-after-insertion nil
  1731. "Non-nil means keep link in list for entire session.
  1732. \\<org-mode-map>
  1733. The command `org-store-link' adds a link pointing to the current
  1734. location to an internal list. These links accumulate during a session.
  1735. The command `org-insert-link' can be used to insert links into any
  1736. Org file (offering completion for all stored links).
  1737. When this option is nil, every link which has been inserted once using
  1738. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1739. unused
  1740. links more efficient."
  1741. :group 'org-link-store
  1742. :type 'boolean)
  1743. (defgroup org-link-follow nil
  1744. "Options concerning following links in Org mode."
  1745. :tag "Org Follow Link"
  1746. :group 'org-link)
  1747. (defcustom org-link-translation-function nil
  1748. "Function to translate links with different syntax to Org syntax.
  1749. This can be used to translate links created for example by the Planner
  1750. or emacs-wiki packages to Org syntax.
  1751. The function must accept two parameters, a TYPE containing the link
  1752. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1753. which is everything after the link protocol. It should return a cons
  1754. with possibly modified values of type and path.
  1755. Org contains a function for this, so if you set this variable to
  1756. `org-translate-link-from-planner', you should be able follow many
  1757. links created by planner."
  1758. :group 'org-link-follow
  1759. :type '(choice (const nil) (function)))
  1760. (defcustom org-follow-link-hook nil
  1761. "Hook that is run after a link has been followed."
  1762. :group 'org-link-follow
  1763. :type 'hook)
  1764. (defcustom org-tab-follows-link nil
  1765. "Non-nil means on links TAB will follow the link.
  1766. Needs to be set before org.el is loaded.
  1767. This really should not be used, it does not make sense, and the
  1768. implementation is bad."
  1769. :group 'org-link-follow
  1770. :type 'boolean)
  1771. (defcustom org-return-follows-link nil
  1772. "Non-nil means on links RET will follow the link.
  1773. In tables, the special behavior of RET has precedence."
  1774. :group 'org-link-follow
  1775. :type 'boolean)
  1776. (defcustom org-mouse-1-follows-link
  1777. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1778. "Non-nil means mouse-1 on a link will follow the link.
  1779. A longer mouse click will still set point. Needs to be set
  1780. before org.el is loaded."
  1781. :group 'org-link-follow
  1782. :version "26.1"
  1783. :package-version '(Org . "8.3")
  1784. :type '(choice
  1785. (const :tag "A double click follows the link" double)
  1786. (const :tag "Unconditionally follow the link with mouse-1" t)
  1787. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1788. (defcustom org-mark-ring-length 4
  1789. "Number of different positions to be recorded in the ring.
  1790. Changing this requires a restart of Emacs to work correctly."
  1791. :group 'org-link-follow
  1792. :type 'integer)
  1793. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1794. "Non-nil means internal fuzzy links can only match headlines.
  1795. When nil, the a fuzzy link may point to a target or a named
  1796. construct in the document. When set to the special value
  1797. `query-to-create', offer to create a new headline when none
  1798. matched.
  1799. Spaces and statistics cookies are ignored during heading searches."
  1800. :group 'org-link-follow
  1801. :version "24.1"
  1802. :type '(choice
  1803. (const :tag "Use fuzzy text search" nil)
  1804. (const :tag "Match only exact headline" t)
  1805. (const :tag "Match exact headline or query to create it"
  1806. query-to-create))
  1807. :safe #'symbolp)
  1808. (defcustom org-link-frame-setup
  1809. '((vm . vm-visit-folder-other-frame)
  1810. (vm-imap . vm-visit-imap-folder-other-frame)
  1811. (gnus . org-gnus-no-new-news)
  1812. (file . find-file-other-window)
  1813. (wl . wl-other-frame))
  1814. "Setup the frame configuration for following links.
  1815. When following a link with Emacs, it may often be useful to display
  1816. this link in another window or frame. This variable can be used to
  1817. set this up for the different types of links.
  1818. For VM, use any of
  1819. `vm-visit-folder'
  1820. `vm-visit-folder-other-window'
  1821. `vm-visit-folder-other-frame'
  1822. For Gnus, use any of
  1823. `gnus'
  1824. `gnus-other-frame'
  1825. `org-gnus-no-new-news'
  1826. For FILE, use any of
  1827. `find-file'
  1828. `find-file-other-window'
  1829. `find-file-other-frame'
  1830. For Wanderlust use any of
  1831. `wl'
  1832. `wl-other-frame'
  1833. For the calendar, use the variable `calendar-setup'.
  1834. For BBDB, it is currently only possible to display the matches in
  1835. another window."
  1836. :group 'org-link-follow
  1837. :type '(list
  1838. (cons (const vm)
  1839. (choice
  1840. (const vm-visit-folder)
  1841. (const vm-visit-folder-other-window)
  1842. (const vm-visit-folder-other-frame)))
  1843. (cons (const vm-imap)
  1844. (choice
  1845. (const vm-visit-imap-folder)
  1846. (const vm-visit-imap-folder-other-window)
  1847. (const vm-visit-imap-folder-other-frame)))
  1848. (cons (const gnus)
  1849. (choice
  1850. (const gnus)
  1851. (const gnus-other-frame)
  1852. (const org-gnus-no-new-news)))
  1853. (cons (const file)
  1854. (choice
  1855. (const find-file)
  1856. (const find-file-other-window)
  1857. (const find-file-other-frame)))
  1858. (cons (const wl)
  1859. (choice
  1860. (const wl)
  1861. (const wl-other-frame)))))
  1862. (defcustom org-display-internal-link-with-indirect-buffer nil
  1863. "Non-nil means use indirect buffer to display infile links.
  1864. Activating internal links (from one location in a file to another location
  1865. in the same file) normally just jumps to the location. When the link is
  1866. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1867. is displayed in
  1868. another window. When this option is set, the other window actually displays
  1869. an indirect buffer clone of the current buffer, to avoid any visibility
  1870. changes to the current buffer."
  1871. :group 'org-link-follow
  1872. :type 'boolean)
  1873. (defcustom org-open-non-existing-files nil
  1874. "Non-nil means `org-open-file' will open non-existing files.
  1875. When nil, an error will be generated.
  1876. This variable applies only to external applications because they
  1877. might choke on non-existing files. If the link is to a file that
  1878. will be opened in Emacs, the variable is ignored."
  1879. :group 'org-link-follow
  1880. :type 'boolean)
  1881. (defcustom org-open-directory-means-index-dot-org nil
  1882. "Non-nil means a link to a directory really means to index.org.
  1883. When nil, following a directory link will run dired or open a finder/explorer
  1884. window on that directory."
  1885. :group 'org-link-follow
  1886. :type 'boolean)
  1887. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1888. "Non-nil means ask for confirmation before executing shell links.
  1889. Shell links can be dangerous: just think about a link
  1890. [[shell:rm -rf ~/*][Google Search]]
  1891. This link would show up in your Org document as \"Google Search\",
  1892. but really it would remove your entire home directory.
  1893. Therefore we advise against setting this variable to nil.
  1894. Just change it to `y-or-n-p' if you want to confirm with a
  1895. single keystroke rather than having to type \"yes\"."
  1896. :group 'org-link-follow
  1897. :type '(choice
  1898. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1899. (const :tag "with y-or-n (faster)" y-or-n-p)
  1900. (const :tag "no confirmation (dangerous)" nil)))
  1901. (put 'org-confirm-shell-link-function
  1902. 'safe-local-variable
  1903. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1904. (defcustom org-confirm-shell-link-not-regexp ""
  1905. "A regexp to skip confirmation for shell links."
  1906. :group 'org-link-follow
  1907. :version "24.1"
  1908. :type 'regexp)
  1909. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1910. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1911. Elisp links can be dangerous: just think about a link
  1912. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1913. This link would show up in your Org document as \"Google Search\",
  1914. but really it would remove your entire home directory.
  1915. Therefore we advise against setting this variable to nil.
  1916. Just change it to `y-or-n-p' if you want to confirm with a
  1917. single keystroke rather than having to type \"yes\"."
  1918. :group 'org-link-follow
  1919. :type '(choice
  1920. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1921. (const :tag "with y-or-n (faster)" y-or-n-p)
  1922. (const :tag "no confirmation (dangerous)" nil)))
  1923. (put 'org-confirm-shell-link-function
  1924. 'safe-local-variable
  1925. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1926. (defcustom org-confirm-elisp-link-not-regexp ""
  1927. "A regexp to skip confirmation for Elisp links."
  1928. :group 'org-link-follow
  1929. :version "24.1"
  1930. :type 'regexp)
  1931. (defconst org-file-apps-defaults-gnu
  1932. '((remote . emacs)
  1933. (system . mailcap)
  1934. (t . mailcap))
  1935. "Default file applications on a UNIX or GNU/Linux system.
  1936. See `org-file-apps'.")
  1937. (defconst org-file-apps-defaults-macosx
  1938. '((remote . emacs)
  1939. (system . "open %s")
  1940. ("ps.gz" . "gv %s")
  1941. ("eps.gz" . "gv %s")
  1942. ("dvi" . "xdvi %s")
  1943. ("fig" . "xfig %s")
  1944. (t . "open %s"))
  1945. "Default file applications on a macOS system.
  1946. The system \"open\" is known as a default, but we use X11 applications
  1947. for some files for which the OS does not have a good default.
  1948. See `org-file-apps'.")
  1949. (defconst org-file-apps-defaults-windowsnt
  1950. (list '(remote . emacs)
  1951. (cons 'system (lambda (file _path)
  1952. (with-no-warnings (w32-shell-execute "open" file))))
  1953. (cons t (lambda (file _path)
  1954. (with-no-warnings (w32-shell-execute "open" file)))))
  1955. "Default file applications on a Windows NT system.
  1956. The system \"open\" is used for most files.
  1957. See `org-file-apps'.")
  1958. (defcustom org-file-apps
  1959. '((auto-mode . emacs)
  1960. ("\\.mm\\'" . default)
  1961. ("\\.x?html?\\'" . default)
  1962. ("\\.pdf\\'" . default))
  1963. "External applications for opening `file:path' items in a document.
  1964. \\<org-mode-map>\
  1965. Org mode uses system defaults for different file types, but
  1966. you can use this variable to set the application for a given file
  1967. extension. The entries in this list are cons cells where the car identifies
  1968. files and the cdr the corresponding command.
  1969. Possible values for the file identifier are:
  1970. \"string\" A string as a file identifier can be interpreted in different
  1971. ways, depending on its contents:
  1972. - Alphanumeric characters only:
  1973. Match links with this file extension.
  1974. Example: (\"pdf\" . \"evince %s\")
  1975. to open PDFs with evince.
  1976. - Regular expression: Match links where the
  1977. filename matches the regexp. If you want to
  1978. use groups here, use shy groups.
  1979. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1980. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1981. to open *.html and *.xhtml with firefox.
  1982. - Regular expression which contains (non-shy) groups:
  1983. Match links where the whole link, including \"::\", and
  1984. anything after that, matches the regexp.
  1985. In a custom command string, %1, %2, etc. are replaced with
  1986. the parts of the link that were matched by the groups.
  1987. For backwards compatibility, if a command string is given
  1988. that does not use any of the group matches, this case is
  1989. handled identically to the second one (i.e. match against
  1990. file name only).
  1991. In a custom function, you can access the group matches with
  1992. (match-string n link).
  1993. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1994. \"evince -p %1 %s\")
  1995. to open [[file:document.pdf::5]] with evince at page 5.
  1996. `directory' Matches a directory
  1997. `remote' Matches a remote file, accessible through tramp or efs.
  1998. Remote files most likely should be visited through Emacs
  1999. because external applications cannot handle such paths.
  2000. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  2001. so all files Emacs knows how to handle. Using this with
  2002. command `emacs' will open most files in Emacs. Beware that this
  2003. will also open html files inside Emacs, unless you add
  2004. (\"html\" . default) to the list as well.
  2005. `system' The system command to open files, like `open' on Windows
  2006. and macOS, and mailcap under GNU/Linux. This is the command
  2007. that will be selected if you call `org-open-at-point' with a
  2008. double prefix argument (`\\[universal-argument] \
  2009. \\[universal-argument] \\[org-open-at-point]').
  2010. t Default for files not matched by any of the other options.
  2011. Possible values for the command are:
  2012. `emacs' The file will be visited by the current Emacs process.
  2013. `default' Use the default application for this file type, which is the
  2014. association for t in the list, most likely in the system-specific
  2015. part. This can be used to overrule an unwanted setting in the
  2016. system-specific variable.
  2017. `system' Use the system command for opening files, like \"open\".
  2018. This command is specified by the entry whose car is `system'.
  2019. Most likely, the system-specific version of this variable
  2020. does define this command, but you can overrule/replace it
  2021. here.
  2022. `mailcap' Use command specified in the mailcaps.
  2023. string A command to be executed by a shell; %s will be replaced
  2024. by the path to the file.
  2025. function A Lisp function, which will be called with two arguments:
  2026. the file path and the original link string, without the
  2027. \"file:\" prefix.
  2028. For more examples, see the system specific constants
  2029. `org-file-apps-defaults-macosx'
  2030. `org-file-apps-defaults-windowsnt'
  2031. `org-file-apps-defaults-gnu'."
  2032. :group 'org-link-follow
  2033. :type '(repeat
  2034. (cons (choice :value ""
  2035. (string :tag "Extension")
  2036. (const :tag "System command to open files" system)
  2037. (const :tag "Default for unrecognized files" t)
  2038. (const :tag "Remote file" remote)
  2039. (const :tag "Links to a directory" directory)
  2040. (const :tag "Any files that have Emacs modes"
  2041. auto-mode))
  2042. (choice :value ""
  2043. (const :tag "Visit with Emacs" emacs)
  2044. (const :tag "Use default" default)
  2045. (const :tag "Use the system command" system)
  2046. (string :tag "Command")
  2047. (function :tag "Function")))))
  2048. (defcustom org-doi-server-url "http://dx.doi.org/"
  2049. "The URL of the DOI server."
  2050. :type 'string
  2051. :version "24.3"
  2052. :group 'org-link-follow)
  2053. (defgroup org-refile nil
  2054. "Options concerning refiling entries in Org mode."
  2055. :tag "Org Refile"
  2056. :group 'org)
  2057. (defcustom org-directory "~/org"
  2058. "Directory with Org files.
  2059. This is just a default location to look for Org files. There is no need
  2060. at all to put your files into this directory. It is used in the
  2061. following situations:
  2062. 1. When a capture template specifies a target file that is not an
  2063. absolute path. The path will then be interpreted relative to
  2064. `org-directory'
  2065. 2. When the value of variable `org-agenda-files' is a single file, any
  2066. relative paths in this file will be taken as relative to
  2067. `org-directory'."
  2068. :group 'org-refile
  2069. :group 'org-capture
  2070. :type 'directory)
  2071. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2072. "Default target for storing notes.
  2073. Used as a fall back file for org-capture.el, for templates that
  2074. do not specify a target file."
  2075. :group 'org-refile
  2076. :group 'org-capture
  2077. :type 'file)
  2078. (defcustom org-reverse-note-order nil
  2079. "Non-nil means store new notes at the beginning of a file or entry.
  2080. When nil, new notes will be filed to the end of a file or entry.
  2081. This can also be a list with cons cells of regular expressions that
  2082. are matched against file names, and values."
  2083. :group 'org-capture
  2084. :group 'org-refile
  2085. :type '(choice
  2086. (const :tag "Reverse always" t)
  2087. (const :tag "Reverse never" nil)
  2088. (repeat :tag "By file name regexp"
  2089. (cons regexp boolean))))
  2090. (defcustom org-log-refile nil
  2091. "Information to record when a task is refiled.
  2092. Possible values are:
  2093. nil Don't add anything
  2094. time Add a time stamp to the task
  2095. note Prompt for a note and add it with template `org-log-note-headings'
  2096. This option can also be set with on a per-file-basis with
  2097. #+STARTUP: nologrefile
  2098. #+STARTUP: logrefile
  2099. #+STARTUP: lognoterefile
  2100. You can have local logging settings for a subtree by setting the LOGGING
  2101. property to one or more of these keywords.
  2102. When bulk-refiling from the agenda, the value `note' is forbidden and
  2103. will temporarily be changed to `time'."
  2104. :group 'org-refile
  2105. :group 'org-progress
  2106. :version "24.1"
  2107. :type '(choice
  2108. (const :tag "No logging" nil)
  2109. (const :tag "Record timestamp" time)
  2110. (const :tag "Record timestamp with note." note)))
  2111. (defcustom org-refile-targets nil
  2112. "Targets for refiling entries with `\\[org-refile]'.
  2113. This is a list of cons cells. Each cell contains:
  2114. - a specification of the files to be considered, either a list of files,
  2115. or a symbol whose function or variable value will be used to retrieve
  2116. a file name or a list of file names. If you use `org-agenda-files' for
  2117. that, all agenda files will be scanned for targets. Nil means consider
  2118. headings in the current buffer.
  2119. - A specification of how to find candidate refile targets. This may be
  2120. any of:
  2121. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2122. This tag has to be present in all target headlines, inheritance will
  2123. not be considered.
  2124. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2125. todo keyword.
  2126. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2127. headlines that are refiling targets.
  2128. - a cons cell (:level . N). Any headline of level N is considered a target.
  2129. Note that, when `org-odd-levels-only' is set, level corresponds to
  2130. order in hierarchy, not to the number of stars.
  2131. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2132. Note that, when `org-odd-levels-only' is set, level corresponds to
  2133. order in hierarchy, not to the number of stars.
  2134. Each element of this list generates a set of possible targets.
  2135. The union of these sets is presented (with completion) to
  2136. the user by `org-refile'.
  2137. You can set the variable `org-refile-target-verify-function' to a function
  2138. to verify each headline found by the simple criteria above.
  2139. When this variable is nil, all top-level headlines in the current buffer
  2140. are used, equivalent to the value `((nil . (:level . 1))'."
  2141. :group 'org-refile
  2142. :type '(repeat
  2143. (cons
  2144. (choice :value org-agenda-files
  2145. (const :tag "All agenda files" org-agenda-files)
  2146. (const :tag "Current buffer" nil)
  2147. (function) (variable) (file))
  2148. (choice :tag "Identify target headline by"
  2149. (cons :tag "Specific tag" (const :value :tag) (string))
  2150. (cons :tag "TODO keyword" (const :value :todo) (string))
  2151. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2152. (cons :tag "Level number" (const :value :level) (integer))
  2153. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2154. (defcustom org-refile-target-verify-function nil
  2155. "Function to verify if the headline at point should be a refile target.
  2156. The function will be called without arguments, with point at the
  2157. beginning of the headline. It should return t and leave point
  2158. where it is if the headline is a valid target for refiling.
  2159. If the target should not be selected, the function must return nil.
  2160. In addition to this, it may move point to a place from where the search
  2161. should be continued. For example, the function may decide that the entire
  2162. subtree of the current entry should be excluded and move point to the end
  2163. of the subtree."
  2164. :group 'org-refile
  2165. :type '(choice
  2166. (const nil)
  2167. (function)))
  2168. (defcustom org-refile-use-cache nil
  2169. "Non-nil means cache refile targets to speed up the process.
  2170. \\<org-mode-map>\
  2171. The cache for a particular file will be updated automatically when
  2172. the buffer has been killed, or when any of the marker used for flagging
  2173. refile targets no longer points at a live buffer.
  2174. If you have added new entries to a buffer that might themselves be targets,
  2175. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2176. if you find that easier, \
  2177. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2178. \\[org-refile]'."
  2179. :group 'org-refile
  2180. :version "24.1"
  2181. :type 'boolean)
  2182. (defcustom org-refile-use-outline-path nil
  2183. "Non-nil means provide refile targets as paths.
  2184. So a level 3 headline will be available as level1/level2/level3.
  2185. When the value is `file', also include the file name (without directory)
  2186. into the path. In this case, you can also stop the completion after
  2187. the file name, to get entries inserted as top level in the file.
  2188. When `full-file-path', include the full file path.
  2189. When `buffer-name', use the buffer name."
  2190. :group 'org-refile
  2191. :type '(choice
  2192. (const :tag "Not" nil)
  2193. (const :tag "Yes" t)
  2194. (const :tag "Start with file name" file)
  2195. (const :tag "Start with full file path" full-file-path)
  2196. (const :tag "Start with buffer name" buffer-name)))
  2197. (defcustom org-outline-path-complete-in-steps t
  2198. "Non-nil means complete the outline path in hierarchical steps.
  2199. When Org uses the refile interface to select an outline path (see
  2200. `org-refile-use-outline-path'), the completion of the path can be
  2201. done in a single go, or it can be done in steps down the headline
  2202. hierarchy. Going in steps is probably the best if you do not use
  2203. a special completion package like `ido' or `icicles'. However,
  2204. when using these packages, going in one step can be very fast,
  2205. while still showing the whole path to the entry."
  2206. :group 'org-refile
  2207. :type 'boolean)
  2208. (defcustom org-refile-allow-creating-parent-nodes nil
  2209. "Non-nil means allow the creation of new nodes as refile targets.
  2210. New nodes are then created by adding \"/new node name\" to the completion
  2211. of an existing node. When the value of this variable is `confirm',
  2212. new node creation must be confirmed by the user (recommended).
  2213. When nil, the completion must match an existing entry.
  2214. Note that, if the new heading is not seen by the criteria
  2215. listed in `org-refile-targets', multiple instances of the same
  2216. heading would be created by trying again to file under the new
  2217. heading."
  2218. :group 'org-refile
  2219. :type '(choice
  2220. (const :tag "Never" nil)
  2221. (const :tag "Always" t)
  2222. (const :tag "Prompt for confirmation" confirm)))
  2223. (defcustom org-refile-active-region-within-subtree nil
  2224. "Non-nil means also refile active region within a subtree.
  2225. By default `org-refile' doesn't allow refiling regions if they
  2226. don't contain a set of subtrees, but it might be convenient to
  2227. do so sometimes: in that case, the first line of the region is
  2228. converted to a headline before refiling."
  2229. :group 'org-refile
  2230. :version "24.1"
  2231. :type 'boolean)
  2232. (defgroup org-todo nil
  2233. "Options concerning TODO items in Org mode."
  2234. :tag "Org TODO"
  2235. :group 'org)
  2236. (defgroup org-progress nil
  2237. "Options concerning Progress logging in Org mode."
  2238. :tag "Org Progress"
  2239. :group 'org-time)
  2240. (defvar org-todo-interpretation-widgets
  2241. '((:tag "Sequence (cycling hits every state)" sequence)
  2242. (:tag "Type (cycling directly to DONE)" type))
  2243. "The available interpretation symbols for customizing `org-todo-keywords'.
  2244. Interested libraries should add to this list.")
  2245. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2246. "List of TODO entry keyword sequences and their interpretation.
  2247. \\<org-mode-map>This is a list of sequences.
  2248. Each sequence starts with a symbol, either `sequence' or `type',
  2249. indicating if the keywords should be interpreted as a sequence of
  2250. action steps, or as different types of TODO items. The first
  2251. keywords are states requiring action - these states will select a headline
  2252. for inclusion into the global TODO list Org produces. If one of the
  2253. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2254. signify that no further action is necessary. If \"|\" is not found,
  2255. the last keyword is treated as the only DONE state of the sequence.
  2256. The command `\\[org-todo]' cycles an entry through these states, and one
  2257. additional state where no keyword is present. For details about this
  2258. cycling, see the manual.
  2259. TODO keywords and interpretation can also be set on a per-file basis with
  2260. the special #+SEQ_TODO and #+TYP_TODO lines.
  2261. Each keyword can optionally specify a character for fast state selection
  2262. \(in combination with the variable `org-use-fast-todo-selection')
  2263. and specifiers for state change logging, using the same syntax that
  2264. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2265. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2266. indicates to record a time stamp each time this state is selected.
  2267. Each keyword may also specify if a timestamp or a note should be
  2268. recorded when entering or leaving the state, by adding additional
  2269. characters in the parenthesis after the keyword. This looks like this:
  2270. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2271. record only the time of the state change. With X and Y being either
  2272. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2273. Y when leaving the state if and only if the *target* state does not
  2274. define X. You may omit any of the fast-selection key or X or /Y,
  2275. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2276. For backward compatibility, this variable may also be just a list
  2277. of keywords. In this case the interpretation (sequence or type) will be
  2278. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2279. :group 'org-todo
  2280. :group 'org-keywords
  2281. :type '(choice
  2282. (repeat :tag "Old syntax, just keywords"
  2283. (string :tag "Keyword"))
  2284. (repeat :tag "New syntax"
  2285. (cons
  2286. (choice
  2287. :tag "Interpretation"
  2288. ;;Quick and dirty way to see
  2289. ;;`org-todo-interpretations'. This takes the
  2290. ;;place of item arguments
  2291. :convert-widget
  2292. (lambda (widget)
  2293. (widget-put widget
  2294. :args (mapcar
  2295. (lambda (x)
  2296. (widget-convert
  2297. (cons 'const x)))
  2298. org-todo-interpretation-widgets))
  2299. widget))
  2300. (repeat
  2301. (string :tag "Keyword"))))))
  2302. (defvar-local org-todo-keywords-1 nil
  2303. "All TODO and DONE keywords active in a buffer.")
  2304. (defvar org-todo-keywords-for-agenda nil)
  2305. (defvar org-done-keywords-for-agenda nil)
  2306. (defvar org-todo-keyword-alist-for-agenda nil)
  2307. (defvar org-tag-alist-for-agenda nil
  2308. "Alist of all tags from all agenda files.")
  2309. (defvar org-tag-groups-alist-for-agenda nil
  2310. "Alist of all groups tags from all current agenda files.")
  2311. (defvar-local org-tag-groups-alist nil)
  2312. (defvar org-agenda-contributing-files nil)
  2313. (defvar-local org-current-tag-alist nil
  2314. "Alist of all tag groups in current buffer.
  2315. This variable takes into consideration `org-tag-alist',
  2316. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2317. (defvar-local org-not-done-keywords nil)
  2318. (defvar-local org-done-keywords nil)
  2319. (defvar-local org-todo-heads nil)
  2320. (defvar-local org-todo-sets nil)
  2321. (defvar-local org-todo-log-states nil)
  2322. (defvar-local org-todo-kwd-alist nil)
  2323. (defvar-local org-todo-key-alist nil)
  2324. (defvar-local org-todo-key-trigger nil)
  2325. (defcustom org-todo-interpretation 'sequence
  2326. "Controls how TODO keywords are interpreted.
  2327. This variable is in principle obsolete and is only used for
  2328. backward compatibility, if the interpretation of todo keywords is
  2329. not given already in `org-todo-keywords'. See that variable for
  2330. more information."
  2331. :group 'org-todo
  2332. :group 'org-keywords
  2333. :type '(choice (const sequence)
  2334. (const type)))
  2335. (defcustom org-use-fast-todo-selection t
  2336. "\\<org-mode-map>\
  2337. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2338. This variable describes if and under what circumstances the cycling
  2339. mechanism for TODO keywords will be replaced by a single-key, direct
  2340. selection scheme.
  2341. When nil, fast selection is never used.
  2342. When the symbol `prefix', it will be used when `org-todo' is called
  2343. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2344. in an Org buffer, and
  2345. `\\[universal-argument] t' in an agenda buffer.
  2346. When t, fast selection is used by default. In this case, the prefix
  2347. argument forces cycling instead.
  2348. In all cases, the special interface is only used if access keys have
  2349. actually been assigned by the user, i.e. if keywords in the configuration
  2350. are followed by a letter in parenthesis, like TODO(t)."
  2351. :group 'org-todo
  2352. :type '(choice
  2353. (const :tag "Never" nil)
  2354. (const :tag "By default" t)
  2355. (const :tag "Only with C-u C-c C-t" prefix)))
  2356. (defcustom org-provide-todo-statistics t
  2357. "Non-nil means update todo statistics after insert and toggle.
  2358. ALL-HEADLINES means update todo statistics by including headlines
  2359. with no TODO keyword as well, counting them as not done.
  2360. A list of TODO keywords means the same, but skip keywords that are
  2361. not in this list.
  2362. When set to a list of two lists, the first list contains keywords
  2363. to consider as TODO keywords, the second list contains keywords
  2364. to consider as DONE keywords.
  2365. When this is set, todo statistics is updated in the parent of the
  2366. current entry each time a todo state is changed."
  2367. :group 'org-todo
  2368. :type '(choice
  2369. (const :tag "Yes, only for TODO entries" t)
  2370. (const :tag "Yes, including all entries" all-headlines)
  2371. (repeat :tag "Yes, for TODOs in this list"
  2372. (string :tag "TODO keyword"))
  2373. (list :tag "Yes, for TODOs and DONEs in these lists"
  2374. (repeat (string :tag "TODO keyword"))
  2375. (repeat (string :tag "DONE keyword")))
  2376. (other :tag "No TODO statistics" nil)))
  2377. (defcustom org-hierarchical-todo-statistics t
  2378. "Non-nil means TODO statistics covers just direct children.
  2379. When nil, all entries in the subtree are considered.
  2380. This has only an effect if `org-provide-todo-statistics' is set.
  2381. To set this to nil for only a single subtree, use a COOKIE_DATA
  2382. property and include the word \"recursive\" into the value."
  2383. :group 'org-todo
  2384. :type 'boolean)
  2385. (defcustom org-after-todo-state-change-hook nil
  2386. "Hook which is run after the state of a TODO item was changed.
  2387. The new state (a string with a TODO keyword, or nil) is available in the
  2388. Lisp variable `org-state'."
  2389. :group 'org-todo
  2390. :type 'hook)
  2391. (defvar org-blocker-hook nil
  2392. "Hook for functions that are allowed to block a state change.
  2393. Functions in this hook should not modify the buffer.
  2394. Each function gets as its single argument a property list,
  2395. see `org-trigger-hook' for more information about this list.
  2396. If any of the functions in this hook returns nil, the state change
  2397. is blocked.")
  2398. (defvar org-trigger-hook nil
  2399. "Hook for functions that are triggered by a state change.
  2400. Each function gets as its single argument a property list with at
  2401. least the following elements:
  2402. (:type type-of-change :position pos-at-entry-start
  2403. :from old-state :to new-state)
  2404. Depending on the type, more properties may be present.
  2405. This mechanism is currently implemented for:
  2406. TODO state changes
  2407. ------------------
  2408. :type todo-state-change
  2409. :from previous state (keyword as a string), or nil, or a symbol
  2410. `todo' or `done', to indicate the general type of state.
  2411. :to new state, like in :from")
  2412. (defcustom org-enforce-todo-dependencies nil
  2413. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2414. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2415. be blocked if any prior sibling is not yet done.
  2416. Finally, if the parent is blocked because of ordered siblings of its own,
  2417. the child will also be blocked."
  2418. :set (lambda (var val)
  2419. (set var val)
  2420. (if val
  2421. (add-hook 'org-blocker-hook
  2422. 'org-block-todo-from-children-or-siblings-or-parent)
  2423. (remove-hook 'org-blocker-hook
  2424. 'org-block-todo-from-children-or-siblings-or-parent)))
  2425. :group 'org-todo
  2426. :type 'boolean)
  2427. (defcustom org-enforce-todo-checkbox-dependencies nil
  2428. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2429. When this is nil, checkboxes have no influence on switching TODO states.
  2430. When non-nil, you first need to check off all check boxes before the TODO
  2431. entry can be switched to DONE.
  2432. This variable needs to be set before org.el is loaded, and you need to
  2433. restart Emacs after a change to make the change effective. The only way
  2434. to change is while Emacs is running is through the customize interface."
  2435. :set (lambda (var val)
  2436. (set var val)
  2437. (if val
  2438. (add-hook 'org-blocker-hook
  2439. 'org-block-todo-from-checkboxes)
  2440. (remove-hook 'org-blocker-hook
  2441. 'org-block-todo-from-checkboxes)))
  2442. :group 'org-todo
  2443. :type 'boolean)
  2444. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2445. "Non-nil means inserting a TODO heading is treated as state change.
  2446. So when the command `\\[org-insert-todo-heading]' is used, state change
  2447. logging will apply if appropriate. When nil, the new TODO item will
  2448. be inserted directly, and no logging will take place."
  2449. :group 'org-todo
  2450. :type 'boolean)
  2451. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2452. "Non-nil means switching TODO states with S-cursor counts as state change.
  2453. This is the default behavior. However, setting this to nil allows a
  2454. convenient way to select a TODO state and bypass any logging associated
  2455. with that."
  2456. :group 'org-todo
  2457. :type 'boolean)
  2458. (defcustom org-todo-state-tags-triggers nil
  2459. "Tag changes that should be triggered by TODO state changes.
  2460. This is a list. Each entry is
  2461. (state-change (tag . flag) .......)
  2462. State-change can be a string with a state, and empty string to indicate the
  2463. state that has no TODO keyword, or it can be one of the symbols `todo'
  2464. or `done', meaning any not-done or done state, respectively."
  2465. :group 'org-todo
  2466. :group 'org-tags
  2467. :type '(repeat
  2468. (cons (choice :tag "When changing to"
  2469. (const :tag "Not-done state" todo)
  2470. (const :tag "Done state" done)
  2471. (string :tag "State"))
  2472. (repeat
  2473. (cons :tag "Tag action"
  2474. (string :tag "Tag")
  2475. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2476. (defcustom org-log-done nil
  2477. "Information to record when a task moves to the DONE state.
  2478. Possible values are:
  2479. nil Don't add anything, just change the keyword
  2480. time Add a time stamp to the task
  2481. note Prompt for a note and add it with template `org-log-note-headings'
  2482. This option can also be set with on a per-file-basis with
  2483. #+STARTUP: nologdone
  2484. #+STARTUP: logdone
  2485. #+STARTUP: lognotedone
  2486. You can have local logging settings for a subtree by setting the LOGGING
  2487. property to one or more of these keywords."
  2488. :group 'org-todo
  2489. :group 'org-progress
  2490. :type '(choice
  2491. (const :tag "No logging" nil)
  2492. (const :tag "Record CLOSED timestamp" time)
  2493. (const :tag "Record CLOSED timestamp with note." note)))
  2494. ;; Normalize old uses of org-log-done.
  2495. (cond
  2496. ((eq org-log-done t) (setq org-log-done 'time))
  2497. ((and (listp org-log-done) (memq 'done org-log-done))
  2498. (setq org-log-done 'note)))
  2499. (defcustom org-log-reschedule nil
  2500. "Information to record when the scheduling date of a tasks is modified.
  2501. Possible values are:
  2502. nil Don't add anything, just change the date
  2503. time Add a time stamp to the task
  2504. note Prompt for a note and add it with template `org-log-note-headings'
  2505. This option can also be set with on a per-file-basis with
  2506. #+STARTUP: nologreschedule
  2507. #+STARTUP: logreschedule
  2508. #+STARTUP: lognotereschedule"
  2509. :group 'org-todo
  2510. :group 'org-progress
  2511. :type '(choice
  2512. (const :tag "No logging" nil)
  2513. (const :tag "Record timestamp" time)
  2514. (const :tag "Record timestamp with note." note)))
  2515. (defcustom org-log-redeadline nil
  2516. "Information to record when the deadline date of a tasks is modified.
  2517. Possible values are:
  2518. nil Don't add anything, just change the date
  2519. time Add a time stamp to the task
  2520. note Prompt for a note and add it with template `org-log-note-headings'
  2521. This option can also be set with on a per-file-basis with
  2522. #+STARTUP: nologredeadline
  2523. #+STARTUP: logredeadline
  2524. #+STARTUP: lognoteredeadline
  2525. You can have local logging settings for a subtree by setting the LOGGING
  2526. property to one or more of these keywords."
  2527. :group 'org-todo
  2528. :group 'org-progress
  2529. :type '(choice
  2530. (const :tag "No logging" nil)
  2531. (const :tag "Record timestamp" time)
  2532. (const :tag "Record timestamp with note." note)))
  2533. (defcustom org-log-note-clock-out nil
  2534. "Non-nil means record a note when clocking out of an item.
  2535. This can also be configured on a per-file basis by adding one of
  2536. the following lines anywhere in the buffer:
  2537. #+STARTUP: lognoteclock-out
  2538. #+STARTUP: nolognoteclock-out"
  2539. :group 'org-todo
  2540. :group 'org-progress
  2541. :type 'boolean)
  2542. (defcustom org-log-done-with-time t
  2543. "Non-nil means the CLOSED time stamp will contain date and time.
  2544. When nil, only the date will be recorded."
  2545. :group 'org-progress
  2546. :type 'boolean)
  2547. (defcustom org-log-note-headings
  2548. '((done . "CLOSING NOTE %t")
  2549. (state . "State %-12s from %-12S %t")
  2550. (note . "Note taken on %t")
  2551. (reschedule . "Rescheduled from %S on %t")
  2552. (delschedule . "Not scheduled, was %S on %t")
  2553. (redeadline . "New deadline from %S on %t")
  2554. (deldeadline . "Removed deadline, was %S on %t")
  2555. (refile . "Refiled on %t")
  2556. (clock-out . ""))
  2557. "Headings for notes added to entries.
  2558. The value is an alist, with the car being a symbol indicating the
  2559. note context, and the cdr is the heading to be used. The heading
  2560. may also be the empty string. The following placeholders can be
  2561. used:
  2562. %t a time stamp.
  2563. %T an active time stamp instead the default inactive one
  2564. %d a short-format time stamp.
  2565. %D an active short-format time stamp.
  2566. %s the new TODO state or time stamp (inactive), in double quotes.
  2567. %S the old TODO state or time stamp (inactive), in double quotes.
  2568. %u the user name.
  2569. %U full user name.
  2570. In fact, it is not a good idea to change the `state' entry,
  2571. because Agenda Log mode depends on the format of these entries."
  2572. :group 'org-todo
  2573. :group 'org-progress
  2574. :type '(list :greedy t
  2575. (cons (const :tag "Heading when closing an item" done) string)
  2576. (cons (const :tag
  2577. "Heading when changing todo state (todo sequence only)"
  2578. state) string)
  2579. (cons (const :tag "Heading when just taking a note" note) string)
  2580. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2581. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2582. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2583. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2584. (cons (const :tag "Heading when refiling" refile) string)
  2585. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2586. (unless (assq 'note org-log-note-headings)
  2587. (push '(note . "%t") org-log-note-headings))
  2588. (defcustom org-log-into-drawer nil
  2589. "Non-nil means insert state change notes and time stamps into a drawer.
  2590. When nil, state changes notes will be inserted after the headline and
  2591. any scheduling and clock lines, but not inside a drawer.
  2592. The value of this variable should be the name of the drawer to use.
  2593. LOGBOOK is proposed as the default drawer for this purpose, you can
  2594. also set this to a string to define the drawer of your choice.
  2595. A value of t is also allowed, representing \"LOGBOOK\".
  2596. A value of t or nil can also be set with on a per-file-basis with
  2597. #+STARTUP: logdrawer
  2598. #+STARTUP: nologdrawer
  2599. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2600. will be ignored.
  2601. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2602. a subtree.
  2603. Do not check directly this variable in a Lisp program. Call
  2604. function `org-log-into-drawer' instead."
  2605. :group 'org-todo
  2606. :group 'org-progress
  2607. :type '(choice
  2608. (const :tag "Not into a drawer" nil)
  2609. (const :tag "LOGBOOK" t)
  2610. (string :tag "Other")))
  2611. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2612. (defun org-log-into-drawer ()
  2613. "Name of the log drawer, as a string, or nil.
  2614. This is the value of `org-log-into-drawer'. However, if the
  2615. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2616. be used instead of the default value."
  2617. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2618. (cond ((equal p "nil") nil)
  2619. ((equal p "t") "LOGBOOK")
  2620. ((stringp p) p)
  2621. (p "LOGBOOK")
  2622. ((stringp org-log-into-drawer) org-log-into-drawer)
  2623. (org-log-into-drawer "LOGBOOK"))))
  2624. (defcustom org-log-state-notes-insert-after-drawers nil
  2625. "Non-nil means insert state change notes after any drawers in entry.
  2626. Only the drawers that *immediately* follow the headline and the
  2627. deadline/scheduled line are skipped.
  2628. When nil, insert notes right after the heading and perhaps the line
  2629. with deadline/scheduling if present.
  2630. This variable will have no effect if `org-log-into-drawer' is
  2631. set."
  2632. :group 'org-todo
  2633. :group 'org-progress
  2634. :type 'boolean)
  2635. (defcustom org-log-states-order-reversed t
  2636. "Non-nil means the latest state note will be directly after heading.
  2637. When nil, the state change notes will be ordered according to time.
  2638. This option can also be set with on a per-file-basis with
  2639. #+STARTUP: logstatesreversed
  2640. #+STARTUP: nologstatesreversed"
  2641. :group 'org-todo
  2642. :group 'org-progress
  2643. :type 'boolean)
  2644. (defcustom org-todo-repeat-to-state nil
  2645. "The TODO state to which a repeater should return the repeating task.
  2646. By default this is the first task of a TODO sequence or the
  2647. previous state of a TYPE_TODO set. But you can specify to use
  2648. the previous state in a TODO sequence or a string.
  2649. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2650. entry, which has precedence over this option."
  2651. :group 'org-todo
  2652. :version "24.1"
  2653. :type '(choice (const :tag "Use the previous TODO state" t)
  2654. (const :tag "Use the head of the TODO sequence" nil)
  2655. (string :tag "Use a specific TODO state")))
  2656. (defcustom org-log-repeat 'time
  2657. "Non-nil means record moving through the DONE state when triggering repeat.
  2658. An auto-repeating task is immediately switched back to TODO when
  2659. marked DONE. If you are not logging state changes (by adding \"@\"
  2660. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2661. record a closing note, there will be no record of the task moving
  2662. through DONE. This variable forces taking a note anyway.
  2663. nil Don't force a record
  2664. time Record a time stamp
  2665. note Prompt for a note and add it with template `org-log-note-headings'
  2666. This option can also be set with on a per-file-basis with
  2667. #+STARTUP: nologrepeat
  2668. #+STARTUP: logrepeat
  2669. #+STARTUP: lognoterepeat
  2670. You can have local logging settings for a subtree by setting the LOGGING
  2671. property to one or more of these keywords."
  2672. :group 'org-todo
  2673. :group 'org-progress
  2674. :type '(choice
  2675. (const :tag "Don't force a record" nil)
  2676. (const :tag "Force recording the DONE state" time)
  2677. (const :tag "Force recording a note with the DONE state" note)))
  2678. (defgroup org-priorities nil
  2679. "Priorities in Org mode."
  2680. :tag "Org Priorities"
  2681. :group 'org-todo)
  2682. (defcustom org-enable-priority-commands t
  2683. "Non-nil means priority commands are active.
  2684. When nil, these commands will be disabled, so that you never accidentally
  2685. set a priority."
  2686. :group 'org-priorities
  2687. :type 'boolean)
  2688. (defcustom org-highest-priority ?A
  2689. "The highest priority of TODO items. A character like ?A, ?B etc.
  2690. Must have a smaller ASCII number than `org-lowest-priority'."
  2691. :group 'org-priorities
  2692. :type 'character)
  2693. (defcustom org-lowest-priority ?C
  2694. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2695. Must have a larger ASCII number than `org-highest-priority'."
  2696. :group 'org-priorities
  2697. :type 'character)
  2698. (defcustom org-default-priority ?B
  2699. "The default priority of TODO items.
  2700. This is the priority an item gets if no explicit priority is given.
  2701. When starting to cycle on an empty priority the first step in the cycle
  2702. depends on `org-priority-start-cycle-with-default'. The resulting first
  2703. step priority must not exceed the range from `org-highest-priority' to
  2704. `org-lowest-priority' which means that `org-default-priority' has to be
  2705. in this range exclusive or inclusive the range boundaries. Else the
  2706. first step refuses to set the default and the second will fall back
  2707. to (depending on the command used) the highest or lowest priority."
  2708. :group 'org-priorities
  2709. :type 'character)
  2710. (defcustom org-priority-start-cycle-with-default t
  2711. "Non-nil means start with default priority when starting to cycle.
  2712. When this is nil, the first step in the cycle will be (depending on the
  2713. command used) one higher or lower than the default priority.
  2714. See also `org-default-priority'."
  2715. :group 'org-priorities
  2716. :type 'boolean)
  2717. (defcustom org-get-priority-function nil
  2718. "Function to extract the priority from a string.
  2719. The string is normally the headline. If this is nil Org computes the
  2720. priority from the priority cookie like [#A] in the headline. It returns
  2721. an integer, increasing by 1000 for each priority level.
  2722. The user can set a different function here, which should take a string
  2723. as an argument and return the numeric priority."
  2724. :group 'org-priorities
  2725. :version "24.1"
  2726. :type '(choice
  2727. (const nil)
  2728. (function)))
  2729. (defgroup org-time nil
  2730. "Options concerning time stamps and deadlines in Org mode."
  2731. :tag "Org Time"
  2732. :group 'org)
  2733. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2734. "Number of minutes to round time stamps to.
  2735. \\<org-mode-map>\
  2736. These are two values, the first applies when first creating a time stamp.
  2737. The second applies when changing it with the commands `S-up' and `S-down'.
  2738. When changing the time stamp, this means that it will change in steps
  2739. of N minutes, as given by the second value.
  2740. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2741. numbers should be factors of 60, so for example 5, 10, 15.
  2742. When this is larger than 1, you can still force an exact time stamp by using
  2743. a double prefix argument to a time stamp command like \
  2744. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2745. and by using a prefix arg to `S-up/down' to specify the exact number
  2746. of minutes to shift."
  2747. :group 'org-time
  2748. :get (lambda (var) ; Make sure both elements are there
  2749. (if (integerp (default-value var))
  2750. (list (default-value var) 5)
  2751. (default-value var)))
  2752. :type '(list
  2753. (integer :tag "when inserting times")
  2754. (integer :tag "when modifying times")))
  2755. ;; Normalize old customizations of this variable.
  2756. (when (integerp org-time-stamp-rounding-minutes)
  2757. (setq org-time-stamp-rounding-minutes
  2758. (list org-time-stamp-rounding-minutes
  2759. org-time-stamp-rounding-minutes)))
  2760. (defcustom org-display-custom-times nil
  2761. "Non-nil means overlay custom formats over all time stamps.
  2762. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2763. To turn this on on a per-file basis, insert anywhere in the file:
  2764. #+STARTUP: customtime"
  2765. :group 'org-time
  2766. :set 'set-default
  2767. :type 'sexp)
  2768. (make-variable-buffer-local 'org-display-custom-times)
  2769. (defcustom org-time-stamp-custom-formats
  2770. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2771. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2772. These are overlaid over the default ISO format if the variable
  2773. `org-display-custom-times' is set. Time like %H:%M should be at the
  2774. end of the second format. The custom formats are also honored by export
  2775. commands, if custom time display is turned on at the time of export."
  2776. :group 'org-time
  2777. :type 'sexp)
  2778. (defun org-time-stamp-format (&optional long inactive)
  2779. "Get the right format for a time string."
  2780. (let ((f (if long (cdr org-time-stamp-formats)
  2781. (car org-time-stamp-formats))))
  2782. (if inactive
  2783. (concat "[" (substring f 1 -1) "]")
  2784. f)))
  2785. (defcustom org-deadline-warning-days 14
  2786. "Number of days before expiration during which a deadline becomes active.
  2787. This variable governs the display in sparse trees and in the agenda.
  2788. When 0 or negative, it means use this number (the absolute value of it)
  2789. even if a deadline has a different individual lead time specified.
  2790. Custom commands can set this variable in the options section."
  2791. :group 'org-time
  2792. :group 'org-agenda-daily/weekly
  2793. :type 'integer)
  2794. (defcustom org-scheduled-delay-days 0
  2795. "Number of days before a scheduled item becomes active.
  2796. This variable governs the display in sparse trees and in the agenda.
  2797. The default value (i.e. 0) means: don't delay scheduled item.
  2798. When negative, it means use this number (the absolute value of it)
  2799. even if a scheduled item has a different individual delay time
  2800. specified.
  2801. Custom commands can set this variable in the options section."
  2802. :group 'org-time
  2803. :group 'org-agenda-daily/weekly
  2804. :version "24.4"
  2805. :package-version '(Org . "8.0")
  2806. :type 'integer)
  2807. (defcustom org-read-date-prefer-future t
  2808. "Non-nil means assume future for incomplete date input from user.
  2809. This affects the following situations:
  2810. 1. The user gives a month but not a year.
  2811. For example, if it is April and you enter \"feb 2\", this will be read
  2812. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2813. 2. The user gives a day, but no month.
  2814. For example, if today is the 15th, and you enter \"3\", Org will read
  2815. this as the third of *next* month. However, if you enter \"17\",
  2816. it will be considered as *this* month.
  2817. If you set this variable to the symbol `time', then also the following
  2818. will work:
  2819. 3. If the user gives a time.
  2820. If the time is before now, it will be interpreted as tomorrow.
  2821. Currently none of this works for ISO week specifications.
  2822. When this option is nil, the current day, month and year will always be
  2823. used as defaults.
  2824. See also `org-agenda-jump-prefer-future'."
  2825. :group 'org-time
  2826. :type '(choice
  2827. (const :tag "Never" nil)
  2828. (const :tag "Check month and day" t)
  2829. (const :tag "Check month, day, and time" time)))
  2830. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2831. "Should the agenda jump command prefer the future for incomplete dates?
  2832. The default is to do the same as configured in `org-read-date-prefer-future'.
  2833. But you can also set a deviating value here.
  2834. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2835. :group 'org-agenda
  2836. :group 'org-time
  2837. :version "24.1"
  2838. :type '(choice
  2839. (const :tag "Use org-read-date-prefer-future"
  2840. org-read-date-prefer-future)
  2841. (const :tag "Never" nil)
  2842. (const :tag "Always" t)))
  2843. (defcustom org-read-date-force-compatible-dates t
  2844. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2845. Depending on the system Emacs is running on, certain dates cannot
  2846. be represented with the type used internally to represent time.
  2847. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2848. correctly. Some systems allow for earlier dates, some for later,
  2849. some for both. One way to find out it to insert any date into an
  2850. Org buffer, putting the cursor on the year and hitting S-up and
  2851. S-down to test the range.
  2852. When this variable is set to t, the date/time prompt will not let
  2853. you specify dates outside the 1970-2037 range, so it is certain that
  2854. these dates will work in whatever version of Emacs you are
  2855. running, and also that you can move a file from one Emacs implementation
  2856. to another. WHenever Org is forcing the year for you, it will display
  2857. a message and beep.
  2858. When this variable is nil, Org will check if the date is
  2859. representable in the specific Emacs implementation you are using.
  2860. If not, it will force a year, usually the current year, and beep
  2861. to remind you. Currently this setting is not recommended because
  2862. the likelihood that you will open your Org files in an Emacs that
  2863. has limited date range is not negligible.
  2864. A workaround for this problem is to use diary sexp dates for time
  2865. stamps outside of this range."
  2866. :group 'org-time
  2867. :version "24.1"
  2868. :type 'boolean)
  2869. (defcustom org-read-date-display-live t
  2870. "Non-nil means display current interpretation of date prompt live.
  2871. This display will be in an overlay, in the minibuffer."
  2872. :group 'org-time
  2873. :type 'boolean)
  2874. (defcustom org-read-date-popup-calendar t
  2875. "Non-nil means pop up a calendar when prompting for a date.
  2876. In the calendar, the date can be selected with mouse-1. However, the
  2877. minibuffer will also be active, and you can simply enter the date as well.
  2878. When nil, only the minibuffer will be available."
  2879. :group 'org-time
  2880. :type 'boolean)
  2881. (defvaralias 'org-popup-calendar-for-date-prompt
  2882. 'org-read-date-popup-calendar)
  2883. (defcustom org-extend-today-until 0
  2884. "The hour when your day really ends. Must be an integer.
  2885. This has influence for the following applications:
  2886. - When switching the agenda to \"today\". It it is still earlier than
  2887. the time given here, the day recognized as TODAY is actually yesterday.
  2888. - When a date is read from the user and it is still before the time given
  2889. here, the current date and time will be assumed to be yesterday, 23:59.
  2890. Also, timestamps inserted in capture templates follow this rule.
  2891. IMPORTANT: This is a feature whose implementation is and likely will
  2892. remain incomplete. Really, it is only here because past midnight seems to
  2893. be the favorite working time of John Wiegley :-)"
  2894. :group 'org-time
  2895. :type 'integer)
  2896. (defcustom org-use-effective-time nil
  2897. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2898. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2899. \"effective time\" of any timestamps between midnight and 8am will be
  2900. 23:59 of the previous day."
  2901. :group 'org-time
  2902. :version "24.1"
  2903. :type 'boolean)
  2904. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2905. "When non-nil, use the last clock out time for `org-todo'.
  2906. Note that this option has precedence over the combined use of
  2907. `org-use-effective-time' and `org-extend-today-until'."
  2908. :group 'org-time
  2909. :version "24.4"
  2910. :package-version '(Org . "8.0")
  2911. :type 'boolean)
  2912. (defcustom org-edit-timestamp-down-means-later nil
  2913. "Non-nil means S-down will increase the time in a time stamp.
  2914. When nil, S-up will increase."
  2915. :group 'org-time
  2916. :type 'boolean)
  2917. (defcustom org-calendar-follow-timestamp-change t
  2918. "Non-nil means make the calendar window follow timestamp changes.
  2919. When a timestamp is modified and the calendar window is visible, it will be
  2920. moved to the new date."
  2921. :group 'org-time
  2922. :type 'boolean)
  2923. (defgroup org-tags nil
  2924. "Options concerning tags in Org mode."
  2925. :tag "Org Tags"
  2926. :group 'org)
  2927. (defcustom org-tag-alist nil
  2928. "Default tags available in Org files.
  2929. The value of this variable is an alist. Associations either:
  2930. (TAG)
  2931. (TAG . SELECT)
  2932. (SPECIAL)
  2933. where TAG is a tag as a string, SELECT is character, used to
  2934. select that tag through the fast tag selection interface, and
  2935. SPECIAL is one of the following keywords: `:startgroup',
  2936. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2937. `:newline'. These keywords are used to define a hierarchy of
  2938. tags. See manual for details.
  2939. When this variable is nil, Org mode bases tag input on what is
  2940. already in the buffer. The value can be overridden locally by
  2941. using a TAGS keyword, e.g.,
  2942. #+TAGS: tag1 tag2
  2943. See also `org-tag-persistent-alist' to sidestep this behavior."
  2944. :group 'org-tags
  2945. :type '(repeat
  2946. (choice
  2947. (cons :tag "Tag with key"
  2948. (string :tag "Tag name")
  2949. (character :tag "Access char"))
  2950. (list :tag "Tag" (string :tag "Tag name"))
  2951. (const :tag "Start radio group" (:startgroup))
  2952. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2953. (const :tag "Group tags delimiter" (:grouptags))
  2954. (const :tag "End radio group" (:endgroup))
  2955. (const :tag "End tag group, non distinct" (:endgrouptag))
  2956. (const :tag "New line" (:newline)))))
  2957. (defcustom org-tag-persistent-alist nil
  2958. "Tags always available in Org files.
  2959. The value of this variable is an alist. Associations either:
  2960. (TAG)
  2961. (TAG . SELECT)
  2962. (SPECIAL)
  2963. where TAG is a tag as a string, SELECT is a character, used to
  2964. select that tag through the fast tag selection interface, and
  2965. SPECIAL is one of the following keywords: `:startgroup',
  2966. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2967. `:newline'. These keywords are used to define a hierarchy of
  2968. tags. See manual for details.
  2969. Unlike to `org-tag-alist', tags defined in this variable do not
  2970. depend on a local TAGS keyword. Instead, to disable these tags
  2971. on a per-file basis, insert anywhere in the file:
  2972. #+STARTUP: noptag"
  2973. :group 'org-tags
  2974. :type '(repeat
  2975. (choice
  2976. (cons :tag "Tag with key"
  2977. (string :tag "Tag name")
  2978. (character :tag "Access char"))
  2979. (list :tag "Tag" (string :tag "Tag name"))
  2980. (const :tag "Start radio group" (:startgroup))
  2981. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2982. (const :tag "Group tags delimiter" (:grouptags))
  2983. (const :tag "End radio group" (:endgroup))
  2984. (const :tag "End tag group, non distinct" (:endgrouptag))
  2985. (const :tag "New line" (:newline)))))
  2986. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2987. "If non-nil, always offer completion for all tags of all agenda files.
  2988. Instead of customizing this variable directly, you might want to
  2989. set it locally for capture buffers, because there no list of
  2990. tags in that file can be created dynamically (there are none).
  2991. (add-hook \\='org-capture-mode-hook
  2992. (lambda ()
  2993. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2994. :group 'org-tags
  2995. :version "24.1"
  2996. :type 'boolean)
  2997. (defvar org-file-tags nil
  2998. "List of tags that can be inherited by all entries in the file.
  2999. The tags will be inherited if the variable `org-use-tag-inheritance'
  3000. says they should be.
  3001. This variable is populated from #+FILETAGS lines.")
  3002. (defcustom org-use-fast-tag-selection 'auto
  3003. "Non-nil means use fast tag selection scheme.
  3004. This is a special interface to select and deselect tags with single keys.
  3005. When nil, fast selection is never used.
  3006. When the symbol `auto', fast selection is used if and only if selection
  3007. characters for tags have been configured, either through the variable
  3008. `org-tag-alist' or through a #+TAGS line in the buffer.
  3009. When t, fast selection is always used and selection keys are assigned
  3010. automatically if necessary."
  3011. :group 'org-tags
  3012. :type '(choice
  3013. (const :tag "Always" t)
  3014. (const :tag "Never" nil)
  3015. (const :tag "When selection characters are configured" auto)))
  3016. (defcustom org-fast-tag-selection-single-key nil
  3017. "Non-nil means fast tag selection exits after first change.
  3018. When nil, you have to press RET to exit it.
  3019. During fast tag selection, you can toggle this flag with `C-c'.
  3020. This variable can also have the value `expert'. In this case, the window
  3021. displaying the tags menu is not even shown, until you press C-c again."
  3022. :group 'org-tags
  3023. :type '(choice
  3024. (const :tag "No" nil)
  3025. (const :tag "Yes" t)
  3026. (const :tag "Expert" expert)))
  3027. (defvar org-fast-tag-selection-include-todo nil
  3028. "Non-nil means fast tags selection interface will also offer TODO states.
  3029. This is an undocumented feature, you should not rely on it.")
  3030. (defcustom org-tags-column -77
  3031. "The column to which tags should be indented in a headline.
  3032. If this number is positive, it specifies the column. If it is negative,
  3033. it means that the tags should be flushright to that column. For example,
  3034. -80 works well for a normal 80 character screen.
  3035. When 0, place tags directly after headline text, with only one space in
  3036. between."
  3037. :group 'org-tags
  3038. :type 'integer)
  3039. (defcustom org-auto-align-tags t
  3040. "Non-nil keeps tags aligned when modifying headlines.
  3041. Some operations (i.e. demoting) change the length of a headline and
  3042. therefore shift the tags around. With this option turned on, after
  3043. each such operation the tags are again aligned to `org-tags-column'."
  3044. :group 'org-tags
  3045. :type 'boolean)
  3046. (defcustom org-use-tag-inheritance t
  3047. "Non-nil means tags in levels apply also for sublevels.
  3048. When nil, only the tags directly given in a specific line apply there.
  3049. This may also be a list of tags that should be inherited, or a regexp that
  3050. matches tags that should be inherited. Additional control is possible
  3051. with the variable `org-tags-exclude-from-inheritance' which gives an
  3052. explicit list of tags to be excluded from inheritance, even if the value of
  3053. `org-use-tag-inheritance' would select it for inheritance.
  3054. If this option is t, a match early-on in a tree can lead to a large
  3055. number of matches in the subtree when constructing the agenda or creating
  3056. a sparse tree. If you only want to see the first match in a tree during
  3057. a search, check out the variable `org-tags-match-list-sublevels'."
  3058. :group 'org-tags
  3059. :type '(choice
  3060. (const :tag "Not" nil)
  3061. (const :tag "Always" t)
  3062. (repeat :tag "Specific tags" (string :tag "Tag"))
  3063. (regexp :tag "Tags matched by regexp")))
  3064. (defcustom org-tags-exclude-from-inheritance nil
  3065. "List of tags that should never be inherited.
  3066. This is a way to exclude a few tags from inheritance. For way to do
  3067. the opposite, to actively allow inheritance for selected tags,
  3068. see the variable `org-use-tag-inheritance'."
  3069. :group 'org-tags
  3070. :type '(repeat (string :tag "Tag")))
  3071. (defun org-tag-inherit-p (tag)
  3072. "Check if TAG is one that should be inherited."
  3073. (cond
  3074. ((member tag org-tags-exclude-from-inheritance) nil)
  3075. ((eq org-use-tag-inheritance t) t)
  3076. ((not org-use-tag-inheritance) nil)
  3077. ((stringp org-use-tag-inheritance)
  3078. (string-match org-use-tag-inheritance tag))
  3079. ((listp org-use-tag-inheritance)
  3080. (member tag org-use-tag-inheritance))
  3081. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3082. (defcustom org-tags-match-list-sublevels t
  3083. "Non-nil means list also sublevels of headlines matching a search.
  3084. This variable applies to tags/property searches, and also to stuck
  3085. projects because this search is based on a tags match as well.
  3086. When set to the symbol `indented', sublevels are indented with
  3087. leading dots.
  3088. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3089. the sublevels of a headline matching a tag search often also match
  3090. the same search. Listing all of them can create very long lists.
  3091. Setting this variable to nil causes subtrees of a match to be skipped.
  3092. This variable is semi-obsolete and probably should always be true. It
  3093. is better to limit inheritance to certain tags using the variables
  3094. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3095. :group 'org-tags
  3096. :type '(choice
  3097. (const :tag "No, don't list them" nil)
  3098. (const :tag "Yes, do list them" t)
  3099. (const :tag "List them, indented with leading dots" indented)))
  3100. (defcustom org-tags-sort-function nil
  3101. "When set, tags are sorted using this function as a comparator."
  3102. :group 'org-tags
  3103. :type '(choice
  3104. (const :tag "No sorting" nil)
  3105. (const :tag "Alphabetical" org-string-collate-lessp)
  3106. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  3107. (function :tag "Custom function" nil)))
  3108. (defvar org-tags-history nil
  3109. "History of minibuffer reads for tags.")
  3110. (defvar org-last-tags-completion-table nil
  3111. "The last used completion table for tags.")
  3112. (defvar org-after-tags-change-hook nil
  3113. "Hook that is run after the tags in a line have changed.")
  3114. (defgroup org-properties nil
  3115. "Options concerning properties in Org mode."
  3116. :tag "Org Properties"
  3117. :group 'org)
  3118. (defcustom org-property-format "%-10s %s"
  3119. "How property key/value pairs should be formatted by `indent-line'.
  3120. When `indent-line' hits a property definition, it will format the line
  3121. according to this format, mainly to make sure that the values are
  3122. lined-up with respect to each other."
  3123. :group 'org-properties
  3124. :type 'string)
  3125. (defcustom org-properties-postprocess-alist nil
  3126. "Alist of properties and functions to adjust inserted values.
  3127. Elements of this alist must be of the form
  3128. ([string] [function])
  3129. where [string] must be a property name and [function] must be a
  3130. lambda expression: this lambda expression must take one argument,
  3131. the value to adjust, and return the new value as a string.
  3132. For example, this element will allow the property \"Remaining\"
  3133. to be updated wrt the relation between the \"Effort\" property
  3134. and the clock summary:
  3135. ((\"Remaining\" (lambda(value)
  3136. (let ((clocksum (org-clock-sum-current-item))
  3137. (effort (org-duration-to-minutes
  3138. (org-entry-get (point) \"Effort\"))))
  3139. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3140. :group 'org-properties
  3141. :version "24.1"
  3142. :type '(alist :key-type (string :tag "Property")
  3143. :value-type (function :tag "Function")))
  3144. (defcustom org-use-property-inheritance nil
  3145. "Non-nil means properties apply also for sublevels.
  3146. This setting is chiefly used during property searches. Turning it on can
  3147. cause significant overhead when doing a search, which is why it is not
  3148. on by default.
  3149. When nil, only the properties directly given in the current entry count.
  3150. When t, every property is inherited. The value may also be a list of
  3151. properties that should have inheritance, or a regular expression matching
  3152. properties that should be inherited.
  3153. However, note that some special properties use inheritance under special
  3154. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3155. and the properties ending in \"_ALL\" when they are used as descriptor
  3156. for valid values of a property.
  3157. Note for programmers:
  3158. When querying an entry with `org-entry-get', you can control if inheritance
  3159. should be used. By default, `org-entry-get' looks only at the local
  3160. properties. You can request inheritance by setting the inherit argument
  3161. to t (to force inheritance) or to `selective' (to respect the setting
  3162. in this variable)."
  3163. :group 'org-properties
  3164. :type '(choice
  3165. (const :tag "Not" nil)
  3166. (const :tag "Always" t)
  3167. (repeat :tag "Specific properties" (string :tag "Property"))
  3168. (regexp :tag "Properties matched by regexp")))
  3169. (defun org-property-inherit-p (property)
  3170. "Return a non-nil value if PROPERTY should be inherited."
  3171. (cond
  3172. ((eq org-use-property-inheritance t) t)
  3173. ((not org-use-property-inheritance) nil)
  3174. ((stringp org-use-property-inheritance)
  3175. (string-match org-use-property-inheritance property))
  3176. ((listp org-use-property-inheritance)
  3177. (member-ignore-case property org-use-property-inheritance))
  3178. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3179. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3180. "The default column format, if no other format has been defined.
  3181. This variable can be set on the per-file basis by inserting a line
  3182. #+COLUMNS: %25ITEM ....."
  3183. :group 'org-properties
  3184. :type 'string)
  3185. (defcustom org-columns-ellipses ".."
  3186. "The ellipses to be used when a field in column view is truncated.
  3187. When this is the empty string, as many characters as possible are shown,
  3188. but then there will be no visual indication that the field has been truncated.
  3189. When this is a string of length N, the last N characters of a truncated
  3190. field are replaced by this string. If the column is narrower than the
  3191. ellipses string, only part of the ellipses string will be shown."
  3192. :group 'org-properties
  3193. :type 'string)
  3194. (defconst org-global-properties-fixed
  3195. '(("VISIBILITY_ALL" . "folded children content all")
  3196. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3197. "List of property/value pairs that can be inherited by any entry.
  3198. These are fixed values, for the preset properties. The user variable
  3199. that can be used to add to this list is `org-global-properties'.
  3200. The entries in this list are cons cells where the car is a property
  3201. name and cdr is a string with the value. If the value represents
  3202. multiple items like an \"_ALL\" property, separate the items by
  3203. spaces.")
  3204. (defcustom org-global-properties nil
  3205. "List of property/value pairs that can be inherited by any entry.
  3206. This list will be combined with the constant `org-global-properties-fixed'.
  3207. The entries in this list are cons cells where the car is a property
  3208. name and cdr is a string with the value.
  3209. You can set buffer-local values for the same purpose in the variable
  3210. `org-file-properties' this by adding lines like
  3211. #+PROPERTY: NAME VALUE"
  3212. :group 'org-properties
  3213. :type '(repeat
  3214. (cons (string :tag "Property")
  3215. (string :tag "Value"))))
  3216. (defvar-local org-file-properties nil
  3217. "List of property/value pairs that can be inherited by any entry.
  3218. Valid for the current buffer.
  3219. This variable is populated from #+PROPERTY lines.")
  3220. (defgroup org-agenda nil
  3221. "Options concerning agenda views in Org mode."
  3222. :tag "Org Agenda"
  3223. :group 'org)
  3224. (defvar-local org-category nil
  3225. "Variable used by Org files to set a category for agenda display.
  3226. Such files should use a file variable to set it, for example
  3227. # -*- mode: org; org-category: \"ELisp\"
  3228. or contain a special line
  3229. #+CATEGORY: ELisp
  3230. If the file does not specify a category, then file's base name
  3231. is used instead.")
  3232. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3233. (defcustom org-agenda-files nil
  3234. "The files to be used for agenda display.
  3235. If an entry is a directory, all files in that directory that are matched
  3236. by `org-agenda-file-regexp' will be part of the file list.
  3237. If the value of the variable is not a list but a single file name, then
  3238. the list of agenda files is actually stored and maintained in that file,
  3239. one agenda file per line. In this file paths can be given relative to
  3240. `org-directory'. Tilde expansion and environment variable substitution
  3241. are also made.
  3242. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3243. and removed with `\\[org-remove-file]'."
  3244. :group 'org-agenda
  3245. :type '(choice
  3246. (repeat :tag "List of files and directories" file)
  3247. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3248. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3249. "Regular expression to match files for `org-agenda-files'.
  3250. If any element in the list in that variable contains a directory instead
  3251. of a normal file, all files in that directory that are matched by this
  3252. regular expression will be included."
  3253. :group 'org-agenda
  3254. :type 'regexp)
  3255. (defcustom org-agenda-text-search-extra-files nil
  3256. "List of extra files to be searched by text search commands.
  3257. These files will be searched in addition to the agenda files by the
  3258. commands `org-search-view' (`\\[org-agenda] s') \
  3259. and `org-occur-in-agenda-files'.
  3260. Note that these files will only be searched for text search commands,
  3261. not for the other agenda views like todo lists, tag searches or the weekly
  3262. agenda. This variable is intended to list notes and possibly archive files
  3263. that should also be searched by these two commands.
  3264. In fact, if the first element in the list is the symbol `agenda-archives',
  3265. then all archive files of all agenda files will be added to the search
  3266. scope."
  3267. :group 'org-agenda
  3268. :type '(set :greedy t
  3269. (const :tag "Agenda Archives" agenda-archives)
  3270. (repeat :inline t (file))))
  3271. (defvaralias 'org-agenda-multi-occur-extra-files
  3272. 'org-agenda-text-search-extra-files)
  3273. (defcustom org-agenda-skip-unavailable-files nil
  3274. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3275. A nil value means to remove them, after a query, from the list."
  3276. :group 'org-agenda
  3277. :type 'boolean)
  3278. (defcustom org-agenda-diary-file 'diary-file
  3279. "File to which to add new entries with the `i' key in agenda and calendar.
  3280. When this is the symbol `diary-file', the functionality in the Emacs
  3281. calendar will be used to add entries to the `diary-file'. But when this
  3282. points to a file, `org-agenda-diary-entry' will be used instead."
  3283. :group 'org-agenda
  3284. :type '(choice
  3285. (const :tag "The standard Emacs diary file" diary-file)
  3286. (file :tag "Special Org file diary entries")))
  3287. (defgroup org-latex nil
  3288. "Options for embedding LaTeX code into Org mode."
  3289. :tag "Org LaTeX"
  3290. :group 'org)
  3291. (defcustom org-format-latex-options
  3292. '(:foreground default :background default :scale 1.0
  3293. :html-foreground "Black" :html-background "Transparent"
  3294. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3295. "Options for creating images from LaTeX fragments.
  3296. This is a property list with the following properties:
  3297. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3298. `default' means use the foreground of the default face.
  3299. `auto' means use the foreground from the text face.
  3300. :background the background color, or \"Transparent\".
  3301. `default' means use the background of the default face.
  3302. `auto' means use the background from the text face.
  3303. :scale a scaling factor for the size of the images, to get more pixels
  3304. :html-foreground, :html-background, :html-scale
  3305. the same numbers for HTML export.
  3306. :matchers a list indicating which matchers should be used to
  3307. find LaTeX fragments. Valid members of this list are:
  3308. \"begin\" find environments
  3309. \"$1\" find single characters surrounded by $.$
  3310. \"$\" find math expressions surrounded by $...$
  3311. \"$$\" find math expressions surrounded by $$....$$
  3312. \"\\(\" find math expressions surrounded by \\(...\\)
  3313. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3314. :group 'org-latex
  3315. :type 'plist)
  3316. (defcustom org-format-latex-signal-error t
  3317. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3318. When nil, just push out a message."
  3319. :group 'org-latex
  3320. :version "24.1"
  3321. :type 'boolean)
  3322. (defcustom org-latex-to-mathml-jar-file nil
  3323. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3324. Use this to specify additional executable file say a jar file.
  3325. When using MathToWeb as the converter, specify the full-path to
  3326. your mathtoweb.jar file."
  3327. :group 'org-latex
  3328. :version "24.1"
  3329. :type '(choice
  3330. (const :tag "None" nil)
  3331. (file :tag "JAR file" :must-match t)))
  3332. (defcustom org-latex-to-mathml-convert-command nil
  3333. "Command to convert LaTeX fragments to MathML.
  3334. Replace format-specifiers in the command as noted below and use
  3335. `shell-command' to convert LaTeX to MathML.
  3336. %j: Executable file in fully expanded form as specified by
  3337. `org-latex-to-mathml-jar-file'.
  3338. %I: Input LaTeX file in fully expanded form.
  3339. %i: The latex fragment to be converted.
  3340. %o: Output MathML file.
  3341. This command is used by `org-create-math-formula'.
  3342. When using MathToWeb as the converter, set this option to
  3343. \"java -jar %j -unicode -force -df %o %I\".
  3344. When using LaTeXML set this option to
  3345. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3346. :group 'org-latex
  3347. :version "24.1"
  3348. :type '(choice
  3349. (const :tag "None" nil)
  3350. (string :tag "\nShell command")))
  3351. (defcustom org-preview-latex-default-process 'dvipng
  3352. "The default process to convert LaTeX fragments to image files.
  3353. All available processes and theirs documents can be found in
  3354. `org-preview-latex-process-alist', which see."
  3355. :group 'org-latex
  3356. :version "26.1"
  3357. :package-version '(Org . "9.0")
  3358. :type 'symbol)
  3359. (defcustom org-preview-latex-process-alist
  3360. '((dvipng
  3361. :programs ("latex" "dvipng")
  3362. :description "dvi > png"
  3363. :message "you need to install the programs: latex and dvipng."
  3364. :image-input-type "dvi"
  3365. :image-output-type "png"
  3366. :image-size-adjust (1.0 . 1.0)
  3367. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3368. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3369. (dvisvgm
  3370. :programs ("latex" "dvisvgm")
  3371. :description "dvi > svg"
  3372. :message "you need to install the programs: latex and dvisvgm."
  3373. :use-xcolor t
  3374. :image-input-type "dvi"
  3375. :image-output-type "svg"
  3376. :image-size-adjust (1.7 . 1.5)
  3377. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3378. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3379. (imagemagick
  3380. :programs ("latex" "convert")
  3381. :description "pdf > png"
  3382. :message "you need to install the programs: latex and imagemagick."
  3383. :use-xcolor t
  3384. :image-input-type "pdf"
  3385. :image-output-type "png"
  3386. :image-size-adjust (1.0 . 1.0)
  3387. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3388. :image-converter
  3389. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3390. "Definitions of external processes for LaTeX previewing.
  3391. Org mode can use some external commands to generate TeX snippet's images for
  3392. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3393. `org-create-formula-image' how to call them.
  3394. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3395. PROPERTIES accepts the following attributes:
  3396. :programs list of strings, required programs.
  3397. :description string, describe the process.
  3398. :message string, message it when required programs cannot be found.
  3399. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3400. :image-output-type string, output file type of image converter (e.g., \"png\").
  3401. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3402. deal with background and foreground color of image.
  3403. Otherwise, dvipng style background and foreground color
  3404. format are generated. You may then refer to them in
  3405. command options with \"%F\" and \"%B\".
  3406. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3407. image size showed in buffer and the cdr element is for
  3408. HTML file. This option is only useful for process
  3409. developers, users should use variable
  3410. `org-format-latex-options' instead.
  3411. :post-clean list of strings, files matched are to be cleaned up once
  3412. the image is generated. When nil, the files with \".dvi\",
  3413. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3414. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3415. be cleaned up.
  3416. :latex-header list of strings, the LaTeX header of the snippet file.
  3417. When nil, the fallback value is used instead, which is
  3418. controlled by `org-format-latex-header',
  3419. `org-latex-default-packages-alist' and
  3420. `org-latex-packages-alist', which see.
  3421. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3422. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3423. replaced with values defined below.
  3424. :image-converter list of image converter commands strings. Each of them is
  3425. given to the shell and supports any of the following
  3426. place-holders defined below.
  3427. Place-holders used by `:image-converter' and `:latex-compiler':
  3428. %f input file name
  3429. %b base name of input file
  3430. %o base directory of input file
  3431. %O absolute output file name
  3432. Place-holders only used by `:image-converter':
  3433. %F foreground of image
  3434. %B background of image
  3435. %D dpi, which is used to adjust image size by some processing commands.
  3436. %S the image size scale ratio, which is used to adjust image size by some
  3437. processing commands."
  3438. :group 'org-latex
  3439. :version "26.1"
  3440. :package-version '(Org . "9.0")
  3441. :type '(alist :tag "LaTeX to image backends"
  3442. :value-type (plist)))
  3443. (defcustom org-preview-latex-image-directory "ltximg/"
  3444. "Path to store latex preview images.
  3445. A relative path here creates many directories relative to the
  3446. processed Org files paths. An absolute path puts all preview
  3447. images at the same place."
  3448. :group 'org-latex
  3449. :version "26.1"
  3450. :package-version '(Org . "9.0")
  3451. :type 'string)
  3452. (defun org-format-latex-mathml-available-p ()
  3453. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3454. (save-match-data
  3455. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3456. org-latex-to-mathml-convert-command)
  3457. (let ((executable (car (split-string
  3458. org-latex-to-mathml-convert-command))))
  3459. (when (executable-find executable)
  3460. (if (string-match
  3461. "%j" org-latex-to-mathml-convert-command)
  3462. (file-readable-p org-latex-to-mathml-jar-file)
  3463. t))))))
  3464. (defcustom org-format-latex-header "\\documentclass{article}
  3465. \\usepackage[usenames]{color}
  3466. \[PACKAGES]
  3467. \[DEFAULT-PACKAGES]
  3468. \\pagestyle{empty} % do not remove
  3469. % The settings below are copied from fullpage.sty
  3470. \\setlength{\\textwidth}{\\paperwidth}
  3471. \\addtolength{\\textwidth}{-3cm}
  3472. \\setlength{\\oddsidemargin}{1.5cm}
  3473. \\addtolength{\\oddsidemargin}{-2.54cm}
  3474. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3475. \\setlength{\\textheight}{\\paperheight}
  3476. \\addtolength{\\textheight}{-\\headheight}
  3477. \\addtolength{\\textheight}{-\\headsep}
  3478. \\addtolength{\\textheight}{-\\footskip}
  3479. \\addtolength{\\textheight}{-3cm}
  3480. \\setlength{\\topmargin}{1.5cm}
  3481. \\addtolength{\\topmargin}{-2.54cm}"
  3482. "The document header used for processing LaTeX fragments.
  3483. It is imperative that this header make sure that no page number
  3484. appears on the page. The package defined in the variables
  3485. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3486. will either replace the placeholder \"[PACKAGES]\" in this
  3487. header, or they will be appended."
  3488. :group 'org-latex
  3489. :type 'string)
  3490. (defun org-set-packages-alist (var val)
  3491. "Set the packages alist and make sure it has 3 elements per entry."
  3492. (set var (mapcar (lambda (x)
  3493. (if (and (consp x) (= (length x) 2))
  3494. (list (car x) (nth 1 x) t)
  3495. x))
  3496. val)))
  3497. (defun org-get-packages-alist (var)
  3498. "Get the packages alist and make sure it has 3 elements per entry."
  3499. (mapcar (lambda (x)
  3500. (if (and (consp x) (= (length x) 2))
  3501. (list (car x) (nth 1 x) t)
  3502. x))
  3503. (default-value var)))
  3504. (defcustom org-latex-default-packages-alist
  3505. '(("AUTO" "inputenc" t ("pdflatex"))
  3506. ("T1" "fontenc" t ("pdflatex"))
  3507. ("" "graphicx" t)
  3508. ("" "grffile" t)
  3509. ("" "longtable" nil)
  3510. ("" "wrapfig" nil)
  3511. ("" "rotating" nil)
  3512. ("normalem" "ulem" t)
  3513. ("" "amsmath" t)
  3514. ("" "textcomp" t)
  3515. ("" "amssymb" t)
  3516. ("" "capt-of" nil)
  3517. ("" "hyperref" nil))
  3518. "Alist of default packages to be inserted in the header.
  3519. Change this only if one of the packages here causes an
  3520. incompatibility with another package you are using.
  3521. The packages in this list are needed by one part or another of
  3522. Org mode to function properly:
  3523. - inputenc, fontenc: for basic font and character selection
  3524. - graphicx: for including images
  3525. - grffile: allow periods and spaces in graphics file names
  3526. - longtable: For multipage tables
  3527. - wrapfig: for figure placement
  3528. - rotating: for sideways figures and tables
  3529. - ulem: for underline and strike-through
  3530. - amsmath: for subscript and superscript and math environments
  3531. - textcomp, amssymb: for various symbols used
  3532. for interpreting the entities in `org-entities'. You can skip
  3533. some of these packages if you don't use any of their symbols.
  3534. - capt-of: for captions outside of floats
  3535. - hyperref: for cross references
  3536. Therefore you should not modify this variable unless you know
  3537. what you are doing. The one reason to change it anyway is that
  3538. you might be loading some other package that conflicts with one
  3539. of the default packages. Each element is either a cell or
  3540. a string.
  3541. A cell is of the format
  3542. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3543. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3544. when compiling LaTeX snippets into images for inclusion into
  3545. non-LaTeX output. COMPILERS is a list of compilers that should
  3546. include the package, see `org-latex-compiler'. If the document
  3547. compiler is not in the list, and the list is non-nil, the package
  3548. will not be inserted in the final document.
  3549. A string will be inserted as-is in the header of the document."
  3550. :group 'org-latex
  3551. :group 'org-export-latex
  3552. :set 'org-set-packages-alist
  3553. :get 'org-get-packages-alist
  3554. :version "26.1"
  3555. :package-version '(Org . "8.3")
  3556. :type '(repeat
  3557. (choice
  3558. (list :tag "options/package pair"
  3559. (string :tag "options")
  3560. (string :tag "package")
  3561. (boolean :tag "Snippet")
  3562. (choice
  3563. (const :tag "For all compilers" nil)
  3564. (repeat :tag "Allowed compiler" string)))
  3565. (string :tag "A line of LaTeX"))))
  3566. (defcustom org-latex-packages-alist nil
  3567. "Alist of packages to be inserted in every LaTeX header.
  3568. These will be inserted after `org-latex-default-packages-alist'.
  3569. Each element is either a cell or a string.
  3570. A cell is of the format:
  3571. (\"options\" \"package\" SNIPPET-FLAG)
  3572. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3573. needed when turning LaTeX snippets into images for inclusion into
  3574. non-LaTeX output.
  3575. A string will be inserted as-is in the header of the document.
  3576. Make sure that you only list packages here which:
  3577. - you want in every file;
  3578. - do not conflict with the setup in `org-format-latex-header';
  3579. - do not conflict with the default packages in
  3580. `org-latex-default-packages-alist'."
  3581. :group 'org-latex
  3582. :group 'org-export-latex
  3583. :set 'org-set-packages-alist
  3584. :get 'org-get-packages-alist
  3585. :type '(repeat
  3586. (choice
  3587. (list :tag "options/package pair"
  3588. (string :tag "options")
  3589. (string :tag "package")
  3590. (boolean :tag "Snippet"))
  3591. (string :tag "A line of LaTeX"))))
  3592. (defgroup org-appearance nil
  3593. "Settings for Org mode appearance."
  3594. :tag "Org Appearance"
  3595. :group 'org)
  3596. (defcustom org-level-color-stars-only nil
  3597. "Non-nil means fontify only the stars in each headline.
  3598. When nil, the entire headline is fontified.
  3599. Changing it requires restart of `font-lock-mode' to become effective
  3600. also in regions already fontified."
  3601. :group 'org-appearance
  3602. :type 'boolean)
  3603. (defcustom org-hide-leading-stars nil
  3604. "Non-nil means hide the first N-1 stars in a headline.
  3605. This works by using the face `org-hide' for these stars. This
  3606. face is white for a light background, and black for a dark
  3607. background. You may have to customize the face `org-hide' to
  3608. make this work.
  3609. Changing it requires restart of `font-lock-mode' to become effective
  3610. also in regions already fontified.
  3611. You may also set this on a per-file basis by adding one of the following
  3612. lines to the buffer:
  3613. #+STARTUP: hidestars
  3614. #+STARTUP: showstars"
  3615. :group 'org-appearance
  3616. :type 'boolean)
  3617. (defcustom org-hidden-keywords nil
  3618. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3619. For example, a value \\='(title) for this list makes the document's title
  3620. appear in the buffer without the initial \"#+TITLE:\" part."
  3621. :group 'org-appearance
  3622. :version "24.1"
  3623. :type '(set (const :tag "#+AUTHOR" author)
  3624. (const :tag "#+DATE" date)
  3625. (const :tag "#+EMAIL" email)
  3626. (const :tag "#+TITLE" title)))
  3627. (defcustom org-custom-properties nil
  3628. "List of properties (as strings) with a special meaning.
  3629. The default use of these custom properties is to let the user
  3630. hide them with `org-toggle-custom-properties-visibility'."
  3631. :group 'org-properties
  3632. :group 'org-appearance
  3633. :version "24.3"
  3634. :type '(repeat (string :tag "Property Name")))
  3635. (defcustom org-fontify-done-headline nil
  3636. "Non-nil means change the face of a headline if it is marked DONE.
  3637. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3638. When this is non-nil, the headline after the keyword is set to the
  3639. `org-headline-done' as an additional indication."
  3640. :group 'org-appearance
  3641. :type 'boolean)
  3642. (defcustom org-fontify-emphasized-text t
  3643. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3644. Changing this variable requires a restart of Emacs to take effect."
  3645. :group 'org-appearance
  3646. :type 'boolean)
  3647. (defcustom org-fontify-whole-heading-line nil
  3648. "Non-nil means fontify the whole line for headings.
  3649. This is useful when setting a background color for the
  3650. org-level-* faces."
  3651. :group 'org-appearance
  3652. :type 'boolean)
  3653. (defcustom org-highlight-latex-and-related nil
  3654. "Non-nil means highlight LaTeX related syntax in the buffer.
  3655. When non nil, the value should be a list containing any of the
  3656. following symbols:
  3657. `latex' Highlight LaTeX snippets and environments.
  3658. `script' Highlight subscript and superscript.
  3659. `entities' Highlight entities."
  3660. :group 'org-appearance
  3661. :version "24.4"
  3662. :package-version '(Org . "8.0")
  3663. :type '(choice
  3664. (const :tag "No highlighting" nil)
  3665. (set :greedy t :tag "Highlight"
  3666. (const :tag "LaTeX snippets and environments" latex)
  3667. (const :tag "Subscript and superscript" script)
  3668. (const :tag "Entities" entities))))
  3669. (defcustom org-hide-emphasis-markers nil
  3670. "Non-nil mean font-lock should hide the emphasis marker characters."
  3671. :group 'org-appearance
  3672. :type 'boolean
  3673. :safe #'booleanp)
  3674. (defcustom org-hide-macro-markers nil
  3675. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3676. :group 'org-appearance
  3677. :type 'boolean)
  3678. (defcustom org-pretty-entities nil
  3679. "Non-nil means show entities as UTF8 characters.
  3680. When nil, the \\name form remains in the buffer."
  3681. :group 'org-appearance
  3682. :version "24.1"
  3683. :type 'boolean)
  3684. (defcustom org-pretty-entities-include-sub-superscripts t
  3685. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3686. :group 'org-appearance
  3687. :version "24.1"
  3688. :type 'boolean)
  3689. (defvar org-emph-re nil
  3690. "Regular expression for matching emphasis.
  3691. After a match, the match groups contain these elements:
  3692. 0 The match of the full regular expression, including the characters
  3693. before and after the proper match
  3694. 1 The character before the proper match, or empty at beginning of line
  3695. 2 The proper match, including the leading and trailing markers
  3696. 3 The leading marker like * or /, indicating the type of highlighting
  3697. 4 The text between the emphasis markers, not including the markers
  3698. 5 The character after the match, empty at the end of a line")
  3699. (defvar org-verbatim-re nil
  3700. "Regular expression for matching verbatim text.")
  3701. (defvar org-emphasis-regexp-components) ; defined just below
  3702. (defvar org-emphasis-alist) ; defined just below
  3703. (defun org-set-emph-re (var val)
  3704. "Set variable and compute the emphasis regular expression."
  3705. (set var val)
  3706. (when (and (boundp 'org-emphasis-alist)
  3707. (boundp 'org-emphasis-regexp-components)
  3708. org-emphasis-alist org-emphasis-regexp-components)
  3709. (pcase-let*
  3710. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3711. (body (if (<= nl 0) body
  3712. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3713. (template
  3714. (format (concat "\\([%s]\\|^\\)" ;before markers
  3715. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3716. "\\([%s]\\|$\\)") ;after markers
  3717. pre border border body border post)))
  3718. (setq org-emph-re (format template "*/_+"))
  3719. (setq org-verbatim-re (format template "=~")))))
  3720. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3721. ;; set this option proved cumbersome. See this message/thread:
  3722. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3723. (defvar org-emphasis-regexp-components
  3724. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3725. "Components used to build the regular expression for emphasis.
  3726. This is a list with five entries. Terminology: In an emphasis string
  3727. like \" *strong word* \", we call the initial space PREMATCH, the final
  3728. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3729. and \"trong wor\" is the body. The different components in this variable
  3730. specify what is allowed/forbidden in each part:
  3731. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3732. post Chars allowed as postmatch. End of line will be allowed too.
  3733. border The chars *forbidden* as border characters.
  3734. body-regexp A regexp like \".\" to match a body character. Don't use
  3735. non-shy groups here, and don't allow newline here.
  3736. newline The maximum number of newlines allowed in an emphasis exp.
  3737. You need to reload Org or to restart Emacs after setting this.")
  3738. (defcustom org-emphasis-alist
  3739. '(("*" bold)
  3740. ("/" italic)
  3741. ("_" underline)
  3742. ("=" org-verbatim verbatim)
  3743. ("~" org-code verbatim)
  3744. ("+" (:strike-through t)))
  3745. "Alist of characters and faces to emphasize text.
  3746. Text starting and ending with a special character will be emphasized,
  3747. for example *bold*, _underlined_ and /italic/. This variable sets the
  3748. marker characters and the face to be used by font-lock for highlighting
  3749. in Org buffers.
  3750. You need to reload Org or to restart Emacs after customizing this."
  3751. :group 'org-appearance
  3752. :set 'org-set-emph-re
  3753. :version "24.4"
  3754. :package-version '(Org . "8.0")
  3755. :type '(repeat
  3756. (list
  3757. (string :tag "Marker character")
  3758. (choice
  3759. (face :tag "Font-lock-face")
  3760. (plist :tag "Face property list"))
  3761. (option (const verbatim)))))
  3762. (defvar org-protecting-blocks '("src" "example" "export")
  3763. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3764. This is needed for font-lock setup.")
  3765. ;;; Functions and variables from their packages
  3766. ;; Declared here to avoid compiler warnings
  3767. (defvar mark-active)
  3768. ;; Various packages
  3769. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3770. (declare-function calendar-forward-day "cal-move" (arg))
  3771. (declare-function calendar-goto-date "cal-move" (date))
  3772. (declare-function calendar-goto-today "cal-move" ())
  3773. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3774. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3775. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3776. (declare-function cdlatex-tab "ext:cdlatex" ())
  3777. (declare-function dired-get-filename
  3778. "dired"
  3779. (&optional localp no-error-if-not-filep))
  3780. (declare-function iswitchb-read-buffer
  3781. "iswitchb"
  3782. (prompt &optional
  3783. default require-match _predicate start matches-set))
  3784. (declare-function org-agenda-change-all-lines
  3785. "org-agenda"
  3786. (newhead hdmarker &optional fixface just-this))
  3787. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3788. "org-agenda"
  3789. (&optional end))
  3790. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3791. (declare-function org-agenda-format-item
  3792. "org-agenda"
  3793. (extra txt &optional level category tags dotime
  3794. remove-re habitp))
  3795. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3796. (declare-function org-agenda-save-markers-for-cut-and-paste
  3797. "org-agenda"
  3798. (beg end))
  3799. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3800. (declare-function org-agenda-skip "org-agenda" ())
  3801. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3802. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3803. (declare-function org-indent-mode "org-indent" (&optional arg))
  3804. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3805. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3806. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3807. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3808. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3809. (declare-function parse-time-string "parse-time" (string))
  3810. (defvar align-mode-rules-list)
  3811. (defvar calc-embedded-close-formula)
  3812. (defvar calc-embedded-open-formula)
  3813. (defvar calc-embedded-open-mode)
  3814. (defvar font-lock-unfontify-region-function)
  3815. (defvar iswitchb-temp-buflist)
  3816. (defvar org-agenda-tags-todo-honor-ignore-options)
  3817. (defvar remember-data-file)
  3818. (defvar texmathp-why)
  3819. ;;;###autoload
  3820. (defun turn-on-orgtbl ()
  3821. "Unconditionally turn on `orgtbl-mode'."
  3822. (require 'org-table)
  3823. (orgtbl-mode 1))
  3824. (defun org-at-table-p (&optional table-type)
  3825. "Non-nil if the cursor is inside an Org table.
  3826. If TABLE-TYPE is non-nil, also check for table.el-type tables."
  3827. (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
  3828. (or (not (derived-mode-p 'org-mode))
  3829. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3830. (and e (or table-type
  3831. (eq 'org (org-element-property :type e))))))))
  3832. (defun org-at-table.el-p ()
  3833. "Non-nil when point is at a table.el table."
  3834. (and (org-match-line "[ \t]*[|+]")
  3835. (let ((element (org-element-at-point)))
  3836. (and (eq (org-element-type element) 'table)
  3837. (eq (org-element-property :type element) 'table.el)))))
  3838. (defun org-at-table-hline-p ()
  3839. "Non-nil when point is inside a hline in a table.
  3840. Assume point is already in a table."
  3841. (org-match-line org-table-hline-regexp))
  3842. (defun org-table-map-tables (function &optional quietly)
  3843. "Apply FUNCTION to the start of all tables in the buffer."
  3844. (org-with-wide-buffer
  3845. (goto-char (point-min))
  3846. (while (re-search-forward org-table-any-line-regexp nil t)
  3847. (unless quietly
  3848. (message "Mapping tables: %d%%"
  3849. (floor (* 100.0 (point)) (buffer-size))))
  3850. (beginning-of-line 1)
  3851. (when (and (looking-at org-table-line-regexp)
  3852. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3853. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3854. (save-excursion (funcall function))
  3855. (or (looking-at org-table-line-regexp)
  3856. (forward-char 1)))
  3857. (re-search-forward org-table-any-border-regexp nil 1)))
  3858. (unless quietly (message "Mapping tables: done")))
  3859. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3860. (declare-function org-clock-update-mode-line "org-clock" ())
  3861. (declare-function org-resolve-clocks "org-clock"
  3862. (&optional also-non-dangling-p prompt last-valid))
  3863. (defun org-at-TBLFM-p (&optional pos)
  3864. "Non-nil when point (or POS) is in #+TBLFM line."
  3865. (save-excursion
  3866. (goto-char (or pos (point)))
  3867. (beginning-of-line)
  3868. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3869. (eq (org-element-type (org-element-at-point)) 'table))))
  3870. (defvar org-clock-start-time)
  3871. (defvar org-clock-marker (make-marker)
  3872. "Marker recording the last clock-in.")
  3873. (defvar org-clock-hd-marker (make-marker)
  3874. "Marker recording the last clock-in, but the headline position.")
  3875. (defvar org-clock-heading ""
  3876. "The heading of the current clock entry.")
  3877. (defun org-clock-is-active ()
  3878. "Return the buffer where the clock is currently running.
  3879. Return nil if no clock is running."
  3880. (marker-buffer org-clock-marker))
  3881. (defun org-check-running-clock ()
  3882. "Check if the current buffer contains the running clock.
  3883. If yes, offer to stop it and to save the buffer with the changes."
  3884. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3885. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3886. (buffer-name))))
  3887. (org-clock-out)
  3888. (when (y-or-n-p "Save changed buffer?")
  3889. (save-buffer))))
  3890. (defun org-clocktable-try-shift (dir n)
  3891. "Check if this line starts a clock table, if yes, shift the time block."
  3892. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3893. (org-clocktable-shift dir n)))
  3894. ;;;###autoload
  3895. (defun org-clock-persistence-insinuate ()
  3896. "Set up hooks for clock persistence."
  3897. (require 'org-clock)
  3898. (add-hook 'org-mode-hook 'org-clock-load)
  3899. (add-hook 'kill-emacs-hook 'org-clock-save))
  3900. (defgroup org-archive nil
  3901. "Options concerning archiving in Org mode."
  3902. :tag "Org Archive"
  3903. :group 'org-structure)
  3904. (defcustom org-archive-location "%s_archive::"
  3905. "The location where subtrees should be archived.
  3906. The value of this variable is a string, consisting of two parts,
  3907. separated by a double-colon. The first part is a filename and
  3908. the second part is a headline.
  3909. When the filename is omitted, archiving happens in the same file.
  3910. %s in the filename will be replaced by the current file
  3911. name (without the directory part). Archiving to a different file
  3912. is useful to keep archived entries from contributing to the
  3913. Org Agenda.
  3914. The archived entries will be filed as subtrees of the specified
  3915. headline. When the headline is omitted, the subtrees are simply
  3916. filed away at the end of the file, as top-level entries. Also in
  3917. the heading you can use %s to represent the file name, this can be
  3918. useful when using the same archive for a number of different files.
  3919. Here are a few examples:
  3920. \"%s_archive::\"
  3921. If the current file is Projects.org, archive in file
  3922. Projects.org_archive, as top-level trees. This is the default.
  3923. \"::* Archived Tasks\"
  3924. Archive in the current file, under the top-level headline
  3925. \"* Archived Tasks\".
  3926. \"~/org/archive.org::\"
  3927. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3928. \"~/org/archive.org::* From %s\"
  3929. Archive in file ~/org/archive.org (absolute path), under headlines
  3930. \"From FILENAME\" where file name is the current file name.
  3931. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3932. The \"datetree/\" string is special, signifying to archive
  3933. items to the datetree. Items are placed in either the CLOSED
  3934. date of the item, or the current date if there is no CLOSED date.
  3935. The heading will be a subentry to the current date. There doesn't
  3936. need to be a heading, but there always needs to be a slash after
  3937. datetree. For example, to store archived items directly in the
  3938. datetree, use \"~/org/datetree.org::datetree/\".
  3939. \"basement::** Finished Tasks\"
  3940. Archive in file ./basement (relative path), as level 3 trees
  3941. below the level 2 heading \"** Finished Tasks\".
  3942. You may set this option on a per-file basis by adding to the buffer a
  3943. line like
  3944. #+ARCHIVE: basement::** Finished Tasks
  3945. You may also define it locally for a subtree by setting an ARCHIVE property
  3946. in the entry. If such a property is found in an entry, or anywhere up
  3947. the hierarchy, it will be used."
  3948. :group 'org-archive
  3949. :type 'string)
  3950. (defcustom org-agenda-skip-archived-trees t
  3951. "Non-nil means the agenda will skip any items located in archived trees.
  3952. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3953. variable is no longer recommended, you should leave it at the value t.
  3954. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3955. :group 'org-archive
  3956. :group 'org-agenda-skip
  3957. :type 'boolean)
  3958. (defcustom org-columns-skip-archived-trees t
  3959. "Non-nil means ignore archived trees when creating column view."
  3960. :group 'org-archive
  3961. :group 'org-properties
  3962. :type 'boolean)
  3963. (defcustom org-cycle-open-archived-trees nil
  3964. "Non-nil means `org-cycle' will open archived trees.
  3965. An archived tree is a tree marked with the tag ARCHIVE.
  3966. When nil, archived trees will stay folded. You can still open them with
  3967. normal outline commands like `show-all', but not with the cycling commands."
  3968. :group 'org-archive
  3969. :group 'org-cycle
  3970. :type 'boolean)
  3971. (defcustom org-sparse-tree-open-archived-trees nil
  3972. "Non-nil means sparse tree construction shows matches in archived trees.
  3973. When nil, matches in these trees are highlighted, but the trees are kept in
  3974. collapsed state."
  3975. :group 'org-archive
  3976. :group 'org-sparse-trees
  3977. :type 'boolean)
  3978. (defcustom org-sparse-tree-default-date-type nil
  3979. "The default date type when building a sparse tree.
  3980. When this is nil, a date is a scheduled or a deadline timestamp.
  3981. Otherwise, these types are allowed:
  3982. all: all timestamps
  3983. active: only active timestamps (<...>)
  3984. inactive: only inactive timestamps ([...])
  3985. scheduled: only scheduled timestamps
  3986. deadline: only deadline timestamps"
  3987. :type '(choice (const :tag "Scheduled or deadline" nil)
  3988. (const :tag "All timestamps" all)
  3989. (const :tag "Only active timestamps" active)
  3990. (const :tag "Only inactive timestamps" inactive)
  3991. (const :tag "Only scheduled timestamps" scheduled)
  3992. (const :tag "Only deadline timestamps" deadline)
  3993. (const :tag "Only closed timestamps" closed))
  3994. :version "26.1"
  3995. :package-version '(Org . "8.3")
  3996. :group 'org-sparse-trees)
  3997. (defun org-cycle-hide-archived-subtrees (state)
  3998. "Re-hide all archived subtrees after a visibility state change.
  3999. STATE should be one of the symbols listed in the docstring of
  4000. `org-cycle-hook'."
  4001. (when (and (not org-cycle-open-archived-trees)
  4002. (not (memq state '(overview folded))))
  4003. (save-excursion
  4004. (let* ((globalp (memq state '(contents all)))
  4005. (beg (if globalp (point-min) (point)))
  4006. (end (if globalp (point-max) (org-end-of-subtree t))))
  4007. (org-hide-archived-subtrees beg end)
  4008. (goto-char beg)
  4009. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4010. (message "%s" (substitute-command-keys
  4011. "Subtree is archived and stays closed. Use \
  4012. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  4013. (defun org-force-cycle-archived ()
  4014. "Cycle subtree even if it is archived."
  4015. (interactive)
  4016. (setq this-command 'org-cycle)
  4017. (let ((org-cycle-open-archived-trees t))
  4018. (call-interactively 'org-cycle)))
  4019. (defun org-hide-archived-subtrees (beg end)
  4020. "Re-hide all archived subtrees after a visibility state change."
  4021. (org-with-wide-buffer
  4022. (let ((case-fold-search nil)
  4023. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4024. (goto-char beg)
  4025. ;; Include headline point is currently on.
  4026. (beginning-of-line)
  4027. (while (and (< (point) end) (re-search-forward re end t))
  4028. (when (member org-archive-tag (org-get-tags nil t))
  4029. (org-flag-subtree t)
  4030. (org-end-of-subtree t))))))
  4031. (defun org-flag-subtree (flag)
  4032. (save-excursion
  4033. (org-back-to-heading t)
  4034. (org-flag-region (line-end-position)
  4035. (progn (org-end-of-subtree t) (point))
  4036. flag
  4037. 'outline)))
  4038. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4039. ;; Declare Column View Code
  4040. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4041. (declare-function org-columns-compute "org-colview" (property))
  4042. ;; Declare ID code
  4043. (declare-function org-id-store-link "org-id")
  4044. (declare-function org-id-locations-load "org-id")
  4045. (declare-function org-id-locations-save "org-id")
  4046. (defvar org-id-track-globally)
  4047. ;;; Variables for pre-computed regular expressions, all buffer local
  4048. (defvar-local org-todo-regexp nil
  4049. "Matches any of the TODO state keywords.
  4050. Since TODO keywords are case-sensitive, `case-fold-search' is
  4051. expected to be bound to nil when matching against this regexp.")
  4052. (defvar-local org-not-done-regexp nil
  4053. "Matches any of the TODO state keywords except the last one.
  4054. Since TODO keywords are case-sensitive, `case-fold-search' is
  4055. expected to be bound to nil when matching against this regexp.")
  4056. (defvar-local org-not-done-heading-regexp nil
  4057. "Matches a TODO headline that is not done.
  4058. Since TODO keywords are case-sensitive, `case-fold-search' is
  4059. expected to be bound to nil when matching against this regexp.")
  4060. (defvar-local org-todo-line-regexp nil
  4061. "Matches a headline and puts TODO state into group 2 if present.
  4062. Since TODO keywords are case-sensitive, `case-fold-search' is
  4063. expected to be bound to nil when matching against this regexp.")
  4064. (defvar-local org-complex-heading-regexp nil
  4065. "Matches a headline and puts everything into groups:
  4066. group 1: Stars
  4067. group 2: The TODO keyword, maybe
  4068. group 3: Priority cookie
  4069. group 4: True headline
  4070. group 5: Tags
  4071. Since TODO keywords are case-sensitive, `case-fold-search' is
  4072. expected to be bound to nil when matching against this regexp.")
  4073. (defvar-local org-complex-heading-regexp-format nil
  4074. "Printf format to make regexp to match an exact headline.
  4075. This regexp will match the headline of any node which has the
  4076. exact headline text that is put into the format, but may have any
  4077. TODO state, priority and tags.")
  4078. (defvar-local org-todo-line-tags-regexp nil
  4079. "Matches a headline and puts TODO state into group 2 if present.
  4080. Also put tags into group 4 if tags are present.")
  4081. (defconst org-plain-time-of-day-regexp
  4082. (concat
  4083. "\\(\\<[012]?[0-9]"
  4084. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4085. "\\(--?"
  4086. "\\(\\<[012]?[0-9]"
  4087. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4088. "\\)?")
  4089. "Regular expression to match a plain time or time range.
  4090. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4091. groups carry important information:
  4092. 0 the full match
  4093. 1 the first time, range or not
  4094. 8 the second time, if it is a range.")
  4095. (defconst org-plain-time-extension-regexp
  4096. (concat
  4097. "\\(\\<[012]?[0-9]"
  4098. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4099. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4100. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4101. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4102. groups carry important information:
  4103. 0 the full match
  4104. 7 hours of duration
  4105. 9 minutes of duration")
  4106. (defconst org-stamp-time-of-day-regexp
  4107. (concat
  4108. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4109. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4110. "\\(--?"
  4111. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4112. "Regular expression to match a timestamp time or time range.
  4113. After a match, the following groups carry important information:
  4114. 0 the full match
  4115. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4116. 2 the first time, range or not
  4117. 4 the second time, if it is a range.")
  4118. (defconst org-startup-options
  4119. '(("fold" org-startup-folded t)
  4120. ("overview" org-startup-folded t)
  4121. ("nofold" org-startup-folded nil)
  4122. ("showall" org-startup-folded nil)
  4123. ("showeverything" org-startup-folded showeverything)
  4124. ("content" org-startup-folded content)
  4125. ("indent" org-startup-indented t)
  4126. ("noindent" org-startup-indented nil)
  4127. ("hidestars" org-hide-leading-stars t)
  4128. ("showstars" org-hide-leading-stars nil)
  4129. ("odd" org-odd-levels-only t)
  4130. ("oddeven" org-odd-levels-only nil)
  4131. ("align" org-startup-align-all-tables t)
  4132. ("noalign" org-startup-align-all-tables nil)
  4133. ("shrink" org-startup-shrink-all-tables t)
  4134. ("inlineimages" org-startup-with-inline-images t)
  4135. ("noinlineimages" org-startup-with-inline-images nil)
  4136. ("latexpreview" org-startup-with-latex-preview t)
  4137. ("nolatexpreview" org-startup-with-latex-preview nil)
  4138. ("customtime" org-display-custom-times t)
  4139. ("logdone" org-log-done time)
  4140. ("lognotedone" org-log-done note)
  4141. ("nologdone" org-log-done nil)
  4142. ("lognoteclock-out" org-log-note-clock-out t)
  4143. ("nolognoteclock-out" org-log-note-clock-out nil)
  4144. ("logrepeat" org-log-repeat state)
  4145. ("lognoterepeat" org-log-repeat note)
  4146. ("logdrawer" org-log-into-drawer t)
  4147. ("nologdrawer" org-log-into-drawer nil)
  4148. ("logstatesreversed" org-log-states-order-reversed t)
  4149. ("nologstatesreversed" org-log-states-order-reversed nil)
  4150. ("nologrepeat" org-log-repeat nil)
  4151. ("logreschedule" org-log-reschedule time)
  4152. ("lognotereschedule" org-log-reschedule note)
  4153. ("nologreschedule" org-log-reschedule nil)
  4154. ("logredeadline" org-log-redeadline time)
  4155. ("lognoteredeadline" org-log-redeadline note)
  4156. ("nologredeadline" org-log-redeadline nil)
  4157. ("logrefile" org-log-refile time)
  4158. ("lognoterefile" org-log-refile note)
  4159. ("nologrefile" org-log-refile nil)
  4160. ("fninline" org-footnote-define-inline t)
  4161. ("nofninline" org-footnote-define-inline nil)
  4162. ("fnlocal" org-footnote-section nil)
  4163. ("fnauto" org-footnote-auto-label t)
  4164. ("fnprompt" org-footnote-auto-label nil)
  4165. ("fnconfirm" org-footnote-auto-label confirm)
  4166. ("fnplain" org-footnote-auto-label plain)
  4167. ("fnadjust" org-footnote-auto-adjust t)
  4168. ("nofnadjust" org-footnote-auto-adjust nil)
  4169. ("constcgs" constants-unit-system cgs)
  4170. ("constSI" constants-unit-system SI)
  4171. ("noptag" org-tag-persistent-alist nil)
  4172. ("hideblocks" org-hide-block-startup t)
  4173. ("nohideblocks" org-hide-block-startup nil)
  4174. ("beamer" org-startup-with-beamer-mode t)
  4175. ("entitiespretty" org-pretty-entities t)
  4176. ("entitiesplain" org-pretty-entities nil))
  4177. "Variable associated with STARTUP options for Org.
  4178. Each element is a list of three items: the startup options (as written
  4179. in the #+STARTUP line), the corresponding variable, and the value to set
  4180. this variable to if the option is found. An optional forth element PUSH
  4181. means to push this value onto the list in the variable.")
  4182. (defcustom org-group-tags t
  4183. "When non-nil (the default), use group tags.
  4184. This can be turned on/off through `org-toggle-tags-groups'."
  4185. :group 'org-tags
  4186. :group 'org-startup
  4187. :type 'boolean)
  4188. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4189. (defun org-toggle-tags-groups ()
  4190. "Toggle support for group tags.
  4191. Support for group tags is controlled by the option
  4192. `org-group-tags', which is non-nil by default."
  4193. (interactive)
  4194. (setq org-group-tags (not org-group-tags))
  4195. (cond ((and (derived-mode-p 'org-agenda-mode)
  4196. org-group-tags)
  4197. (org-agenda-redo))
  4198. ((derived-mode-p 'org-mode)
  4199. (let ((org-inhibit-startup t)) (org-mode))))
  4200. (message "Groups tags support has been turned %s"
  4201. (if org-group-tags "on" "off")))
  4202. (defun org--tag-add-to-alist (alist1 alist2)
  4203. "Merge tags from ALIST1 into ALIST2.
  4204. Duplicates tags outside a group are removed. Keywords and order
  4205. are preserved.
  4206. The function assumes ALIST1 and ALIST2 are proper tag alists.
  4207. See `org-tag-alist' for their structure."
  4208. (cond
  4209. ((null alist2) alist1)
  4210. ((null alist1) alist2)
  4211. (t
  4212. (let ((to-add nil)
  4213. (group-flag nil))
  4214. (dolist (tag-pair alist1)
  4215. (pcase tag-pair
  4216. (`(,(or :startgrouptag :startgroup))
  4217. (setq group-flag t)
  4218. (push tag-pair to-add))
  4219. (`(,(or :endgrouptag :endgroup))
  4220. (setq group-flag nil)
  4221. (push tag-pair to-add))
  4222. (`(,(or :grouptags :newline))
  4223. (push tag-pair to-add))
  4224. (`(,tag . ,_)
  4225. ;; Remove duplicates from ALIST1, unless they are in
  4226. ;; a group. Indeed, it makes sense to have a tag appear in
  4227. ;; multiple groups.
  4228. (when (or group-flag (not (assoc tag alist2)))
  4229. (push tag-pair to-add)))
  4230. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  4231. ;; Preserve order of ALIST1.
  4232. (append (nreverse to-add) alist2)))))
  4233. (defun org-set-regexps-and-options (&optional tags-only)
  4234. "Precompute regular expressions used in the current buffer.
  4235. When optional argument TAGS-ONLY is non-nil, only compute tags
  4236. related expressions."
  4237. (when (derived-mode-p 'org-mode)
  4238. (let ((alist (org--setup-collect-keywords
  4239. (org-make-options-regexp
  4240. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4241. (and (not tags-only)
  4242. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4243. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4244. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4245. ;; Startup options. Get this early since it does change
  4246. ;; behavior for other options (e.g., tags).
  4247. (let ((startup (cdr (assq 'startup alist))))
  4248. (dolist (option startup)
  4249. (let ((entry (assoc-string option org-startup-options t)))
  4250. (when entry
  4251. (let ((var (nth 1 entry))
  4252. (val (nth 2 entry)))
  4253. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4254. (unless (listp (symbol-value var))
  4255. (set (make-local-variable var) nil))
  4256. (add-to-list var val)))))))
  4257. (setq-local org-file-tags
  4258. (mapcar #'org-add-prop-inherited
  4259. (cdr (assq 'filetags alist))))
  4260. (setq org-current-tag-alist
  4261. (org--tag-add-to-alist
  4262. org-tag-persistent-alist
  4263. (let ((tags (cdr (assq 'tags alist))))
  4264. (if tags (org-tag-string-to-alist tags)
  4265. org-tag-alist))))
  4266. (setq org-tag-groups-alist
  4267. (org-tag-alist-to-groups org-current-tag-alist))
  4268. (unless tags-only
  4269. ;; File properties.
  4270. (setq-local org-file-properties (cdr (assq 'property alist)))
  4271. ;; Archive location.
  4272. (let ((archive (cdr (assq 'archive alist))))
  4273. (when archive (setq-local org-archive-location archive)))
  4274. ;; Category.
  4275. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4276. (when cat
  4277. (setq-local org-category (intern cat))
  4278. (setq-local org-file-properties
  4279. (org--update-property-plist
  4280. "CATEGORY" cat org-file-properties))))
  4281. ;; Columns.
  4282. (let ((column (cdr (assq 'columns alist))))
  4283. (when column (setq-local org-columns-default-format column)))
  4284. ;; Constants.
  4285. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4286. ;; Link abbreviations.
  4287. (let ((links (cdr (assq 'link alist))))
  4288. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4289. ;; Priorities.
  4290. (let ((priorities (cdr (assq 'priorities alist))))
  4291. (when priorities
  4292. (setq-local org-highest-priority (nth 0 priorities))
  4293. (setq-local org-lowest-priority (nth 1 priorities))
  4294. (setq-local org-default-priority (nth 2 priorities))))
  4295. ;; Scripts.
  4296. (let ((scripts (assq 'scripts alist)))
  4297. (when scripts
  4298. (setq-local org-use-sub-superscripts (cdr scripts))))
  4299. ;; TODO keywords.
  4300. (setq-local org-todo-kwd-alist nil)
  4301. (setq-local org-todo-key-alist nil)
  4302. (setq-local org-todo-key-trigger nil)
  4303. (setq-local org-todo-keywords-1 nil)
  4304. (setq-local org-done-keywords nil)
  4305. (setq-local org-todo-heads nil)
  4306. (setq-local org-todo-sets nil)
  4307. (setq-local org-todo-log-states nil)
  4308. (let ((todo-sequences
  4309. (or (nreverse (cdr (assq 'todo alist)))
  4310. (let ((d (default-value 'org-todo-keywords)))
  4311. (if (not (stringp (car d))) d
  4312. ;; XXX: Backward compatibility code.
  4313. (list (cons org-todo-interpretation d)))))))
  4314. (dolist (sequence todo-sequences)
  4315. (let* ((sequence (or (run-hook-with-args-until-success
  4316. 'org-todo-setup-filter-hook sequence)
  4317. sequence))
  4318. (sequence-type (car sequence))
  4319. (keywords (cdr sequence))
  4320. (sep (member "|" keywords))
  4321. names alist)
  4322. (dolist (k (remove "|" keywords))
  4323. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4324. k)
  4325. (error "Invalid TODO keyword %s" k))
  4326. (let ((name (match-string 1 k))
  4327. (key (match-string 2 k))
  4328. (log (org-extract-log-state-settings k)))
  4329. (push name names)
  4330. (push (cons name (and key (string-to-char key))) alist)
  4331. (when log (push log org-todo-log-states))))
  4332. (let* ((names (nreverse names))
  4333. (done (if sep (org-remove-keyword-keys (cdr sep))
  4334. (last names)))
  4335. (head (car names))
  4336. (tail (list sequence-type head (car done) (org-last done))))
  4337. (add-to-list 'org-todo-heads head 'append)
  4338. (push names org-todo-sets)
  4339. (setq org-done-keywords (append org-done-keywords done nil))
  4340. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4341. (setq org-todo-key-alist
  4342. (append org-todo-key-alist
  4343. (and alist
  4344. (append '((:startgroup))
  4345. (nreverse alist)
  4346. '((:endgroup))))))
  4347. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4348. (setq org-todo-sets (nreverse org-todo-sets)
  4349. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4350. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4351. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4352. ;; Compute the regular expressions and other local variables.
  4353. ;; Using `org-outline-regexp-bol' would complicate them much,
  4354. ;; because of the fixed white space at the end of that string.
  4355. (unless org-done-keywords
  4356. (setq org-done-keywords
  4357. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4358. (setq org-not-done-keywords
  4359. (org-delete-all org-done-keywords
  4360. (copy-sequence org-todo-keywords-1))
  4361. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4362. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4363. org-not-done-heading-regexp
  4364. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4365. org-todo-line-regexp
  4366. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4367. org-complex-heading-regexp
  4368. (concat "^\\(\\*+\\)"
  4369. "\\(?: +" org-todo-regexp "\\)?"
  4370. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4371. "\\(?: +\\(.*?\\)\\)??"
  4372. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4373. "[ \t]*$")
  4374. org-complex-heading-regexp-format
  4375. (concat "^\\(\\*+\\)"
  4376. "\\(?: +" org-todo-regexp "\\)?"
  4377. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4378. "\\(?: +"
  4379. ;; Stats cookies can be stuck to body.
  4380. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4381. "\\(%s\\)"
  4382. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4383. "\\)"
  4384. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4385. "[ \t]*$")
  4386. org-todo-line-tags-regexp
  4387. (concat "^\\(\\*+\\)"
  4388. "\\(?: +" org-todo-regexp "\\)?"
  4389. "\\(?: +\\(.*?\\)\\)??"
  4390. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4391. "[ \t]*$"))
  4392. (org-compute-latex-and-related-regexp)))))
  4393. (defun org--setup-collect-keywords (regexp &optional files alist)
  4394. "Return setup keywords values as an alist.
  4395. REGEXP matches a subset of setup keywords. FILES is a list of
  4396. file names already visited. It is used to avoid circular setup
  4397. files. ALIST, when non-nil, is the alist computed so far.
  4398. Return value contains the following keys: `archive', `category',
  4399. `columns', `constants', `filetags', `link', `priorities',
  4400. `property', `scripts', `startup', `tags' and `todo'."
  4401. (org-with-wide-buffer
  4402. (goto-char (point-min))
  4403. (let ((case-fold-search t))
  4404. (while (re-search-forward regexp nil t)
  4405. (let ((element (org-element-at-point)))
  4406. (when (eq (org-element-type element) 'keyword)
  4407. (let ((key (org-element-property :key element))
  4408. (value (org-element-property :value element)))
  4409. (cond
  4410. ((equal key "ARCHIVE")
  4411. (when (org-string-nw-p value)
  4412. (push (cons 'archive value) alist)))
  4413. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4414. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4415. ((equal key "CONSTANTS")
  4416. (let* ((constants (assq 'constants alist))
  4417. (store (cdr constants)))
  4418. (dolist (pair (split-string value))
  4419. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4420. pair)
  4421. (let* ((name (match-string 1 pair))
  4422. (value (match-string 2 pair))
  4423. (old (assoc name store)))
  4424. (if old (setcdr old value)
  4425. (push (cons name value) store)))))
  4426. (if constants (setcdr constants store)
  4427. (push (cons 'constants store) alist))))
  4428. ((equal key "FILETAGS")
  4429. (when (org-string-nw-p value)
  4430. (let ((old (assq 'filetags alist))
  4431. (new (apply #'nconc
  4432. (mapcar (lambda (x) (org-split-string x ":"))
  4433. (split-string value)))))
  4434. (if old (setcdr old (append new (cdr old)))
  4435. (push (cons 'filetags new) alist)))))
  4436. ((equal key "LINK")
  4437. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4438. (let ((links (assq 'link alist))
  4439. (pair (cons (match-string-no-properties 1 value)
  4440. (match-string-no-properties 2 value))))
  4441. (if links (push pair (cdr links))
  4442. (push (list 'link pair) alist)))))
  4443. ((equal key "OPTIONS")
  4444. (when (and (org-string-nw-p value)
  4445. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4446. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4447. ((equal key "PRIORITIES")
  4448. (push (cons 'priorities
  4449. (let ((prio (split-string value)))
  4450. (if (< (length prio) 3) '(?A ?C ?B)
  4451. (mapcar #'string-to-char prio))))
  4452. alist))
  4453. ((equal key "PROPERTY")
  4454. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4455. (let* ((property (assq 'property alist))
  4456. (value (org--update-property-plist
  4457. (match-string-no-properties 1 value)
  4458. (match-string-no-properties 2 value)
  4459. (cdr property))))
  4460. (if property (setcdr property value)
  4461. (push (cons 'property value) alist)))))
  4462. ((equal key "STARTUP")
  4463. (let ((startup (assq 'startup alist)))
  4464. (if startup
  4465. (setcdr startup
  4466. (append (cdr startup) (split-string value)))
  4467. (push (cons 'startup (split-string value)) alist))))
  4468. ((equal key "TAGS")
  4469. (let ((tag-cell (assq 'tags alist)))
  4470. (if tag-cell
  4471. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4472. (push (cons 'tags value) alist))))
  4473. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4474. (let ((todo (assq 'todo alist))
  4475. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4476. (split-string value))))
  4477. (if todo (push value (cdr todo))
  4478. (push (list 'todo value) alist))))
  4479. ((equal key "SETUPFILE")
  4480. (unless buffer-read-only ; Do not check in Gnus messages.
  4481. (let ((f (and (org-string-nw-p value)
  4482. (expand-file-name
  4483. (org-unbracket-string "\"" "\"" value)))))
  4484. (when (and f (file-readable-p f) (not (member f files)))
  4485. (with-temp-buffer
  4486. (setq default-directory (file-name-directory f))
  4487. (insert-file-contents f)
  4488. (setq alist
  4489. ;; Fake Org mode to benefit from cache
  4490. ;; without recurring needlessly.
  4491. (let ((major-mode 'org-mode))
  4492. (org--setup-collect-keywords
  4493. regexp (cons f files) alist)))))))))))))))
  4494. alist)
  4495. (defun org-tag-string-to-alist (s)
  4496. "Return tag alist associated to string S.
  4497. S is a value for TAGS keyword or produced with
  4498. `org-tag-alist-to-string'. Return value is an alist suitable for
  4499. `org-tag-alist' or `org-tag-persistent-alist'."
  4500. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4501. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  4502. "\\(?:(\\(.\\))\\)?\\'"))
  4503. alist group-flag)
  4504. (dolist (tokens lines (cdr (nreverse alist)))
  4505. (push '(:newline) alist)
  4506. (while tokens
  4507. (let ((token (pop tokens)))
  4508. (pcase token
  4509. ("{"
  4510. (push '(:startgroup) alist)
  4511. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4512. ("}"
  4513. (push '(:endgroup) alist)
  4514. (setq group-flag nil))
  4515. ("["
  4516. (push '(:startgrouptag) alist)
  4517. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4518. ("]"
  4519. (push '(:endgrouptag) alist)
  4520. (setq group-flag nil))
  4521. (":"
  4522. (push '(:grouptags) alist))
  4523. ((guard (string-match tag-re token))
  4524. (let ((tag (match-string 1 token))
  4525. (key (and (match-beginning 2)
  4526. (string-to-char (match-string 2 token)))))
  4527. ;; Push all tags in groups, no matter if they already
  4528. ;; appear somewhere else in the list.
  4529. (when (or group-flag (not (assoc tag alist)))
  4530. (push (cons tag key) alist))))))))))
  4531. (defun org-tag-alist-to-string (alist &optional skip-key)
  4532. "Return tag string associated to ALIST.
  4533. ALIST is an alist, as defined in `org-tag-alist' or
  4534. `org-tag-persistent-alist', or produced with
  4535. `org-tag-string-to-alist'.
  4536. Return value is a string suitable as a value for \"TAGS\"
  4537. keyword.
  4538. When optional argument SKIP-KEY is non-nil, skip selection keys
  4539. next to tags."
  4540. (mapconcat (lambda (token)
  4541. (pcase token
  4542. (`(:startgroup) "{")
  4543. (`(:endgroup) "}")
  4544. (`(:startgrouptag) "[")
  4545. (`(:endgrouptag) "]")
  4546. (`(:grouptags) ":")
  4547. (`(:newline) "\\n")
  4548. ((and
  4549. (guard (not skip-key))
  4550. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4551. (format "%s(%c)" tag key))
  4552. (`(,(and tag (pred stringp)) . ,_) tag)
  4553. (_ (user-error "Invalid tag token: %S" token))))
  4554. alist
  4555. " "))
  4556. (defun org-tag-alist-to-groups (alist)
  4557. "Return group alist from tag ALIST.
  4558. ALIST is an alist, as defined in `org-tag-alist' or
  4559. `org-tag-persistent-alist', or produced with
  4560. `org-tag-string-to-alist'. Return value is an alist following
  4561. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4562. a string, summarizing TAGS, as a list of strings."
  4563. (let (groups group-status current-group)
  4564. (dolist (token alist (nreverse groups))
  4565. (pcase token
  4566. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4567. (`(,(or :endgroup :endgrouptag))
  4568. (when (eq group-status 'append)
  4569. (push (nreverse current-group) groups))
  4570. (setq group-status nil current-group nil))
  4571. (`(:grouptags) (setq group-status 'append))
  4572. ((and `(,tag . ,_) (guard group-status))
  4573. (if (eq group-status 'append) (push tag current-group)
  4574. (setq current-group (list tag))))
  4575. (_ nil)))))
  4576. (defvar org--file-cache (make-hash-table :test #'equal)
  4577. "Hash table to store contents of files referenced via a URL.
  4578. This is the cache of file URLs read using `org-file-contents'.")
  4579. (defun org-reset-file-cache ()
  4580. "Reset the cache of files downloaded by `org-file-contents'."
  4581. (clrhash org--file-cache))
  4582. (defun org-file-url-p (file)
  4583. "Non-nil if FILE is a URL."
  4584. (require 'ffap)
  4585. (string-match-p ffap-url-regexp file))
  4586. (defun org-file-contents (file &optional noerror nocache)
  4587. "Return the contents of FILE, as a string.
  4588. FILE can be a file name or URL.
  4589. If FILE is a URL, download the contents. If the URL contents are
  4590. already cached in the `org--file-cache' hash table, the download step
  4591. is skipped.
  4592. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4593. from file or URL.
  4594. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4595. is available. This option applies only if FILE is a URL."
  4596. (let* ((is-url (org-file-url-p file))
  4597. (cache (and is-url
  4598. (not nocache)
  4599. (gethash file org--file-cache))))
  4600. (cond
  4601. (cache)
  4602. (is-url
  4603. (with-current-buffer (url-retrieve-synchronously file)
  4604. (goto-char (point-min))
  4605. ;; Move point to after the url-retrieve header.
  4606. (search-forward "\n\n" nil :move)
  4607. ;; Search for the success code only in the url-retrieve header.
  4608. (if (save-excursion
  4609. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4610. ;; Update the cache `org--file-cache' and return contents.
  4611. (puthash file
  4612. (buffer-substring-no-properties (point) (point-max))
  4613. org--file-cache)
  4614. (funcall (if noerror #'message #'user-error)
  4615. "Unable to fetch file from %S"
  4616. file))))
  4617. (t
  4618. (with-temp-buffer
  4619. (condition-case nil
  4620. (progn
  4621. (insert-file-contents file)
  4622. (buffer-string))
  4623. (file-error
  4624. (funcall (if noerror #'message #'user-error)
  4625. "Unable to read file %S"
  4626. file))))))))
  4627. (defun org-extract-log-state-settings (x)
  4628. "Extract the log state setting from a TODO keyword string.
  4629. This will extract info from a string like \"WAIT(w@/!)\"."
  4630. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4631. (let ((kw (match-string 1 x))
  4632. (log1 (and (match-end 3) (match-string 3 x)))
  4633. (log2 (and (match-end 4) (match-string 4 x))))
  4634. (and (or log1 log2)
  4635. (list kw
  4636. (and log1 (if (equal log1 "!") 'time 'note))
  4637. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4638. (defun org-remove-keyword-keys (list)
  4639. "Remove a pair of parenthesis at the end of each string in LIST."
  4640. (mapcar (lambda (x)
  4641. (if (string-match "(.*)$" x)
  4642. (substring x 0 (match-beginning 0))
  4643. x))
  4644. list))
  4645. (defun org-assign-fast-keys (alist)
  4646. "Assign fast keys to a keyword-key alist.
  4647. Respect keys that are already there."
  4648. (let (new e (alt ?0))
  4649. (while (setq e (pop alist))
  4650. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4651. (cdr e)) ;; Key already assigned.
  4652. (push e new)
  4653. (let ((clist (string-to-list (downcase (car e))))
  4654. (used (append new alist)))
  4655. (when (= (car clist) ?@)
  4656. (pop clist))
  4657. (while (and clist (rassoc (car clist) used))
  4658. (pop clist))
  4659. (unless clist
  4660. (while (rassoc alt used)
  4661. (cl-incf alt)))
  4662. (push (cons (car e) (or (car clist) alt)) new))))
  4663. (nreverse new)))
  4664. ;;; Some variables used in various places
  4665. (defvar org-window-configuration nil
  4666. "Used in various places to store a window configuration.")
  4667. (defvar org-selected-window nil
  4668. "Used in various places to store a window configuration.")
  4669. (defvar org-finish-function nil
  4670. "Function to be called when `C-c C-c' is used.
  4671. This is for getting out of special buffers like capture.")
  4672. (defvar org-last-state)
  4673. ;; Defined somewhere in this file, but used before definition.
  4674. (defvar org-entities) ;; defined in org-entities.el
  4675. (defvar org-struct-menu)
  4676. (defvar org-org-menu)
  4677. (defvar org-tbl-menu)
  4678. ;;;; Define the Org mode
  4679. ;; We use a before-change function to check if a table might need
  4680. ;; an update.
  4681. (defvar org-table-may-need-update t
  4682. "Indicates that a table might need an update.
  4683. This variable is set by `org-before-change-function'.
  4684. `org-table-align' sets it back to nil.")
  4685. (defun org-before-change-function (_beg _end)
  4686. "Every change indicates that a table might need an update."
  4687. (setq org-table-may-need-update t))
  4688. (defvar org-mode-map)
  4689. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4690. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4691. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4692. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4693. (defvar org-table-buffer-is-an nil)
  4694. (defvar bidi-paragraph-direction)
  4695. (defvar buffer-face-mode-face)
  4696. (require 'outline)
  4697. ;; Other stuff we need.
  4698. (require 'time-date)
  4699. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4700. (require 'easymenu)
  4701. (autoload 'easy-menu-add "easymenu")
  4702. (require 'overlay)
  4703. ;; (require 'org-macs) moved higher up in the file before it is first used
  4704. (require 'org-entities)
  4705. ;; (require 'org-compat) moved higher up in the file before it is first used
  4706. (require 'org-faces)
  4707. (require 'org-list)
  4708. (require 'org-pcomplete)
  4709. (require 'org-src)
  4710. (require 'org-footnote)
  4711. (require 'org-macro)
  4712. ;; babel
  4713. (require 'ob)
  4714. ;;;###autoload
  4715. (define-derived-mode org-mode outline-mode "Org"
  4716. "Outline-based notes management and organizer, alias
  4717. \"Carsten's outline-mode for keeping track of everything.\"
  4718. Org mode develops organizational tasks around a NOTES file which
  4719. contains information about projects as plain text. Org mode is
  4720. implemented on top of Outline mode, which is ideal to keep the content
  4721. of large files well structured. It supports ToDo items, deadlines and
  4722. time stamps, which magically appear in the diary listing of the Emacs
  4723. calendar. Tables are easily created with a built-in table editor.
  4724. Plain text URL-like links connect to websites, emails (VM), Usenet
  4725. messages (Gnus), BBDB entries, and any files related to the project.
  4726. For printing and sharing of notes, an Org file (or a part of it)
  4727. can be exported as a structured ASCII or HTML file.
  4728. The following commands are available:
  4729. \\{org-mode-map}"
  4730. ;; Get rid of Outline menus, they are not needed
  4731. ;; Need to do this here because define-derived-mode sets up
  4732. ;; the keymap so late. Still, it is a waste to call this each time
  4733. ;; we switch another buffer into Org mode.
  4734. (define-key org-mode-map [menu-bar headings] 'undefined)
  4735. (define-key org-mode-map [menu-bar hide] 'undefined)
  4736. (define-key org-mode-map [menu-bar show] 'undefined)
  4737. (org-load-modules-maybe)
  4738. (org-install-agenda-files-menu)
  4739. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4740. (add-to-invisibility-spec '(org-hide-block . t))
  4741. (add-to-invisibility-spec '(org-hide-drawer . t))
  4742. (setq-local outline-regexp org-outline-regexp)
  4743. (setq-local outline-level 'org-outline-level)
  4744. (setq bidi-paragraph-direction 'left-to-right)
  4745. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4746. (unless org-display-table
  4747. (setq org-display-table (make-display-table)))
  4748. (set-display-table-slot
  4749. org-display-table 4
  4750. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4751. org-ellipsis)))
  4752. (setq buffer-display-table org-display-table))
  4753. (org-set-regexps-and-options)
  4754. (org-set-font-lock-defaults)
  4755. (when (and org-tag-faces (not org-tags-special-faces-re))
  4756. ;; tag faces set outside customize.... force initialization.
  4757. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4758. ;; Calc embedded
  4759. (setq-local calc-embedded-open-mode "# ")
  4760. ;; Modify a few syntax entries
  4761. (modify-syntax-entry ?\" "\"")
  4762. (modify-syntax-entry ?\\ "_")
  4763. (modify-syntax-entry ?~ "_")
  4764. (modify-syntax-entry ?< "(>")
  4765. (modify-syntax-entry ?> ")<")
  4766. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4767. ;; Activate before-change-function
  4768. (setq-local org-table-may-need-update t)
  4769. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4770. ;; Check for running clock before killing a buffer
  4771. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4772. ;; Initialize macros templates.
  4773. (org-macro-initialize-templates)
  4774. ;; Initialize radio targets.
  4775. (org-update-radio-target-regexp)
  4776. ;; Indentation.
  4777. (setq-local indent-line-function 'org-indent-line)
  4778. (setq-local indent-region-function 'org-indent-region)
  4779. ;; Filling and auto-filling.
  4780. (org-setup-filling)
  4781. ;; Comments.
  4782. (org-setup-comments-handling)
  4783. ;; Initialize cache.
  4784. (org-element-cache-reset)
  4785. ;; Beginning/end of defun
  4786. (setq-local beginning-of-defun-function 'org-backward-element)
  4787. (setq-local end-of-defun-function
  4788. (lambda ()
  4789. (if (not (org-at-heading-p))
  4790. (org-forward-element)
  4791. (org-forward-element)
  4792. (forward-char -1))))
  4793. ;; Next error for sparse trees
  4794. (setq-local next-error-function 'org-occur-next-match)
  4795. ;; Make sure dependence stuff works reliably, even for users who set it
  4796. ;; too late :-(
  4797. (if org-enforce-todo-dependencies
  4798. (add-hook 'org-blocker-hook
  4799. 'org-block-todo-from-children-or-siblings-or-parent)
  4800. (remove-hook 'org-blocker-hook
  4801. 'org-block-todo-from-children-or-siblings-or-parent))
  4802. (if org-enforce-todo-checkbox-dependencies
  4803. (add-hook 'org-blocker-hook
  4804. 'org-block-todo-from-checkboxes)
  4805. (remove-hook 'org-blocker-hook
  4806. 'org-block-todo-from-checkboxes))
  4807. ;; Align options lines
  4808. (setq-local
  4809. align-mode-rules-list
  4810. '((org-in-buffer-settings
  4811. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4812. (modes . '(org-mode)))))
  4813. ;; Imenu
  4814. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4815. ;; Make isearch reveal context
  4816. (setq-local outline-isearch-open-invisible-function
  4817. (lambda (&rest _) (org-show-context 'isearch)))
  4818. ;; Setup the pcomplete hooks
  4819. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4820. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4821. (setq-local pcomplete-default-completion-function 'ignore)
  4822. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4823. (setq-local pcomplete-termination-string "")
  4824. (setq-local buffer-face-mode-face 'org-default)
  4825. ;; If empty file that did not turn on Org mode automatically, make
  4826. ;; it to.
  4827. (when (and org-insert-mode-line-in-empty-file
  4828. (called-interactively-p 'any)
  4829. (= (point-min) (point-max)))
  4830. (insert "# -*- mode: org -*-\n\n"))
  4831. (unless org-inhibit-startup
  4832. (org-unmodified
  4833. (when org-startup-with-beamer-mode (org-beamer-mode))
  4834. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4835. (org-table-map-tables
  4836. (cond ((and org-startup-align-all-tables
  4837. org-startup-shrink-all-tables)
  4838. (lambda () (org-table-align) (org-table-shrink)))
  4839. (org-startup-align-all-tables #'org-table-align)
  4840. (t #'org-table-shrink))
  4841. t))
  4842. (when org-startup-with-inline-images (org-display-inline-images))
  4843. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4844. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4845. (when org-startup-truncated (setq truncate-lines t))
  4846. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4847. (org-refresh-effort-properties)))
  4848. ;; Try to set `org-hide' face correctly.
  4849. (let ((foreground (org-find-invisible-foreground)))
  4850. (when foreground
  4851. (set-face-foreground 'org-hide foreground))))
  4852. ;; Update `customize-package-emacs-version-alist'
  4853. (add-to-list 'customize-package-emacs-version-alist
  4854. '(Org ("8.0" . "24.4")
  4855. ("8.1" . "24.4")
  4856. ("8.2" . "24.4")
  4857. ("8.2.7" . "24.4")
  4858. ("8.3" . "26.1")
  4859. ("9.0" . "26.1")
  4860. ("9.1" . "26.1")
  4861. ("9.2" . "27.1")))
  4862. (defvar org-mode-transpose-word-syntax-table
  4863. (let ((st (make-syntax-table text-mode-syntax-table)))
  4864. (dolist (c org-emphasis-alist st)
  4865. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4866. (when (fboundp 'abbrev-table-put)
  4867. (abbrev-table-put org-mode-abbrev-table
  4868. :parents (list text-mode-abbrev-table)))
  4869. (defun org-find-invisible-foreground ()
  4870. (let ((candidates (remove
  4871. "unspecified-bg"
  4872. (nconc
  4873. (list (face-background 'default)
  4874. (face-background 'org-default))
  4875. (mapcar
  4876. (lambda (alist)
  4877. (when (boundp alist)
  4878. (cdr (assq 'background-color (symbol-value alist)))))
  4879. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4880. (list (face-foreground 'org-hide))))))
  4881. (car (remove nil candidates))))
  4882. (defun org-current-time (&optional rounding-minutes past)
  4883. "Current time, possibly rounded to ROUNDING-MINUTES.
  4884. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4885. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4886. the rounding returns a past time."
  4887. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4888. (car org-time-stamp-rounding-minutes)))
  4889. (time (decode-time)) res)
  4890. (if (< r 1)
  4891. (current-time)
  4892. (setq res
  4893. (apply 'encode-time
  4894. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4895. (nthcdr 2 time))))
  4896. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4897. (seconds-to-time (- (float-time res) (* r 60)))
  4898. res))))
  4899. (defun org-today ()
  4900. "Return today date, considering `org-extend-today-until'."
  4901. (time-to-days
  4902. (time-subtract (current-time)
  4903. (list 0 (* 3600 org-extend-today-until) 0))))
  4904. ;;;; Font-Lock stuff, including the activators
  4905. (defvar org-mouse-map (make-sparse-keymap))
  4906. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4907. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4908. (when org-mouse-1-follows-link
  4909. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4910. (when org-tab-follows-link
  4911. (org-defkey org-mouse-map (kbd "<tab>") #'org-open-at-point)
  4912. (org-defkey org-mouse-map (kbd "TAB") #'org-open-at-point))
  4913. (require 'font-lock)
  4914. (defconst org-non-link-chars "]\t\n\r<>")
  4915. (defvar org-link-types-re nil
  4916. "Matches a link that has a url-like prefix like \"http:\"")
  4917. (defvar org-link-re-with-space nil
  4918. "Matches a link with spaces, optional angular brackets around it.")
  4919. (defvar org-link-re-with-space2 nil
  4920. "Matches a link with spaces, optional angular brackets around it.")
  4921. (defvar org-link-re-with-space3 nil
  4922. "Matches a link with spaces, only for internal part in bracket links.")
  4923. (defvar org-angle-link-re nil
  4924. "Matches link with angular brackets, spaces are allowed.")
  4925. (defvar org-plain-link-re nil
  4926. "Matches plain link, without spaces.")
  4927. (defvar org-bracket-link-regexp nil
  4928. "Matches a link in double brackets.")
  4929. (defvar org-bracket-link-analytic-regexp nil
  4930. "Regular expression used to analyze links.
  4931. Here is what the match groups contain after a match:
  4932. 1: http:
  4933. 2: http
  4934. 3: path
  4935. 4: [desc]
  4936. 5: desc")
  4937. (defvar org-bracket-link-analytic-regexp++ nil
  4938. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4939. (defvar org-any-link-re nil
  4940. "Regular expression matching any link.")
  4941. (defconst org-match-sexp-depth 3
  4942. "Number of stacked braces for sub/superscript matching.")
  4943. (defun org-create-multibrace-regexp (left right n)
  4944. "Create a regular expression which will match a balanced sexp.
  4945. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4946. as single character strings.
  4947. The regexp returned will match the entire expression including the
  4948. delimiters. It will also define a single group which contains the
  4949. match except for the outermost delimiters. The maximum depth of
  4950. stacked delimiters is N. Escaping delimiters is not possible."
  4951. (let* ((nothing (concat "[^" left right "]*?"))
  4952. (or "\\|")
  4953. (re nothing)
  4954. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4955. (while (> n 1)
  4956. (setq n (1- n)
  4957. re (concat re or next)
  4958. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4959. (concat left "\\(" re "\\)" right)))
  4960. (defconst org-match-substring-regexp
  4961. (concat
  4962. "\\(\\S-\\)\\([_^]\\)\\("
  4963. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4964. "\\|"
  4965. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4966. "\\|"
  4967. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4968. "The regular expression matching a sub- or superscript.")
  4969. (defconst org-match-substring-with-braces-regexp
  4970. (concat
  4971. "\\(\\S-\\)\\([_^]\\)"
  4972. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4973. "The regular expression matching a sub- or superscript, forcing braces.")
  4974. (defun org-make-link-regexps ()
  4975. "Update the link regular expressions.
  4976. This should be called after the variable `org-link-parameters' has changed."
  4977. (let ((types-re (regexp-opt (org-link-types) t)))
  4978. (setq org-link-types-re
  4979. (concat "\\`" types-re ":")
  4980. org-link-re-with-space
  4981. (concat "<?" types-re ":"
  4982. "\\([^" org-non-link-chars " ]"
  4983. "[^" org-non-link-chars "]*"
  4984. "[^" org-non-link-chars " ]\\)>?")
  4985. org-link-re-with-space2
  4986. (concat "<?" types-re ":"
  4987. "\\([^" org-non-link-chars " ]"
  4988. "[^\t\n\r]*"
  4989. "[^" org-non-link-chars " ]\\)>?")
  4990. org-link-re-with-space3
  4991. (concat "<?" types-re ":"
  4992. "\\([^" org-non-link-chars " ]"
  4993. "[^\t\n\r]*\\)")
  4994. org-angle-link-re
  4995. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  4996. types-re)
  4997. org-plain-link-re
  4998. (concat
  4999. "\\<" types-re ":"
  5000. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  5001. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  5002. org-bracket-link-regexp
  5003. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  5004. org-bracket-link-analytic-regexp
  5005. (concat
  5006. "\\[\\["
  5007. "\\(" types-re ":\\)?"
  5008. "\\([^]]+\\)"
  5009. "\\]"
  5010. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5011. "\\]")
  5012. org-bracket-link-analytic-regexp++
  5013. (concat
  5014. "\\[\\["
  5015. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  5016. "\\([^]]+\\)"
  5017. "\\]"
  5018. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5019. "\\]")
  5020. org-any-link-re
  5021. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  5022. org-angle-link-re "\\)\\|\\("
  5023. org-plain-link-re "\\)"))))
  5024. (org-make-link-regexps)
  5025. (defvar org-emph-face nil)
  5026. (defun org-do-emphasis-faces (limit)
  5027. "Run through the buffer and emphasize strings."
  5028. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  5029. (car org-emphasis-regexp-components))))
  5030. (catch :exit
  5031. (while (re-search-forward quick-re limit t)
  5032. (let* ((marker (match-string 2))
  5033. (verbatim? (member marker '("~" "="))))
  5034. (when (save-excursion
  5035. (goto-char (match-beginning 0))
  5036. (and
  5037. ;; Do not match table hlines.
  5038. (not (and (equal marker "+")
  5039. (org-match-line
  5040. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  5041. ;; Do not match headline stars. Do not consider
  5042. ;; stars of a headline as closing marker for bold
  5043. ;; markup either.
  5044. (not (and (equal marker "*")
  5045. (save-excursion
  5046. (forward-char)
  5047. (skip-chars-backward "*")
  5048. (looking-at-p org-outline-regexp-bol))))
  5049. ;; Match full emphasis markup regexp.
  5050. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  5051. ;; Do not span over paragraph boundaries.
  5052. (not (string-match-p org-element-paragraph-separate
  5053. (match-string 2)))
  5054. ;; Do not span over cells in table rows.
  5055. (not (and (save-match-data (org-match-line "[ \t]*|"))
  5056. (string-match-p "|" (match-string 4))))))
  5057. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  5058. (font-lock-prepend-text-property
  5059. (match-beginning 2) (match-end 2) 'face face)
  5060. (when verbatim?
  5061. (org-remove-flyspell-overlays-in
  5062. (match-beginning 0) (match-end 0)))
  5063. (add-text-properties (match-beginning 2) (match-end 2)
  5064. '(font-lock-multiline t org-emphasis t))
  5065. (when org-hide-emphasis-markers
  5066. (add-text-properties (match-end 4) (match-beginning 5)
  5067. '(invisible org-link))
  5068. (add-text-properties (match-beginning 3) (match-end 3)
  5069. '(invisible org-link)))
  5070. (throw :exit t))))))))
  5071. (defun org-emphasize (&optional char)
  5072. "Insert or change an emphasis, i.e. a font like bold or italic.
  5073. If there is an active region, change that region to a new emphasis.
  5074. If there is no region, just insert the marker characters and position
  5075. the cursor between them.
  5076. CHAR should be the marker character. If it is a space, it means to
  5077. remove the emphasis of the selected region.
  5078. If CHAR is not given (for example in an interactive call) it will be
  5079. prompted for."
  5080. (interactive)
  5081. (let ((erc org-emphasis-regexp-components)
  5082. (string "") beg end move s)
  5083. (if (org-region-active-p)
  5084. (setq beg (region-beginning)
  5085. end (region-end)
  5086. string (buffer-substring beg end))
  5087. (setq move t))
  5088. (unless char
  5089. (message "Emphasis marker or tag: [%s]"
  5090. (mapconcat #'car org-emphasis-alist ""))
  5091. (setq char (read-char-exclusive)))
  5092. (if (equal char ?\s)
  5093. (setq s ""
  5094. move nil)
  5095. (unless (assoc (char-to-string char) org-emphasis-alist)
  5096. (user-error "No such emphasis marker: \"%c\"" char))
  5097. (setq s (char-to-string char)))
  5098. (while (and (> (length string) 1)
  5099. (equal (substring string 0 1) (substring string -1))
  5100. (assoc (substring string 0 1) org-emphasis-alist))
  5101. (setq string (substring string 1 -1)))
  5102. (setq string (concat s string s))
  5103. (when beg (delete-region beg end))
  5104. (unless (or (bolp)
  5105. (string-match (concat "[" (nth 0 erc) "\n]")
  5106. (char-to-string (char-before (point)))))
  5107. (insert " "))
  5108. (unless (or (eobp)
  5109. (string-match (concat "[" (nth 1 erc) "\n]")
  5110. (char-to-string (char-after (point)))))
  5111. (insert " ") (backward-char 1))
  5112. (insert string)
  5113. (and move (backward-char 1))))
  5114. (defconst org-nonsticky-props
  5115. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5116. (defsubst org-rear-nonsticky-at (pos)
  5117. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5118. (defun org-activate-links (limit)
  5119. "Add link properties to links.
  5120. This includes angle, plain, and bracket links."
  5121. (catch :exit
  5122. (while (re-search-forward org-any-link-re limit t)
  5123. (let* ((start (match-beginning 0))
  5124. (end (match-end 0))
  5125. (style (cond ((eq ?< (char-after start)) 'angle)
  5126. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5127. (t 'plain))))
  5128. (when (and (memq style org-highlight-links)
  5129. ;; Do not confuse plain links with tags.
  5130. (not (and (eq style 'plain)
  5131. (let ((face (get-text-property
  5132. (max (1- start) (point-min)) 'face)))
  5133. (if (consp face) (memq 'org-tag face)
  5134. (eq 'org-tag face))))))
  5135. (let* ((link-object (save-excursion
  5136. (goto-char start)
  5137. (save-match-data (org-element-link-parser))))
  5138. (link (org-element-property :raw-link link-object))
  5139. (type (org-element-property :type link-object))
  5140. (path (org-element-property :path link-object))
  5141. (properties ;for link's visible part
  5142. (list
  5143. 'face (pcase (org-link-get-parameter type :face)
  5144. ((and (pred functionp) face) (funcall face path))
  5145. ((and (pred facep) face) face)
  5146. ((and (pred consp) face) face) ;anonymous
  5147. (_ 'org-link))
  5148. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5149. 'highlight)
  5150. 'keymap (or (org-link-get-parameter type :keymap)
  5151. org-mouse-map)
  5152. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5153. ((and (pred stringp) echo) echo)
  5154. ((and (pred functionp) echo) echo)
  5155. (_ (concat "LINK: " link)))
  5156. 'htmlize-link (pcase (org-link-get-parameter type
  5157. :htmlize-link)
  5158. ((and (pred functionp) f) (funcall f))
  5159. (_ `(:uri ,link)))
  5160. 'font-lock-multiline t)))
  5161. (org-remove-flyspell-overlays-in start end)
  5162. (org-rear-nonsticky-at end)
  5163. (if (not (eq 'bracket style))
  5164. (add-text-properties start end properties)
  5165. ;; Handle invisible parts in bracket links.
  5166. (remove-text-properties start end '(invisible nil))
  5167. (let ((hidden
  5168. (append `(invisible
  5169. ,(or (org-link-get-parameter type :display)
  5170. 'org-link))
  5171. properties))
  5172. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5173. (visible-end (or (match-end 4) (match-end 2))))
  5174. (add-text-properties start visible-start hidden)
  5175. (add-text-properties visible-start visible-end properties)
  5176. (add-text-properties visible-end end hidden)
  5177. (org-rear-nonsticky-at visible-start)
  5178. (org-rear-nonsticky-at visible-end)))
  5179. (let ((f (org-link-get-parameter type :activate-func)))
  5180. (when (functionp f)
  5181. (funcall f start end path (eq style 'bracket))))
  5182. (throw :exit t))))) ;signal success
  5183. nil))
  5184. (defun org-activate-code (limit)
  5185. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5186. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5187. (remove-text-properties (match-beginning 0) (match-end 0)
  5188. '(display t invisible t intangible t))
  5189. t))
  5190. (defcustom org-src-fontify-natively t
  5191. "When non-nil, fontify code in code blocks.
  5192. See also the `org-block' face."
  5193. :type 'boolean
  5194. :version "26.1"
  5195. :package-version '(Org . "8.3")
  5196. :group 'org-appearance
  5197. :group 'org-babel)
  5198. (defcustom org-allow-promoting-top-level-subtree nil
  5199. "When non-nil, allow promoting a top level subtree.
  5200. The leading star of the top level headline will be replaced
  5201. by a #."
  5202. :type 'boolean
  5203. :version "24.1"
  5204. :group 'org-appearance)
  5205. (defun org-fontify-meta-lines-and-blocks (limit)
  5206. (condition-case nil
  5207. (org-fontify-meta-lines-and-blocks-1 limit)
  5208. (error (message "Org mode fontification error in %S at %d"
  5209. (current-buffer)
  5210. (line-number-at-pos)))))
  5211. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5212. "Fontify #+ lines and blocks."
  5213. (let ((case-fold-search t))
  5214. (when (re-search-forward
  5215. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5216. limit t)
  5217. (let ((beg (match-beginning 0))
  5218. (block-start (match-end 0))
  5219. (block-end nil)
  5220. (lang (match-string 7))
  5221. (beg1 (line-beginning-position 2))
  5222. (dc1 (downcase (match-string 2)))
  5223. (dc3 (downcase (match-string 3)))
  5224. end end1 quoting block-type)
  5225. (cond
  5226. ((and (match-end 4) (equal dc3 "+begin"))
  5227. ;; Truly a block
  5228. (setq block-type (downcase (match-string 5))
  5229. quoting (member block-type org-protecting-blocks))
  5230. (when (re-search-forward
  5231. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5232. nil t) ;; on purpose, we look further than LIMIT
  5233. (setq end (min (point-max) (match-end 0))
  5234. end1 (min (point-max) (1- (match-beginning 0))))
  5235. (setq block-end (match-beginning 0))
  5236. (when quoting
  5237. (org-remove-flyspell-overlays-in beg1 end1)
  5238. (remove-text-properties beg end
  5239. '(display t invisible t intangible t)))
  5240. (add-text-properties
  5241. beg end '(font-lock-fontified t font-lock-multiline t))
  5242. (add-text-properties beg beg1 '(face org-meta-line))
  5243. (org-remove-flyspell-overlays-in beg beg1)
  5244. (add-text-properties ; For end_src
  5245. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5246. (org-remove-flyspell-overlays-in end1 end)
  5247. (cond
  5248. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5249. (org-src-font-lock-fontify-block lang block-start block-end)
  5250. (add-text-properties beg1 block-end '(src-block t)))
  5251. (quoting
  5252. (add-text-properties beg1 (min (point-max) (1+ end1))
  5253. (list 'face
  5254. (list :inherit
  5255. (let ((face-name
  5256. (intern (format "org-block-%s" lang))))
  5257. (append (and (facep face-name) (list face-name))
  5258. '(org-block))))))) ; end of source block
  5259. ((not org-fontify-quote-and-verse-blocks))
  5260. ((string= block-type "quote")
  5261. (add-face-text-property
  5262. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5263. ((string= block-type "verse")
  5264. (add-face-text-property
  5265. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5266. (add-text-properties beg beg1 '(face org-block-begin-line))
  5267. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5268. '(face org-block-end-line))
  5269. t))
  5270. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5271. (org-remove-flyspell-overlays-in
  5272. (match-beginning 0)
  5273. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5274. (add-text-properties
  5275. beg (match-end 3)
  5276. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5277. '(font-lock-fontified t invisible t)
  5278. '(font-lock-fontified t face org-document-info-keyword)))
  5279. (add-text-properties
  5280. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5281. (if (string-equal dc1 "+title:")
  5282. '(font-lock-fontified t face org-document-title)
  5283. '(font-lock-fontified t face org-document-info))))
  5284. ((string-prefix-p "+caption" dc1)
  5285. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5286. (remove-text-properties (match-beginning 0) (match-end 0)
  5287. '(display t invisible t intangible t))
  5288. ;; Handle short captions.
  5289. (save-excursion
  5290. (beginning-of-line)
  5291. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5292. (add-text-properties (line-beginning-position) (match-end 1)
  5293. '(font-lock-fontified t face org-meta-line))
  5294. (add-text-properties (match-end 0) (line-end-position)
  5295. '(font-lock-fontified t face org-block))
  5296. t)
  5297. ((member dc3 '(" " ""))
  5298. (org-remove-flyspell-overlays-in beg (match-end 0))
  5299. (add-text-properties
  5300. beg (match-end 0)
  5301. '(font-lock-fontified t face font-lock-comment-face)))
  5302. (t ;; just any other in-buffer setting, but not indented
  5303. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5304. (remove-text-properties (match-beginning 0) (match-end 0)
  5305. '(display t invisible t intangible t))
  5306. (add-text-properties beg (match-end 0)
  5307. '(font-lock-fontified t face org-meta-line))
  5308. t))))))
  5309. (defun org-fontify-drawers (limit)
  5310. "Fontify drawers."
  5311. (when (re-search-forward org-drawer-regexp limit t)
  5312. (add-text-properties
  5313. (match-beginning 0) (match-end 0)
  5314. '(font-lock-fontified t face org-special-keyword))
  5315. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5316. t))
  5317. (defun org-fontify-macros (limit)
  5318. "Fontify macros."
  5319. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  5320. (let ((begin (match-beginning 0))
  5321. (opening-end (match-beginning 1)))
  5322. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  5323. (match-string 1))
  5324. (let ((end (match-end 1))
  5325. (closing-start (match-beginning 1)))
  5326. (add-text-properties
  5327. begin end
  5328. '(font-lock-multiline t font-lock-fontified t face org-macro))
  5329. (org-remove-flyspell-overlays-in begin end)
  5330. (when org-hide-macro-markers
  5331. (add-text-properties begin opening-end '(invisible t))
  5332. (add-text-properties closing-start end '(invisible t)))
  5333. t)))))
  5334. (defun org-activate-footnote-links (limit)
  5335. "Add text properties for footnotes."
  5336. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5337. (when fn
  5338. (let* ((beg (nth 1 fn))
  5339. (end (nth 2 fn))
  5340. (label (car fn))
  5341. (referencep (/= (line-beginning-position) beg)))
  5342. (when (and referencep (nth 3 fn))
  5343. (save-excursion
  5344. (goto-char beg)
  5345. (search-forward (or label "fn:"))
  5346. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5347. (add-text-properties beg end
  5348. (list 'mouse-face 'highlight
  5349. 'keymap org-mouse-map
  5350. 'help-echo
  5351. (if referencep "Footnote reference"
  5352. "Footnote definition")
  5353. 'font-lock-fontified t
  5354. 'font-lock-multiline t
  5355. 'face 'org-footnote))))))
  5356. (defun org-activate-dates (limit)
  5357. "Add text properties for dates."
  5358. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5359. (not (equal (char-before (match-beginning 0)) 91)))
  5360. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5361. (add-text-properties (match-beginning 0) (match-end 0)
  5362. (list 'mouse-face 'highlight
  5363. 'keymap org-mouse-map))
  5364. (org-rear-nonsticky-at (match-end 0))
  5365. (when org-display-custom-times
  5366. ;; If it's a date range, activate custom time for second date.
  5367. (when (match-end 3)
  5368. (org-display-custom-time (match-beginning 3) (match-end 3)))
  5369. (org-display-custom-time (match-beginning 1) (match-end 1)))
  5370. t))
  5371. (defvar-local org-target-link-regexp nil
  5372. "Regular expression matching radio targets in plain text.")
  5373. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5374. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5375. border border border))
  5376. "Regular expression matching a link target.")
  5377. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5378. "Regular expression matching a radio target.")
  5379. (defconst org-any-target-regexp
  5380. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5381. "Regular expression matching any target.")
  5382. (defun org-activate-target-links (limit)
  5383. "Add text properties for target matches."
  5384. (when org-target-link-regexp
  5385. (let ((case-fold-search t))
  5386. (when (re-search-forward org-target-link-regexp limit t)
  5387. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5388. (add-text-properties (match-beginning 1) (match-end 1)
  5389. (list 'mouse-face 'highlight
  5390. 'keymap org-mouse-map
  5391. 'help-echo "Radio target link"
  5392. 'org-linked-text t))
  5393. (org-rear-nonsticky-at (match-end 1))
  5394. t))))
  5395. (defun org-update-radio-target-regexp ()
  5396. "Find all radio targets in this file and update the regular expression.
  5397. Also refresh fontification if needed."
  5398. (interactive)
  5399. (let ((old-regexp org-target-link-regexp)
  5400. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5401. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5402. (targets
  5403. (org-with-wide-buffer
  5404. (goto-char (point-min))
  5405. (let (rtn)
  5406. (while (re-search-forward org-radio-target-regexp nil t)
  5407. ;; Make sure point is really within the object.
  5408. (backward-char)
  5409. (let ((obj (org-element-context)))
  5410. (when (eq (org-element-type obj) 'radio-target)
  5411. (cl-pushnew (org-element-property :value obj) rtn
  5412. :test #'equal))))
  5413. rtn))))
  5414. (setq org-target-link-regexp
  5415. (and targets
  5416. (concat before-re
  5417. (mapconcat
  5418. (lambda (x)
  5419. (replace-regexp-in-string
  5420. " +" "\\s-+" (regexp-quote x) t t))
  5421. targets
  5422. "\\|")
  5423. after-re)))
  5424. (unless (equal old-regexp org-target-link-regexp)
  5425. ;; Clean-up cache.
  5426. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5427. ((not org-target-link-regexp) old-regexp)
  5428. (t
  5429. (concat before-re
  5430. (mapconcat
  5431. (lambda (re)
  5432. (substring re (length before-re)
  5433. (- (length after-re))))
  5434. (list old-regexp org-target-link-regexp)
  5435. "\\|")
  5436. after-re)))))
  5437. (org-with-wide-buffer
  5438. (goto-char (point-min))
  5439. (while (re-search-forward regexp nil t)
  5440. (org-element-cache-refresh (match-beginning 1)))))
  5441. ;; Re fontify buffer.
  5442. (when (memq 'radio org-highlight-links)
  5443. (org-restart-font-lock)))))
  5444. (defvar org-latex-and-related-regexp nil
  5445. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5446. (defun org-compute-latex-and-related-regexp ()
  5447. "Compute regular expression for LaTeX, entities and sub/superscript.
  5448. Result depends on variable `org-highlight-latex-and-related'."
  5449. (setq-local
  5450. org-latex-and-related-regexp
  5451. (let* ((re-sub
  5452. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5453. ((eq org-use-sub-superscripts '{})
  5454. (list org-match-substring-with-braces-regexp))
  5455. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5456. (re-latex
  5457. (when (memq 'latex org-highlight-latex-and-related)
  5458. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5459. (delq nil
  5460. (mapcar (lambda (x)
  5461. (and (member (car x) matchers) (nth 1 x)))
  5462. org-latex-regexps)))))
  5463. (re-entities
  5464. (when (memq 'entities org-highlight-latex-and-related)
  5465. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5466. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5467. (defun org-do-latex-and-related (limit)
  5468. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5469. LIMIT bounds the search for syntax to highlight. Stop at first
  5470. highlighted object, if any. Return t if some highlighting was
  5471. done, nil otherwise."
  5472. (when (org-string-nw-p org-latex-and-related-regexp)
  5473. (catch 'found
  5474. (while (re-search-forward org-latex-and-related-regexp limit t)
  5475. (unless
  5476. (cl-some
  5477. (lambda (f)
  5478. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5479. (save-excursion
  5480. (goto-char (1+ (match-beginning 0)))
  5481. (face-at-point nil t)))
  5482. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5483. '(?_ ?^))
  5484. 1
  5485. 0)))
  5486. (font-lock-prepend-text-property
  5487. (+ offset (match-beginning 0)) (match-end 0)
  5488. 'face 'org-latex-and-related)
  5489. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5490. '(font-lock-multiline t)))
  5491. (throw 'found t)))
  5492. nil)))
  5493. (defun org-restart-font-lock ()
  5494. "Restart `font-lock-mode', to force refontification."
  5495. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5496. (font-lock-mode -1)
  5497. (font-lock-mode 1)))
  5498. (defun org-activate-tags (limit)
  5499. (when (re-search-forward org-tag-line-re limit t)
  5500. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5501. (add-text-properties (match-beginning 1) (match-end 1)
  5502. (list 'mouse-face 'highlight
  5503. 'keymap org-mouse-map))
  5504. (org-rear-nonsticky-at (match-end 1))
  5505. t))
  5506. (defun org-outline-level ()
  5507. "Compute the outline level of the heading at point.
  5508. If this is called at a normal headline, the level is the number
  5509. of stars. Use `org-reduced-level' to remove the effect of
  5510. `org-odd-levels'. Unlike to `org-current-level', this function
  5511. takes into consideration inlinetasks."
  5512. (org-with-wide-buffer
  5513. (end-of-line)
  5514. (if (re-search-backward org-outline-regexp-bol nil t)
  5515. (1- (- (match-end 0) (match-beginning 0)))
  5516. 0)))
  5517. (defvar org-font-lock-keywords nil)
  5518. (defsubst org-re-property (property &optional literal allow-null value)
  5519. "Return a regexp matching a PROPERTY line.
  5520. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5521. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5522. non-nil, match properties even without a value.
  5523. Match group 3 is set to the value when it exists. If there is no
  5524. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5525. With optional argument VALUE, match only property lines with
  5526. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5527. unless LITERAL is non-nil."
  5528. (concat
  5529. "^\\(?4:[ \t]*\\)"
  5530. (format "\\(?1::\\(?2:%s\\):\\)"
  5531. (if literal property (regexp-quote property)))
  5532. (cond (value
  5533. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5534. (if literal value (regexp-quote value))))
  5535. (allow-null
  5536. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5537. (t
  5538. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5539. (defconst org-property-re
  5540. (org-re-property "\\S-+" 'literal t)
  5541. "Regular expression matching a property line.
  5542. There are four matching groups:
  5543. 1: :PROPKEY: including the leading and trailing colon,
  5544. 2: PROPKEY without the leading and trailing colon,
  5545. 3: PROPVAL without leading or trailing spaces,
  5546. 4: the indentation of the current line,
  5547. 5: trailing whitespace.")
  5548. (defvar org-font-lock-hook nil
  5549. "Functions to be called for special font lock stuff.")
  5550. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5551. (defvar org-font-lock-set-keywords-hook nil
  5552. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5553. This is called after `org-font-lock-extra-keywords' is defined, but before
  5554. it is installed to be used by font lock. This can be useful if something
  5555. needs to be inserted at a specific position in the font-lock sequence.")
  5556. (defun org-font-lock-hook (limit)
  5557. "Run `org-font-lock-hook' within LIMIT."
  5558. (run-hook-with-args 'org-font-lock-hook limit))
  5559. (defun org-set-font-lock-defaults ()
  5560. "Set font lock defaults for the current buffer."
  5561. (let* ((em org-fontify-emphasized-text)
  5562. (lk org-highlight-links)
  5563. (org-font-lock-extra-keywords
  5564. (list
  5565. ;; Call the hook
  5566. '(org-font-lock-hook)
  5567. ;; Headlines
  5568. `(,(if org-fontify-whole-heading-line
  5569. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5570. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5571. (1 (org-get-level-face 1))
  5572. (2 (org-get-level-face 2))
  5573. (3 (org-get-level-face 3)))
  5574. ;; Table lines
  5575. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5576. (1 'org-table t))
  5577. ;; Table internals
  5578. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5579. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5580. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5581. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5582. ;; Drawers
  5583. '(org-fontify-drawers)
  5584. ;; Properties
  5585. (list org-property-re
  5586. '(1 'org-special-keyword t)
  5587. '(3 'org-property-value t))
  5588. ;; Link related fontification.
  5589. '(org-activate-links)
  5590. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5591. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5592. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5593. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5594. ;; Targets.
  5595. (list org-any-target-regexp '(0 'org-target t))
  5596. ;; Diary sexps.
  5597. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5598. ;; Macro
  5599. '(org-fontify-macros)
  5600. ;; TODO keyword
  5601. (list (format org-heading-keyword-regexp-format
  5602. org-todo-regexp)
  5603. '(2 (org-get-todo-face 2) t))
  5604. ;; DONE
  5605. (if org-fontify-done-headline
  5606. (list (format org-heading-keyword-regexp-format
  5607. (concat
  5608. "\\(?:"
  5609. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5610. "\\)"))
  5611. '(2 'org-headline-done t))
  5612. nil)
  5613. ;; Priorities
  5614. '(org-font-lock-add-priority-faces)
  5615. ;; Tags
  5616. '(org-font-lock-add-tag-faces)
  5617. ;; Tags groups
  5618. (when (and org-group-tags org-tag-groups-alist)
  5619. (list (concat org-outline-regexp-bol ".+\\(:"
  5620. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5621. ":\\).*$")
  5622. '(1 'org-tag-group prepend)))
  5623. ;; Special keywords
  5624. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5625. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5626. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5627. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5628. ;; Emphasis
  5629. (when em '(org-do-emphasis-faces))
  5630. ;; Checkboxes
  5631. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5632. 1 'org-checkbox prepend)
  5633. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5634. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5635. (0 (org-get-checkbox-statistics-face) t)))
  5636. ;; Description list items
  5637. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5638. 1 'org-list-dt prepend)
  5639. ;; ARCHIVEd headings
  5640. (list (concat
  5641. org-outline-regexp-bol
  5642. "\\(.*:" org-archive-tag ":.*\\)")
  5643. '(1 'org-archived prepend))
  5644. ;; Specials
  5645. '(org-do-latex-and-related)
  5646. '(org-fontify-entities)
  5647. '(org-raise-scripts)
  5648. ;; Code
  5649. '(org-activate-code (1 'org-code t))
  5650. ;; COMMENT
  5651. (list (format
  5652. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5653. org-todo-regexp
  5654. org-comment-string)
  5655. '(9 'org-special-keyword t))
  5656. ;; Blocks and meta lines
  5657. '(org-fontify-meta-lines-and-blocks))))
  5658. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5659. (run-hooks 'org-font-lock-set-keywords-hook)
  5660. ;; Now set the full font-lock-keywords
  5661. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5662. (setq-local font-lock-defaults
  5663. '(org-font-lock-keywords t nil nil backward-paragraph))
  5664. (kill-local-variable 'font-lock-keywords)
  5665. nil))
  5666. (defun org-toggle-pretty-entities ()
  5667. "Toggle the composition display of entities as UTF8 characters."
  5668. (interactive)
  5669. (setq-local org-pretty-entities (not org-pretty-entities))
  5670. (org-restart-font-lock)
  5671. (if org-pretty-entities
  5672. (message "Entities are now displayed as UTF8 characters")
  5673. (save-restriction
  5674. (widen)
  5675. (decompose-region (point-min) (point-max))
  5676. (message "Entities are now displayed as plain text"))))
  5677. (defvar-local org-custom-properties-overlays nil
  5678. "List of overlays used for custom properties.")
  5679. (defun org-toggle-custom-properties-visibility ()
  5680. "Display or hide properties in `org-custom-properties'."
  5681. (interactive)
  5682. (if org-custom-properties-overlays
  5683. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5684. (setq org-custom-properties-overlays nil))
  5685. (when org-custom-properties
  5686. (org-with-wide-buffer
  5687. (goto-char (point-min))
  5688. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5689. (while (re-search-forward regexp nil t)
  5690. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5691. (when (and end (< (point) end))
  5692. ;; Hide first custom property in current drawer.
  5693. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5694. (overlay-put o 'invisible t)
  5695. (overlay-put o 'org-custom-property t)
  5696. (push o org-custom-properties-overlays))
  5697. ;; Hide additional custom properties in the same drawer.
  5698. (while (re-search-forward regexp end t)
  5699. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5700. (overlay-put o 'invisible t)
  5701. (overlay-put o 'org-custom-property t)
  5702. (push o org-custom-properties-overlays)))))
  5703. ;; Each entry is limited to a single property drawer.
  5704. (outline-next-heading)))))))
  5705. (defun org-fontify-entities (limit)
  5706. "Find an entity to fontify."
  5707. (let (ee)
  5708. (when org-pretty-entities
  5709. (catch 'match
  5710. ;; "\_ "-family is left out on purpose. Only the first one,
  5711. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5712. ;; confusing when adding a second white space character.
  5713. (while (re-search-forward
  5714. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5715. limit t)
  5716. (when (and (not (org-at-comment-p))
  5717. (setq ee (org-entity-get (match-string 1)))
  5718. (= (length (nth 6 ee)) 1))
  5719. (let* ((end (if (equal (match-string 2) "{}")
  5720. (match-end 2)
  5721. (match-end 1))))
  5722. (add-text-properties
  5723. (match-beginning 0) end
  5724. (list 'font-lock-fontified t))
  5725. (compose-region (match-beginning 0) end
  5726. (nth 6 ee) nil)
  5727. (backward-char 1)
  5728. (throw 'match t))))
  5729. nil))))
  5730. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5731. "Fontify string S like in Org mode."
  5732. (with-temp-buffer
  5733. (insert s)
  5734. (let ((org-odd-levels-only odd-levels))
  5735. (org-mode)
  5736. (org-font-lock-ensure)
  5737. (buffer-string))))
  5738. (defvar org-m nil)
  5739. (defvar org-l nil)
  5740. (defvar org-f nil)
  5741. (defun org-get-level-face (n)
  5742. "Get the right face for match N in font-lock matching of headlines."
  5743. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5744. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5745. (if org-cycle-level-faces
  5746. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5747. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5748. (cond
  5749. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5750. ((eq n 2) org-f)
  5751. (t (unless org-level-color-stars-only org-f))))
  5752. (defun org-face-from-face-or-color (context inherit face-or-color)
  5753. "Create a face list that inherits INHERIT, but sets the foreground color.
  5754. When FACE-OR-COLOR is not a string, just return it."
  5755. (if (stringp face-or-color)
  5756. (list :inherit inherit
  5757. (cdr (assoc context org-faces-easy-properties))
  5758. face-or-color)
  5759. face-or-color))
  5760. (defun org-get-todo-face (kwd)
  5761. "Get the right face for a TODO keyword KWD.
  5762. If KWD is a number, get the corresponding match group."
  5763. (when (numberp kwd) (setq kwd (match-string kwd)))
  5764. (or (org-face-from-face-or-color
  5765. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5766. (and (member kwd org-done-keywords) 'org-done)
  5767. 'org-todo))
  5768. (defun org-get-priority-face (priority)
  5769. "Get the right face for PRIORITY.
  5770. PRIORITY is a character."
  5771. (or (org-face-from-face-or-color
  5772. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5773. 'org-priority))
  5774. (defun org-get-tag-face (tag)
  5775. "Get the right face for TAG.
  5776. If TAG is a number, get the corresponding match group."
  5777. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5778. (or (org-face-from-face-or-color
  5779. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5780. 'org-tag)))
  5781. (defun org-font-lock-add-priority-faces (limit)
  5782. "Add the special priority faces."
  5783. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5784. (add-text-properties
  5785. (match-beginning 1) (match-end 1)
  5786. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5787. 'font-lock-fontified t))))
  5788. (defun org-font-lock-add-tag-faces (limit)
  5789. "Add the special tag faces."
  5790. (when (and org-tag-faces org-tags-special-faces-re)
  5791. (while (re-search-forward org-tags-special-faces-re limit t)
  5792. (add-text-properties (match-beginning 1) (match-end 1)
  5793. (list 'face (org-get-tag-face 1)
  5794. 'font-lock-fontified t))
  5795. (backward-char 1))))
  5796. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5797. "Remove fontification and activation overlays from links."
  5798. (font-lock-default-unfontify-region beg end)
  5799. (let* ((buffer-undo-list t)
  5800. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5801. (inhibit-modification-hooks t)
  5802. deactivate-mark buffer-file-name buffer-file-truename)
  5803. (decompose-region beg end)
  5804. (remove-text-properties beg end
  5805. '(mouse-face t keymap t org-linked-text t
  5806. invisible t intangible t
  5807. org-emphasis t))
  5808. (org-remove-font-lock-display-properties beg end)))
  5809. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5810. ((raise 0.3) (height 0.7))
  5811. ((raise -0.5))
  5812. ((raise 0.5)))
  5813. "Display properties for showing superscripts and subscripts.")
  5814. (defun org-remove-font-lock-display-properties (beg end)
  5815. "Remove specific display properties that have been added by font lock.
  5816. The will remove the raise properties that are used to show superscripts
  5817. and subscripts."
  5818. (let (next prop)
  5819. (while (< beg end)
  5820. (setq next (next-single-property-change beg 'display nil end)
  5821. prop (get-text-property beg 'display))
  5822. (when (member prop org-script-display)
  5823. (put-text-property beg next 'display nil))
  5824. (setq beg next))))
  5825. (defun org-raise-scripts (limit)
  5826. "Add raise properties to sub/superscripts."
  5827. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5828. (re-search-forward
  5829. (if (eq org-use-sub-superscripts t)
  5830. org-match-substring-regexp
  5831. org-match-substring-with-braces-regexp)
  5832. limit t))
  5833. (let* ((pos (point)) table-p comment-p
  5834. (mpos (match-beginning 3))
  5835. (emph-p (get-text-property mpos 'org-emphasis))
  5836. (link-p (get-text-property mpos 'mouse-face))
  5837. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5838. (goto-char (point-at-bol))
  5839. (setq table-p (looking-at-p org-table-dataline-regexp)
  5840. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5841. (goto-char pos)
  5842. ;; Handle a_b^c
  5843. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5844. (unless (or comment-p emph-p link-p keyw-p)
  5845. (put-text-property (match-beginning 3) (match-end 0)
  5846. 'display
  5847. (if (equal (char-after (match-beginning 2)) ?^)
  5848. (nth (if table-p 3 1) org-script-display)
  5849. (nth (if table-p 2 0) org-script-display)))
  5850. (add-text-properties (match-beginning 2) (match-end 2)
  5851. (list 'invisible t))
  5852. (when (and (eq (char-after (match-beginning 3)) ?{)
  5853. (eq (char-before (match-end 3)) ?}))
  5854. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5855. (list 'invisible t))
  5856. (add-text-properties (1- (match-end 3)) (match-end 3)
  5857. (list 'invisible t))))
  5858. t)))
  5859. (defun org-remove-empty-overlays-at (pos)
  5860. "Remove outline overlays that do not contain non-white stuff."
  5861. (dolist (o (overlays-at pos))
  5862. (and (eq 'outline (overlay-get o 'invisible))
  5863. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5864. (overlay-end o))))
  5865. (delete-overlay o))))
  5866. (defun org-show-empty-lines-in-parent ()
  5867. "Move to the parent and re-show empty lines before visible headlines."
  5868. (save-excursion
  5869. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5870. (org-cycle-show-empty-lines context))))
  5871. (defun org-files-list ()
  5872. "Return `org-agenda-files' list, plus all open Org files.
  5873. This is useful for operations that need to scan all of a user's
  5874. open and agenda-wise Org files."
  5875. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5876. (dolist (buf (buffer-list))
  5877. (with-current-buffer buf
  5878. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5879. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5880. :test #'equal))))
  5881. files))
  5882. (defsubst org-entry-beginning-position ()
  5883. "Return the beginning position of the current entry."
  5884. (save-excursion (org-back-to-heading t) (point)))
  5885. (defsubst org-entry-end-position ()
  5886. "Return the end position of the current entry."
  5887. (save-excursion (outline-next-heading) (point)))
  5888. (defun org-subtree-end-visible-p ()
  5889. "Is the end of the current subtree visible?"
  5890. (pos-visible-in-window-p
  5891. (save-excursion (org-end-of-subtree t) (point))))
  5892. (defun org-first-headline-recenter ()
  5893. "Move cursor to the first headline and recenter the headline."
  5894. (let ((window (get-buffer-window)))
  5895. (when window
  5896. (goto-char (point-min))
  5897. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5898. (set-window-start window (line-beginning-position))))))
  5899. ;;; Visibility (headlines, blocks, drawers)
  5900. ;;;; Headlines visibility
  5901. (defun org-show-entry ()
  5902. "Show the body directly following this heading.
  5903. Show the heading too, if it is currently invisible."
  5904. (interactive)
  5905. (save-excursion
  5906. (ignore-errors
  5907. (org-back-to-heading t)
  5908. (org-flag-region
  5909. (line-end-position 0)
  5910. (save-excursion
  5911. (if (re-search-forward
  5912. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5913. (match-beginning 1)
  5914. (point-max)))
  5915. nil
  5916. 'outline))))
  5917. (defun org-show-children (&optional level)
  5918. "Show all direct subheadings of this heading.
  5919. Prefix arg LEVEL is how many levels below the current level
  5920. should be shown. Default is enough to cause the following
  5921. heading to appear."
  5922. (interactive "p")
  5923. (save-excursion
  5924. (org-back-to-heading t)
  5925. (let* ((current-level (funcall outline-level))
  5926. (max-level (org-get-valid-level
  5927. current-level
  5928. (if level (prefix-numeric-value level) 1)))
  5929. (end (save-excursion (org-end-of-subtree t t)))
  5930. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5931. (past-first-child nil)
  5932. ;; Make sure to skip inlinetasks.
  5933. (re (format regexp-fmt
  5934. current-level
  5935. (cond
  5936. ((not (featurep 'org-inlinetask)) "")
  5937. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5938. 3))
  5939. (t (1- org-inlinetask-min-level))))))
  5940. ;; Display parent heading.
  5941. (org-flag-heading nil)
  5942. (forward-line)
  5943. ;; Display children. First child may be deeper than expected
  5944. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5945. ;; MAX-LEVEL accordingly.
  5946. (while (re-search-forward re end t)
  5947. (unless past-first-child
  5948. (setq re (format regexp-fmt
  5949. current-level
  5950. (max (funcall outline-level) max-level)))
  5951. (setq past-first-child t))
  5952. (org-flag-heading nil)))))
  5953. (defun org-show-subtree ()
  5954. "Show everything after this heading at deeper levels."
  5955. (interactive)
  5956. (org-flag-region
  5957. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5958. ;;;; Blocks visibility
  5959. (defun org-hide-block-toggle-maybe ()
  5960. "Toggle visibility of block at point.
  5961. Unlike to `org-hide-block-toggle', this function does not throw
  5962. an error. Return a non-nil value when toggling is successful."
  5963. (interactive)
  5964. (ignore-errors (org-hide-block-toggle)))
  5965. (defun org-hide-block-toggle (&optional force)
  5966. "Toggle the visibility of the current block.
  5967. When optional argument FORCE is `off', make block visible. If it
  5968. is non-nil, hide it unconditionally. Throw an error when not at
  5969. a block. Return a non-nil value when toggling is successful."
  5970. (interactive)
  5971. (let ((element (org-element-at-point)))
  5972. (unless (memq (org-element-type element)
  5973. '(center-block comment-block dynamic-block example-block
  5974. export-block quote-block special-block
  5975. src-block verse-block))
  5976. (user-error "Not at a block"))
  5977. (let* ((post (org-element-property :post-affiliated element))
  5978. (start (save-excursion
  5979. (goto-char post)
  5980. (line-end-position)))
  5981. (end (save-excursion
  5982. (goto-char (org-element-property :end element))
  5983. (skip-chars-backward " \t\n")
  5984. (line-end-position))))
  5985. ;; Do nothing when not before or at the block opening line or at
  5986. ;; the block closing line.
  5987. (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
  5988. (cond ((eq force 'off)
  5989. (org-flag-region start end nil 'org-hide-block))
  5990. (force
  5991. (org-flag-region start end t 'org-hide-block))
  5992. ((eq (get-char-property start 'invisible) 'org-hide-block)
  5993. (org-flag-region start end nil 'org-hide-block))
  5994. (t
  5995. (org-flag-region start end t 'org-hide-block)))
  5996. ;; When the block is hidden away, make sure point is left in
  5997. ;; a visible part of the buffer.
  5998. (when (invisible-p (max (1- (point)) (point-min)))
  5999. (goto-char post))
  6000. ;; Signal success.
  6001. t))))
  6002. (defun org-hide-block-toggle-all ()
  6003. "Toggle the visibility of all blocks in the current buffer."
  6004. (org-block-map 'org-hide-block-toggle))
  6005. (defun org-hide-block-all ()
  6006. "Fold all blocks in the current buffer."
  6007. (interactive)
  6008. (org-show-all '(blocks))
  6009. (org-block-map 'org-hide-block-toggle-maybe))
  6010. ;;;; Drawers visibility
  6011. (defun org-cycle-hide-drawers (state &optional exceptions)
  6012. "Re-hide all drawers after a visibility state change.
  6013. STATE should be one of the symbols listed in the docstring of
  6014. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  6015. a list of strings specifying which drawers should not be hidden."
  6016. (when (and (derived-mode-p 'org-mode)
  6017. (not (memq state '(overview folded contents))))
  6018. (save-excursion
  6019. (let* ((globalp (eq state 'all))
  6020. (beg (if globalp (point-min) (point)))
  6021. (end (if globalp (point-max)
  6022. (if (eq state 'children)
  6023. (save-excursion (outline-next-heading) (point))
  6024. (org-end-of-subtree t)))))
  6025. (goto-char beg)
  6026. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6027. (unless (member-ignore-case (match-string 1) exceptions)
  6028. (let ((drawer (org-element-at-point)))
  6029. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6030. (org-flag-drawer t drawer)
  6031. ;; Make sure to skip drawer entirely or we might flag
  6032. ;; it another time when matching its ending line with
  6033. ;; `org-drawer-regexp'.
  6034. (goto-char (org-element-property :end drawer))))))))))
  6035. (defun org-flag-drawer (flag &optional element)
  6036. "When FLAG is non-nil, hide the drawer we are at.
  6037. Otherwise make it visible. When optional argument ELEMENT is
  6038. a parsed drawer, as returned by `org-element-at-point', hide or
  6039. show that drawer instead."
  6040. (let ((drawer (or element
  6041. (and (save-excursion
  6042. (beginning-of-line)
  6043. (looking-at-p org-drawer-regexp))
  6044. (org-element-at-point)))))
  6045. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6046. (let ((post (org-element-property :post-affiliated drawer)))
  6047. (org-flag-region
  6048. (save-excursion (goto-char post) (line-end-position))
  6049. (save-excursion (goto-char (org-element-property :end drawer))
  6050. (skip-chars-backward " \t\n")
  6051. (line-end-position))
  6052. flag 'org-hide-drawer)
  6053. ;; When the drawer is hidden away, make sure point lies in
  6054. ;; a visible part of the buffer.
  6055. (when (invisible-p (max (1- (point)) (point-min)))
  6056. (goto-char post))))))
  6057. ;;;; Visibility cycling
  6058. (defvar-local org-cycle-global-status nil)
  6059. (put 'org-cycle-global-status 'org-state t)
  6060. (defvar-local org-cycle-subtree-status nil)
  6061. (put 'org-cycle-subtree-status 'org-state t)
  6062. (defun org-show-all (&optional types)
  6063. "Show all contents in the visible part of the buffer.
  6064. By default, the function expands headings, blocks and drawers.
  6065. When optional argument TYPE is a list of symbols among `blocks',
  6066. `drawers' and `headings', to only expand one specific type."
  6067. (dolist (type (or types '(blocks drawers headings)))
  6068. (org-flag-region (point-min) (point-max) nil
  6069. (pcase type
  6070. (`blocks 'org-hide-block)
  6071. (`drawers 'org-hide-drawer)
  6072. (`headings 'outline)
  6073. (_ (error "Invalid type: %S" type))))))
  6074. ;;;###autoload
  6075. (defun org-cycle (&optional arg)
  6076. "TAB-action and visibility cycling for Org mode.
  6077. This is the command invoked in Org mode by the `TAB' key. Its main
  6078. purpose is outline visibility cycling, but it also invokes other actions
  6079. in special contexts.
  6080. When this function is called with a `\\[universal-argument]' prefix, rotate \
  6081. the entire
  6082. buffer through 3 states (global cycling)
  6083. 1. OVERVIEW: Show only top-level headlines.
  6084. 2. CONTENTS: Show all headlines of all levels, but no body text.
  6085. 3. SHOW ALL: Show everything.
  6086. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  6087. switch to the startup visibility,
  6088. determined by the variable `org-startup-folded', and by any VISIBILITY
  6089. properties in the buffer.
  6090. With a `\\[universal-argument] \\[universal-argument] \
  6091. \\[universal-argument]' prefix argument, show the entire buffer, including
  6092. any drawers.
  6093. When inside a table, re-align the table and move to the next field.
  6094. When point is at the beginning of a headline, rotate the subtree started
  6095. by this line through 3 different states (local cycling)
  6096. 1. FOLDED: Only the main headline is shown.
  6097. 2. CHILDREN: The main headline and the direct children are shown.
  6098. From this state, you can move to one of the children
  6099. and zoom in further.
  6100. 3. SUBTREE: Show the entire subtree, including body text.
  6101. If there is no subtree, switch directly from CHILDREN to FOLDED.
  6102. When point is at the beginning of an empty headline and the variable
  6103. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  6104. of the headline by demoting and promoting it to likely levels. This
  6105. speeds up creation document structure by pressing `TAB' once or several
  6106. times right after creating a new headline.
  6107. When there is a numeric prefix, go up to a heading with level ARG, do
  6108. a `show-subtree' and return to the previous cursor position. If ARG
  6109. is negative, go up that many levels.
  6110. When point is not at the beginning of a headline, execute the global
  6111. binding for `TAB', which is re-indenting the line. See the option
  6112. `org-cycle-emulate-tab' for details.
  6113. As a special case, if point is at the beginning of the buffer and there is
  6114. no headline in line 1, this function will act as if called with prefix arg
  6115. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  6116. prefix arg, but only
  6117. if the variable `org-cycle-global-at-bob' is t."
  6118. (interactive "P")
  6119. (org-load-modules-maybe)
  6120. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  6121. (and org-cycle-level-after-item/entry-creation
  6122. (or (org-cycle-level)
  6123. (org-cycle-item-indentation))))
  6124. (let* ((limit-level
  6125. (or org-cycle-max-level
  6126. (and (boundp 'org-inlinetask-min-level)
  6127. org-inlinetask-min-level
  6128. (1- org-inlinetask-min-level))))
  6129. (nstars (and limit-level
  6130. (if org-odd-levels-only
  6131. (and limit-level (1- (* limit-level 2)))
  6132. limit-level)))
  6133. (org-outline-regexp
  6134. (if (not (derived-mode-p 'org-mode))
  6135. outline-regexp
  6136. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  6137. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  6138. (not (looking-at org-outline-regexp))))
  6139. (org-cycle-hook
  6140. (if bob-special
  6141. (delq 'org-optimize-window-after-visibility-change
  6142. (copy-sequence org-cycle-hook))
  6143. org-cycle-hook))
  6144. (pos (point)))
  6145. (cond
  6146. ((equal arg '(16))
  6147. (setq last-command 'dummy)
  6148. (org-set-startup-visibility)
  6149. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  6150. ((equal arg '(64))
  6151. (org-show-all)
  6152. (org-unlogged-message "Entire buffer visible, including drawers"))
  6153. ((equal arg '(4)) (org-cycle-internal-global))
  6154. ;; Try hiding block at point.
  6155. ((org-hide-block-toggle-maybe))
  6156. ;; Try cdlatex TAB completion
  6157. ((org-try-cdlatex-tab))
  6158. ;; Table: enter it or move to the next field.
  6159. ((org-at-table-p 'any)
  6160. (if (org-at-table.el-p)
  6161. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6162. Use `\\[org-edit-special]' to edit table.el tables"))
  6163. (if arg (org-table-edit-field t)
  6164. (org-table-justify-field-maybe)
  6165. (call-interactively 'org-table-next-field))))
  6166. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  6167. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6168. (bob-special (org-cycle-internal-global))
  6169. ;; Drawers: delegate to `org-flag-drawer'.
  6170. ((save-excursion
  6171. (beginning-of-line 1)
  6172. (looking-at org-drawer-regexp))
  6173. (org-flag-drawer ; toggle block visibility
  6174. (not (get-char-property (match-end 0) 'invisible))))
  6175. ;; Show-subtree, ARG levels up from here.
  6176. ((integerp arg)
  6177. (save-excursion
  6178. (org-back-to-heading)
  6179. (outline-up-heading (if (< arg 0) (- arg)
  6180. (- (funcall outline-level) arg)))
  6181. (org-show-subtree)))
  6182. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6183. ((and (featurep 'org-inlinetask)
  6184. (org-inlinetask-at-task-p)
  6185. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6186. (org-inlinetask-toggle-visibility))
  6187. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6188. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6189. (save-excursion (move-beginning-of-line 1)
  6190. (looking-at org-outline-regexp)))
  6191. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6192. (org-cycle-internal-local))
  6193. ;; From there: TAB emulation and template completion.
  6194. (buffer-read-only (org-back-to-heading))
  6195. ((run-hook-with-args-until-success
  6196. 'org-tab-after-check-for-cycling-hook))
  6197. ((run-hook-with-args-until-success
  6198. 'org-tab-before-tab-emulation-hook))
  6199. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6200. (or (not (bolp))
  6201. (not (looking-at org-outline-regexp))))
  6202. (call-interactively (global-key-binding "\t")))
  6203. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6204. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6205. (or (and (eq org-cycle-emulate-tab 'white)
  6206. (= (match-end 0) (point-at-eol)))
  6207. (and (eq org-cycle-emulate-tab 'whitestart)
  6208. (>= (match-end 0) pos))))
  6209. t
  6210. (eq org-cycle-emulate-tab t))
  6211. (call-interactively (global-key-binding "\t")))
  6212. (t (save-excursion
  6213. (org-back-to-heading)
  6214. (org-cycle)))))))
  6215. (defun org-cycle-internal-global ()
  6216. "Do the global cycling action."
  6217. ;; Hack to avoid display of messages for .org attachments in Gnus
  6218. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6219. (cond
  6220. ((and (eq last-command this-command)
  6221. (eq org-cycle-global-status 'overview))
  6222. ;; We just created the overview - now do table of contents
  6223. ;; This can be slow in very large buffers, so indicate action
  6224. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6225. (unless ga (org-unlogged-message "CONTENTS..."))
  6226. (org-content)
  6227. (unless ga (org-unlogged-message "CONTENTS...done"))
  6228. (setq org-cycle-global-status 'contents)
  6229. (run-hook-with-args 'org-cycle-hook 'contents))
  6230. ((and (eq last-command this-command)
  6231. (eq org-cycle-global-status 'contents))
  6232. ;; We just showed the table of contents - now show everything
  6233. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6234. (org-show-all '(headings blocks))
  6235. (unless ga (org-unlogged-message "SHOW ALL"))
  6236. (setq org-cycle-global-status 'all)
  6237. (run-hook-with-args 'org-cycle-hook 'all))
  6238. (t
  6239. ;; Default action: go to overview
  6240. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6241. (org-overview)
  6242. (unless ga (org-unlogged-message "OVERVIEW"))
  6243. (setq org-cycle-global-status 'overview)
  6244. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6245. (defvar org-called-with-limited-levels nil
  6246. "Non-nil when `org-with-limited-levels' is currently active.")
  6247. (defun org-cycle-internal-local ()
  6248. "Do the local cycling action."
  6249. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6250. ;; First, determine end of headline (EOH), end of subtree or item
  6251. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6252. (save-excursion
  6253. (if (org-at-item-p)
  6254. (progn
  6255. (beginning-of-line)
  6256. (setq struct (org-list-struct))
  6257. (setq eoh (point-at-eol))
  6258. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6259. (setq has-children (org-list-has-child-p (point) struct)))
  6260. (org-back-to-heading)
  6261. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6262. (setq eos (save-excursion (org-end-of-subtree t t)
  6263. (when (bolp) (backward-char)) (point)))
  6264. (setq has-children
  6265. (or (save-excursion
  6266. (let ((level (funcall outline-level)))
  6267. (outline-next-heading)
  6268. (and (org-at-heading-p t)
  6269. (> (funcall outline-level) level))))
  6270. (save-excursion
  6271. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6272. ;; Determine end invisible part of buffer (EOL)
  6273. (beginning-of-line 2)
  6274. (while (and (not (eobp)) ;This is like `next-line'.
  6275. (get-char-property (1- (point)) 'invisible))
  6276. (goto-char (next-single-char-property-change (point) 'invisible))
  6277. (and (eolp) (beginning-of-line 2)))
  6278. (setq eol (point)))
  6279. ;; Find out what to do next and set `this-command'
  6280. (cond
  6281. ((= eos eoh)
  6282. ;; Nothing is hidden behind this heading
  6283. (unless (org-before-first-heading-p)
  6284. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6285. (org-unlogged-message "EMPTY ENTRY")
  6286. (setq org-cycle-subtree-status nil)
  6287. (save-excursion
  6288. (goto-char eos)
  6289. (outline-next-heading)
  6290. (when (org-invisible-p) (org-flag-heading nil))))
  6291. ((and (or (>= eol eos)
  6292. (not (string-match "\\S-" (buffer-substring eol eos))))
  6293. (or has-children
  6294. (not (setq children-skipped
  6295. org-cycle-skip-children-state-if-no-children))))
  6296. ;; Entire subtree is hidden in one line: children view
  6297. (unless (org-before-first-heading-p)
  6298. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6299. (if (org-at-item-p)
  6300. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6301. (org-show-entry)
  6302. (org-with-limited-levels (org-show-children))
  6303. (org-show-set-visibility 'canonical)
  6304. ;; Fold every list in subtree to top-level items.
  6305. (when (eq org-cycle-include-plain-lists 'integrate)
  6306. (save-excursion
  6307. (org-back-to-heading)
  6308. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6309. (beginning-of-line 1)
  6310. (let* ((struct (org-list-struct))
  6311. (prevs (org-list-prevs-alist struct))
  6312. (end (org-list-get-bottom-point struct)))
  6313. (dolist (e (org-list-get-all-items (point) struct prevs))
  6314. (org-list-set-item-visibility e struct 'folded))
  6315. (goto-char (if (< end eos) end eos)))))))
  6316. (org-unlogged-message "CHILDREN")
  6317. (save-excursion
  6318. (goto-char eos)
  6319. (outline-next-heading)
  6320. (when (org-invisible-p) (org-flag-heading nil)))
  6321. (setq org-cycle-subtree-status 'children)
  6322. (unless (org-before-first-heading-p)
  6323. (run-hook-with-args 'org-cycle-hook 'children)))
  6324. ((or children-skipped
  6325. (and (eq last-command this-command)
  6326. (eq org-cycle-subtree-status 'children)))
  6327. ;; We just showed the children, or no children are there,
  6328. ;; now show everything.
  6329. (unless (org-before-first-heading-p)
  6330. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6331. (org-flag-region eoh eos nil 'outline)
  6332. (org-unlogged-message
  6333. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6334. (setq org-cycle-subtree-status 'subtree)
  6335. (unless (org-before-first-heading-p)
  6336. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6337. (t
  6338. ;; Default action: hide the subtree.
  6339. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6340. (org-flag-region eoh eos t 'outline)
  6341. (org-unlogged-message "FOLDED")
  6342. (setq org-cycle-subtree-status 'folded)
  6343. (unless (org-before-first-heading-p)
  6344. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6345. ;;;###autoload
  6346. (defun org-global-cycle (&optional arg)
  6347. "Cycle the global visibility. For details see `org-cycle'.
  6348. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6349. With a numeric prefix, show all headlines up to that level."
  6350. (interactive "P")
  6351. (let ((org-cycle-include-plain-lists
  6352. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6353. (cond
  6354. ((integerp arg)
  6355. (org-show-all '(headings blocks))
  6356. (outline-hide-sublevels arg)
  6357. (setq org-cycle-global-status 'contents))
  6358. ((equal arg '(4))
  6359. (org-set-startup-visibility)
  6360. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6361. (t
  6362. (org-cycle '(4))))))
  6363. (defun org-set-startup-visibility ()
  6364. "Set the visibility required by startup options and properties."
  6365. (cond
  6366. ((eq org-startup-folded t)
  6367. (org-overview))
  6368. ((eq org-startup-folded 'content)
  6369. (org-content))
  6370. ((or (eq org-startup-folded 'showeverything)
  6371. (eq org-startup-folded nil))
  6372. (org-show-all)))
  6373. (unless (eq org-startup-folded 'showeverything)
  6374. (when org-hide-block-startup (org-hide-block-all))
  6375. (org-set-visibility-according-to-property)
  6376. (org-cycle-hide-archived-subtrees 'all)
  6377. (org-cycle-hide-drawers 'all)
  6378. (org-cycle-show-empty-lines t)))
  6379. (defun org-set-visibility-according-to-property ()
  6380. "Switch subtree visibilities according to :VISIBILITY: property."
  6381. (interactive)
  6382. (org-with-wide-buffer
  6383. (goto-char (point-min))
  6384. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6385. (if (not (org-at-property-p)) (outline-next-heading)
  6386. (let ((state (match-string 3)))
  6387. (save-excursion
  6388. (org-back-to-heading t)
  6389. (outline-hide-subtree)
  6390. (org-reveal)
  6391. (cond
  6392. ((equal state "folded")
  6393. (outline-hide-subtree))
  6394. ((equal state "children")
  6395. (org-show-hidden-entry)
  6396. (org-show-children))
  6397. ((equal state "content")
  6398. (save-excursion
  6399. (save-restriction
  6400. (org-narrow-to-subtree)
  6401. (org-content))))
  6402. ((member state '("all" "showall"))
  6403. (outline-show-subtree)))))))))
  6404. (defun org-overview ()
  6405. "Switch to overview mode, showing only top-level headlines.
  6406. This shows all headlines with a level equal or greater than the level
  6407. of the first headline in the buffer. This is important, because if the
  6408. first headline is not level one, then (hide-sublevels 1) gives confusing
  6409. results."
  6410. (interactive)
  6411. (save-excursion
  6412. (let ((level
  6413. (save-excursion
  6414. (goto-char (point-min))
  6415. (when (re-search-forward org-outline-regexp-bol nil t)
  6416. (goto-char (match-beginning 0))
  6417. (funcall outline-level)))))
  6418. (and level (outline-hide-sublevels level)))))
  6419. (defun org-content (&optional arg)
  6420. "Show all headlines in the buffer, like a table of contents.
  6421. With numerical argument N, show content up to level N."
  6422. (interactive "P")
  6423. (org-overview)
  6424. (save-excursion
  6425. ;; Visit all headings and show their offspring
  6426. (and (integerp arg) (org-overview))
  6427. (goto-char (point-max))
  6428. (catch 'exit
  6429. (while (and (progn (condition-case nil
  6430. (outline-previous-visible-heading 1)
  6431. (error (goto-char (point-min))))
  6432. t)
  6433. (looking-at org-outline-regexp))
  6434. (if (integerp arg)
  6435. (org-show-children (1- arg))
  6436. (outline-show-branches))
  6437. (when (bobp) (throw 'exit nil))))))
  6438. (defun org-optimize-window-after-visibility-change (state)
  6439. "Adjust the window after a change in outline visibility.
  6440. This function is the default value of the hook `org-cycle-hook'."
  6441. (when (get-buffer-window (current-buffer))
  6442. (cond
  6443. ((eq state 'content) nil)
  6444. ((eq state 'all) nil)
  6445. ((eq state 'folded) nil)
  6446. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6447. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6448. (defun org-clean-visibility-after-subtree-move ()
  6449. "Fix visibility issues after moving a subtree."
  6450. ;; First, find a reasonable region to look at:
  6451. ;; Start two siblings above, end three below
  6452. (let* ((beg (save-excursion
  6453. (and (org-get-last-sibling)
  6454. (org-get-last-sibling))
  6455. (point)))
  6456. (end (save-excursion
  6457. (and (org-get-next-sibling)
  6458. (org-get-next-sibling)
  6459. (org-get-next-sibling))
  6460. (if (org-at-heading-p)
  6461. (point-at-eol)
  6462. (point))))
  6463. (level (looking-at "\\*+"))
  6464. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6465. (save-excursion
  6466. (save-restriction
  6467. (narrow-to-region beg end)
  6468. (when re
  6469. ;; Properly fold already folded siblings
  6470. (goto-char (point-min))
  6471. (while (re-search-forward re nil t)
  6472. (when (and (not (org-invisible-p))
  6473. (org-invisible-p (line-end-position)))
  6474. (outline-hide-entry))))
  6475. (org-cycle-hide-drawers 'all)
  6476. (org-cycle-show-empty-lines 'overview)))))
  6477. (defun org-cycle-show-empty-lines (state)
  6478. "Show empty lines above all visible headlines.
  6479. The region to be covered depends on STATE when called through
  6480. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6481. entire buffer covered. Note that an empty line is only shown if there
  6482. are at least `org-cycle-separator-lines' empty lines before the headline."
  6483. (when (/= org-cycle-separator-lines 0)
  6484. (save-excursion
  6485. (let* ((n (abs org-cycle-separator-lines))
  6486. (re (cond
  6487. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6488. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6489. (t (let ((ns (number-to-string (- n 2))))
  6490. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6491. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6492. beg end)
  6493. (cond
  6494. ((memq state '(overview contents t))
  6495. (setq beg (point-min) end (point-max)))
  6496. ((memq state '(children folded))
  6497. (setq beg (point)
  6498. end (progn (org-end-of-subtree t t)
  6499. (line-beginning-position 2)))))
  6500. (when beg
  6501. (goto-char beg)
  6502. (while (re-search-forward re end t)
  6503. (unless (get-char-property (match-end 1) 'invisible)
  6504. (let ((e (match-end 1))
  6505. (b (if (>= org-cycle-separator-lines 0)
  6506. (match-beginning 1)
  6507. (save-excursion
  6508. (goto-char (match-beginning 0))
  6509. (skip-chars-backward " \t\n")
  6510. (line-end-position)))))
  6511. (org-flag-region b e nil 'outline))))))))
  6512. ;; Never hide empty lines at the end of the file.
  6513. (save-excursion
  6514. (goto-char (point-max))
  6515. (outline-previous-heading)
  6516. (outline-end-of-heading)
  6517. (when (and (looking-at "[ \t\n]+")
  6518. (= (match-end 0) (point-max)))
  6519. (org-flag-region (point) (match-end 0) nil 'outline))))
  6520. ;;;; Reveal point location
  6521. (defun org-show-context (&optional key)
  6522. "Make sure point and context are visible.
  6523. Optional argument KEY, when non-nil, is a symbol. See
  6524. `org-show-context-detail' for allowed values and how much is to
  6525. be shown."
  6526. (org-show-set-visibility
  6527. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  6528. ((cdr (assq key org-show-context-detail)))
  6529. (t (cdr (assq 'default org-show-context-detail))))))
  6530. (defun org-show-set-visibility (detail)
  6531. "Set visibility around point according to DETAIL.
  6532. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  6533. `tree', `canonical' or t. See `org-show-context-detail' for more
  6534. information."
  6535. ;; Show current heading and possibly its entry, following headline
  6536. ;; or all children.
  6537. (if (and (org-at-heading-p) (not (eq detail 'local)))
  6538. (org-flag-heading nil)
  6539. (org-show-entry)
  6540. ;; If point is hidden within a drawer or a block, make sure to
  6541. ;; expose it.
  6542. (dolist (o (overlays-at (point)))
  6543. (when (memq (overlay-get o 'invisible)
  6544. '(org-hide-block org-hide-drawer outline))
  6545. (delete-overlay o)))
  6546. (unless (org-before-first-heading-p)
  6547. (org-with-limited-levels
  6548. (cl-case detail
  6549. ((tree canonical t) (org-show-children))
  6550. ((nil minimal ancestors))
  6551. (t (save-excursion
  6552. (outline-next-heading)
  6553. (org-flag-heading nil)))))))
  6554. ;; Show all siblings.
  6555. (when (eq detail 'lineage) (org-show-siblings))
  6556. ;; Show ancestors, possibly with their children.
  6557. (when (memq detail '(ancestors lineage tree canonical t))
  6558. (save-excursion
  6559. (while (org-up-heading-safe)
  6560. (org-flag-heading nil)
  6561. (when (memq detail '(canonical t)) (org-show-entry))
  6562. (when (memq detail '(tree canonical t)) (org-show-children))))))
  6563. (defvar org-reveal-start-hook nil
  6564. "Hook run before revealing a location.")
  6565. (defun org-reveal (&optional siblings)
  6566. "Show current entry, hierarchy above it, and the following headline.
  6567. This can be used to show a consistent set of context around
  6568. locations exposed with `org-show-context'.
  6569. With optional argument SIBLINGS, on each level of the hierarchy all
  6570. siblings are shown. This repairs the tree structure to what it would
  6571. look like when opened with hierarchical calls to `org-cycle'.
  6572. With a \\[universal-argument] \\[universal-argument] prefix, \
  6573. go to the parent and show the entire tree."
  6574. (interactive "P")
  6575. (run-hooks 'org-reveal-start-hook)
  6576. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6577. ((equal siblings '(16))
  6578. (save-excursion
  6579. (when (org-up-heading-safe)
  6580. (org-show-subtree)
  6581. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6582. (t (org-show-set-visibility 'lineage))))
  6583. ;;; Indirect buffer display of subtrees
  6584. (defvar org-indirect-dedicated-frame nil
  6585. "This is the frame being used for indirect tree display.")
  6586. (defvar org-last-indirect-buffer nil)
  6587. (defun org-tree-to-indirect-buffer (&optional arg)
  6588. "Create indirect buffer and narrow it to current subtree.
  6589. With a numerical prefix ARG, go up to this level and then take that tree.
  6590. If ARG is negative, go up that many levels.
  6591. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6592. indirect buffer previously made with this command, to avoid proliferation of
  6593. indirect buffers. However, when you call the command with a \
  6594. `\\[universal-argument]' prefix, or
  6595. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6596. so that you can work with several indirect buffers at the same time. If
  6597. `org-indirect-buffer-display' is `dedicated-frame', the \
  6598. `\\[universal-argument]' prefix also
  6599. requests that a new frame be made for the new buffer, so that the dedicated
  6600. frame is not changed."
  6601. (interactive "P")
  6602. (let ((cbuf (current-buffer))
  6603. (cwin (selected-window))
  6604. (pos (point))
  6605. beg end level heading ibuf)
  6606. (save-excursion
  6607. (org-back-to-heading t)
  6608. (when (numberp arg)
  6609. (setq level (org-outline-level))
  6610. (when (< arg 0) (setq arg (+ level arg)))
  6611. (while (> (setq level (org-outline-level)) arg)
  6612. (org-up-heading-safe)))
  6613. (setq beg (point)
  6614. heading (org-get-heading 'no-tags))
  6615. (org-end-of-subtree t t)
  6616. (when (org-at-heading-p) (backward-char 1))
  6617. (setq end (point)))
  6618. (when (and (buffer-live-p org-last-indirect-buffer)
  6619. (not (eq org-indirect-buffer-display 'new-frame))
  6620. (not arg))
  6621. (kill-buffer org-last-indirect-buffer))
  6622. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6623. org-last-indirect-buffer ibuf)
  6624. (cond
  6625. ((or (eq org-indirect-buffer-display 'new-frame)
  6626. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6627. (select-frame (make-frame))
  6628. (delete-other-windows)
  6629. (pop-to-buffer-same-window ibuf)
  6630. (org-set-frame-title heading))
  6631. ((eq org-indirect-buffer-display 'dedicated-frame)
  6632. (raise-frame
  6633. (select-frame (or (and org-indirect-dedicated-frame
  6634. (frame-live-p org-indirect-dedicated-frame)
  6635. org-indirect-dedicated-frame)
  6636. (setq org-indirect-dedicated-frame (make-frame)))))
  6637. (delete-other-windows)
  6638. (pop-to-buffer-same-window ibuf)
  6639. (org-set-frame-title (concat "Indirect: " heading)))
  6640. ((eq org-indirect-buffer-display 'current-window)
  6641. (pop-to-buffer-same-window ibuf))
  6642. ((eq org-indirect-buffer-display 'other-window)
  6643. (pop-to-buffer ibuf))
  6644. (t (error "Invalid value")))
  6645. (narrow-to-region beg end)
  6646. (org-show-all '(headings blocks))
  6647. (goto-char pos)
  6648. (run-hook-with-args 'org-cycle-hook 'all)
  6649. (and (window-live-p cwin) (select-window cwin))))
  6650. (defun org-get-indirect-buffer (&optional buffer heading)
  6651. (setq buffer (or buffer (current-buffer)))
  6652. (let ((n 1) (base (buffer-name buffer)) bname)
  6653. (while (buffer-live-p
  6654. (get-buffer
  6655. (setq bname
  6656. (concat base "-"
  6657. (if heading (concat heading "-" (number-to-string n))
  6658. (number-to-string n))))))
  6659. (setq n (1+ n)))
  6660. (condition-case nil
  6661. (make-indirect-buffer buffer bname 'clone)
  6662. (error (make-indirect-buffer buffer bname)))))
  6663. (defun org-set-frame-title (title)
  6664. "Set the title of the current frame to the string TITLE."
  6665. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6666. ;;;; Structure editing
  6667. ;;; Inserting headlines
  6668. (defun org--line-empty-p (n)
  6669. "Is the Nth next line empty?
  6670. Counts the current line as N = 1 and the previous line as N = 0;
  6671. see `beginning-of-line'."
  6672. (save-excursion
  6673. (and (not (bobp))
  6674. (or (beginning-of-line n) t)
  6675. (save-match-data
  6676. (looking-at "[ \t]*$")))))
  6677. (defun org-previous-line-empty-p ()
  6678. "Is the previous line a blank line?
  6679. When NEXT is non-nil, check the next line instead."
  6680. (org--line-empty-p 0))
  6681. (defun org-next-line-empty-p ()
  6682. "Is the previous line a blank line?
  6683. When NEXT is non-nil, check the next line instead."
  6684. (org--line-empty-p 2))
  6685. (defun org--blank-before-heading-p (&optional parent)
  6686. "Non-nil when an empty line should precede a new heading here.
  6687. When optional argument PARENT is non-nil, consider parent
  6688. headline instead of current one."
  6689. (pcase (assq 'heading org-blank-before-new-entry)
  6690. (`(heading . auto)
  6691. (save-excursion
  6692. (org-with-limited-levels
  6693. (unless (and (org-before-first-heading-p)
  6694. (not (outline-next-heading)))
  6695. (org-back-to-heading t)
  6696. (when parent (org-up-heading-safe))
  6697. (cond ((not (bobp))
  6698. (org-previous-line-empty-p))
  6699. ((outline-next-heading)
  6700. (org-previous-line-empty-p))
  6701. ;; Ignore trailing spaces on last buffer line.
  6702. ((progn (skip-chars-backward " \t") (bolp))
  6703. (org-previous-line-empty-p))
  6704. (t nil))))))
  6705. (`(heading . ,value) value)
  6706. (_ nil)))
  6707. (defun org-insert-heading (&optional arg invisible-ok top)
  6708. "Insert a new heading or an item with the same depth at point.
  6709. If point is at the beginning of a heading, insert a new heading
  6710. or a new headline above the current one. When at the beginning
  6711. of a regular line of text, turn it into a heading.
  6712. If point is in the middle of a line, split it and create a new
  6713. headline with the text in the current line after point (see
  6714. `org-M-RET-may-split-line' on how to modify this behavior). As
  6715. a special case, on a headline, splitting can only happen on the
  6716. title itself. E.g., this excludes breaking stars or tags.
  6717. With a `\\[universal-argument]' prefix, set \
  6718. `org-insert-heading-respect-content' to
  6719. a non-nil value for the duration of the command. This forces the
  6720. insertion of a heading after the current subtree, independently
  6721. on the location of point.
  6722. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6723. insert the heading at the end of the tree
  6724. above the current heading. For example, if point is within a
  6725. 2nd-level heading, then it will insert a 2nd-level heading at
  6726. the end of the 1st-level parent subtree.
  6727. When INVISIBLE-OK is set, stop at invisible headlines when going
  6728. back. This is important for non-interactive uses of the
  6729. command.
  6730. When optional argument TOP is non-nil, insert a level 1 heading,
  6731. unconditionally."
  6732. (interactive "P")
  6733. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6734. (level (org-current-level))
  6735. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6736. (cond
  6737. ((or org-insert-heading-respect-content
  6738. (member arg '((4) (16)))
  6739. (and (not invisible-ok)
  6740. (invisible-p (max (1- (point)) (point-min)))))
  6741. ;; Position point at the location of insertion.
  6742. (if (not level) ;before first headline
  6743. (org-with-limited-levels (outline-next-heading))
  6744. ;; Make sure we end up on a visible headline if INVISIBLE-OK
  6745. ;; is nil.
  6746. (org-with-limited-levels (org-back-to-heading invisible-ok))
  6747. (cond ((equal arg '(16))
  6748. (org-up-heading-safe)
  6749. (org-end-of-subtree t t))
  6750. (t
  6751. (org-end-of-subtree t t))))
  6752. (unless (bolp) (insert "\n")) ;ensure final newline
  6753. (unless (and blank? (org-previous-line-empty-p))
  6754. (org-N-empty-lines-before-current (if blank? 1 0)))
  6755. (insert stars " \n")
  6756. (forward-char -1))
  6757. ;; At a headline...
  6758. ((org-at-heading-p)
  6759. (cond ((bolp)
  6760. (when blank? (save-excursion (insert "\n")))
  6761. (save-excursion (insert stars " \n"))
  6762. (unless (and blank? (org-previous-line-empty-p))
  6763. (org-N-empty-lines-before-current (if blank? 1 0)))
  6764. (end-of-line))
  6765. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6766. (org-match-line org-complex-heading-regexp)
  6767. (org-pos-in-match-range (point) 4))
  6768. ;; Grab the text that should moved to the new headline.
  6769. ;; Preserve tags.
  6770. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6771. (if (looking-at "[ \t]*$") (replace-match "")
  6772. (org-align-tags))
  6773. (end-of-line)
  6774. (when blank? (insert "\n"))
  6775. (insert "\n" stars " ")
  6776. (when (org-string-nw-p split) (insert split))
  6777. (when (eobp) (save-excursion (insert "\n")))))
  6778. (t
  6779. (end-of-line)
  6780. (when blank? (insert "\n"))
  6781. (insert "\n" stars " ")
  6782. (when (eobp) (save-excursion (insert "\n"))))))
  6783. ;; On regular text, turn line into a headline or split, if
  6784. ;; appropriate.
  6785. ((bolp)
  6786. (insert stars " ")
  6787. (unless (and blank? (org-previous-line-empty-p))
  6788. (org-N-empty-lines-before-current (if blank? 1 0))))
  6789. (t
  6790. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6791. (end-of-line))
  6792. (insert "\n" stars " ")
  6793. (unless (and blank? (org-previous-line-empty-p))
  6794. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6795. (run-hooks 'org-insert-heading-hook))
  6796. (defun org-N-empty-lines-before-current (n)
  6797. "Make the number of empty lines before current exactly N.
  6798. So this will delete or add empty lines."
  6799. (let ((column (current-column)))
  6800. (beginning-of-line)
  6801. (unless (bobp)
  6802. (let ((start (save-excursion
  6803. (skip-chars-backward " \r\t\n")
  6804. (line-end-position))))
  6805. (delete-region start (line-end-position 0))))
  6806. (insert (make-string n ?\n))
  6807. (move-to-column column)))
  6808. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6809. "Return the heading of the current entry, without the stars.
  6810. When NO-TAGS is non-nil, don't include tags.
  6811. When NO-TODO is non-nil, don't include TODO keywords.
  6812. When NO-PRIORITY is non-nil, don't include priority cookie.
  6813. When NO-COMMENT is non-nil, don't include COMMENT string."
  6814. (save-excursion
  6815. (org-back-to-heading t)
  6816. (let ((case-fold-search nil))
  6817. (looking-at org-complex-heading-regexp)
  6818. (let ((todo (and (not no-todo) (match-string 2)))
  6819. (priority (and (not no-priority) (match-string 3)))
  6820. (headline (pcase (match-string 4)
  6821. (`nil "")
  6822. ((and (guard no-comment) h)
  6823. (replace-regexp-in-string
  6824. (eval-when-compile
  6825. (format "\\`%s[ \t]+" org-comment-string))
  6826. "" h))
  6827. (h h)))
  6828. (tags (and (not no-tags) (match-string 5))))
  6829. (mapconcat #'identity
  6830. (delq nil (list todo priority headline tags))
  6831. " ")))))
  6832. (defun org-heading-components ()
  6833. "Return the components of the current heading.
  6834. This is a list with the following elements:
  6835. - the level as an integer
  6836. - the reduced level, different if `org-odd-levels-only' is set.
  6837. - the TODO keyword, or nil
  6838. - the priority character, like ?A, or nil if no priority is given
  6839. - the headline text itself, or the tags string if no headline text
  6840. - the tags string, or nil."
  6841. (save-excursion
  6842. (org-back-to-heading t)
  6843. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6844. (list (length (match-string 1))
  6845. (org-reduced-level (length (match-string 1)))
  6846. (match-string-no-properties 2)
  6847. (and (match-end 3) (aref (match-string 3) 2))
  6848. (match-string-no-properties 4)
  6849. (match-string-no-properties 5)))))
  6850. (defun org-get-entry ()
  6851. "Get the entry text, after heading, entire subtree."
  6852. (save-excursion
  6853. (org-back-to-heading t)
  6854. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6855. (defun org-edit-headline (&optional heading)
  6856. "Edit the current headline.
  6857. Set it to HEADING when provided."
  6858. (interactive)
  6859. (org-with-wide-buffer
  6860. (org-back-to-heading t)
  6861. (let ((case-fold-search nil))
  6862. (when (looking-at org-complex-heading-regexp)
  6863. (let* ((old (match-string-no-properties 4))
  6864. (new (save-match-data
  6865. (org-trim (or heading (read-string "Edit: " old))))))
  6866. (unless (equal old new)
  6867. (if old (replace-match new t t nil 4)
  6868. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6869. (insert " " new))
  6870. (org-align-tags)
  6871. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6872. (defun org-insert-heading-after-current ()
  6873. "Insert a new heading with same level as current, after current subtree."
  6874. (interactive)
  6875. (org-back-to-heading)
  6876. (org-insert-heading)
  6877. (org-move-subtree-down)
  6878. (end-of-line 1))
  6879. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6880. "Insert heading with `org-insert-heading-respect-content' set to t."
  6881. (interactive)
  6882. (org-insert-heading '(4) invisible-ok))
  6883. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6884. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6885. (interactive)
  6886. (org-insert-todo-heading force-state '(4)))
  6887. (defun org-insert-todo-heading (arg &optional force-heading)
  6888. "Insert a new heading with the same level and TODO state as current heading.
  6889. If the heading has no TODO state, or if the state is DONE, use
  6890. the first state (TODO by default). Also with one prefix arg,
  6891. force first state. With two prefix args, force inserting at the
  6892. end of the parent subtree.
  6893. When called at a plain list item, insert a new item with an
  6894. unchecked check box."
  6895. (interactive "P")
  6896. (when (or force-heading (not (org-insert-item 'checkbox)))
  6897. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6898. force-heading))
  6899. (save-excursion
  6900. (org-forward-heading-same-level -1)
  6901. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6902. (let* ((new-mark-x
  6903. (if (or (equal arg '(4))
  6904. (not (match-beginning 2))
  6905. (member (match-string 2) org-done-keywords))
  6906. (car org-todo-keywords-1)
  6907. (match-string 2)))
  6908. (new-mark
  6909. (or
  6910. (run-hook-with-args-until-success
  6911. 'org-todo-get-default-hook new-mark-x nil)
  6912. new-mark-x)))
  6913. (beginning-of-line 1)
  6914. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6915. (if org-treat-insert-todo-heading-as-state-change
  6916. (org-todo new-mark)
  6917. (insert new-mark " "))))
  6918. (when org-provide-todo-statistics
  6919. (org-update-parent-todo-statistics))))
  6920. (defun org-insert-subheading (arg)
  6921. "Insert a new subheading and demote it.
  6922. Works for outline headings and for plain lists alike."
  6923. (interactive "P")
  6924. (org-insert-heading arg)
  6925. (cond
  6926. ((org-at-heading-p) (org-do-demote))
  6927. ((org-at-item-p) (org-indent-item))))
  6928. (defun org-insert-todo-subheading (arg)
  6929. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6930. Works for outline headings and for plain lists alike."
  6931. (interactive "P")
  6932. (org-insert-todo-heading arg)
  6933. (cond
  6934. ((org-at-heading-p) (org-do-demote))
  6935. ((org-at-item-p) (org-indent-item))))
  6936. ;;; Promotion and Demotion
  6937. (defvar org-after-demote-entry-hook nil
  6938. "Hook run after an entry has been demoted.
  6939. The cursor will be at the beginning of the entry.
  6940. When a subtree is being demoted, the hook will be called for each node.")
  6941. (defvar org-after-promote-entry-hook nil
  6942. "Hook run after an entry has been promoted.
  6943. The cursor will be at the beginning of the entry.
  6944. When a subtree is being promoted, the hook will be called for each node.")
  6945. (defun org-promote-subtree ()
  6946. "Promote the entire subtree.
  6947. See also `org-promote'."
  6948. (interactive)
  6949. (save-excursion
  6950. (org-with-limited-levels (org-map-tree 'org-promote)))
  6951. (org-fix-position-after-promote))
  6952. (defun org-demote-subtree ()
  6953. "Demote the entire subtree.
  6954. See `org-demote' and `org-promote'."
  6955. (interactive)
  6956. (save-excursion
  6957. (org-with-limited-levels (org-map-tree 'org-demote)))
  6958. (org-fix-position-after-promote))
  6959. (defun org-do-promote ()
  6960. "Promote the current heading higher up the tree.
  6961. If the region is active in `transient-mark-mode', promote all
  6962. headings in the region."
  6963. (interactive)
  6964. (save-excursion
  6965. (if (org-region-active-p)
  6966. (org-map-region 'org-promote (region-beginning) (region-end))
  6967. (org-promote)))
  6968. (org-fix-position-after-promote))
  6969. (defun org-do-demote ()
  6970. "Demote the current heading lower down the tree.
  6971. If the region is active in `transient-mark-mode', demote all
  6972. headings in the region."
  6973. (interactive)
  6974. (save-excursion
  6975. (if (org-region-active-p)
  6976. (org-map-region 'org-demote (region-beginning) (region-end))
  6977. (org-demote)))
  6978. (org-fix-position-after-promote))
  6979. (defun org-fix-position-after-promote ()
  6980. "Fix cursor position and indentation after demoting/promoting."
  6981. (let ((pos (point)))
  6982. (when (save-excursion
  6983. (beginning-of-line)
  6984. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6985. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6986. (cond ((eobp) (insert " "))
  6987. ((eolp) (insert " "))
  6988. ((equal (char-after) ?\s) (forward-char 1))))))
  6989. (defun org-current-level ()
  6990. "Return the level of the current entry, or nil if before the first headline.
  6991. The level is the number of stars at the beginning of the
  6992. headline. Use `org-reduced-level' to remove the effect of
  6993. `org-odd-levels'. Unlike to `org-outline-level', this function
  6994. ignores inlinetasks."
  6995. (let ((level (org-with-limited-levels (org-outline-level))))
  6996. (and (> level 0) level)))
  6997. (defun org-get-previous-line-level ()
  6998. "Return the outline depth of the last headline before the current line.
  6999. Returns 0 for the first headline in the buffer, and nil if before the
  7000. first headline."
  7001. (and (org-current-level)
  7002. (or (and (/= (line-beginning-position) (point-min))
  7003. (save-excursion (beginning-of-line 0) (org-current-level)))
  7004. 0)))
  7005. (defun org-reduced-level (l)
  7006. "Compute the effective level of a heading.
  7007. This takes into account the setting of `org-odd-levels-only'."
  7008. (cond
  7009. ((zerop l) 0)
  7010. (org-odd-levels-only (1+ (floor (/ l 2))))
  7011. (t l)))
  7012. (defun org-level-increment ()
  7013. "Return the number of stars that will be added or removed at a
  7014. time to headlines when structure editing, based on the value of
  7015. `org-odd-levels-only'."
  7016. (if org-odd-levels-only 2 1))
  7017. (defun org-get-valid-level (level &optional change)
  7018. "Rectify a level change under the influence of `org-odd-levels-only'.
  7019. LEVEL is a current level, CHANGE is by how much the level should
  7020. be modified. Even if CHANGE is nil, LEVEL may be returned
  7021. modified because even level numbers will become the next higher
  7022. odd number. Returns values greater than 0."
  7023. (if org-odd-levels-only
  7024. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7025. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  7026. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7027. (max 1 (+ level (or change 0)))))
  7028. (defun org-promote ()
  7029. "Promote the current heading higher up the tree."
  7030. (org-with-wide-buffer
  7031. (org-back-to-heading t)
  7032. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7033. after-change-functions))
  7034. (level (save-match-data (funcall outline-level)))
  7035. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7036. (diff (abs (- level (length up-head) -1))))
  7037. (cond
  7038. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7039. (replace-match "# " nil t))
  7040. ((= level 1)
  7041. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7042. (t (replace-match up-head nil t)))
  7043. (unless (= level 1)
  7044. (when org-auto-align-tags (org-align-tags))
  7045. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7046. (run-hooks 'org-after-promote-entry-hook))))
  7047. (defun org-demote ()
  7048. "Demote the current heading lower down the tree."
  7049. (org-with-wide-buffer
  7050. (org-back-to-heading t)
  7051. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7052. after-change-functions))
  7053. (level (save-match-data (funcall outline-level)))
  7054. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7055. (diff (abs (- level (length down-head) -1))))
  7056. (replace-match down-head nil t)
  7057. (when org-auto-align-tags (org-align-tags))
  7058. (when org-adapt-indentation (org-fixup-indentation diff))
  7059. (run-hooks 'org-after-demote-entry-hook))))
  7060. (defun org-cycle-level ()
  7061. "Cycle the level of an empty headline through possible states.
  7062. This goes first to child, then to parent, level, then up the hierarchy.
  7063. After top level, it switches back to sibling level."
  7064. (interactive)
  7065. (let ((org-adapt-indentation nil))
  7066. (when (org-point-at-end-of-empty-headline)
  7067. (setq this-command 'org-cycle-level) ; Only needed for caching
  7068. (let ((cur-level (org-current-level))
  7069. (prev-level (org-get-previous-line-level)))
  7070. (cond
  7071. ;; If first headline in file, promote to top-level.
  7072. ((= prev-level 0)
  7073. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7074. do (org-do-promote)))
  7075. ;; If same level as prev, demote one.
  7076. ((= prev-level cur-level)
  7077. (org-do-demote))
  7078. ;; If parent is top-level, promote to top level if not already.
  7079. ((= prev-level 1)
  7080. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7081. do (org-do-promote)))
  7082. ;; If top-level, return to prev-level.
  7083. ((= cur-level 1)
  7084. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7085. do (org-do-demote)))
  7086. ;; If less than prev-level, promote one.
  7087. ((< cur-level prev-level)
  7088. (org-do-promote))
  7089. ;; If deeper than prev-level, promote until higher than
  7090. ;; prev-level.
  7091. ((> cur-level prev-level)
  7092. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7093. do (org-do-promote))))
  7094. t))))
  7095. (defun org-map-tree (fun)
  7096. "Call FUN for every heading underneath the current one."
  7097. (org-back-to-heading t)
  7098. (let ((level (funcall outline-level)))
  7099. (save-excursion
  7100. (funcall fun)
  7101. (while (and (progn
  7102. (outline-next-heading)
  7103. (> (funcall outline-level) level))
  7104. (not (eobp)))
  7105. (funcall fun)))))
  7106. (defun org-map-region (fun beg end)
  7107. "Call FUN for every heading between BEG and END."
  7108. (let ((org-ignore-region t))
  7109. (save-excursion
  7110. (setq end (copy-marker end))
  7111. (goto-char beg)
  7112. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7113. (< (point) end))
  7114. (funcall fun))
  7115. (while (and (progn
  7116. (outline-next-heading)
  7117. (< (point) end))
  7118. (not (eobp)))
  7119. (funcall fun)))))
  7120. (defun org-fixup-indentation (diff)
  7121. "Change the indentation in the current entry by DIFF.
  7122. DIFF is an integer. Indentation is done according to the
  7123. following rules:
  7124. - Planning information and property drawers are always indented
  7125. according to the new level of the headline;
  7126. - Footnote definitions and their contents are ignored;
  7127. - Inlinetasks' boundaries are not shifted;
  7128. - Empty lines are ignored;
  7129. - Other lines' indentation are shifted by DIFF columns, unless
  7130. it would introduce a structural change in the document, in
  7131. which case no shifting is done at all.
  7132. Assume point is at a heading or an inlinetask beginning."
  7133. (org-with-wide-buffer
  7134. (narrow-to-region (line-beginning-position)
  7135. (save-excursion
  7136. (if (org-with-limited-levels (org-at-heading-p))
  7137. (org-with-limited-levels (outline-next-heading))
  7138. (org-inlinetask-goto-end))
  7139. (point)))
  7140. (forward-line)
  7141. ;; Indent properly planning info and property drawer.
  7142. (when (looking-at-p org-planning-line-re)
  7143. (org-indent-line)
  7144. (forward-line))
  7145. (when (looking-at org-property-drawer-re)
  7146. (goto-char (match-end 0))
  7147. (forward-line)
  7148. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7149. (catch 'no-shift
  7150. (when (zerop diff) (throw 'no-shift nil))
  7151. ;; If DIFF is negative, first check if a shift is possible at all
  7152. ;; (e.g., it doesn't break structure). This can only happen if
  7153. ;; some contents are not properly indented.
  7154. (let ((case-fold-search t))
  7155. (when (< diff 0)
  7156. (let ((diff (- diff))
  7157. (forbidden-re (concat org-outline-regexp
  7158. "\\|"
  7159. (substring org-footnote-definition-re 1))))
  7160. (save-excursion
  7161. (while (not (eobp))
  7162. (cond
  7163. ((looking-at-p "[ \t]*$") (forward-line))
  7164. ((and (looking-at-p org-footnote-definition-re)
  7165. (let ((e (org-element-at-point)))
  7166. (and (eq (org-element-type e) 'footnote-definition)
  7167. (goto-char (org-element-property :end e))))))
  7168. ((looking-at-p org-outline-regexp) (forward-line))
  7169. ;; Give up if shifting would move before column 0 or
  7170. ;; if it would introduce a headline or a footnote
  7171. ;; definition.
  7172. (t
  7173. (skip-chars-forward " \t")
  7174. (let ((ind (current-column)))
  7175. (when (or (< ind diff)
  7176. (and (= ind diff) (looking-at-p forbidden-re)))
  7177. (throw 'no-shift nil)))
  7178. ;; Ignore contents of example blocks and source
  7179. ;; blocks if their indentation is meant to be
  7180. ;; preserved. Jump to block's closing line.
  7181. (beginning-of-line)
  7182. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7183. (let ((e (org-element-at-point)))
  7184. (and (memq (org-element-type e)
  7185. '(example-block src-block))
  7186. (or org-src-preserve-indentation
  7187. (org-element-property :preserve-indent e))
  7188. (goto-char (org-element-property :end e))
  7189. (progn (skip-chars-backward " \r\t\n")
  7190. (beginning-of-line)
  7191. t))))
  7192. (forward-line))))))))
  7193. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7194. ;; by DIFF. Also skip contents of source or example blocks
  7195. ;; when indentation is meant to be preserved.
  7196. (while (not (eobp))
  7197. (cond
  7198. ((and (looking-at-p org-footnote-definition-re)
  7199. (let ((e (org-element-at-point)))
  7200. (and (eq (org-element-type e) 'footnote-definition)
  7201. (goto-char (org-element-property :end e))))))
  7202. ((looking-at-p org-outline-regexp) (forward-line))
  7203. ((looking-at-p "[ \t]*$") (forward-line))
  7204. (t
  7205. (indent-line-to (+ (org-get-indentation) diff))
  7206. (beginning-of-line)
  7207. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7208. (let ((e (org-element-at-point)))
  7209. (and (memq (org-element-type e)
  7210. '(example-block src-block))
  7211. (or org-src-preserve-indentation
  7212. (org-element-property :preserve-indent e))
  7213. (goto-char (org-element-property :end e))
  7214. (progn (skip-chars-backward " \r\t\n")
  7215. (beginning-of-line)
  7216. t))))
  7217. (forward-line)))))))))
  7218. (defun org-convert-to-odd-levels ()
  7219. "Convert an Org file with all levels allowed to one with odd levels.
  7220. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7221. level 5 etc."
  7222. (interactive)
  7223. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7224. (let ((outline-level 'org-outline-level)
  7225. (org-odd-levels-only nil) n)
  7226. (save-excursion
  7227. (goto-char (point-min))
  7228. (while (re-search-forward "^\\*\\*+ " nil t)
  7229. (setq n (- (length (match-string 0)) 2))
  7230. (while (>= (setq n (1- n)) 0)
  7231. (org-demote))
  7232. (end-of-line 1))))))
  7233. (defun org-convert-to-oddeven-levels ()
  7234. "Convert an Org file with only odd levels to one with odd/even levels.
  7235. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7236. file contains a section with an even level, conversion would
  7237. destroy the structure of the file. An error is signaled in this
  7238. case."
  7239. (interactive)
  7240. (goto-char (point-min))
  7241. ;; First check if there are no even levels
  7242. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7243. (org-show-set-visibility 'canonical)
  7244. (error "Not all levels are odd in this file. Conversion not possible"))
  7245. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7246. (let ((outline-regexp org-outline-regexp)
  7247. (outline-level 'org-outline-level)
  7248. (org-odd-levels-only nil) n)
  7249. (save-excursion
  7250. (goto-char (point-min))
  7251. (while (re-search-forward "^\\*\\*+ " nil t)
  7252. (setq n (/ (1- (length (match-string 0))) 2))
  7253. (while (>= (setq n (1- n)) 0)
  7254. (org-promote))
  7255. (end-of-line 1))))))
  7256. (defun org-tr-level (n)
  7257. "Make N odd if required."
  7258. (if org-odd-levels-only (1+ (/ n 2)) n))
  7259. ;;; Vertical tree motion, cutting and pasting of subtrees
  7260. (defun org-move-subtree-up (&optional arg)
  7261. "Move the current subtree up past ARG headlines of the same level."
  7262. (interactive "p")
  7263. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7264. (defun org-move-subtree-down (&optional arg)
  7265. "Move the current subtree down past ARG headlines of the same level."
  7266. (interactive "p")
  7267. (setq arg (prefix-numeric-value arg))
  7268. (org-preserve-local-variables
  7269. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7270. 'org-get-last-sibling))
  7271. (ins-point (make-marker))
  7272. (cnt (abs arg))
  7273. (col (current-column))
  7274. beg end txt folded)
  7275. ;; Select the tree
  7276. (org-back-to-heading)
  7277. (setq beg (point))
  7278. (save-match-data
  7279. (save-excursion (outline-end-of-heading)
  7280. (setq folded (org-invisible-p)))
  7281. (progn (org-end-of-subtree nil t)
  7282. (unless (eobp) (backward-char))))
  7283. (outline-next-heading)
  7284. (setq end (point))
  7285. (goto-char beg)
  7286. ;; Find insertion point, with error handling
  7287. (while (> cnt 0)
  7288. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  7289. (goto-char beg)
  7290. (user-error "Cannot move past superior level or buffer limit"))
  7291. (setq cnt (1- cnt)))
  7292. (when (> arg 0)
  7293. ;; Moving forward - still need to move over subtree
  7294. (org-end-of-subtree t t)
  7295. (save-excursion
  7296. (org-back-over-empty-lines)
  7297. (or (bolp) (newline))))
  7298. (move-marker ins-point (point))
  7299. (setq txt (buffer-substring beg end))
  7300. (org-save-markers-in-region beg end)
  7301. (delete-region beg end)
  7302. (org-remove-empty-overlays-at beg)
  7303. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  7304. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  7305. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7306. (let ((bbb (point)))
  7307. (insert-before-markers txt)
  7308. (org-reinstall-markers-in-region bbb)
  7309. (move-marker ins-point bbb))
  7310. (or (bolp) (insert "\n"))
  7311. (goto-char ins-point)
  7312. (org-skip-whitespace)
  7313. (move-marker ins-point nil)
  7314. (if folded
  7315. (outline-hide-subtree)
  7316. (org-show-entry)
  7317. (org-show-children))
  7318. (org-clean-visibility-after-subtree-move)
  7319. ;; move back to the initial column we were at
  7320. (move-to-column col))))
  7321. (defvar org-subtree-clip ""
  7322. "Clipboard for cut and paste of subtrees.
  7323. This is actually only a copy of the kill, because we use the normal kill
  7324. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7325. (defvar org-subtree-clip-folded nil
  7326. "Was the last copied subtree folded?
  7327. This is used to fold the tree back after pasting.")
  7328. (defun org-cut-subtree (&optional n)
  7329. "Cut the current subtree into the clipboard.
  7330. With prefix arg N, cut this many sequential subtrees.
  7331. This is a short-hand for marking the subtree and then cutting it."
  7332. (interactive "p")
  7333. (org-copy-subtree n 'cut))
  7334. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7335. "Copy the current subtree into the clipboard.
  7336. With prefix arg N, copy this many sequential subtrees.
  7337. This is a short-hand for marking the subtree and then copying it.
  7338. If CUT is non-nil, actually cut the subtree.
  7339. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7340. of some markers in the region, even if CUT is non-nil. This is
  7341. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7342. (interactive "p")
  7343. (org-preserve-local-variables
  7344. (let (beg end folded (beg0 (point)))
  7345. (if (called-interactively-p 'any)
  7346. (org-back-to-heading nil) ; take what looks like a subtree
  7347. (org-back-to-heading t)) ; take what is really there
  7348. (setq beg (point))
  7349. (skip-chars-forward " \t\r\n")
  7350. (save-match-data
  7351. (if nosubtrees
  7352. (outline-next-heading)
  7353. (save-excursion (outline-end-of-heading)
  7354. (setq folded (org-invisible-p)))
  7355. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7356. (org-end-of-subtree t t)))
  7357. ;; Include the end of an inlinetask
  7358. (when (and (featurep 'org-inlinetask)
  7359. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7360. "END[ \t]*$")))
  7361. (end-of-line))
  7362. (setq end (point))
  7363. (goto-char beg0)
  7364. (when (> end beg)
  7365. (setq org-subtree-clip-folded folded)
  7366. (when (or cut force-store-markers)
  7367. (org-save-markers-in-region beg end))
  7368. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7369. (setq org-subtree-clip (current-kill 0))
  7370. (message "%s: Subtree(s) with %d characters"
  7371. (if cut "Cut" "Copied")
  7372. (length org-subtree-clip))))))
  7373. (defun org-paste-subtree (&optional level tree for-yank remove)
  7374. "Paste the clipboard as a subtree, with modification of headline level.
  7375. The entire subtree is promoted or demoted in order to match a new headline
  7376. level.
  7377. If the cursor is at the beginning of a headline, the same level as
  7378. that headline is used to paste the tree.
  7379. If not, the new level is derived from the *visible* headings
  7380. before and after the insertion point, and taken to be the inferior headline
  7381. level of the two. So if the previous visible heading is level 3 and the
  7382. next is level 4 (or vice versa), level 4 will be used for insertion.
  7383. This makes sure that the subtree remains an independent subtree and does
  7384. not swallow low level entries.
  7385. You can also force a different level, either by using a numeric prefix
  7386. argument, or by inserting the heading marker by hand. For example, if the
  7387. cursor is after \"*****\", then the tree will be shifted to level 5.
  7388. If optional TREE is given, use this text instead of the kill ring.
  7389. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7390. move back over whitespace before inserting, and move point to the end of
  7391. the inserted text when done.
  7392. When REMOVE is non-nil, remove the subtree from the clipboard."
  7393. (interactive "P")
  7394. (setq tree (or tree (and kill-ring (current-kill 0))))
  7395. (unless (org-kill-is-subtree-p tree)
  7396. (user-error
  7397. (substitute-command-keys
  7398. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  7399. (org-with-limited-levels
  7400. (let* ((visp (not (org-invisible-p)))
  7401. (txt tree)
  7402. (old-level (if (string-match org-outline-regexp-bol txt)
  7403. (- (match-end 0) (match-beginning 0) 1)
  7404. -1))
  7405. (force-level
  7406. (cond
  7407. (level (prefix-numeric-value level))
  7408. ;; When point is right after the stars in an otherwise
  7409. ;; empty headline, use stars as the forced level.
  7410. ((and (looking-at-p "[ \t]*$")
  7411. (string-match-p "^\\*+ *"
  7412. (buffer-substring (line-beginning-position)
  7413. (point))))
  7414. (org-outline-level))
  7415. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  7416. (previous-level
  7417. (save-excursion
  7418. (org-previous-visible-heading 1)
  7419. (if (org-at-heading-p) (org-outline-level) 1)))
  7420. (next-level
  7421. (save-excursion
  7422. (if (org-at-heading-p) (org-outline-level)
  7423. (org-next-visible-heading 1)
  7424. (if (org-at-heading-p) (org-outline-level) 1))))
  7425. (new-level (or force-level (max previous-level next-level)))
  7426. (shift (if (or (= old-level -1)
  7427. (= new-level -1)
  7428. (= old-level new-level))
  7429. 0
  7430. (- new-level old-level)))
  7431. (delta (if (> shift 0) -1 1))
  7432. (func (if (> shift 0) #'org-demote #'org-promote))
  7433. (org-odd-levels-only nil)
  7434. beg end newend)
  7435. ;; Remove the forced level indicator.
  7436. (when (and force-level (not level))
  7437. (delete-region (line-beginning-position) (point)))
  7438. ;; Paste before the next visible heading or at end of buffer,
  7439. ;; unless point is at the beginning of a headline.
  7440. (unless (and (bolp) (org-at-heading-p))
  7441. (org-next-visible-heading 1)
  7442. (unless (bolp) (insert "\n")))
  7443. (setq beg (point))
  7444. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7445. (insert-before-markers txt)
  7446. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7447. (setq newend (point))
  7448. (org-reinstall-markers-in-region beg)
  7449. (setq end (point))
  7450. (goto-char beg)
  7451. (skip-chars-forward " \t\n\r")
  7452. (setq beg (point))
  7453. (when (and (org-invisible-p) visp)
  7454. (save-excursion (outline-show-heading)))
  7455. ;; Shift if necessary.
  7456. (unless (= shift 0)
  7457. (save-restriction
  7458. (narrow-to-region beg end)
  7459. (while (not (= shift 0))
  7460. (org-map-region func (point-min) (point-max))
  7461. (setq shift (+ delta shift)))
  7462. (goto-char (point-min))
  7463. (setq newend (point-max))))
  7464. (when (or for-yank (called-interactively-p 'interactive))
  7465. (message "Clipboard pasted as level %d subtree" new-level))
  7466. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7467. kill-ring
  7468. (equal org-subtree-clip (current-kill 0))
  7469. org-subtree-clip-folded)
  7470. ;; The tree was folded before it was killed/copied
  7471. (outline-hide-subtree))
  7472. (when for-yank (goto-char newend))
  7473. (when remove (pop kill-ring)))))
  7474. (defun org-kill-is-subtree-p (&optional txt)
  7475. "Check if the current kill is an outline subtree, or a set of trees.
  7476. Returns nil if kill does not start with a headline, or if the first
  7477. headline level is not the largest headline level in the tree.
  7478. So this will actually accept several entries of equal levels as well,
  7479. which is OK for `org-paste-subtree'.
  7480. If optional TXT is given, check this string instead of the current kill."
  7481. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7482. (re (org-get-limited-outline-regexp))
  7483. (^re (concat "^" re))
  7484. (start-level (and kill
  7485. (string-match
  7486. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7487. kill)
  7488. (- (match-end 2) (match-beginning 2) 1)))
  7489. (start (1+ (or (match-beginning 2) -1))))
  7490. (if (not start-level)
  7491. (progn
  7492. nil) ;; does not even start with a heading
  7493. (catch 'exit
  7494. (while (setq start (string-match ^re kill (1+ start)))
  7495. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7496. (throw 'exit nil)))
  7497. t))))
  7498. (defvar org-markers-to-move nil
  7499. "Markers that should be moved with a cut-and-paste operation.
  7500. Those markers are stored together with their positions relative to
  7501. the start of the region.")
  7502. (defun org-save-markers-in-region (beg end)
  7503. "Check markers in region.
  7504. If these markers are between BEG and END, record their position relative
  7505. to BEG, so that after moving the block of text, we can put the markers back
  7506. into place.
  7507. This function gets called just before an entry or tree gets cut from the
  7508. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7509. called immediately, to move the markers with the entries."
  7510. (setq org-markers-to-move nil)
  7511. (when (featurep 'org-clock)
  7512. (org-clock-save-markers-for-cut-and-paste beg end))
  7513. (when (featurep 'org-agenda)
  7514. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7515. (defun org-check-and-save-marker (marker beg end)
  7516. "Check if MARKER is between BEG and END.
  7517. If yes, remember the marker and the distance to BEG."
  7518. (when (and (marker-buffer marker)
  7519. (equal (marker-buffer marker) (current-buffer))
  7520. (>= marker beg) (< marker end))
  7521. (push (cons marker (- marker beg)) org-markers-to-move)))
  7522. (defun org-reinstall-markers-in-region (beg)
  7523. "Move all remembered markers to their position relative to BEG."
  7524. (dolist (x org-markers-to-move)
  7525. (move-marker (car x) (+ beg (cdr x))))
  7526. (setq org-markers-to-move nil))
  7527. (defun org-narrow-to-subtree ()
  7528. "Narrow buffer to the current subtree."
  7529. (interactive)
  7530. (save-excursion
  7531. (save-match-data
  7532. (org-with-limited-levels
  7533. (narrow-to-region
  7534. (progn (org-back-to-heading t) (point))
  7535. (progn (org-end-of-subtree t t)
  7536. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7537. (point)))))))
  7538. (defun org-toggle-narrow-to-subtree ()
  7539. "Narrow to the subtree at point or widen a narrowed buffer."
  7540. (interactive)
  7541. (if (buffer-narrowed-p)
  7542. (widen)
  7543. (org-narrow-to-subtree)))
  7544. (defun org-narrow-to-block ()
  7545. "Narrow buffer to the current block."
  7546. (interactive)
  7547. (let* ((case-fold-search t)
  7548. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7549. "^[ \t]*#\\+end_.*")))
  7550. (if blockp
  7551. (narrow-to-region (car blockp) (cdr blockp))
  7552. (user-error "Not in a block"))))
  7553. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7554. "Clone the task (subtree) at point N times.
  7555. The clones will be inserted as siblings.
  7556. In interactive use, the user will be prompted for the number of
  7557. clones to be produced. If the entry has a timestamp, the user
  7558. will also be prompted for a time shift, which may be a repeater
  7559. as used in time stamps, for example `+3d'. To disable this,
  7560. you can call the function with a universal prefix argument.
  7561. When a valid repeater is given and the entry contains any time
  7562. stamps, the clones will become a sequence in time, with time
  7563. stamps in the subtree shifted for each clone produced. If SHIFT
  7564. is nil or the empty string, time stamps will be left alone. The
  7565. ID property of the original subtree is removed.
  7566. In each clone, all the CLOCK entries will be removed. This
  7567. prevents Org from considering that the clocked times overlap.
  7568. If the original subtree did contain time stamps with a repeater,
  7569. the following will happen:
  7570. - the repeater will be removed in each clone
  7571. - an additional clone will be produced, with the current, unshifted
  7572. date(s) in the entry.
  7573. - the original entry will be placed *after* all the clones, with
  7574. repeater intact.
  7575. - the start days in the repeater in the original entry will be shifted
  7576. to past the last clone.
  7577. In this way you can spell out a number of instances of a repeating task,
  7578. and still retain the repeater to cover future instances of the task.
  7579. As described above, N+1 clones are produced when the original
  7580. subtree has a repeater. Setting N to 0, then, can be used to
  7581. remove the repeater from a subtree and create a shifted clone
  7582. with the original repeater."
  7583. (interactive "nNumber of clones to produce: ")
  7584. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7585. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7586. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7587. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7588. (shift
  7589. (or shift
  7590. (if (and (not (equal current-prefix-arg '(4)))
  7591. (save-excursion
  7592. (goto-char beg)
  7593. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7594. (read-from-minibuffer
  7595. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7596. ""))) ;No time shift
  7597. (doshift
  7598. (and (org-string-nw-p shift)
  7599. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7600. shift)
  7601. (user-error "Invalid shift specification %s" shift)))))
  7602. (goto-char end-of-tree)
  7603. (unless (bolp) (insert "\n"))
  7604. (let* ((end (point))
  7605. (template (buffer-substring beg end))
  7606. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7607. (shift-what (pcase (and doshift (match-string 2 shift))
  7608. (`nil nil)
  7609. ("d" 'day)
  7610. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7611. ("m" 'month)
  7612. ("y" 'year)
  7613. (_ (error "Unsupported time unit"))))
  7614. (nmin 1)
  7615. (nmax n)
  7616. (n-no-remove -1)
  7617. (idprop (org-entry-get nil "ID")))
  7618. (when (and doshift
  7619. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7620. template))
  7621. (delete-region beg end)
  7622. (setq end beg)
  7623. (setq nmin 0)
  7624. (setq nmax (1+ nmax))
  7625. (setq n-no-remove nmax))
  7626. (goto-char end)
  7627. (cl-loop for n from nmin to nmax do
  7628. (insert
  7629. ;; Prepare clone.
  7630. (with-temp-buffer
  7631. (insert template)
  7632. (org-mode)
  7633. (goto-char (point-min))
  7634. (org-show-subtree)
  7635. (and idprop (if org-clone-delete-id
  7636. (org-entry-delete nil "ID")
  7637. (org-id-get-create t)))
  7638. (unless (= n 0)
  7639. (while (re-search-forward org-clock-line-re nil t)
  7640. (delete-region (line-beginning-position)
  7641. (line-beginning-position 2)))
  7642. (goto-char (point-min))
  7643. (while (re-search-forward org-drawer-regexp nil t)
  7644. (org-remove-empty-drawer-at (point))))
  7645. (goto-char (point-min))
  7646. (when doshift
  7647. (while (re-search-forward org-ts-regexp-both nil t)
  7648. (org-timestamp-change (* n shift-n) shift-what))
  7649. (unless (= n n-no-remove)
  7650. (goto-char (point-min))
  7651. (while (re-search-forward org-ts-regexp nil t)
  7652. (save-excursion
  7653. (goto-char (match-beginning 0))
  7654. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7655. (delete-region (match-beginning 1) (match-end 1)))))))
  7656. (buffer-string)))))
  7657. (goto-char beg)))
  7658. ;;; Outline Sorting
  7659. (defun org-sort (&optional with-case)
  7660. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7661. Optional argument WITH-CASE means sort case-sensitively."
  7662. (interactive "P")
  7663. (org-call-with-arg
  7664. (cond ((org-at-table-p) #'org-table-sort-lines)
  7665. ((org-at-item-p) #'org-sort-list)
  7666. (t #'org-sort-entries))
  7667. with-case))
  7668. (defun org-sort-remove-invisible (s)
  7669. "Remove invisible part of links and emphasis markers from string S."
  7670. (remove-text-properties 0 (length s) org-rm-props s)
  7671. (replace-regexp-in-string
  7672. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7673. (replace-regexp-in-string
  7674. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7675. (org-link-display-format s)
  7676. t t) t t))
  7677. (defvar org-priority-regexp) ; defined later in the file
  7678. (defvar org-after-sorting-entries-or-items-hook nil
  7679. "Hook that is run after a bunch of entries or items have been sorted.
  7680. When children are sorted, the cursor is in the parent line when this
  7681. hook gets called. When a region or a plain list is sorted, the cursor
  7682. will be in the first entry of the sorted region/list.")
  7683. (defun org-sort-entries
  7684. (&optional with-case sorting-type getkey-func compare-func property
  7685. interactive?)
  7686. "Sort entries on a certain level of an outline tree.
  7687. If there is an active region, the entries in the region are sorted.
  7688. Else, if the cursor is before the first entry, sort the top-level items.
  7689. Else, the children of the entry at point are sorted.
  7690. Sorting can be alphabetically, numerically, by date/time as given by
  7691. a time stamp, by a property, by priority order, or by a custom function.
  7692. The command prompts for the sorting type unless it has been given to the
  7693. function through the SORTING-TYPE argument, which needs to be a character,
  7694. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7695. the precise meaning of each character:
  7696. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7697. c By creation time, which is assumed to be the first inactive time stamp
  7698. at the beginning of a line.
  7699. d By deadline date/time.
  7700. k By clocking time.
  7701. n Numerically, by converting the beginning of the entry/item to a number.
  7702. o By order of TODO keywords.
  7703. p By priority according to the cookie.
  7704. r By the value of a property.
  7705. s By scheduled date/time.
  7706. t By date/time, either the first active time stamp in the entry, or, if
  7707. none exist, by the first inactive one.
  7708. Capital letters will reverse the sort order.
  7709. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7710. called with point at the beginning of the record. It must return a
  7711. value that is compatible with COMPARE-FUNC, the function used to
  7712. compare entries.
  7713. Comparing entries ignores case by default. However, with an optional argument
  7714. WITH-CASE, the sorting considers case as well.
  7715. Sorting is done against the visible part of the headlines, it ignores hidden
  7716. links.
  7717. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7718. A non-nil value for INTERACTIVE? is used to signal that this
  7719. function is being called interactively."
  7720. (interactive (list current-prefix-arg nil nil nil nil t))
  7721. (let ((case-func (if with-case 'identity 'downcase))
  7722. start beg end stars re re2
  7723. txt what tmp)
  7724. ;; Find beginning and end of region to sort
  7725. (cond
  7726. ((org-region-active-p)
  7727. ;; we will sort the region
  7728. (setq end (region-end)
  7729. what "region")
  7730. (goto-char (region-beginning))
  7731. (unless (org-at-heading-p) (outline-next-heading))
  7732. (setq start (point)))
  7733. ((or (org-at-heading-p)
  7734. (ignore-errors (progn (org-back-to-heading) t)))
  7735. ;; we will sort the children of the current headline
  7736. (org-back-to-heading)
  7737. (setq start (point)
  7738. end (progn (org-end-of-subtree t t)
  7739. (or (bolp) (insert "\n"))
  7740. (when (>= (org-back-over-empty-lines) 1)
  7741. (forward-line 1))
  7742. (point))
  7743. what "children")
  7744. (goto-char start)
  7745. (outline-show-subtree)
  7746. (outline-next-heading))
  7747. (t
  7748. ;; we will sort the top-level entries in this file
  7749. (goto-char (point-min))
  7750. (or (org-at-heading-p) (outline-next-heading))
  7751. (setq start (point))
  7752. (goto-char (point-max))
  7753. (beginning-of-line 1)
  7754. (when (looking-at ".*?\\S-")
  7755. ;; File ends in a non-white line
  7756. (end-of-line 1)
  7757. (insert "\n"))
  7758. (setq end (point-max))
  7759. (setq what "top-level")
  7760. (goto-char start)
  7761. (org-show-all '(headings blocks))))
  7762. (setq beg (point))
  7763. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7764. (looking-at "\\(\\*+\\)")
  7765. (setq stars (match-string 1)
  7766. re (concat "^" (regexp-quote stars) " +")
  7767. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7768. txt (buffer-substring beg end))
  7769. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7770. (when (and (not (equal stars "*")) (string-match re2 txt))
  7771. (user-error "Region to sort contains a level above the first entry"))
  7772. (unless sorting-type
  7773. (message
  7774. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7775. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7776. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7777. what)
  7778. (setq sorting-type (read-char-exclusive)))
  7779. (unless getkey-func
  7780. (and (= (downcase sorting-type) ?f)
  7781. (setq getkey-func
  7782. (or (and interactive?
  7783. (org-read-function
  7784. "Function for extracting keys: "))
  7785. (error "Missing key extractor")))))
  7786. (and (= (downcase sorting-type) ?r)
  7787. (not property)
  7788. (setq property
  7789. (completing-read "Property: "
  7790. (mapcar #'list (org-buffer-property-keys t))
  7791. nil t)))
  7792. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7793. (message "Sorting entries...")
  7794. (save-restriction
  7795. (narrow-to-region start end)
  7796. (let ((restore-clock?
  7797. ;; The clock marker is lost when using `sort-subr'; mark
  7798. ;; the clock with temporary `:org-clock-marker-backup'
  7799. ;; text property.
  7800. (when (and (eq (org-clock-is-active) (current-buffer))
  7801. (<= start (marker-position org-clock-marker))
  7802. (>= end (marker-position org-clock-marker)))
  7803. (with-silent-modifications
  7804. (put-text-property (1- org-clock-marker) org-clock-marker
  7805. :org-clock-marker-backup t))
  7806. t))
  7807. (dcst (downcase sorting-type))
  7808. (case-fold-search nil)
  7809. (now (current-time)))
  7810. (org-preserve-local-variables
  7811. (sort-subr
  7812. (/= dcst sorting-type)
  7813. ;; This function moves to the beginning character of the
  7814. ;; "record" to be sorted.
  7815. (lambda nil
  7816. (if (re-search-forward re nil t)
  7817. (goto-char (match-beginning 0))
  7818. (goto-char (point-max))))
  7819. ;; This function moves to the last character of the "record" being
  7820. ;; sorted.
  7821. (lambda nil
  7822. (save-match-data
  7823. (condition-case nil
  7824. (outline-forward-same-level 1)
  7825. (error
  7826. (goto-char (point-max))))))
  7827. ;; This function returns the value that gets sorted against.
  7828. (lambda ()
  7829. (cond
  7830. ((= dcst ?n)
  7831. (string-to-number
  7832. (org-sort-remove-invisible (org-get-heading t t t t))))
  7833. ((= dcst ?a)
  7834. (funcall case-func
  7835. (org-sort-remove-invisible (org-get-heading t t t t))))
  7836. ((= dcst ?k)
  7837. (or (get-text-property (point) :org-clock-minutes) 0))
  7838. ((= dcst ?t)
  7839. (let ((end (save-excursion (outline-next-heading) (point))))
  7840. (if (or (re-search-forward org-ts-regexp end t)
  7841. (re-search-forward org-ts-regexp-both end t))
  7842. (org-time-string-to-seconds (match-string 0))
  7843. (float-time now))))
  7844. ((= dcst ?c)
  7845. (let ((end (save-excursion (outline-next-heading) (point))))
  7846. (if (re-search-forward
  7847. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7848. end t)
  7849. (org-time-string-to-seconds (match-string 0))
  7850. (float-time now))))
  7851. ((= dcst ?s)
  7852. (let ((end (save-excursion (outline-next-heading) (point))))
  7853. (if (re-search-forward org-scheduled-time-regexp end t)
  7854. (org-time-string-to-seconds (match-string 1))
  7855. (float-time now))))
  7856. ((= dcst ?d)
  7857. (let ((end (save-excursion (outline-next-heading) (point))))
  7858. (if (re-search-forward org-deadline-time-regexp end t)
  7859. (org-time-string-to-seconds (match-string 1))
  7860. (float-time now))))
  7861. ((= dcst ?p)
  7862. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7863. (string-to-char (match-string 2))
  7864. org-default-priority))
  7865. ((= dcst ?r)
  7866. (or (org-entry-get nil property) ""))
  7867. ((= dcst ?o)
  7868. (when (looking-at org-complex-heading-regexp)
  7869. (let* ((m (match-string 2))
  7870. (s (if (member m org-done-keywords) '- '+)))
  7871. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7872. ((= dcst ?f)
  7873. (if getkey-func
  7874. (progn
  7875. (setq tmp (funcall getkey-func))
  7876. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7877. tmp)
  7878. (error "Invalid key function `%s'" getkey-func)))
  7879. (t (error "Invalid sorting type `%c'" sorting-type))))
  7880. nil
  7881. (cond
  7882. ((= dcst ?a) 'org-string-collate-lessp)
  7883. ((= dcst ?f)
  7884. (or compare-func
  7885. (and interactive?
  7886. (org-read-function
  7887. (concat "Function for comparing keys "
  7888. "(empty for default `sort-subr' predicate): ")
  7889. 'allow-empty))))
  7890. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7891. (when restore-clock?
  7892. (move-marker org-clock-marker
  7893. (1+ (next-single-property-change
  7894. start :org-clock-marker-backup)))
  7895. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7896. '(:org-clock-marker-backup t)))))
  7897. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7898. (message "Sorting entries...done")))
  7899. (defun org-contextualize-keys (alist contexts)
  7900. "Return valid elements in ALIST depending on CONTEXTS.
  7901. `org-agenda-custom-commands' or `org-capture-templates' are the
  7902. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7903. or `org-capture-templates-contexts' are the associated contexts
  7904. definitions."
  7905. (let ((contexts
  7906. ;; normalize contexts
  7907. (mapcar
  7908. (lambda(c) (cond ((listp (cadr c))
  7909. (list (car c) (car c) (nth 1 c)))
  7910. ((string= "" (cadr c))
  7911. (list (car c) (car c) (nth 2 c)))
  7912. (t c)))
  7913. contexts))
  7914. (a alist) r s)
  7915. ;; loop over all commands or templates
  7916. (dolist (c a)
  7917. (let (vrules repl)
  7918. (cond
  7919. ((not (assoc (car c) contexts))
  7920. (push c r))
  7921. ((and (assoc (car c) contexts)
  7922. (setq vrules (org-contextualize-validate-key
  7923. (car c) contexts)))
  7924. (mapc (lambda (vr)
  7925. (unless (equal (car vr) (cadr vr))
  7926. (setq repl vr)))
  7927. vrules)
  7928. (if (not repl) (push c r)
  7929. (push (cadr repl) s)
  7930. (push
  7931. (cons (car c)
  7932. (cdr (or (assoc (cadr repl) alist)
  7933. (error "Undefined key `%s' as contextual replacement for `%s'"
  7934. (cadr repl) (car c)))))
  7935. r))))))
  7936. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7937. (delq
  7938. nil
  7939. (delete-dups
  7940. (mapcar (lambda (x)
  7941. (let ((tpl (car x)))
  7942. (unless (delq
  7943. nil
  7944. (mapcar (lambda (y)
  7945. (equal y tpl))
  7946. s))
  7947. x)))
  7948. (reverse r))))))
  7949. (defun org-contextualize-validate-key (key contexts)
  7950. "Check CONTEXTS for agenda or capture KEY."
  7951. (let (res)
  7952. (dolist (r contexts)
  7953. (dolist (rr (car (last r)))
  7954. (when
  7955. (and (equal key (car r))
  7956. (if (functionp rr) (funcall rr)
  7957. (or (and (eq (car rr) 'in-file)
  7958. (buffer-file-name)
  7959. (string-match (cdr rr) (buffer-file-name)))
  7960. (and (eq (car rr) 'in-mode)
  7961. (string-match (cdr rr) (symbol-name major-mode)))
  7962. (and (eq (car rr) 'in-buffer)
  7963. (string-match (cdr rr) (buffer-name)))
  7964. (when (and (eq (car rr) 'not-in-file)
  7965. (buffer-file-name))
  7966. (not (string-match (cdr rr) (buffer-file-name))))
  7967. (when (eq (car rr) 'not-in-mode)
  7968. (not (string-match (cdr rr) (symbol-name major-mode))))
  7969. (when (eq (car rr) 'not-in-buffer)
  7970. (not (string-match (cdr rr) (buffer-name)))))))
  7971. (push r res))))
  7972. (delete-dups (delq nil res))))
  7973. ;; Defined to provide a value for defcustom, since there is no
  7974. ;; string-collate-greaterp in Emacs.
  7975. (defun org-string-collate-greaterp (s1 s2)
  7976. "Return non-nil if S1 is greater than S2 in collation order."
  7977. (not (org-string-collate-lessp s1 s2)))
  7978. ;;;###autoload
  7979. (defun org-run-like-in-org-mode (cmd)
  7980. "Run a command, pretending that the current buffer is in Org mode.
  7981. This will temporarily bind local variables that are typically bound in
  7982. Org mode to the values they have in Org mode, and then interactively
  7983. call CMD."
  7984. (org-load-modules-maybe)
  7985. (let (binds)
  7986. (dolist (var (org-get-local-variables))
  7987. (when (or (not (boundp (car var)))
  7988. (eq (symbol-value (car var))
  7989. (default-value (car var))))
  7990. (push (list (car var) `(quote ,(cadr var))) binds)))
  7991. (eval `(let ,binds
  7992. (call-interactively (quote ,cmd))))))
  7993. (defun org-get-category (&optional pos force-refresh)
  7994. "Get the category applying to position POS."
  7995. (save-match-data
  7996. (when force-refresh (org-refresh-category-properties))
  7997. (let ((pos (or pos (point))))
  7998. (or (get-text-property pos 'org-category)
  7999. (progn (org-refresh-category-properties)
  8000. (get-text-property pos 'org-category))))))
  8001. ;;; Refresh properties
  8002. (defun org-refresh-properties (dprop tprop)
  8003. "Refresh buffer text properties.
  8004. DPROP is the drawer property and TPROP is either the
  8005. corresponding text property to set, or an alist with each element
  8006. being a text property (as a symbol) and a function to apply to
  8007. the value of the drawer property."
  8008. (let* ((case-fold-search t)
  8009. (inhibit-read-only t)
  8010. (inherit? (org-property-inherit-p dprop))
  8011. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  8012. (global (and inherit? (org--property-global-value dprop nil))))
  8013. (with-silent-modifications
  8014. (org-with-point-at 1
  8015. ;; Set global values (e.g., values defined through
  8016. ;; "#+PROPERTY:" keywords) to the whole buffer.
  8017. (when global (put-text-property (point-min) (point-max) tprop global))
  8018. ;; Set local values.
  8019. (while (re-search-forward property-re nil t)
  8020. (when (org-at-property-p)
  8021. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  8022. (outline-next-heading))))))
  8023. (defun org-refresh-property (tprop p &optional inherit)
  8024. "Refresh the buffer text property TPROP from the drawer property P.
  8025. The refresh happens only for the current headline, or the whole
  8026. sub-tree if optional argument INHERIT is non-nil."
  8027. (unless (org-before-first-heading-p)
  8028. (save-excursion
  8029. (org-back-to-heading t)
  8030. (let ((start (point))
  8031. (end (save-excursion
  8032. (if inherit (org-end-of-subtree t t)
  8033. (or (outline-next-heading) (point-max))))))
  8034. (if (symbolp tprop)
  8035. ;; TPROP is a text property symbol.
  8036. (put-text-property start end tprop p)
  8037. ;; TPROP is an alist with (property . function) elements.
  8038. (pcase-dolist (`(,prop . ,f) tprop)
  8039. (put-text-property start end prop (funcall f p))))))))
  8040. (defun org-refresh-category-properties ()
  8041. "Refresh category text properties in the buffer."
  8042. (let ((case-fold-search t)
  8043. (inhibit-read-only t)
  8044. (default-category
  8045. (cond ((null org-category)
  8046. (if buffer-file-name
  8047. (file-name-sans-extension
  8048. (file-name-nondirectory buffer-file-name))
  8049. "???"))
  8050. ((symbolp org-category) (symbol-name org-category))
  8051. (t org-category))))
  8052. (with-silent-modifications
  8053. (org-with-wide-buffer
  8054. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8055. ;; This is the default category for the buffer. If none is
  8056. ;; found, fall-back to `org-category' or buffer file name.
  8057. (put-text-property
  8058. (point-min) (point-max)
  8059. 'org-category
  8060. (catch 'buffer-category
  8061. (goto-char (point-max))
  8062. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8063. (let ((element (org-element-at-point)))
  8064. (when (eq (org-element-type element) 'keyword)
  8065. (throw 'buffer-category
  8066. (org-element-property :value element)))))
  8067. default-category))
  8068. ;; Set sub-tree specific categories.
  8069. (goto-char (point-min))
  8070. (let ((regexp (org-re-property "CATEGORY")))
  8071. (while (re-search-forward regexp nil t)
  8072. (let ((value (match-string-no-properties 3)))
  8073. (when (org-at-property-p)
  8074. (put-text-property
  8075. (save-excursion (org-back-to-heading t) (point))
  8076. (save-excursion (org-end-of-subtree t t) (point))
  8077. 'org-category
  8078. value)))))))))
  8079. (defun org-refresh-stats-properties ()
  8080. "Refresh stats text properties in the buffer."
  8081. (with-silent-modifications
  8082. (org-with-point-at 1
  8083. (let ((regexp (concat org-outline-regexp-bol
  8084. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8085. (while (re-search-forward regexp nil t)
  8086. (let* ((numerator (string-to-number (match-string 1)))
  8087. (denominator (and (match-end 2)
  8088. (string-to-number (match-string 2))))
  8089. (stats (cond ((not denominator) numerator) ;percent
  8090. ((= denominator 0) 0)
  8091. (t (/ (* numerator 100) denominator)))))
  8092. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8093. 'org-stats stats)))))))
  8094. (defun org-refresh-effort-properties ()
  8095. "Refresh effort properties"
  8096. (org-refresh-properties
  8097. org-effort-property
  8098. '((effort . identity)
  8099. (effort-minutes . org-duration-to-minutes))))
  8100. ;;;; Link Stuff
  8101. ;;; Link abbreviations
  8102. (defun org-link-expand-abbrev (link)
  8103. "Apply replacements as defined in `org-link-abbrev-alist'."
  8104. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8105. (let* ((key (match-string 1 link))
  8106. (as (or (assoc key org-link-abbrev-alist-local)
  8107. (assoc key org-link-abbrev-alist)))
  8108. (tag (and (match-end 2) (match-string 3 link)))
  8109. rpl)
  8110. (if (not as)
  8111. link
  8112. (setq rpl (cdr as))
  8113. (cond
  8114. ((symbolp rpl) (funcall rpl tag))
  8115. ((string-match "%(\\([^)]+\\))" rpl)
  8116. (replace-match
  8117. (save-match-data
  8118. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8119. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8120. ((string-match "%h" rpl)
  8121. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8122. (t (concat rpl tag)))))
  8123. link))
  8124. ;;; Storing and inserting links
  8125. (defvar org-insert-link-history nil
  8126. "Minibuffer history for links inserted with `org-insert-link'.")
  8127. (defvar org-stored-links nil
  8128. "Contains the links stored with `org-store-link'.")
  8129. (defvar org-store-link-plist nil
  8130. "Plist with info about the most recently link created with `org-store-link'.")
  8131. (defun org-store-link-functions ()
  8132. "Return a list of functions that are called to create and store a link.
  8133. The functions defined in the :store property of
  8134. `org-link-parameters'.
  8135. Each function will be called in turn until one returns a non-nil
  8136. value. Each function should check if it is responsible for
  8137. creating this link (for example by looking at the major mode).
  8138. If not, it must exit and return nil. If yes, it should return
  8139. a non-nil value after calling `org-store-link-props' with a list
  8140. of properties and values. Special properties are:
  8141. :type The link prefix, like \"http\". This must be given.
  8142. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8143. This is obligatory as well.
  8144. :description Optional default description for the second pair
  8145. of brackets in an Org mode link. The user can still change
  8146. this when inserting this link into an Org mode buffer.
  8147. In addition to these, any additional properties can be specified
  8148. and then used in capture templates."
  8149. (cl-loop for link in org-link-parameters
  8150. with store-func
  8151. do (setq store-func (org-link-get-parameter (car link) :store))
  8152. if store-func
  8153. collect store-func))
  8154. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8155. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8156. ;;;###autoload
  8157. (defun org-store-link (arg &optional interactive?)
  8158. "Store an org-link to the current location.
  8159. \\<org-mode-map>
  8160. This link is added to `org-stored-links' and can later be inserted
  8161. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8162. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8163. A single
  8164. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8165. `org-gnus-prefer-web-links' for links to Usenet articles.
  8166. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8167. skipping storing functions that are not
  8168. part of Org core.
  8169. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8170. prefix ARG forces storing a link for each line in the
  8171. active region.
  8172. Assume the function is called interactively if INTERACTIVE? is
  8173. non-nil."
  8174. (interactive "P\np")
  8175. (org-load-modules-maybe)
  8176. (if (and (equal arg '(64)) (org-region-active-p))
  8177. (save-excursion
  8178. (let ((end (region-end)))
  8179. (goto-char (region-beginning))
  8180. (set-mark (point))
  8181. (while (< (point-at-eol) end)
  8182. (move-end-of-line 1) (activate-mark)
  8183. (let (current-prefix-arg)
  8184. (call-interactively 'org-store-link))
  8185. (move-beginning-of-line 2)
  8186. (set-mark (point)))))
  8187. (setq org-store-link-plist nil)
  8188. (let (link cpltxt desc description search txt custom-id agenda-link)
  8189. (cond
  8190. ;; Store a link using an external link type, if any function is
  8191. ;; available. If more than one can generate a link from current
  8192. ;; location, ask which one to use.
  8193. ((and (not (equal arg '(16)))
  8194. (let ((results-alist nil))
  8195. (dolist (f (org-store-link-functions))
  8196. (when (funcall f)
  8197. ;; XXX: return value is not link's plist, so we
  8198. ;; store the new value before it is modified. It
  8199. ;; would be cleaner to ask store link functions to
  8200. ;; return the plist instead.
  8201. (push (cons f (copy-sequence org-store-link-plist))
  8202. results-alist)))
  8203. (pcase results-alist
  8204. (`nil nil)
  8205. (`((,_ . ,_)) t) ;single choice: nothing to do
  8206. (`((,name . ,_) . ,_)
  8207. ;; Reinstate link plist associated to the chosen
  8208. ;; function.
  8209. (apply #'org-store-link-props
  8210. (cdr (assoc-string
  8211. (completing-read
  8212. "Which function for creating the link? "
  8213. (mapcar #'car results-alist)
  8214. nil t (symbol-name name))
  8215. results-alist)))
  8216. t))))
  8217. (setq link (plist-get org-store-link-plist :link))
  8218. (setq desc (or (plist-get org-store-link-plist :description)
  8219. link)))
  8220. ;; Store a link from a source code buffer.
  8221. ((org-src-edit-buffer-p)
  8222. (let ((coderef-format (org-src-coderef-format)))
  8223. (cond ((org-match-line (org-src-coderef-regexp coderef-format))
  8224. (setq link (format "(%s)" (match-string-no-properties 3))))
  8225. (interactive?
  8226. (let ((label (read-string "Code line label: ")))
  8227. (end-of-line)
  8228. (setq link (format coderef-format label))
  8229. (let ((gc (- 79 (length link))))
  8230. (if (< (current-column) gc)
  8231. (org-move-to-column gc t)
  8232. (insert " ")))
  8233. (insert link)
  8234. (setq link (concat "(" label ")"))
  8235. (setq desc nil)))
  8236. (t (setq link nil)))))
  8237. ;; We are in the agenda, link to referenced location
  8238. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8239. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8240. (get-text-property (point) 'org-marker))))
  8241. (when m
  8242. (org-with-point-at m
  8243. (setq agenda-link (org-store-link nil interactive?))))))
  8244. ((eq major-mode 'calendar-mode)
  8245. (let ((cd (calendar-cursor-to-date)))
  8246. (setq link
  8247. (format-time-string
  8248. (car org-time-stamp-formats)
  8249. (apply 'encode-time
  8250. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8251. nil nil nil))))
  8252. (org-store-link-props :type "calendar" :date cd)))
  8253. ((eq major-mode 'help-mode)
  8254. (setq link (concat "help:" (save-excursion
  8255. (goto-char (point-min))
  8256. (looking-at "^[^ ]+")
  8257. (match-string 0))))
  8258. (org-store-link-props :type "help"))
  8259. ((eq major-mode 'w3-mode)
  8260. (setq cpltxt (if (and (buffer-name)
  8261. (not (string-match "Untitled" (buffer-name))))
  8262. (buffer-name)
  8263. (url-view-url t))
  8264. link (url-view-url t))
  8265. (org-store-link-props :type "w3" :url (url-view-url t)))
  8266. ((eq major-mode 'image-mode)
  8267. (setq cpltxt (concat "file:"
  8268. (abbreviate-file-name buffer-file-name))
  8269. link cpltxt)
  8270. (org-store-link-props :type "image" :file buffer-file-name))
  8271. ;; In dired, store a link to the file of the current line
  8272. ((derived-mode-p 'dired-mode)
  8273. (let ((file (dired-get-filename nil t)))
  8274. (setq file (if file
  8275. (abbreviate-file-name
  8276. (expand-file-name (dired-get-filename nil t)))
  8277. ;; otherwise, no file so use current directory.
  8278. default-directory))
  8279. (setq cpltxt (concat "file:" file)
  8280. link cpltxt)))
  8281. ((setq search (run-hook-with-args-until-success
  8282. 'org-create-file-search-functions))
  8283. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8284. "::" search))
  8285. (setq cpltxt (or description link)))
  8286. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8287. (org-with-limited-levels
  8288. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8289. (cond
  8290. ;; Store a link using the target at point
  8291. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8292. (setq cpltxt
  8293. (concat "file:"
  8294. (abbreviate-file-name
  8295. (buffer-file-name (buffer-base-buffer)))
  8296. "::" (match-string 1))
  8297. link cpltxt))
  8298. ((and (featurep 'org-id)
  8299. (or (eq org-id-link-to-org-use-id t)
  8300. (and interactive?
  8301. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8302. (and (eq org-id-link-to-org-use-id
  8303. 'create-if-interactive-and-no-custom-id)
  8304. (not custom-id))))
  8305. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8306. ;; Store a link using the ID at point
  8307. (setq link (condition-case nil
  8308. (prog1 (org-id-store-link)
  8309. (setq desc (or (plist-get org-store-link-plist
  8310. :description)
  8311. "")))
  8312. (error
  8313. ;; Probably before first headline, link only to file
  8314. (concat "file:"
  8315. (abbreviate-file-name
  8316. (buffer-file-name (buffer-base-buffer))))))))
  8317. (t
  8318. ;; Just link to current headline
  8319. (setq cpltxt (concat "file:"
  8320. (abbreviate-file-name
  8321. (buffer-file-name (buffer-base-buffer)))))
  8322. ;; Add a context search string
  8323. (when (org-xor org-context-in-file-links
  8324. (equal arg '(4)))
  8325. (let* ((element (org-element-at-point))
  8326. (name (org-element-property :name element)))
  8327. (setq txt (cond
  8328. ((org-at-heading-p) nil)
  8329. (name)
  8330. ((org-region-active-p)
  8331. (buffer-substring (region-beginning) (region-end)))))
  8332. (when (or (null txt) (string-match "\\S-" txt))
  8333. (setq cpltxt
  8334. (concat cpltxt "::"
  8335. (condition-case nil
  8336. (org-make-org-heading-search-string txt)
  8337. (error "")))
  8338. desc (or name
  8339. (nth 4 (ignore-errors (org-heading-components)))
  8340. "NONE")))))
  8341. (when (string-match "::\\'" cpltxt)
  8342. (setq cpltxt (substring cpltxt 0 -2)))
  8343. (setq link cpltxt)))))
  8344. ((buffer-file-name (buffer-base-buffer))
  8345. ;; Just link to this file here.
  8346. (setq cpltxt (concat "file:"
  8347. (abbreviate-file-name
  8348. (buffer-file-name (buffer-base-buffer)))))
  8349. ;; Add a context string.
  8350. (when (org-xor org-context-in-file-links
  8351. (equal arg '(4)))
  8352. (setq txt (if (org-region-active-p)
  8353. (buffer-substring (region-beginning) (region-end))
  8354. (buffer-substring (point-at-bol) (point-at-eol))))
  8355. ;; Only use search option if there is some text.
  8356. (when (string-match "\\S-" txt)
  8357. (setq cpltxt
  8358. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8359. desc "NONE")))
  8360. (setq link cpltxt))
  8361. (interactive?
  8362. (user-error "No method for storing a link from this buffer"))
  8363. (t (setq link nil)))
  8364. ;; We're done setting link and desc, clean up
  8365. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8366. (setq link (or link cpltxt)
  8367. desc (or desc cpltxt))
  8368. (cond ((not desc))
  8369. ((equal desc "NONE") (setq desc nil))
  8370. (t (setq desc
  8371. (replace-regexp-in-string
  8372. org-bracket-link-analytic-regexp
  8373. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8374. desc))))
  8375. ;; Return the link
  8376. (if (not (and interactive? link))
  8377. (or agenda-link (and link (org-make-link-string link desc)))
  8378. (push (list link desc) org-stored-links)
  8379. (message "Stored: %s" (or desc link))
  8380. (when custom-id
  8381. (setq link (concat "file:" (abbreviate-file-name
  8382. (buffer-file-name)) "::#" custom-id))
  8383. (push (list link desc) org-stored-links))
  8384. (car org-stored-links)))))
  8385. (defun org-store-link-props (&rest plist)
  8386. "Store link properties.
  8387. The properties are pre-processed by extracting names, addresses
  8388. and dates."
  8389. (let ((x (plist-get plist :from)))
  8390. (when x
  8391. (let ((adr (mail-extract-address-components x)))
  8392. (setq plist (plist-put plist :fromname (car adr)))
  8393. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8394. (let ((x (plist-get plist :to)))
  8395. (when x
  8396. (let ((adr (mail-extract-address-components x)))
  8397. (setq plist (plist-put plist :toname (car adr)))
  8398. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8399. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8400. (when x
  8401. (setq plist (plist-put plist :date-timestamp
  8402. (format-time-string
  8403. (org-time-stamp-format t) x)))
  8404. (setq plist (plist-put plist :date-timestamp-inactive
  8405. (format-time-string
  8406. (org-time-stamp-format t t) x)))))
  8407. (let ((from (plist-get plist :from))
  8408. (to (plist-get plist :to)))
  8409. (when (and from to org-from-is-user-regexp)
  8410. (setq plist
  8411. (plist-put plist :fromto
  8412. (if (string-match org-from-is-user-regexp from)
  8413. (concat "to %t")
  8414. (concat "from %f"))))))
  8415. (setq org-store-link-plist plist))
  8416. (defun org-add-link-props (&rest plist)
  8417. "Add these properties to the link property list."
  8418. (let (key value)
  8419. (while plist
  8420. (setq key (pop plist) value (pop plist))
  8421. (setq org-store-link-plist
  8422. (plist-put org-store-link-plist key value)))))
  8423. (defun org-email-link-description (&optional fmt)
  8424. "Return the description part of an email link.
  8425. This takes information from `org-store-link-plist' and formats it
  8426. according to FMT (default from `org-email-link-description-format')."
  8427. (setq fmt (or fmt org-email-link-description-format))
  8428. (let* ((p org-store-link-plist)
  8429. (to (plist-get p :toaddress))
  8430. (from (plist-get p :fromaddress))
  8431. (table
  8432. (list
  8433. (cons "%c" (plist-get p :fromto))
  8434. (cons "%F" (plist-get p :from))
  8435. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8436. (cons "%T" (plist-get p :to))
  8437. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8438. (cons "%s" (plist-get p :subject))
  8439. (cons "%d" (plist-get p :date))
  8440. (cons "%m" (plist-get p :message-id)))))
  8441. (when (string-match "%c" fmt)
  8442. ;; Check if the user wrote this message
  8443. (if (and org-from-is-user-regexp from to
  8444. (save-match-data (string-match org-from-is-user-regexp from)))
  8445. (setq fmt (replace-match "to %t" t t fmt))
  8446. (setq fmt (replace-match "from %f" t t fmt))))
  8447. (org-replace-escapes fmt table)))
  8448. (defun org-make-org-heading-search-string (&optional string)
  8449. "Make search string for the current headline or STRING."
  8450. (let ((s (or string
  8451. (and (derived-mode-p 'org-mode)
  8452. (save-excursion
  8453. (org-back-to-heading t)
  8454. (org-element-property :raw-value (org-element-at-point))))))
  8455. (lines org-context-in-file-links))
  8456. (unless string (setq s (concat "*" s))) ;Add * for headlines
  8457. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8458. (when (and string (integerp lines) (> lines 0))
  8459. (let ((slines (org-split-string s "\n")))
  8460. (when (< lines (length slines))
  8461. (setq s (mapconcat
  8462. 'identity
  8463. (reverse (nthcdr (- (length slines) lines)
  8464. (reverse slines))) "\n")))))
  8465. (mapconcat #'identity (split-string s) " ")))
  8466. (defconst org-link-escape-chars
  8467. ;;%20 %5B %5D %25
  8468. '(?\s ?\[ ?\] ?%)
  8469. "List of characters that should be escaped in a link when stored to Org.
  8470. This is the list that is used for internal purposes.")
  8471. (defun org-make-link-string (link &optional description)
  8472. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8473. (unless (org-string-nw-p link) (error "Empty link"))
  8474. (let ((uri (cond ((string-match org-link-types-re link)
  8475. (concat (match-string 1 link)
  8476. (org-link-escape (substring link (match-end 1)))))
  8477. ((or (file-name-absolute-p link)
  8478. (string-match-p "\\`\\.\\.?/" link))
  8479. (org-link-escape link))
  8480. ;; For readability, do not encode space characters
  8481. ;; in fuzzy links.
  8482. (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
  8483. (description
  8484. (and (org-string-nw-p description)
  8485. ;; Remove brackets from description, as they are fatal.
  8486. (replace-regexp-in-string
  8487. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8488. (org-trim description)))))
  8489. (format "[[%s]%s]"
  8490. uri
  8491. (if description (format "[%s]" description) ""))))
  8492. (defun org-link-escape (text &optional table merge)
  8493. "Return percent escaped representation of TEXT.
  8494. TEXT is a string with the text to escape.
  8495. Optional argument TABLE is a list with characters that should be
  8496. escaped. When nil, `org-link-escape-chars' is used.
  8497. If optional argument MERGE is set, merge TABLE into
  8498. `org-link-escape-chars'."
  8499. (let ((characters-to-encode
  8500. (cond ((null table) org-link-escape-chars)
  8501. (merge (append org-link-escape-chars table))
  8502. (t table))))
  8503. (mapconcat
  8504. (lambda (c)
  8505. (if (or (memq c characters-to-encode)
  8506. (and org-url-hexify-p (or (< c 32) (> c 126))))
  8507. (mapconcat (lambda (e) (format "%%%.2X" e))
  8508. (or (encode-coding-char c 'utf-8)
  8509. (error "Unable to percent escape character: %c" c))
  8510. "")
  8511. (char-to-string c)))
  8512. text "")))
  8513. (defun org-link-unescape (str)
  8514. "Unhex hexified Unicode parts in string STR.
  8515. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  8516. reciprocal of `org-link-escape', which see."
  8517. (if (org-string-nw-p str)
  8518. (replace-regexp-in-string
  8519. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  8520. str))
  8521. (defun org-link-unescape-compound (hex)
  8522. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  8523. Note: this function also decodes single byte encodings like
  8524. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  8525. (save-match-data
  8526. (let* ((bytes (cdr (split-string hex "%")))
  8527. (ret "")
  8528. (eat 0)
  8529. (sum 0))
  8530. (while bytes
  8531. (let* ((val (string-to-number (pop bytes) 16))
  8532. (shift-xor
  8533. (if (= 0 eat)
  8534. (cond
  8535. ((>= val 252) (cons 6 252))
  8536. ((>= val 248) (cons 5 248))
  8537. ((>= val 240) (cons 4 240))
  8538. ((>= val 224) (cons 3 224))
  8539. ((>= val 192) (cons 2 192))
  8540. (t (cons 0 0)))
  8541. (cons 6 128))))
  8542. (when (>= val 192) (setq eat (car shift-xor)))
  8543. (setq val (logxor val (cdr shift-xor)))
  8544. (setq sum (+ (lsh sum (car shift-xor)) val))
  8545. (when (> eat 0) (setq eat (- eat 1)))
  8546. (cond
  8547. ((= 0 eat) ;multi byte
  8548. (setq ret (concat ret (char-to-string sum)))
  8549. (setq sum 0))
  8550. ((not bytes) ; single byte(s)
  8551. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  8552. ret)))
  8553. (defun org-link-unescape-single-byte-sequence (hex)
  8554. "Unhexify hex-encoded single byte character sequences."
  8555. (mapconcat (lambda (byte)
  8556. (char-to-string (string-to-number byte 16)))
  8557. (cdr (split-string hex "%")) ""))
  8558. (defun org-fixup-message-id-for-http (s)
  8559. "Replace special characters in a message id, so it can be used in an http query."
  8560. (when (string-match "%" s)
  8561. (setq s (mapconcat (lambda (c)
  8562. (if (eq c ?%)
  8563. "%25"
  8564. (char-to-string c)))
  8565. s "")))
  8566. (while (string-match "<" s)
  8567. (setq s (replace-match "%3C" t t s)))
  8568. (while (string-match ">" s)
  8569. (setq s (replace-match "%3E" t t s)))
  8570. (while (string-match "@" s)
  8571. (setq s (replace-match "%40" t t s)))
  8572. s)
  8573. (defun org-link-prettify (link)
  8574. "Return a human-readable representation of LINK.
  8575. The car of LINK must be a raw link.
  8576. The cdr of LINK must be either a link description or nil."
  8577. (let ((desc (or (cadr link) "<no description>")))
  8578. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  8579. "<" (car link) ">")))
  8580. ;;;###autoload
  8581. (defun org-insert-link-global ()
  8582. "Insert a link like Org mode does.
  8583. This command can be called in any mode to insert a link in Org syntax."
  8584. (interactive)
  8585. (org-load-modules-maybe)
  8586. (org-run-like-in-org-mode 'org-insert-link))
  8587. (defun org-insert-all-links (arg &optional pre post)
  8588. "Insert all links in `org-stored-links'.
  8589. When a universal prefix, do not delete the links from `org-stored-links'.
  8590. When `ARG' is a number, insert the last N link(s).
  8591. `PRE' and `POST' are optional arguments to define a string to
  8592. prepend or to append."
  8593. (interactive "P")
  8594. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  8595. (links (copy-sequence org-stored-links))
  8596. (pr (or pre "- "))
  8597. (po (or post "\n"))
  8598. (cnt 1) l)
  8599. (if (null org-stored-links)
  8600. (message "No link to insert")
  8601. (while (and (or (listp arg) (>= arg cnt))
  8602. (setq l (if (listp arg)
  8603. (pop links)
  8604. (pop org-stored-links))))
  8605. (setq cnt (1+ cnt))
  8606. (insert pr)
  8607. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  8608. (insert po)))))
  8609. (defun org-insert-last-stored-link (arg)
  8610. "Insert the last link stored in `org-stored-links'."
  8611. (interactive "p")
  8612. (org-insert-all-links arg "" "\n"))
  8613. (defun org-link-fontify-links-to-this-file ()
  8614. "Fontify links to the current file in `org-stored-links'."
  8615. (let ((f (buffer-file-name)) a b)
  8616. (setq a (mapcar (lambda(l)
  8617. (let ((ll (car l)))
  8618. (when (and (string-match "^file:\\(.+\\)::" ll)
  8619. (equal f (expand-file-name (match-string 1 ll))))
  8620. ll)))
  8621. org-stored-links))
  8622. (when (featurep 'org-id)
  8623. (setq b (mapcar (lambda(l)
  8624. (let ((ll (car l)))
  8625. (when (and (string-match "^id:\\(.+\\)$" ll)
  8626. (equal f (expand-file-name
  8627. (or (org-id-find-id-file
  8628. (match-string 1 ll)) ""))))
  8629. ll)))
  8630. org-stored-links)))
  8631. (mapcar (lambda(l)
  8632. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  8633. (delq nil (append a b)))))
  8634. (defvar org--links-history nil)
  8635. (defun org-insert-link (&optional complete-file link-location default-description)
  8636. "Insert a link. At the prompt, enter the link.
  8637. Completion can be used to insert any of the link protocol prefixes in use.
  8638. The history can be used to select a link previously stored with
  8639. `org-store-link'. When the empty string is entered (i.e. if you just
  8640. press `RET' at the prompt), the link defaults to the most recently
  8641. stored link. As `SPC' triggers completion in the minibuffer, you need to
  8642. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  8643. You will also be prompted for a description, and if one is given, it will
  8644. be displayed in the buffer instead of the link.
  8645. If there is already a link at point, this command will allow you to edit
  8646. link and description parts.
  8647. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  8648. file name can be
  8649. selected using completion. The path to the file will be relative to the
  8650. current directory if the file is in the current directory or a subdirectory.
  8651. Otherwise, the link will be the absolute path as completed in the minibuffer
  8652. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  8653. option `org-link-file-path-type'.
  8654. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  8655. absolute path even if the file is in
  8656. the current directory or below.
  8657. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8658. prefix negates `org-keep-stored-link-after-insertion'.
  8659. If the LINK-LOCATION parameter is non-nil, this value will be used as
  8660. the link location instead of reading one interactively.
  8661. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  8662. be used as the default description. Otherwise, if
  8663. `org-make-link-description-function' is non-nil, this function
  8664. will be called with the link target, and the result will be the
  8665. default link description. When called non-interactivily, don't
  8666. allow to edit the default description."
  8667. (interactive "P")
  8668. (let* ((wcf (current-window-configuration))
  8669. (origbuf (current-buffer))
  8670. (region (when (org-region-active-p)
  8671. (buffer-substring (region-beginning) (region-end))))
  8672. (remove (and region (list (region-beginning) (region-end))))
  8673. (desc region)
  8674. (link link-location)
  8675. (abbrevs org-link-abbrev-alist-local)
  8676. entry all-prefixes auto-desc)
  8677. (cond
  8678. (link-location) ; specified by arg, just use it.
  8679. ((org-in-regexp org-bracket-link-regexp 1)
  8680. ;; We do have a link at point, and we are going to edit it.
  8681. (setq remove (list (match-beginning 0) (match-end 0)))
  8682. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  8683. (setq link (read-string "Link: "
  8684. (org-link-unescape
  8685. (match-string-no-properties 1)))))
  8686. ((or (org-in-regexp org-angle-link-re)
  8687. (org-in-regexp org-plain-link-re))
  8688. ;; Convert to bracket link
  8689. (setq remove (list (match-beginning 0) (match-end 0))
  8690. link (read-string "Link: "
  8691. (org-unbracket-string "<" ">" (match-string 0)))))
  8692. ((member complete-file '((4) (16)))
  8693. ;; Completing read for file names.
  8694. (setq link (org-file-complete-link complete-file)))
  8695. (t
  8696. ;; Read link, with completion for stored links.
  8697. (org-link-fontify-links-to-this-file)
  8698. (org-switch-to-buffer-other-window "*Org Links*")
  8699. (with-current-buffer "*Org Links*"
  8700. (erase-buffer)
  8701. (insert "Insert a link.
  8702. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  8703. (when org-stored-links
  8704. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  8705. (insert (mapconcat 'org-link-prettify
  8706. (reverse org-stored-links) "\n")))
  8707. (goto-char (point-min)))
  8708. (let ((cw (selected-window)))
  8709. (select-window (get-buffer-window "*Org Links*" 'visible))
  8710. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  8711. (unless (pos-visible-in-window-p (point-max))
  8712. (org-fit-window-to-buffer))
  8713. (and (window-live-p cw) (select-window cw)))
  8714. (setq all-prefixes (append (mapcar 'car abbrevs)
  8715. (mapcar 'car org-link-abbrev-alist)
  8716. (org-link-types)))
  8717. (unwind-protect
  8718. ;; Fake a link history, containing the stored links.
  8719. (let ((org--links-history
  8720. (append (mapcar #'car org-stored-links)
  8721. org-insert-link-history)))
  8722. (setq link
  8723. (org-completing-read
  8724. "Link: "
  8725. (append
  8726. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  8727. (mapcar #'car org-stored-links))
  8728. nil nil nil
  8729. 'org--links-history
  8730. (caar org-stored-links)))
  8731. (unless (org-string-nw-p link) (user-error "No link selected"))
  8732. (dolist (l org-stored-links)
  8733. (when (equal link (cadr l))
  8734. (setq link (car l))
  8735. (setq auto-desc t)))
  8736. (when (or (member link all-prefixes)
  8737. (and (equal ":" (substring link -1))
  8738. (member (substring link 0 -1) all-prefixes)
  8739. (setq link (substring link 0 -1))))
  8740. (setq link (with-current-buffer origbuf
  8741. (org-link-try-special-completion link)))))
  8742. (set-window-configuration wcf)
  8743. (kill-buffer "*Org Links*"))
  8744. (setq entry (assoc link org-stored-links))
  8745. (or entry (push link org-insert-link-history))
  8746. (setq desc (or desc (nth 1 entry)))))
  8747. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  8748. (not org-keep-stored-link-after-insertion))
  8749. (setq org-stored-links (delq (assoc link org-stored-links)
  8750. org-stored-links)))
  8751. (when (and (string-match org-plain-link-re link)
  8752. (not (string-match org-ts-regexp link)))
  8753. ;; URL-like link, normalize the use of angular brackets.
  8754. (setq link (org-unbracket-string "<" ">" link)))
  8755. ;; Check if we are linking to the current file with a search
  8756. ;; option If yes, simplify the link by using only the search
  8757. ;; option.
  8758. (when (and buffer-file-name
  8759. (let ((case-fold-search nil))
  8760. (string-match "\\`file:\\(.+?\\)::" link)))
  8761. (let ((path (match-string-no-properties 1 link))
  8762. (search (substring-no-properties link (match-end 0))))
  8763. (save-match-data
  8764. (when (equal (file-truename buffer-file-name) (file-truename path))
  8765. ;; We are linking to this same file, with a search option
  8766. (setq link search)))))
  8767. ;; Check if we can/should use a relative path. If yes, simplify
  8768. ;; the link.
  8769. (let ((case-fold-search nil))
  8770. (when (string-match "\\`\\(file\\|docview\\):" link)
  8771. (let* ((type (match-string-no-properties 0 link))
  8772. (path-start (match-end 0))
  8773. (search (and (string-match "::\\(.*\\)\\'" link)
  8774. (match-string 1 link)))
  8775. (path
  8776. (if search
  8777. (substring-no-properties
  8778. link path-start (match-beginning 0))
  8779. (substring-no-properties link (match-end 0))))
  8780. (origpath path))
  8781. (cond
  8782. ((or (eq org-link-file-path-type 'absolute)
  8783. (equal complete-file '(16)))
  8784. (setq path (abbreviate-file-name (expand-file-name path))))
  8785. ((eq org-link-file-path-type 'noabbrev)
  8786. (setq path (expand-file-name path)))
  8787. ((eq org-link-file-path-type 'relative)
  8788. (setq path (file-relative-name path)))
  8789. (t
  8790. (save-match-data
  8791. (if (string-match (concat "^" (regexp-quote
  8792. (expand-file-name
  8793. (file-name-as-directory
  8794. default-directory))))
  8795. (expand-file-name path))
  8796. ;; We are linking a file with relative path name.
  8797. (setq path (substring (expand-file-name path)
  8798. (match-end 0)))
  8799. (setq path (abbreviate-file-name (expand-file-name path)))))))
  8800. (setq link (concat type path (and search (concat "::" search))))
  8801. (when (equal desc origpath)
  8802. (setq desc path)))))
  8803. (unless auto-desc
  8804. (let ((initial-input
  8805. (cond
  8806. (default-description)
  8807. ((not org-make-link-description-function) desc)
  8808. (t (condition-case nil
  8809. (funcall org-make-link-description-function link desc)
  8810. (error
  8811. (message "Can't get link description from `%s'"
  8812. (symbol-name org-make-link-description-function))
  8813. (sit-for 2)
  8814. nil))))))
  8815. (setq desc (if (called-interactively-p 'any)
  8816. (read-string "Description: " initial-input)
  8817. initial-input))))
  8818. (unless (string-match "\\S-" desc) (setq desc nil))
  8819. (when remove (apply 'delete-region remove))
  8820. (insert (org-make-link-string link desc))
  8821. ;; Redisplay so as the new link has proper invisible characters.
  8822. (sit-for 0)))
  8823. (defun org-link-try-special-completion (type)
  8824. "If there is completion support for link type TYPE, offer it."
  8825. (let ((fun (org-link-get-parameter type :complete)))
  8826. (if (functionp fun)
  8827. (funcall fun)
  8828. (read-string "Link (no completion support): " (concat type ":")))))
  8829. (defun org-file-complete-link (&optional arg)
  8830. "Create a file link using completion."
  8831. (let ((file (read-file-name "File: "))
  8832. (pwd (file-name-as-directory (expand-file-name ".")))
  8833. (pwd1 (file-name-as-directory (abbreviate-file-name
  8834. (expand-file-name ".")))))
  8835. (cond ((equal arg '(16))
  8836. (concat "file:"
  8837. (abbreviate-file-name (expand-file-name file))))
  8838. ((string-match
  8839. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  8840. (concat "file:" (match-string 1 file)))
  8841. ((string-match
  8842. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  8843. (expand-file-name file))
  8844. (concat "file:"
  8845. (match-string 1 (expand-file-name file))))
  8846. (t (concat "file:" file)))))
  8847. ;;; Opening/following a link
  8848. (defvar org-link-search-failed nil)
  8849. (defvar org-open-link-functions nil
  8850. "Hook for functions finding a plain text link.
  8851. These functions must take a single argument, the link content.
  8852. They will be called for links that look like [[link text][description]]
  8853. when LINK TEXT does not have a protocol like \"http:\" and does not look
  8854. like a filename (e.g. \"./blue.png\").
  8855. These functions will be called *before* Org attempts to resolve the
  8856. link by doing text searches in the current buffer - so if you want a
  8857. link \"[[target]]\" to still find \"<<target>>\", your function should
  8858. handle this as a special case.
  8859. When the function does handle the link, it must return a non-nil value.
  8860. If it decides that it is not responsible for this link, it must return
  8861. nil to indicate that that Org can continue with other options like
  8862. exact and fuzzy text search.")
  8863. (defun org-next-link (&optional search-backward)
  8864. "Move forward to the next link.
  8865. If the link is in hidden text, expose it."
  8866. (interactive "P")
  8867. (when (and org-link-search-failed (eq this-command last-command))
  8868. (goto-char (point-min))
  8869. (message "Link search wrapped back to beginning of buffer"))
  8870. (setq org-link-search-failed nil)
  8871. (let* ((pos (point))
  8872. (ct (org-context))
  8873. (a (assq :link ct))
  8874. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  8875. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  8876. ((looking-at org-any-link-re)
  8877. ;; Don't stay stuck at link without an org-link face
  8878. (forward-char (if search-backward -1 1))))
  8879. (if (funcall srch-fun org-any-link-re nil t)
  8880. (progn
  8881. (goto-char (match-beginning 0))
  8882. (when (org-invisible-p) (org-show-context)))
  8883. (goto-char pos)
  8884. (setq org-link-search-failed t)
  8885. (message "No further link found"))))
  8886. (defun org-previous-link ()
  8887. "Move backward to the previous link.
  8888. If the link is in hidden text, expose it."
  8889. (interactive)
  8890. (funcall 'org-next-link t))
  8891. (defun org-translate-link (s)
  8892. "Translate a link string if a translation function has been defined."
  8893. (with-temp-buffer
  8894. (insert (org-trim s))
  8895. (org-trim (org-element-interpret-data (org-element-context)))))
  8896. (defun org-translate-link-from-planner (type path)
  8897. "Translate a link from Emacs Planner syntax so that Org can follow it.
  8898. This is still an experimental function, your mileage may vary."
  8899. (cond
  8900. ((member type '("http" "https" "news" "ftp"))
  8901. ;; standard Internet links are the same.
  8902. nil)
  8903. ((and (equal type "irc") (string-match "^//" path))
  8904. ;; Planner has two / at the beginning of an irc link, we have 1.
  8905. ;; We should have zero, actually....
  8906. (setq path (substring path 1)))
  8907. ((and (equal type "lisp") (string-match "^/" path))
  8908. ;; Planner has a slash, we do not.
  8909. (setq type "elisp" path (substring path 1)))
  8910. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  8911. ;; A typical message link. Planner has the id after the final slash,
  8912. ;; we separate it with a hash mark
  8913. (setq path (concat (match-string 1 path) "#"
  8914. (org-unbracket-string "<" ">" (match-string 2 path))))))
  8915. (cons type path))
  8916. (defun org-find-file-at-mouse (ev)
  8917. "Open file link or URL at mouse."
  8918. (interactive "e")
  8919. (mouse-set-point ev)
  8920. (org-open-at-point 'in-emacs))
  8921. (defun org-open-at-mouse (ev)
  8922. "Open file link or URL at mouse.
  8923. See the docstring of `org-open-file' for details."
  8924. (interactive "e")
  8925. (mouse-set-point ev)
  8926. (when (eq major-mode 'org-agenda-mode)
  8927. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  8928. (org-open-at-point))
  8929. (defvar org-window-config-before-follow-link nil
  8930. "The window configuration before following a link.
  8931. This is saved in case the need arises to restore it.")
  8932. ;;;###autoload
  8933. (defun org-open-at-point-global ()
  8934. "Follow a link or a time-stamp like Org mode does.
  8935. Also follow links and emails as seen by `thing-at-point'.
  8936. This command can be called in any mode to follow an external
  8937. link or a time-stamp that has Org mode syntax. Its behavior
  8938. is undefined when called on internal links like fuzzy links.
  8939. Raise a user error when there is nothing to follow."
  8940. (interactive)
  8941. (let ((tap-url (thing-at-point 'url))
  8942. (tap-email (thing-at-point 'email)))
  8943. (cond ((org-in-regexp org-any-link-re)
  8944. (org-open-link-from-string (match-string-no-properties 0)))
  8945. ((or (org-in-regexp org-ts-regexp-both nil t)
  8946. (org-in-regexp org-tsr-regexp-both nil t))
  8947. (org-follow-timestamp-link))
  8948. (tap-url (org-open-link-from-string tap-url))
  8949. (tap-email (org-open-link-from-string
  8950. (concat "mailto:" tap-email)))
  8951. (t (user-error "No link found")))))
  8952. ;;;###autoload
  8953. (defun org-open-link-from-string (s &optional arg reference-buffer)
  8954. "Open a link in the string S, as if it was in Org mode."
  8955. (interactive "sLink: \nP")
  8956. (let ((reference-buffer (or reference-buffer (current-buffer))))
  8957. (with-temp-buffer
  8958. (let ((org-inhibit-startup (not reference-buffer)))
  8959. (org-mode)
  8960. (insert s)
  8961. (goto-char (point-min))
  8962. (when reference-buffer
  8963. (setq org-link-abbrev-alist-local
  8964. (with-current-buffer reference-buffer
  8965. org-link-abbrev-alist-local)))
  8966. (org-open-at-point arg reference-buffer)))))
  8967. (defvar org-open-at-point-functions nil
  8968. "Hook that is run when following a link at point.
  8969. Functions in this hook must return t if they identify and follow
  8970. a link at point. If they don't find anything interesting at point,
  8971. they must return nil.")
  8972. (defvar org-link-search-inhibit-query nil)
  8973. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  8974. (defun org--open-doi-link (path)
  8975. "Open a \"doi\" type link.
  8976. PATH is a the path to search for, as a string."
  8977. (browse-url (url-encode-url (concat org-doi-server-url path))))
  8978. (defun org--open-elisp-link (path)
  8979. "Open a \"elisp\" type link.
  8980. PATH is the sexp to evaluate, as a string."
  8981. (let ((cmd path))
  8982. (if (or (and (org-string-nw-p
  8983. org-confirm-elisp-link-not-regexp)
  8984. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  8985. (not org-confirm-elisp-link-function)
  8986. (funcall org-confirm-elisp-link-function
  8987. (format "Execute \"%s\" as elisp? "
  8988. (org-add-props cmd nil 'face 'org-warning))))
  8989. (message "%s => %s" cmd
  8990. (if (eq (string-to-char cmd) ?\()
  8991. (eval (read cmd))
  8992. (call-interactively (read cmd))))
  8993. (user-error "Abort"))))
  8994. (defun org--open-help-link (path)
  8995. "Open a \"help\" type link.
  8996. PATH is a symbol name, as a string."
  8997. (pcase (intern path)
  8998. ((and (pred fboundp) variable) (describe-function variable))
  8999. ((and (pred boundp) function) (describe-variable function))
  9000. (name (user-error "Unknown function or variable: %s" name))))
  9001. (defun org--open-shell-link (path)
  9002. "Open a \"shell\" type link.
  9003. PATH is the command to execute, as a string."
  9004. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9005. (cmd path))
  9006. (if (or (and (org-string-nw-p
  9007. org-confirm-shell-link-not-regexp)
  9008. (string-match
  9009. org-confirm-shell-link-not-regexp cmd))
  9010. (not org-confirm-shell-link-function)
  9011. (funcall org-confirm-shell-link-function
  9012. (format "Execute \"%s\" in shell? "
  9013. (org-add-props cmd nil
  9014. 'face 'org-warning))))
  9015. (progn
  9016. (message "Executing %s" cmd)
  9017. (shell-command cmd buf)
  9018. (when (featurep 'midnight)
  9019. (setq clean-buffer-list-kill-buffer-names
  9020. (cons (buffer-name buf)
  9021. clean-buffer-list-kill-buffer-names))))
  9022. (user-error "Abort"))))
  9023. (defun org-open-at-point (&optional arg reference-buffer)
  9024. "Open link, timestamp, footnote or tags at point.
  9025. When point is on a link, follow it. Normally, files will be
  9026. opened by an appropriate application. If the optional prefix
  9027. argument ARG is non-nil, Emacs will visit the file. With
  9028. a double prefix argument, try to open outside of Emacs, in the
  9029. application the system uses for this file type.
  9030. When point is on a timestamp, open the agenda at the day
  9031. specified.
  9032. When point is a footnote definition, move to the first reference
  9033. found. If it is on a reference, move to the associated
  9034. definition.
  9035. When point is on a headline, display a list of every link in the
  9036. entry, so it is possible to pick one, or all, of them. If point
  9037. is on a tag, call `org-tags-view' instead.
  9038. When optional argument REFERENCE-BUFFER is non-nil, it should
  9039. specify a buffer from where the link search should happen. This
  9040. is used internally by `org-open-link-from-string'.
  9041. On top of syntactically correct links, this function will also
  9042. try to open links and time-stamps in comments, example
  9043. blocks... i.e., whenever point is on something looking like
  9044. a timestamp or a link."
  9045. (interactive "P")
  9046. ;; On a code block, open block's results.
  9047. (unless (call-interactively 'org-babel-open-src-block-result)
  9048. (org-load-modules-maybe)
  9049. (setq org-window-config-before-follow-link (current-window-configuration))
  9050. (org-remove-occur-highlights nil nil t)
  9051. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9052. (let* ((context
  9053. ;; Only consider supported types, even if they are not
  9054. ;; the closest one.
  9055. (org-element-lineage
  9056. (org-element-context)
  9057. '(clock footnote-definition footnote-reference headline
  9058. inlinetask link timestamp)
  9059. t))
  9060. (type (org-element-type context))
  9061. (value (org-element-property :value context)))
  9062. (cond
  9063. ;; On a headline or an inlinetask, but not on a timestamp,
  9064. ;; a link, a footnote reference.
  9065. ((memq type '(headline inlinetask))
  9066. (org-match-line org-complex-heading-regexp)
  9067. (if (and (match-beginning 5)
  9068. (>= (point) (match-beginning 5))
  9069. (< (point) (match-end 5)))
  9070. ;; On tags.
  9071. (org-tags-view arg (substring (match-string 5) 0 -1))
  9072. ;; Not on tags.
  9073. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  9074. (`(nil . ,_)
  9075. (require 'org-attach)
  9076. (org-attach-reveal 'if-exists))
  9077. (`(,links . ,links-end)
  9078. (dolist (link (if (stringp links) (list links) links))
  9079. (search-forward link nil links-end)
  9080. (goto-char (match-beginning 0))
  9081. (org-open-at-point))))))
  9082. ;; On a footnote reference or at definition's label.
  9083. ((or (eq type 'footnote-reference)
  9084. (and (eq type 'footnote-definition)
  9085. (save-excursion
  9086. ;; Do not validate action when point is on the
  9087. ;; spaces right after the footnote label, in
  9088. ;; order to be on par with behavior on links.
  9089. (skip-chars-forward " \t")
  9090. (let ((begin
  9091. (org-element-property :contents-begin context)))
  9092. (if begin (< (point) begin)
  9093. (= (org-element-property :post-affiliated context)
  9094. (line-beginning-position)))))))
  9095. (org-footnote-action))
  9096. ;; No valid context. Ignore catch-all types like `headline'.
  9097. ;; If point is on something looking like a link or
  9098. ;; a time-stamp, try opening it. It may be useful in
  9099. ;; comments, example blocks...
  9100. ((memq type '(footnote-definition headline inlinetask nil))
  9101. (call-interactively #'org-open-at-point-global))
  9102. ;; On a clock line, make sure point is on the timestamp
  9103. ;; before opening it.
  9104. ((and (eq type 'clock)
  9105. value
  9106. (>= (point) (org-element-property :begin value))
  9107. (<= (point) (org-element-property :end value)))
  9108. (org-follow-timestamp-link))
  9109. ;; Do nothing on white spaces after an object.
  9110. ((>= (point)
  9111. (save-excursion
  9112. (goto-char (org-element-property :end context))
  9113. (skip-chars-backward " \t")
  9114. (point)))
  9115. (user-error "No link found"))
  9116. ((eq type 'timestamp) (org-follow-timestamp-link))
  9117. ((eq type 'link)
  9118. (let ((type (org-element-property :type context))
  9119. (path (org-link-unescape (org-element-property :path context))))
  9120. ;; Switch back to REFERENCE-BUFFER needed when called in
  9121. ;; a temporary buffer through `org-open-link-from-string'.
  9122. (with-current-buffer (or reference-buffer (current-buffer))
  9123. (cond
  9124. ((equal type "file")
  9125. (if (string-match "[*?{]" (file-name-nondirectory path))
  9126. (dired path)
  9127. ;; Look into `org-link-parameters' in order to find
  9128. ;; a DEDICATED-FUNCTION to open file. The function
  9129. ;; will be applied on raw link instead of parsed
  9130. ;; link due to the limitation in `org-add-link-type'
  9131. ;; ("open" function called with a single argument).
  9132. ;; If no such function is found, fallback to
  9133. ;; `org-open-file'.
  9134. (let* ((option (org-element-property :search-option context))
  9135. (app (org-element-property :application context))
  9136. (dedicated-function
  9137. (org-link-get-parameter
  9138. (if app (concat type "+" app) type)
  9139. :follow)))
  9140. (if dedicated-function
  9141. (funcall dedicated-function
  9142. (concat path
  9143. (and option (concat "::" option))))
  9144. (apply #'org-open-file
  9145. path
  9146. (cond (arg)
  9147. ((equal app "emacs") 'emacs)
  9148. ((equal app "sys") 'system))
  9149. (cond ((not option) nil)
  9150. ((string-match-p "\\`[0-9]+\\'" option)
  9151. (list (string-to-number option)))
  9152. (t (list nil
  9153. (org-link-unescape option)))))))))
  9154. ((functionp (org-link-get-parameter type :follow))
  9155. (funcall (org-link-get-parameter type :follow) path))
  9156. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9157. (unless (run-hook-with-args-until-success
  9158. 'org-open-link-functions path)
  9159. (if (not arg) (org-mark-ring-push)
  9160. (switch-to-buffer-other-window
  9161. (org-get-buffer-for-internal-link (current-buffer))))
  9162. (let ((destination
  9163. (org-with-wide-buffer
  9164. (if (equal type "radio")
  9165. (org-search-radio-target
  9166. (org-element-property :path context))
  9167. (org-link-search
  9168. (if (member type '("custom-id" "coderef"))
  9169. (org-element-property :raw-link context)
  9170. path)
  9171. ;; Prevent fuzzy links from matching
  9172. ;; themselves.
  9173. (and (equal type "fuzzy")
  9174. (+ 2 (org-element-property :begin context)))))
  9175. (point))))
  9176. (unless (and (<= (point-min) destination)
  9177. (>= (point-max) destination))
  9178. (widen))
  9179. (goto-char destination))))
  9180. (t (browse-url-at-point))))))
  9181. (t (user-error "No link found")))))
  9182. (run-hook-with-args 'org-follow-link-hook)))
  9183. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9184. "Offer links in the current entry and return the selected link.
  9185. If there is only one link, return it.
  9186. If NTH is an integer, return the NTH link found.
  9187. If ZERO is a string, check also this string for a link, and if
  9188. there is one, return it."
  9189. (with-current-buffer buffer
  9190. (org-with-wide-buffer
  9191. (goto-char marker)
  9192. (let ((cnt ?0)
  9193. have-zero end links link c)
  9194. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9195. (push (match-string 0 zero) links)
  9196. (setq cnt (1- cnt) have-zero t))
  9197. (save-excursion
  9198. (org-back-to-heading t)
  9199. (setq end (save-excursion (outline-next-heading) (point)))
  9200. (while (re-search-forward org-any-link-re end t)
  9201. (push (match-string 0) links))
  9202. (setq links (org-uniquify (reverse links))))
  9203. (cond
  9204. ((null links)
  9205. (message "No links"))
  9206. ((equal (length links) 1)
  9207. (setq link (car links)))
  9208. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9209. (setq link (nth (if have-zero nth (1- nth)) links)))
  9210. (t ; we have to select a link
  9211. (save-excursion
  9212. (save-window-excursion
  9213. (delete-other-windows)
  9214. (with-output-to-temp-buffer "*Select Link*"
  9215. (dolist (l links)
  9216. (cond
  9217. ((not (string-match org-bracket-link-regexp l))
  9218. (princ (format "[%c] %s\n" (cl-incf cnt)
  9219. (org-unbracket-string "<" ">" l))))
  9220. ((match-end 3)
  9221. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9222. (match-string 3 l) (match-string 1 l))))
  9223. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9224. (match-string 1 l)))))))
  9225. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9226. (message "Select link to open, RET to open all:")
  9227. (setq c (read-char-exclusive))
  9228. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9229. (when (equal c ?q) (user-error "Abort"))
  9230. (if (equal c ?\C-m)
  9231. (setq link links)
  9232. (setq nth (- c ?0))
  9233. (when have-zero (setq nth (1+ nth)))
  9234. (unless (and (integerp nth) (>= (length links) nth))
  9235. (user-error "Invalid link selection"))
  9236. (setq link (nth (1- nth) links)))))
  9237. (cons link end)))))
  9238. ;; TODO: These functions are deprecated since `org-open-at-point'
  9239. ;; hard-codes behavior for "file+emacs" and "file+sys" types.
  9240. (defun org-open-file-with-system (path)
  9241. "Open file at PATH using the system way of opening it."
  9242. (org-open-file path 'system))
  9243. (defun org-open-file-with-emacs (path)
  9244. "Open file at PATH in Emacs."
  9245. (org-open-file path 'emacs))
  9246. ;;; File search
  9247. (defvar org-create-file-search-functions nil
  9248. "List of functions to construct the right search string for a file link.
  9249. These functions are called in turn with point at the location to
  9250. which the link should point.
  9251. A function in the hook should first test if it would like to
  9252. handle this file type, for example by checking the `major-mode'
  9253. or the file extension. If it decides not to handle this file, it
  9254. should just return nil to give other functions a chance. If it
  9255. does handle the file, it must return the search string to be used
  9256. when following the link. The search string will be part of the
  9257. file link, given after a double colon, and `org-open-at-point'
  9258. will automatically search for it. If special measures must be
  9259. taken to make the search successful, another function should be
  9260. added to the companion hook `org-execute-file-search-functions',
  9261. which see.
  9262. A function in this hook may also use `setq' to set the variable
  9263. `description' to provide a suggestion for the descriptive text to
  9264. be used for this link when it gets inserted into an Org buffer
  9265. with \\[org-insert-link].")
  9266. (defvar org-execute-file-search-functions nil
  9267. "List of functions to execute a file search triggered by a link.
  9268. Functions added to this hook must accept a single argument, the
  9269. search string that was part of the file link, the part after the
  9270. double colon. The function must first check if it would like to
  9271. handle this search, for example by checking the `major-mode' or
  9272. the file extension. If it decides not to handle this search, it
  9273. should just return nil to give other functions a chance. If it
  9274. does handle the search, it must return a non-nil value to keep
  9275. other functions from trying.
  9276. Each function can access the current prefix argument through the
  9277. variable `current-prefix-arg'. Note that a single prefix is used
  9278. to force opening a link in Emacs, so it may be good to only use a
  9279. numeric or double prefix to guide the search function.
  9280. In case this is needed, a function in this hook can also restore
  9281. the window configuration before `org-open-at-point' was called using:
  9282. (set-window-configuration org-window-config-before-follow-link)")
  9283. (defun org-search-radio-target (target)
  9284. "Search a radio target matching TARGET in current buffer.
  9285. White spaces are not significant."
  9286. (let ((re (format "<<<%s>>>"
  9287. (mapconcat #'regexp-quote
  9288. (split-string target)
  9289. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9290. (origin (point)))
  9291. (goto-char (point-min))
  9292. (catch :radio-match
  9293. (while (re-search-forward re nil t)
  9294. (backward-char)
  9295. (let ((object (org-element-context)))
  9296. (when (eq (org-element-type object) 'radio-target)
  9297. (goto-char (org-element-property :begin object))
  9298. (org-show-context 'link-search)
  9299. (throw :radio-match nil))))
  9300. (goto-char origin)
  9301. (user-error "No match for radio target: %s" target))))
  9302. (defun org-link-search (s &optional avoid-pos stealth)
  9303. "Search for a search string S.
  9304. If S starts with \"#\", it triggers a custom ID search.
  9305. If S is enclosed within parenthesis, it initiates a coderef
  9306. search.
  9307. If S is surrounded by forward slashes, it is interpreted as
  9308. a regular expression. In Org mode files, this will create an
  9309. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9310. to list matches. If the current buffer is in `dired-mode', grep
  9311. will be used to search in all files.
  9312. When AVOID-POS is given, ignore matches near that position.
  9313. When optional argument STEALTH is non-nil, do not modify
  9314. visibility around point, thus ignoring `org-show-context-detail'
  9315. variable.
  9316. Search is case-insensitive and ignores white spaces. Return type
  9317. of matched result, which is either `dedicated' or `fuzzy'."
  9318. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9319. (let* ((case-fold-search t)
  9320. (origin (point))
  9321. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9322. (starred (eq (string-to-char normalized) ?*))
  9323. (words (split-string (if starred (substring s 1) s)))
  9324. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9325. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9326. type)
  9327. (cond
  9328. ;; Check if there are any special search functions.
  9329. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9330. ((eq (string-to-char s) ?#)
  9331. ;; Look for a custom ID S if S starts with "#".
  9332. (let* ((id (substring normalized 1))
  9333. (match (org-find-property "CUSTOM_ID" id)))
  9334. (if match (progn (goto-char match) (setf type 'dedicated))
  9335. (error "No match for custom ID: %s" id))))
  9336. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9337. ;; Look for coderef targets if S is enclosed within parenthesis.
  9338. (let ((coderef (match-string-no-properties 1 normalized))
  9339. (re (substring s-single-re 1 -1)))
  9340. (goto-char (point-min))
  9341. (catch :coderef-match
  9342. (while (re-search-forward re nil t)
  9343. (let ((element (org-element-at-point)))
  9344. (when (and (memq (org-element-type element)
  9345. '(example-block src-block))
  9346. ;; Build proper regexp according to current
  9347. ;; block's label format.
  9348. (let ((label-fmt
  9349. (regexp-quote
  9350. (or (org-element-property :label-fmt element)
  9351. org-coderef-label-format))))
  9352. (save-excursion
  9353. (beginning-of-line)
  9354. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9355. (format label-fmt coderef))))))
  9356. (setq type 'dedicated)
  9357. (goto-char (match-beginning 1))
  9358. (throw :coderef-match nil))))
  9359. (goto-char origin)
  9360. (error "No match for coderef: %s" coderef))))
  9361. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9362. ;; Look for a regular expression.
  9363. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9364. (match-string 1 s)))
  9365. ;; From here, we handle fuzzy links.
  9366. ;;
  9367. ;; Look for targets, only if not in a headline search.
  9368. ((and (not starred)
  9369. (let ((target (format "<<%s>>" s-multi-re)))
  9370. (catch :target-match
  9371. (goto-char (point-min))
  9372. (while (re-search-forward target nil t)
  9373. (backward-char)
  9374. (let ((context (org-element-context)))
  9375. (when (eq (org-element-type context) 'target)
  9376. (setq type 'dedicated)
  9377. (goto-char (org-element-property :begin context))
  9378. (throw :target-match t))))
  9379. nil))))
  9380. ;; Look for elements named after S, only if not in a headline
  9381. ;; search.
  9382. ((and (not starred)
  9383. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9384. (catch :name-match
  9385. (goto-char (point-min))
  9386. (while (re-search-forward name nil t)
  9387. (let ((element (org-element-at-point)))
  9388. (when (equal words
  9389. (split-string
  9390. (org-element-property :name element)))
  9391. (setq type 'dedicated)
  9392. (beginning-of-line)
  9393. (throw :name-match t))))
  9394. nil))))
  9395. ;; Regular text search. Prefer headlines in Org mode buffers.
  9396. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9397. ;; statistics cookies and tags.
  9398. ((and (derived-mode-p 'org-mode)
  9399. (let ((title-re
  9400. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9401. org-outline-regexp-bol
  9402. org-comment-string
  9403. (mapconcat #'regexp-quote words ".+")))
  9404. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9405. (comment-re (eval-when-compile
  9406. (format "\\`%s[ \t]+" org-comment-string))))
  9407. (goto-char (point-min))
  9408. (catch :found
  9409. (while (re-search-forward title-re nil t)
  9410. (when (equal words
  9411. (split-string
  9412. (replace-regexp-in-string
  9413. cookie-re ""
  9414. (replace-regexp-in-string
  9415. comment-re "" (org-get-heading t t t)))))
  9416. (throw :found t)))
  9417. nil)))
  9418. (beginning-of-line)
  9419. (setq type 'dedicated))
  9420. ;; Offer to create non-existent headline depending on
  9421. ;; `org-link-search-must-match-exact-headline'.
  9422. ((and (derived-mode-p 'org-mode)
  9423. (not org-link-search-inhibit-query)
  9424. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9425. (yes-or-no-p "No match - create this as a new heading? "))
  9426. (goto-char (point-max))
  9427. (unless (bolp) (newline))
  9428. (org-insert-heading nil t t)
  9429. (insert s "\n")
  9430. (beginning-of-line 0))
  9431. ;; Only headlines are looked after. No need to process
  9432. ;; further: throw an error.
  9433. ((and (derived-mode-p 'org-mode)
  9434. (or starred org-link-search-must-match-exact-headline))
  9435. (goto-char origin)
  9436. (error "No match for fuzzy expression: %s" normalized))
  9437. ;; Regular text search.
  9438. ((catch :fuzzy-match
  9439. (goto-char (point-min))
  9440. (while (re-search-forward s-multi-re nil t)
  9441. ;; Skip match if it contains AVOID-POS or it is included in
  9442. ;; a link with a description but outside the description.
  9443. (unless (or (and avoid-pos
  9444. (<= (match-beginning 0) avoid-pos)
  9445. (> (match-end 0) avoid-pos))
  9446. (and (save-match-data
  9447. (org-in-regexp org-bracket-link-regexp))
  9448. (match-beginning 3)
  9449. (or (> (match-beginning 3) (point))
  9450. (<= (match-end 3) (point)))
  9451. (org-element-lineage
  9452. (save-match-data (org-element-context))
  9453. '(link) t)))
  9454. (goto-char (match-beginning 0))
  9455. (setq type 'fuzzy)
  9456. (throw :fuzzy-match t)))
  9457. nil))
  9458. ;; All failed. Throw an error.
  9459. (t (goto-char origin)
  9460. (error "No match for fuzzy expression: %s" normalized)))
  9461. ;; Disclose surroundings of match, if appropriate.
  9462. (when (and (derived-mode-p 'org-mode) (not stealth))
  9463. (org-show-context 'link-search))
  9464. type))
  9465. (defun org-get-buffer-for-internal-link (buffer)
  9466. "Return a buffer to be used for displaying the link target of internal links."
  9467. (cond
  9468. ((not org-display-internal-link-with-indirect-buffer)
  9469. buffer)
  9470. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9471. (message "Buffer is already a clone, not making another one")
  9472. ;; we also do not modify visibility in this case
  9473. buffer)
  9474. (t ; make a new indirect buffer for displaying the link
  9475. (let* ((bn (buffer-name buffer))
  9476. (ibn (concat bn "(Clone)"))
  9477. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9478. (with-current-buffer ib (org-overview))
  9479. ib))))
  9480. (defun org-do-occur (regexp &optional cleanup)
  9481. "Call the Emacs command `occur'.
  9482. If CLEANUP is non-nil, remove the printout of the regular expression
  9483. in the *Occur* buffer. This is useful if the regex is long and not useful
  9484. to read."
  9485. (occur regexp)
  9486. (when cleanup
  9487. (let ((cwin (selected-window)) win beg end)
  9488. (when (setq win (get-buffer-window "*Occur*"))
  9489. (select-window win))
  9490. (goto-char (point-min))
  9491. (when (re-search-forward "match[a-z]+" nil t)
  9492. (setq beg (match-end 0))
  9493. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  9494. (setq end (1- (match-beginning 0)))))
  9495. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  9496. (goto-char (point-min))
  9497. (select-window cwin))))
  9498. ;;; The Mark Ring
  9499. (defvar org-mark-ring nil
  9500. "Mark ring for positions before jumps in Org mode.")
  9501. (defvar org-mark-ring-last-goto nil
  9502. "Last position in the mark ring used to go back.")
  9503. ;; Fill and close the ring
  9504. (setq org-mark-ring nil)
  9505. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  9506. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  9507. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  9508. org-mark-ring)
  9509. (defun org-mark-ring-push (&optional pos buffer)
  9510. "Put the current position into the mark ring and rotate it.
  9511. Also push position into the Emacs mark ring. If optional
  9512. argument POS and BUFFER are not nil, mark this location instead."
  9513. (interactive)
  9514. (let ((pos (or pos (point)))
  9515. (buffer (or buffer (current-buffer))))
  9516. (with-current-buffer buffer
  9517. (org-with-point-at pos (push-mark nil t)))
  9518. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  9519. (move-marker (car org-mark-ring) pos buffer))
  9520. (message
  9521. (substitute-command-keys
  9522. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  9523. (defun org-mark-ring-goto (&optional n)
  9524. "Jump to the previous position in the mark ring.
  9525. With prefix arg N, jump back that many stored positions. When
  9526. called several times in succession, walk through the entire ring.
  9527. Org mode commands jumping to a different position in the current file,
  9528. or to another Org file, automatically push the old position onto the ring."
  9529. (interactive "p")
  9530. (let (p m)
  9531. (if (eq last-command this-command)
  9532. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  9533. (setq p org-mark-ring))
  9534. (setq org-mark-ring-last-goto p)
  9535. (setq m (car p))
  9536. (pop-to-buffer-same-window (marker-buffer m))
  9537. (goto-char m)
  9538. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  9539. (defun org-add-angle-brackets (s)
  9540. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  9541. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  9542. s)
  9543. ;;; Following specific links
  9544. (defvar org-agenda-buffer-tmp-name)
  9545. (defvar org-agenda-start-on-weekday)
  9546. (defun org-follow-timestamp-link ()
  9547. "Open an agenda view for the time-stamp date/range at point."
  9548. (cond
  9549. ((org-at-date-range-p t)
  9550. (let ((org-agenda-start-on-weekday)
  9551. (t1 (match-string 1))
  9552. (t2 (match-string 2)) tt1 tt2)
  9553. (setq tt1 (time-to-days (org-time-string-to-time t1))
  9554. tt2 (time-to-days (org-time-string-to-time t2)))
  9555. (let ((org-agenda-buffer-tmp-name
  9556. (format "*Org Agenda(a:%s)"
  9557. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  9558. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  9559. ((org-at-timestamp-p 'lax)
  9560. (let ((org-agenda-buffer-tmp-name
  9561. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  9562. (org-agenda-list nil (time-to-days (org-time-string-to-time
  9563. (substring (match-string 1) 0 10)))
  9564. 1)))
  9565. (t (error "This should not happen"))))
  9566. ;;; Following file links
  9567. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  9568. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  9569. (declare-function mailcap-mime-info
  9570. "mailcap" (string &optional request no-decode))
  9571. (defvar org-wait nil)
  9572. (defun org-open-file (path &optional in-emacs line search)
  9573. "Open the file at PATH.
  9574. First, this expands any special file name abbreviations. Then the
  9575. configuration variable `org-file-apps' is checked if it contains an
  9576. entry for this file type, and if yes, the corresponding command is launched.
  9577. If no application is found, Emacs simply visits the file.
  9578. With optional prefix argument IN-EMACS, Emacs will visit the file.
  9579. With a double \\[universal-argument] \\[universal-argument] \
  9580. prefix arg, Org tries to avoid opening in Emacs
  9581. and to use an external application to visit the file.
  9582. Optional LINE specifies a line to go to, optional SEARCH a string
  9583. to search for. If LINE or SEARCH is given, the file will be
  9584. opened in Emacs, unless an entry from org-file-apps that makes
  9585. use of groups in a regexp matches.
  9586. If you want to change the way frames are used when following a
  9587. link, please customize `org-link-frame-setup'.
  9588. If the file does not exist, an error is thrown."
  9589. (let* ((file (if (equal path "")
  9590. buffer-file-name
  9591. (substitute-in-file-name (expand-file-name path))))
  9592. (file-apps (append org-file-apps (org-default-apps)))
  9593. (apps (cl-remove-if
  9594. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9595. (apps-dlink (cl-remove-if-not
  9596. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9597. (remp (and (assq 'remote apps) (file-remote-p file)))
  9598. (dirp (unless remp (file-directory-p file)))
  9599. (file (if (and dirp org-open-directory-means-index-dot-org)
  9600. (concat (file-name-as-directory file) "index.org")
  9601. file))
  9602. (a-m-a-p (assq 'auto-mode apps))
  9603. (dfile (downcase file))
  9604. ;; Reconstruct the original link from the PATH, LINE and
  9605. ;; SEARCH args.
  9606. (link (cond (line (concat file "::" (number-to-string line)))
  9607. (search (concat file "::" search))
  9608. (t file)))
  9609. (dlink (downcase link))
  9610. (ext
  9611. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  9612. (match-string 1 dfile)))
  9613. (save-position-maybe
  9614. (let ((old-buffer (current-buffer))
  9615. (old-pos (point))
  9616. (old-mode major-mode))
  9617. (lambda ()
  9618. (and (derived-mode-p 'org-mode)
  9619. (eq old-mode 'org-mode)
  9620. (or (not (eq old-buffer (current-buffer)))
  9621. (not (eq old-pos (point))))
  9622. (org-mark-ring-push old-pos old-buffer)))))
  9623. cmd link-match-data)
  9624. (cond
  9625. ((member in-emacs '((16) system))
  9626. (setq cmd (cdr (assq 'system apps))))
  9627. (in-emacs (setq cmd 'emacs))
  9628. (t
  9629. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  9630. (and dirp (cdr (assq 'directory apps)))
  9631. ;; First, try matching against apps-dlink if we
  9632. ;; get a match here, store the match data for
  9633. ;; later.
  9634. (let ((match (assoc-default dlink apps-dlink
  9635. 'string-match)))
  9636. (if match
  9637. (progn (setq link-match-data (match-data))
  9638. match)
  9639. (progn (setq in-emacs (or in-emacs line search))
  9640. nil))) ; if we have no match in apps-dlink,
  9641. ; always open the file in emacs if line or search
  9642. ; is given (for backwards compatibility)
  9643. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  9644. 'string-match)
  9645. (cdr (assoc ext apps))
  9646. (cdr (assq t apps))))))
  9647. (when (eq cmd 'system)
  9648. (setq cmd (cdr (assq 'system apps))))
  9649. (when (eq cmd 'default)
  9650. (setq cmd (cdr (assoc t apps))))
  9651. (when (eq cmd 'mailcap)
  9652. (require 'mailcap)
  9653. (mailcap-parse-mailcaps)
  9654. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  9655. (command (mailcap-mime-info mime-type)))
  9656. (if (stringp command)
  9657. (setq cmd command)
  9658. (setq cmd 'emacs))))
  9659. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  9660. (not (file-exists-p file))
  9661. (not org-open-non-existing-files))
  9662. (user-error "No such file: %s" file))
  9663. (cond
  9664. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  9665. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  9666. (while (string-match "['\"]%s['\"]" cmd)
  9667. (setq cmd (replace-match "%s" t t cmd)))
  9668. (setq cmd (replace-regexp-in-string
  9669. "%s"
  9670. (shell-quote-argument (convert-standard-filename file))
  9671. cmd
  9672. nil t))
  9673. ;; Replace "%1", "%2" etc. in command with group matches from regex
  9674. (save-match-data
  9675. (let ((match-index 1)
  9676. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  9677. (set-match-data link-match-data)
  9678. (while (<= match-index number-of-groups)
  9679. (let ((regex (concat "%" (number-to-string match-index)))
  9680. (replace-with (match-string match-index dlink)))
  9681. (while (string-match regex cmd)
  9682. (setq cmd (replace-match replace-with t t cmd))))
  9683. (setq match-index (+ match-index 1)))))
  9684. (save-window-excursion
  9685. (message "Running %s...done" cmd)
  9686. (start-process-shell-command cmd nil cmd)
  9687. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  9688. ((or (stringp cmd)
  9689. (eq cmd 'emacs))
  9690. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  9691. (widen)
  9692. (cond (line (org-goto-line line)
  9693. (when (derived-mode-p 'org-mode) (org-reveal)))
  9694. (search (condition-case err
  9695. (org-link-search search)
  9696. ;; Save position before error-ing out so user
  9697. ;; can easily move back to the original buffer.
  9698. (error (funcall save-position-maybe)
  9699. (error (nth 1 err)))))))
  9700. ((functionp cmd)
  9701. (save-match-data
  9702. (set-match-data link-match-data)
  9703. (condition-case nil
  9704. (funcall cmd file link)
  9705. ;; FIXME: Remove this check when most default installations
  9706. ;; of Emacs have at least Org 9.0.
  9707. ((debug wrong-number-of-arguments wrong-type-argument
  9708. invalid-function)
  9709. (user-error "Please see Org News for version 9.0 about \
  9710. `org-file-apps'--Lisp error: %S" cmd)))))
  9711. ((consp cmd)
  9712. ;; FIXME: Remove this check when most default installations of
  9713. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  9714. ;; fall back to `org-link-frame-setup' for an old usage of
  9715. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  9716. (user-error "Please see Org News for version 9.0 about \
  9717. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  9718. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  9719. (funcall save-position-maybe)))
  9720. (defun org-file-apps-entry-match-against-dlink-p (entry)
  9721. "This function returns non-nil if `entry' uses a regular
  9722. expression which should be matched against the whole link by
  9723. org-open-file.
  9724. It assumes that is the case when the entry uses a regular
  9725. expression which has at least one grouping construct and the
  9726. action is either a lisp form or a command string containing
  9727. `%1', i.e. using at least one subexpression match as a
  9728. parameter."
  9729. (let ((selector (car entry))
  9730. (action (cdr entry)))
  9731. (if (stringp selector)
  9732. (and (> (regexp-opt-depth selector) 0)
  9733. (or (and (stringp action)
  9734. (string-match "%[0-9]" action))
  9735. (consp action)))
  9736. nil)))
  9737. (defun org-default-apps ()
  9738. "Return the default applications for this operating system."
  9739. (cond
  9740. ((eq system-type 'darwin)
  9741. org-file-apps-defaults-macosx)
  9742. ((eq system-type 'windows-nt)
  9743. org-file-apps-defaults-windowsnt)
  9744. (t org-file-apps-defaults-gnu)))
  9745. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  9746. "Convert extensions to regular expressions in the cars of LIST.
  9747. Also, weed out any non-string entries, because the return value is used
  9748. only for regexp matching.
  9749. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  9750. point to the symbol `emacs', indicating that the file should
  9751. be opened in Emacs."
  9752. (append
  9753. (delq nil
  9754. (mapcar (lambda (x)
  9755. (unless (not (stringp (car x)))
  9756. (if (string-match "\\W" (car x))
  9757. x
  9758. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  9759. list))
  9760. (when add-auto-mode
  9761. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  9762. ;;;; Refiling
  9763. (defun org-get-org-file ()
  9764. "Read a filename, with default directory `org-directory'."
  9765. (let ((default (or org-default-notes-file remember-data-file)))
  9766. (read-file-name (format "File name [%s]: " default)
  9767. (file-name-as-directory org-directory)
  9768. default)))
  9769. (defun org-notes-order-reversed-p ()
  9770. "Check if the current file should receive notes in reversed order."
  9771. (cond
  9772. ((not org-reverse-note-order) nil)
  9773. ((eq t org-reverse-note-order) t)
  9774. ((not (listp org-reverse-note-order)) nil)
  9775. (t (catch 'exit
  9776. (dolist (entry org-reverse-note-order)
  9777. (when (string-match (car entry) buffer-file-name)
  9778. (throw 'exit (cdr entry))))))))
  9779. (defvar org-refile-target-table nil
  9780. "The list of refile targets, created by `org-refile'.")
  9781. (defvar org-agenda-new-buffers nil
  9782. "Buffers created to visit agenda files.")
  9783. (defvar org-refile-cache nil
  9784. "Cache for refile targets.")
  9785. (defvar org-refile-markers nil
  9786. "All the markers used for caching refile locations.")
  9787. (defun org-refile-marker (pos)
  9788. "Get a new refile marker, but only if caching is in use."
  9789. (if (not org-refile-use-cache)
  9790. pos
  9791. (let ((m (make-marker)))
  9792. (move-marker m pos)
  9793. (push m org-refile-markers)
  9794. m)))
  9795. (defun org-refile-cache-clear ()
  9796. "Clear the refile cache and disable all the markers."
  9797. (dolist (m org-refile-markers) (move-marker m nil))
  9798. (setq org-refile-markers nil)
  9799. (setq org-refile-cache nil)
  9800. (message "Refile cache has been cleared"))
  9801. (defun org-refile-cache-check-set (set)
  9802. "Check if all the markers in the cache still have live buffers."
  9803. (let (marker)
  9804. (catch 'exit
  9805. (while (and set (setq marker (nth 3 (pop set))))
  9806. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  9807. (when (and marker (null (marker-buffer marker)))
  9808. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  9809. (sit-for 3)
  9810. (throw 'exit nil)))
  9811. t)))
  9812. (defun org-refile-cache-put (set &rest identifiers)
  9813. "Push the refile targets SET into the cache, under IDENTIFIERS."
  9814. (let* ((key (sha1 (prin1-to-string identifiers)))
  9815. (entry (assoc key org-refile-cache)))
  9816. (if entry
  9817. (setcdr entry set)
  9818. (push (cons key set) org-refile-cache))))
  9819. (defun org-refile-cache-get (&rest identifiers)
  9820. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  9821. (cond
  9822. ((not org-refile-cache) nil)
  9823. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  9824. (t
  9825. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  9826. org-refile-cache))))
  9827. (and set (org-refile-cache-check-set set) set)))))
  9828. (defvar org-outline-path-cache nil
  9829. "Alist between buffer positions and outline paths.
  9830. It value is an alist (POSITION . PATH) where POSITION is the
  9831. buffer position at the beginning of an entry and PATH is a list
  9832. of strings describing the outline path for that entry, in reverse
  9833. order.")
  9834. (defun org-refile-get-targets (&optional default-buffer)
  9835. "Produce a table with refile targets."
  9836. (let ((case-fold-search nil)
  9837. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  9838. (entries (or org-refile-targets '((nil . (:level . 1)))))
  9839. targets tgs files desc descre)
  9840. (message "Getting targets...")
  9841. (with-current-buffer (or default-buffer (current-buffer))
  9842. (dolist (entry entries)
  9843. (setq files (car entry) desc (cdr entry))
  9844. (cond
  9845. ((null files) (setq files (list (current-buffer))))
  9846. ((eq files 'org-agenda-files)
  9847. (setq files (org-agenda-files 'unrestricted)))
  9848. ((and (symbolp files) (fboundp files))
  9849. (setq files (funcall files)))
  9850. ((and (symbolp files) (boundp files))
  9851. (setq files (symbol-value files))))
  9852. (when (stringp files) (setq files (list files)))
  9853. (cond
  9854. ((eq (car desc) :tag)
  9855. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  9856. ((eq (car desc) :todo)
  9857. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  9858. ((eq (car desc) :regexp)
  9859. (setq descre (cdr desc)))
  9860. ((eq (car desc) :level)
  9861. (setq descre (concat "^\\*\\{" (number-to-string
  9862. (if org-odd-levels-only
  9863. (1- (* 2 (cdr desc)))
  9864. (cdr desc)))
  9865. "\\}[ \t]")))
  9866. ((eq (car desc) :maxlevel)
  9867. (setq descre (concat "^\\*\\{1," (number-to-string
  9868. (if org-odd-levels-only
  9869. (1- (* 2 (cdr desc)))
  9870. (cdr desc)))
  9871. "\\}[ \t]")))
  9872. (t (error "Bad refiling target description %s" desc)))
  9873. (dolist (f files)
  9874. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  9875. (or
  9876. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  9877. (progn
  9878. (when (bufferp f)
  9879. (setq f (buffer-file-name (buffer-base-buffer f))))
  9880. (setq f (and f (expand-file-name f)))
  9881. (when (eq org-refile-use-outline-path 'file)
  9882. (push (list (file-name-nondirectory f) f nil nil) tgs))
  9883. (when (eq org-refile-use-outline-path 'buffer-name)
  9884. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  9885. (when (eq org-refile-use-outline-path 'full-file-path)
  9886. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  9887. (org-with-wide-buffer
  9888. (goto-char (point-min))
  9889. (setq org-outline-path-cache nil)
  9890. (while (re-search-forward descre nil t)
  9891. (beginning-of-line)
  9892. (let ((case-fold-search nil))
  9893. (looking-at org-complex-heading-regexp))
  9894. (let ((begin (point))
  9895. (heading (match-string-no-properties 4)))
  9896. (unless (or (and
  9897. org-refile-target-verify-function
  9898. (not
  9899. (funcall org-refile-target-verify-function)))
  9900. (not heading))
  9901. (let ((re (format org-complex-heading-regexp-format
  9902. (regexp-quote heading)))
  9903. (target
  9904. (if (not org-refile-use-outline-path) heading
  9905. (mapconcat
  9906. #'identity
  9907. (append
  9908. (pcase org-refile-use-outline-path
  9909. (`file (list (file-name-nondirectory
  9910. (buffer-file-name
  9911. (buffer-base-buffer)))))
  9912. (`full-file-path
  9913. (list (buffer-file-name
  9914. (buffer-base-buffer))))
  9915. (`buffer-name
  9916. (list (buffer-name
  9917. (buffer-base-buffer))))
  9918. (_ nil))
  9919. (mapcar (lambda (s) (replace-regexp-in-string
  9920. "/" "\\/" s nil t))
  9921. (org-get-outline-path t t)))
  9922. "/"))))
  9923. (push (list target f re (org-refile-marker (point)))
  9924. tgs)))
  9925. (when (= (point) begin)
  9926. ;; Verification function has not moved point.
  9927. (end-of-line)))))))
  9928. (when org-refile-use-cache
  9929. (org-refile-cache-put tgs (buffer-file-name) descre))
  9930. (setq targets (append tgs targets))))))
  9931. (message "Getting targets...done")
  9932. (delete-dups (nreverse targets))))
  9933. (defun org--get-outline-path-1 (&optional use-cache)
  9934. "Return outline path to current headline.
  9935. Outline path is a list of strings, in reverse order. When
  9936. optional argument USE-CACHE is non-nil, make use of a cache. See
  9937. `org-get-outline-path' for details.
  9938. Assume buffer is widened and point is on a headline."
  9939. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  9940. (let ((p (point))
  9941. (heading (let ((case-fold-search nil))
  9942. (looking-at org-complex-heading-regexp)
  9943. (if (not (match-end 4)) ""
  9944. ;; Remove statistics cookies.
  9945. (org-trim
  9946. (org-link-display-format
  9947. (replace-regexp-in-string
  9948. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  9949. (match-string-no-properties 4))))))))
  9950. (if (org-up-heading-safe)
  9951. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  9952. (when use-cache
  9953. (push (cons p path) org-outline-path-cache))
  9954. path)
  9955. ;; This is a new root node. Since we assume we are moving
  9956. ;; forward, we can drop previous cache so as to limit number
  9957. ;; of associations there.
  9958. (let ((path (list heading)))
  9959. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  9960. path)))))
  9961. (defun org-get-outline-path (&optional with-self use-cache)
  9962. "Return the outline path to the current entry.
  9963. An outline path is a list of ancestors for current headline, as
  9964. a list of strings. Statistics cookies are removed and links are
  9965. replaced with their description, if any, or their path otherwise.
  9966. When optional argument WITH-SELF is non-nil, the path also
  9967. includes the current headline.
  9968. When optional argument USE-CACHE is non-nil, cache outline paths
  9969. between calls to this function so as to avoid backtracking. This
  9970. argument is useful when planning to find more than one outline
  9971. path in the same document. In that case, there are two
  9972. conditions to satisfy:
  9973. - `org-outline-path-cache' is set to nil before starting the
  9974. process;
  9975. - outline paths are computed by increasing buffer positions."
  9976. (org-with-wide-buffer
  9977. (and (or (and with-self (org-back-to-heading t))
  9978. (org-up-heading-safe))
  9979. (reverse (org--get-outline-path-1 use-cache)))))
  9980. (defun org-format-outline-path (path &optional width prefix separator)
  9981. "Format the outline path PATH for display.
  9982. WIDTH is the maximum number of characters that is available.
  9983. PREFIX is a prefix to be included in the returned string,
  9984. such as the file name.
  9985. SEPARATOR is inserted between the different parts of the path,
  9986. the default is \"/\"."
  9987. (setq width (or width 79))
  9988. (setq path (delq nil path))
  9989. (unless (> width 0)
  9990. (user-error "Argument `width' must be positive"))
  9991. (setq separator (or separator "/"))
  9992. (let* ((org-odd-levels-only nil)
  9993. (fpath (concat
  9994. prefix (and prefix path separator)
  9995. (mapconcat
  9996. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  9997. (cl-loop for head in path
  9998. for n from 0
  9999. collect (org-add-props
  10000. head nil 'face
  10001. (nth (% n org-n-level-faces) org-level-faces)))
  10002. separator))))
  10003. (when (> (length fpath) width)
  10004. (if (< width 7)
  10005. ;; It's unlikely that `width' will be this small, but don't
  10006. ;; waste characters by adding ".." if it is.
  10007. (setq fpath (substring fpath 0 width))
  10008. (setf (substring fpath (- width 2)) "..")))
  10009. fpath))
  10010. (defun org-display-outline-path (&optional file current separator just-return-string)
  10011. "Display the current outline path in the echo area.
  10012. If FILE is non-nil, prepend the output with the file name.
  10013. If CURRENT is non-nil, append the current heading to the output.
  10014. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10015. the different parts of the path and defaults to \"/\".
  10016. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10017. (interactive "P")
  10018. (let* (case-fold-search
  10019. (bfn (buffer-file-name (buffer-base-buffer)))
  10020. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10021. res)
  10022. (when current (setq path (append path
  10023. (save-excursion
  10024. (org-back-to-heading t)
  10025. (when (looking-at org-complex-heading-regexp)
  10026. (list (match-string 4)))))))
  10027. (setq res
  10028. (org-format-outline-path
  10029. path
  10030. (1- (frame-width))
  10031. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10032. separator))
  10033. (if just-return-string
  10034. (org-no-properties res)
  10035. (org-unlogged-message "%s" res))))
  10036. (defvar org-refile-history nil
  10037. "History for refiling operations.")
  10038. (defvar org-after-refile-insert-hook nil
  10039. "Hook run after `org-refile' has inserted its stuff at the new location.
  10040. Note that this is still *before* the stuff will be removed from
  10041. the *old* location.")
  10042. (defvar org-capture-last-stored-marker)
  10043. (defvar org-refile-keep nil
  10044. "Non-nil means `org-refile' will copy instead of refile.")
  10045. (defun org-copy ()
  10046. "Like `org-refile', but copy."
  10047. (interactive)
  10048. (let ((org-refile-keep t))
  10049. (funcall 'org-refile nil nil nil "Copy")))
  10050. (defun org-refile (&optional arg default-buffer rfloc msg)
  10051. "Move the entry or entries at point to another heading.
  10052. The list of target headings is compiled using the information in
  10053. `org-refile-targets', which see.
  10054. At the target location, the entry is filed as a subitem of the
  10055. target heading. Depending on `org-reverse-note-order', the new
  10056. subitem will either be the first or the last subitem.
  10057. If there is an active region, all entries in that region will be
  10058. refiled. However, the region must fulfill the requirement that
  10059. the first heading sets the top-level of the moved text.
  10060. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10061. location
  10062. and not actually move anything.
  10063. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10064. location where the last
  10065. refiling operation has put the subtree.
  10066. With a numeric prefix argument of `2', refile to the running clock.
  10067. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10068. being set to t and copy to the target location, don't move it.
  10069. Beware that keeping refiled entries may result in duplicated ID
  10070. properties.
  10071. RFLOC can be a refile location obtained in a different way.
  10072. MSG is a string to replace \"Refile\" in the default prompt with
  10073. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10074. See also `org-refile-use-outline-path'.
  10075. If you are using target caching (see `org-refile-use-cache'), you
  10076. have to clear the target cache in order to find new targets.
  10077. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10078. prefix argument (`C-u C-u C-u C-c C-w')."
  10079. (interactive "P")
  10080. (if (member arg '(0 (64)))
  10081. (org-refile-cache-clear)
  10082. (let* ((actionmsg (cond (msg msg)
  10083. ((equal arg 3) "Refile (and keep)")
  10084. (t "Refile")))
  10085. (regionp (org-region-active-p))
  10086. (region-start (and regionp (region-beginning)))
  10087. (region-end (and regionp (region-end)))
  10088. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10089. pos it nbuf file level reversed)
  10090. (setq last-command nil)
  10091. (when regionp
  10092. (goto-char region-start)
  10093. (or (bolp) (goto-char (point-at-bol)))
  10094. (setq region-start (point))
  10095. (unless (or (org-kill-is-subtree-p
  10096. (buffer-substring region-start region-end))
  10097. (prog1 org-refile-active-region-within-subtree
  10098. (let ((s (point-at-eol)))
  10099. (org-toggle-heading)
  10100. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10101. (user-error "The region is not a (sequence of) subtree(s)")))
  10102. (if (equal arg '(16))
  10103. (org-refile-goto-last-stored)
  10104. (when (or
  10105. (and (equal arg 2)
  10106. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10107. (prog1
  10108. (setq it (list (or org-clock-heading "running clock")
  10109. (buffer-file-name
  10110. (marker-buffer org-clock-hd-marker))
  10111. ""
  10112. (marker-position org-clock-hd-marker)))
  10113. (setq arg nil)))
  10114. (setq it
  10115. (or rfloc
  10116. (let (heading-text)
  10117. (save-excursion
  10118. (unless (and arg (listp arg))
  10119. (org-back-to-heading t)
  10120. (setq heading-text
  10121. (replace-regexp-in-string
  10122. org-bracket-link-regexp
  10123. "\\3"
  10124. (or (nth 4 (org-heading-components))
  10125. ""))))
  10126. (org-refile-get-location
  10127. (cond ((and arg (listp arg)) "Goto")
  10128. (regionp (concat actionmsg " region to"))
  10129. (t (concat actionmsg " subtree \""
  10130. heading-text "\" to")))
  10131. default-buffer
  10132. (and (not (equal '(4) arg))
  10133. org-refile-allow-creating-parent-nodes)))))))
  10134. (setq file (nth 1 it)
  10135. pos (nth 3 it))
  10136. (when (and (not arg)
  10137. pos
  10138. (equal (buffer-file-name) file)
  10139. (if regionp
  10140. (and (>= pos region-start)
  10141. (<= pos region-end))
  10142. (and (>= pos (point))
  10143. (< pos (save-excursion
  10144. (org-end-of-subtree t t))))))
  10145. (error "Cannot refile to position inside the tree or region"))
  10146. (setq nbuf (or (find-buffer-visiting file)
  10147. (find-file-noselect file)))
  10148. (if (and arg (not (equal arg 3)))
  10149. (progn
  10150. (pop-to-buffer-same-window nbuf)
  10151. (goto-char (cond (pos)
  10152. ((org-notes-order-reversed-p) (point-min))
  10153. (t (point-max))))
  10154. (org-show-context 'org-goto))
  10155. (if regionp
  10156. (progn
  10157. (org-kill-new (buffer-substring region-start region-end))
  10158. (org-save-markers-in-region region-start region-end))
  10159. (org-copy-subtree 1 nil t))
  10160. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10161. (find-file-noselect file)))
  10162. (setq reversed (org-notes-order-reversed-p))
  10163. (org-with-wide-buffer
  10164. (if pos
  10165. (progn
  10166. (goto-char pos)
  10167. (setq level (org-get-valid-level (funcall outline-level) 1))
  10168. (goto-char
  10169. (if reversed
  10170. (or (outline-next-heading) (point-max))
  10171. (or (save-excursion (org-get-next-sibling))
  10172. (org-end-of-subtree t t)
  10173. (point-max)))))
  10174. (setq level 1)
  10175. (if (not reversed)
  10176. (goto-char (point-max))
  10177. (goto-char (point-min))
  10178. (or (outline-next-heading) (goto-char (point-max)))))
  10179. (unless (bolp) (newline))
  10180. (org-paste-subtree level nil nil t)
  10181. (when org-log-refile
  10182. (org-add-log-setup 'refile nil nil org-log-refile)
  10183. (unless (eq org-log-refile 'note)
  10184. (save-excursion (org-add-log-note))))
  10185. (and org-auto-align-tags
  10186. (let ((org-loop-over-headlines-in-active-region nil))
  10187. (org-align-tags)))
  10188. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10189. :last-refile)))
  10190. (when bookmark-name
  10191. (with-demoted-errors
  10192. (bookmark-set bookmark-name))))
  10193. ;; If we are refiling for capture, make sure that the
  10194. ;; last-capture pointers point here
  10195. (when (bound-and-true-p org-capture-is-refiling)
  10196. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10197. :last-capture-marker)))
  10198. (when bookmark-name
  10199. (with-demoted-errors
  10200. (bookmark-set bookmark-name))))
  10201. (move-marker org-capture-last-stored-marker (point)))
  10202. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10203. (run-hooks 'org-after-refile-insert-hook)))
  10204. (unless org-refile-keep
  10205. (if regionp
  10206. (delete-region (point) (+ (point) (- region-end region-start)))
  10207. (org-preserve-local-variables
  10208. (delete-region
  10209. (and (org-back-to-heading t) (point))
  10210. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
  10211. (when (featurep 'org-inlinetask)
  10212. (org-inlinetask-remove-END-maybe))
  10213. (setq org-markers-to-move nil)
  10214. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10215. (defun org-refile-goto-last-stored ()
  10216. "Go to the location where the last refile was stored."
  10217. (interactive)
  10218. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10219. (message "This is the location of the last refile"))
  10220. (defun org-refile--get-location (refloc tbl)
  10221. "When user refile to REFLOC, find the associated target in TBL.
  10222. Also check `org-refile-target-table'."
  10223. (car (delq
  10224. nil
  10225. (mapcar
  10226. (lambda (r) (or (assoc r tbl)
  10227. (assoc r org-refile-target-table)))
  10228. (list (replace-regexp-in-string "/$" "" refloc)
  10229. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10230. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10231. "Prompt the user for a refile location, using PROMPT.
  10232. PROMPT should not be suffixed with a colon and a space, because
  10233. this function appends the default value from
  10234. `org-refile-history' automatically, if that is not empty."
  10235. (let ((org-refile-targets org-refile-targets)
  10236. (org-refile-use-outline-path org-refile-use-outline-path))
  10237. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10238. (unless org-refile-target-table
  10239. (user-error "No refile targets"))
  10240. (let* ((cbuf (current-buffer))
  10241. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10242. (cfunc (if (and org-refile-use-outline-path
  10243. org-outline-path-complete-in-steps)
  10244. #'org-olpath-completing-read
  10245. #'completing-read))
  10246. (extra (if org-refile-use-outline-path "/" ""))
  10247. (cbnex (concat (buffer-name) extra))
  10248. (filename (and cfn (expand-file-name cfn)))
  10249. (tbl (mapcar
  10250. (lambda (x)
  10251. (if (and (not (member org-refile-use-outline-path
  10252. '(file full-file-path)))
  10253. (not (equal filename (nth 1 x))))
  10254. (cons (concat (car x) extra " ("
  10255. (file-name-nondirectory (nth 1 x)) ")")
  10256. (cdr x))
  10257. (cons (concat (car x) extra) (cdr x))))
  10258. org-refile-target-table))
  10259. (completion-ignore-case t)
  10260. cdef
  10261. (prompt (concat prompt
  10262. (or (and (car org-refile-history)
  10263. (concat " (default " (car org-refile-history) ")"))
  10264. (and (assoc cbnex tbl) (setq cdef cbnex)
  10265. (concat " (default " cbnex ")"))) ": "))
  10266. pa answ parent-target child parent old-hist)
  10267. (setq old-hist org-refile-history)
  10268. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10269. nil 'org-refile-history (or cdef (car org-refile-history))))
  10270. (if (setq pa (org-refile--get-location answ tbl))
  10271. (progn
  10272. (org-refile-check-position pa)
  10273. (when (or (not org-refile-history)
  10274. (not (eq old-hist org-refile-history))
  10275. (not (equal (car pa) (car org-refile-history))))
  10276. (setq org-refile-history
  10277. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10278. org-refile-history
  10279. (cdr org-refile-history))))
  10280. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10281. (pop org-refile-history)))
  10282. pa)
  10283. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10284. (progn
  10285. (setq parent (match-string 1 answ)
  10286. child (match-string 2 answ))
  10287. (setq parent-target (org-refile--get-location parent tbl))
  10288. (when (and parent-target
  10289. (or (eq new-nodes t)
  10290. (and (eq new-nodes 'confirm)
  10291. (y-or-n-p (format "Create new node \"%s\"? "
  10292. child)))))
  10293. (org-refile-new-child parent-target child)))
  10294. (user-error "Invalid target location")))))
  10295. (declare-function org-string-nw-p "org-macs" (s))
  10296. (defun org-refile-check-position (refile-pointer)
  10297. "Check if the refile pointer matches the headline to which it points."
  10298. (let* ((file (nth 1 refile-pointer))
  10299. (re (nth 2 refile-pointer))
  10300. (pos (nth 3 refile-pointer))
  10301. buffer)
  10302. (if (and (not (markerp pos)) (not file))
  10303. (user-error "Please indicate a target file in the refile path")
  10304. (when (org-string-nw-p re)
  10305. (setq buffer (if (markerp pos)
  10306. (marker-buffer pos)
  10307. (or (find-buffer-visiting file)
  10308. (find-file-noselect file))))
  10309. (with-current-buffer buffer
  10310. (org-with-wide-buffer
  10311. (goto-char pos)
  10312. (beginning-of-line 1)
  10313. (unless (looking-at-p re)
  10314. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10315. (defun org-refile-new-child (parent-target child)
  10316. "Use refile target PARENT-TARGET to add new CHILD below it."
  10317. (unless parent-target
  10318. (error "Cannot find parent for new node"))
  10319. (let ((file (nth 1 parent-target))
  10320. (pos (nth 3 parent-target))
  10321. level)
  10322. (with-current-buffer (or (find-buffer-visiting file)
  10323. (find-file-noselect file))
  10324. (org-with-wide-buffer
  10325. (if pos
  10326. (goto-char pos)
  10327. (goto-char (point-max))
  10328. (unless (bolp) (newline)))
  10329. (when (looking-at org-outline-regexp)
  10330. (setq level (funcall outline-level))
  10331. (org-end-of-subtree t t))
  10332. (org-back-over-empty-lines)
  10333. (insert "\n" (make-string
  10334. (if pos (org-get-valid-level level 1) 1) ?*)
  10335. " " child "\n")
  10336. (beginning-of-line 0)
  10337. (list (concat (car parent-target) "/" child) file "" (point))))))
  10338. (defun org-olpath-completing-read (prompt collection &rest args)
  10339. "Read an outline path like a file name."
  10340. (let ((thetable collection))
  10341. (apply #'completing-read
  10342. prompt
  10343. (lambda (string predicate &optional flag)
  10344. (cond
  10345. ((eq flag nil) (try-completion string thetable))
  10346. ((eq flag t)
  10347. (let ((l (length string)))
  10348. (mapcar (lambda (x)
  10349. (let ((r (substring x l))
  10350. (f (if (string-match " ([^)]*)$" x)
  10351. (match-string 0 x)
  10352. "")))
  10353. (if (string-match "/" r)
  10354. (concat string (substring r 0 (match-end 0)) f)
  10355. x)))
  10356. (all-completions string thetable predicate))))
  10357. ;; Exact match?
  10358. ((eq flag 'lambda) (assoc string thetable))))
  10359. args)))
  10360. ;;;; Dynamic blocks
  10361. (defun org-find-dblock (name)
  10362. "Find the first dynamic block with name NAME in the buffer.
  10363. If not found, stay at current position and return nil."
  10364. (let ((case-fold-search t) pos)
  10365. (save-excursion
  10366. (goto-char (point-min))
  10367. (setq pos (and (re-search-forward
  10368. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10369. (match-beginning 0))))
  10370. (when pos (goto-char pos))
  10371. pos))
  10372. (defun org-create-dblock (plist)
  10373. "Create a dynamic block section, with parameters taken from PLIST.
  10374. PLIST must contain a :name entry which is used as the name of the block."
  10375. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10376. (end-of-line 1)
  10377. (newline))
  10378. (let ((col (current-column))
  10379. (name (plist-get plist :name)))
  10380. (insert "#+BEGIN: " name)
  10381. (while plist
  10382. (if (eq (car plist) :name)
  10383. (setq plist (cddr plist))
  10384. (insert " " (prin1-to-string (pop plist)))))
  10385. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10386. (beginning-of-line -2)))
  10387. (defun org-prepare-dblock ()
  10388. "Prepare dynamic block for refresh.
  10389. This empties the block, puts the cursor at the insert position and returns
  10390. the property list including an extra property :name with the block name."
  10391. (unless (looking-at org-dblock-start-re)
  10392. (user-error "Not at a dynamic block"))
  10393. (let* ((begdel (1+ (match-end 0)))
  10394. (name (org-no-properties (match-string 1)))
  10395. (params (append (list :name name)
  10396. (read (concat "(" (match-string 3) ")")))))
  10397. (save-excursion
  10398. (beginning-of-line 1)
  10399. (skip-chars-forward " \t")
  10400. (setq params (plist-put params :indentation-column (current-column))))
  10401. (unless (re-search-forward org-dblock-end-re nil t)
  10402. (error "Dynamic block not terminated"))
  10403. (setq params
  10404. (append params
  10405. (list :content (buffer-substring
  10406. begdel (match-beginning 0)))))
  10407. (delete-region begdel (match-beginning 0))
  10408. (goto-char begdel)
  10409. (open-line 1)
  10410. params))
  10411. (defun org-map-dblocks (&optional command)
  10412. "Apply COMMAND to all dynamic blocks in the current buffer.
  10413. If COMMAND is not given, use `org-update-dblock'."
  10414. (let ((cmd (or command 'org-update-dblock)))
  10415. (save-excursion
  10416. (goto-char (point-min))
  10417. (while (re-search-forward org-dblock-start-re nil t)
  10418. (goto-char (match-beginning 0))
  10419. (save-excursion
  10420. (condition-case nil
  10421. (funcall cmd)
  10422. (error (message "Error during update of dynamic block"))))
  10423. (unless (re-search-forward org-dblock-end-re nil t)
  10424. (error "Dynamic block not terminated"))))))
  10425. (defun org-dblock-update (&optional arg)
  10426. "User command for updating dynamic blocks.
  10427. Update the dynamic block at point. With prefix ARG, update all dynamic
  10428. blocks in the buffer."
  10429. (interactive "P")
  10430. (if arg
  10431. (org-update-all-dblocks)
  10432. (or (looking-at org-dblock-start-re)
  10433. (org-beginning-of-dblock))
  10434. (org-update-dblock)))
  10435. (defun org-update-dblock ()
  10436. "Update the dynamic block at point.
  10437. This means to empty the block, parse for parameters and then call
  10438. the correct writing function."
  10439. (interactive)
  10440. (save-excursion
  10441. (let* ((win (selected-window))
  10442. (pos (point))
  10443. (line (org-current-line))
  10444. (params (org-prepare-dblock))
  10445. (name (plist-get params :name))
  10446. (indent (plist-get params :indentation-column))
  10447. (cmd (intern (concat "org-dblock-write:" name))))
  10448. (message "Updating dynamic block `%s' at line %d..." name line)
  10449. (funcall cmd params)
  10450. (message "Updating dynamic block `%s' at line %d...done" name line)
  10451. (goto-char pos)
  10452. (when (and indent (> indent 0))
  10453. (setq indent (make-string indent ?\ ))
  10454. (save-excursion
  10455. (select-window win)
  10456. (org-beginning-of-dblock)
  10457. (forward-line 1)
  10458. (while (not (looking-at org-dblock-end-re))
  10459. (insert indent)
  10460. (beginning-of-line 2))
  10461. (when (looking-at org-dblock-end-re)
  10462. (and (looking-at "[ \t]+")
  10463. (replace-match ""))
  10464. (insert indent)))))))
  10465. (defun org-beginning-of-dblock ()
  10466. "Find the beginning of the dynamic block at point.
  10467. Error if there is no such block at point."
  10468. (let ((pos (point))
  10469. beg)
  10470. (end-of-line 1)
  10471. (if (and (re-search-backward org-dblock-start-re nil t)
  10472. (setq beg (match-beginning 0))
  10473. (re-search-forward org-dblock-end-re nil t)
  10474. (> (match-end 0) pos))
  10475. (goto-char beg)
  10476. (goto-char pos)
  10477. (error "Not in a dynamic block"))))
  10478. (defun org-update-all-dblocks ()
  10479. "Update all dynamic blocks in the buffer.
  10480. This function can be used in a hook."
  10481. (interactive)
  10482. (when (derived-mode-p 'org-mode)
  10483. (org-map-dblocks 'org-update-dblock)))
  10484. ;;;; Completion
  10485. (declare-function org-export-backend-options "ox" (cl-x) t)
  10486. (defun org-get-export-keywords ()
  10487. "Return a list of all currently understood export keywords.
  10488. Export keywords include options, block names, attributes and
  10489. keywords relative to each registered export back-end."
  10490. (let (keywords)
  10491. (dolist (backend
  10492. (bound-and-true-p org-export-registered-backends)
  10493. (delq nil keywords))
  10494. ;; Back-end name (for keywords, like #+LATEX:)
  10495. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  10496. (dolist (option-entry (org-export-backend-options backend))
  10497. ;; Back-end options.
  10498. (push (nth 1 option-entry) keywords)))))
  10499. (defconst org-options-keywords
  10500. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  10501. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  10502. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  10503. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  10504. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  10505. (defcustom org-structure-template-alist
  10506. '(("a" . "export ascii")
  10507. ("c" . "center")
  10508. ("C" . "comment")
  10509. ("e" . "example")
  10510. ("E" . "export")
  10511. ("h" . "export html")
  10512. ("l" . "export latex")
  10513. ("q" . "quote")
  10514. ("s" . "src")
  10515. ("v" . "verse"))
  10516. "An alist of keys and block types.
  10517. `org-insert-structure-template' will display a menu with this
  10518. list of templates to choose from. The block type is inserted,
  10519. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  10520. The menu keys are defined by the car of each entry in this alist.
  10521. If two entries have the keys \"a\" and \"aa\" respectively, the
  10522. former will be inserted by typing \"a TAB/RET/SPC\" and the
  10523. latter will be inserted by typing \"aa\". If an entry with the
  10524. key \"aab\" is later added, it can be inserted by typing \"ab\".
  10525. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  10526. block can be inserted by pressing TAB after the string \"<KEY\"."
  10527. :group 'org-edit-structure
  10528. :type '(repeat
  10529. (cons (string :tag "Key")
  10530. (string :tag "Template")))
  10531. :package-version '(Org . "9.2"))
  10532. (defun org--insert-structure-template-mks ()
  10533. "Present `org-structure-template-alist' with `org-mks'.
  10534. Menus are added if keys require more than one keystroke. Tabs
  10535. are added to single key entries when more than one stroke is
  10536. needed. Keys longer than two characters are reduced to two
  10537. characters."
  10538. (let* (case-fold-search
  10539. (templates (append org-structure-template-alist
  10540. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  10541. (keys (mapcar #'car templates))
  10542. (start-letters
  10543. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  10544. ;; Sort each element of `org-structure-template-alist' into
  10545. ;; sublists according to the first letter.
  10546. (superlist
  10547. (mapcar (lambda (letter)
  10548. (list letter
  10549. (cl-remove-if-not
  10550. (apply-partially #'string-match-p (concat "^" letter))
  10551. templates :key #'car)))
  10552. start-letters)))
  10553. (org-mks
  10554. (apply #'append
  10555. ;; Make an `org-mks' table. If only one element is
  10556. ;; present in a sublist, make it part of the top-menu,
  10557. ;; otherwise make a submenu according to the starting
  10558. ;; letter and populate it.
  10559. (mapcar (lambda (sublist)
  10560. (if (eq 1 (length (cadr sublist)))
  10561. (mapcar (lambda (elm)
  10562. (list (substring (car elm) 0 1)
  10563. (cdr elm) ""))
  10564. (cadr sublist))
  10565. ;; Create submenu.
  10566. (let* ((topkey (car sublist))
  10567. (elms (cadr sublist))
  10568. (keys (mapcar #'car elms))
  10569. (long (> (length elms) 3)))
  10570. (append
  10571. (list
  10572. ;; Make a description of the submenu.
  10573. (list topkey
  10574. (concat
  10575. (mapconcat #'cdr
  10576. (cl-subseq elms 0 (if long 3 (length elms)))
  10577. ", ")
  10578. (when long ", ..."))))
  10579. ;; List of entries in submenu.
  10580. (cl-mapcar #'list
  10581. (org--insert-structure-template-unique-keys keys)
  10582. (mapcar #'cdr elms)
  10583. (make-list (length elms) ""))))))
  10584. superlist))
  10585. "Select a key\n============"
  10586. "Key: ")))
  10587. (defun org--insert-structure-template-unique-keys (keys)
  10588. "Make a list of unique, two characters long elements from KEYS.
  10589. Elements of length one have a tab appended. Elements of length
  10590. two are kept as is. Longer elements are truncated to length two.
  10591. If an element cannot be made unique, an error is raised."
  10592. (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  10593. menu-keys)
  10594. (dolist (key orderd-keys)
  10595. (let ((potential-key
  10596. (cl-case (length key)
  10597. (1 (concat key "\t"))
  10598. (2 key)
  10599. (otherwise
  10600. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  10601. (mapcar (apply-partially #'concat (substring key 0 1))
  10602. (split-string (substring key 1) "" t)))))))
  10603. (if (or (not potential-key) (assoc potential-key menu-keys))
  10604. (user-error "Could not make unique key for %s." key)
  10605. (push (cons potential-key key) menu-keys))))
  10606. (mapcar #'car
  10607. (cl-sort menu-keys #'<
  10608. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  10609. (defun org-insert-structure-template (type)
  10610. "Insert a block structure of the type #+begin_foo/#+end_foo.
  10611. Select a block from `org-structure-template-alist' then type
  10612. either RET, TAB or SPC to write the block type. With an active
  10613. region, wrap the region in the block. Otherwise, insert an empty
  10614. block."
  10615. (interactive
  10616. (list (pcase (org--insert-structure-template-mks)
  10617. (`("\t" . ,_) (read-string "Structure type: "))
  10618. (`(,_ ,choice . ,_) choice))))
  10619. (let* ((region? (use-region-p))
  10620. (col (current-indentation))
  10621. (indent (make-string col ?\s))
  10622. (special? (string-match-p "\\(src\\|export\\)\\'" type))
  10623. (region-string (and region?
  10624. (buffer-substring (region-beginning)
  10625. (region-end))))
  10626. (region-end-blank (and region?
  10627. (save-excursion
  10628. (goto-char (region-end))
  10629. (when (looking-at "[ \t]*$")
  10630. (replace-match "")
  10631. t))))
  10632. s)
  10633. (when region? (delete-region (region-beginning) (region-end)))
  10634. (unless (save-excursion (skip-chars-backward "[ \t]") (bolp))
  10635. (insert "\n"))
  10636. (beginning-of-line)
  10637. (save-excursion
  10638. (insert
  10639. (with-temp-buffer
  10640. (when region?
  10641. (insert region-string "\n")
  10642. (when (string-match-p
  10643. (concat "\\`" (regexp-opt '("example" "export" "src")))
  10644. type)
  10645. (org-escape-code-in-region (point-min) (point-max))))
  10646. (goto-char (point-min))
  10647. ;; Delete trailing white-lines.
  10648. (when region?
  10649. (while (looking-at-p "^[ \t]*$")
  10650. (delete-region (line-beginning-position)
  10651. (line-beginning-position 2))))
  10652. (save-excursion
  10653. (while (not (eobp))
  10654. (unless (looking-at-p indent)
  10655. (insert indent))
  10656. (forward-line)))
  10657. (insert
  10658. indent
  10659. (format "#+begin_%s%s\n" type (if special? " " "")))
  10660. (unless region? (indent-to col))
  10661. (setq s (point))
  10662. (goto-char (point-max))
  10663. (skip-chars-backward "[ \t\n]" s)
  10664. (delete-region (line-end-position) (point-max))
  10665. (insert "\n" indent
  10666. (format "#+end_%s" (car (split-string type)))
  10667. (if region-end-blank "" "\n"))
  10668. (buffer-substring (point-min) (point))))
  10669. (when (and (eobp) (not (bolp))) (insert "\n")))
  10670. (cond (special?
  10671. (end-of-line))
  10672. (t
  10673. (forward-line)
  10674. (skip-chars-forward "[ \t]*")))))
  10675. ;;;; TODO, DEADLINE, Comments
  10676. (defun org-toggle-comment ()
  10677. "Change the COMMENT state of an entry."
  10678. (interactive)
  10679. (save-excursion
  10680. (org-back-to-heading)
  10681. (let ((case-fold-search nil))
  10682. (looking-at org-complex-heading-regexp))
  10683. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  10684. (skip-chars-forward " \t")
  10685. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  10686. (if (org-in-commented-heading-p t)
  10687. (delete-region (point)
  10688. (progn (search-forward " " (line-end-position) 'move)
  10689. (skip-chars-forward " \t")
  10690. (point)))
  10691. (insert org-comment-string)
  10692. (unless (eolp) (insert " ")))))
  10693. (defvar org-last-todo-state-is-todo nil
  10694. "This is non-nil when the last TODO state change led to a TODO state.
  10695. If the last change removed the TODO tag or switched to DONE, then
  10696. this is nil.")
  10697. (defvar org-todo-setup-filter-hook nil
  10698. "Hook for functions that pre-filter todo specs.
  10699. Each function takes a todo spec and returns either nil or the spec
  10700. transformed into canonical form." )
  10701. (defvar org-todo-get-default-hook nil
  10702. "Hook for functions that get a default item for todo.
  10703. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  10704. nil or a string to be used for the todo mark." )
  10705. (defvar org-agenda-headline-snapshot-before-repeat)
  10706. (defun org-current-effective-time ()
  10707. "Return current time adjusted for `org-extend-today-until' variable."
  10708. (let* ((ct (org-current-time))
  10709. (dct (decode-time ct))
  10710. (ct1
  10711. (cond
  10712. (org-use-last-clock-out-time-as-effective-time
  10713. (or (org-clock-get-last-clock-out-time) ct))
  10714. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  10715. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  10716. (t ct))))
  10717. ct1))
  10718. (defun org-todo-yesterday (&optional arg)
  10719. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  10720. (interactive "P")
  10721. (if (eq major-mode 'org-agenda-mode)
  10722. (apply 'org-agenda-todo-yesterday arg)
  10723. (let* ((org-use-effective-time t)
  10724. (hour (nth 2 (decode-time (org-current-time))))
  10725. (org-extend-today-until (1+ hour)))
  10726. (org-todo arg))))
  10727. (defvar org-block-entry-blocking ""
  10728. "First entry preventing the TODO state change.")
  10729. (defun org-cancel-repeater ()
  10730. "Cancel a repeater by setting its numeric value to zero."
  10731. (interactive)
  10732. (save-excursion
  10733. (org-back-to-heading t)
  10734. (let ((bound1 (point))
  10735. (bound0 (save-excursion (outline-next-heading) (point))))
  10736. (when (and (re-search-forward
  10737. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  10738. org-deadline-time-regexp "\\)\\|\\("
  10739. org-ts-regexp "\\)")
  10740. bound0 t)
  10741. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  10742. bound1 t))
  10743. (replace-match "0" t nil nil 1)))))
  10744. (defvar org-state)
  10745. (defvar org-blocked-by-checkboxes)
  10746. (defun org-todo (&optional arg)
  10747. "Change the TODO state of an item.
  10748. The state of an item is given by a keyword at the start of the heading,
  10749. like
  10750. *** TODO Write paper
  10751. *** DONE Call mom
  10752. The different keywords are specified in the variable `org-todo-keywords'.
  10753. By default the available states are \"TODO\" and \"DONE\". So, for this
  10754. example: when the item starts with TODO, it is changed to DONE.
  10755. When it starts with DONE, the DONE is removed. And when neither TODO nor
  10756. DONE are present, add TODO at the beginning of the heading.
  10757. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  10758. state.
  10759. With numeric prefix ARG, switch to that state.
  10760. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  10761. next set of TODO \
  10762. keywords (nextset).
  10763. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  10764. prefix, circumvent any state blocking.
  10765. With a numeric prefix arg of 0, inhibit note taking for the change.
  10766. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  10767. When called through ELisp, arg is also interpreted in the following way:
  10768. `none' -> empty state
  10769. \"\" -> switch to empty state
  10770. `done' -> switch to DONE
  10771. `nextset' -> switch to the next set of keywords
  10772. `previousset' -> switch to the previous set of keywords
  10773. \"WAITING\" -> switch to the specified keyword, but only if it
  10774. really is a member of `org-todo-keywords'."
  10775. (interactive "P")
  10776. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10777. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10778. 'region-start-level 'region))
  10779. org-loop-over-headlines-in-active-region)
  10780. (org-map-entries
  10781. `(org-todo ,arg)
  10782. org-loop-over-headlines-in-active-region
  10783. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  10784. (when (equal arg '(16)) (setq arg 'nextset))
  10785. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  10786. (let ((org-blocker-hook org-blocker-hook)
  10787. commentp
  10788. case-fold-search)
  10789. (when (equal arg '(64))
  10790. (setq arg nil org-blocker-hook nil))
  10791. (when (and org-blocker-hook
  10792. (or org-inhibit-blocking
  10793. (org-entry-get nil "NOBLOCKING")))
  10794. (setq org-blocker-hook nil))
  10795. (save-excursion
  10796. (catch 'exit
  10797. (org-back-to-heading t)
  10798. (when (org-in-commented-heading-p t)
  10799. (org-toggle-comment)
  10800. (setq commentp t))
  10801. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  10802. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  10803. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  10804. (let* ((match-data (match-data))
  10805. (startpos (copy-marker (line-beginning-position)))
  10806. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  10807. (org-log-done org-log-done)
  10808. (org-log-repeat org-log-repeat)
  10809. (org-todo-log-states org-todo-log-states)
  10810. (org-inhibit-logging
  10811. (if (equal arg 0)
  10812. (progn (setq arg nil) 'note) org-inhibit-logging))
  10813. (this (match-string 1))
  10814. (hl-pos (match-beginning 0))
  10815. (head (org-get-todo-sequence-head this))
  10816. (ass (assoc head org-todo-kwd-alist))
  10817. (interpret (nth 1 ass))
  10818. (done-word (nth 3 ass))
  10819. (final-done-word (nth 4 ass))
  10820. (org-last-state (or this ""))
  10821. (completion-ignore-case t)
  10822. (member (member this org-todo-keywords-1))
  10823. (tail (cdr member))
  10824. (org-state (cond
  10825. ((and org-todo-key-trigger
  10826. (or (and (equal arg '(4))
  10827. (eq org-use-fast-todo-selection 'prefix))
  10828. (and (not arg) org-use-fast-todo-selection
  10829. (not (eq org-use-fast-todo-selection
  10830. 'prefix)))))
  10831. ;; Use fast selection.
  10832. (org-fast-todo-selection))
  10833. ((and (equal arg '(4))
  10834. (or (not org-use-fast-todo-selection)
  10835. (not org-todo-key-trigger)))
  10836. ;; Read a state with completion.
  10837. (completing-read
  10838. "State: " (mapcar #'list org-todo-keywords-1)
  10839. nil t))
  10840. ((eq arg 'right)
  10841. (if this
  10842. (if tail (car tail) nil)
  10843. (car org-todo-keywords-1)))
  10844. ((eq arg 'left)
  10845. (unless (equal member org-todo-keywords-1)
  10846. (if this
  10847. (nth (- (length org-todo-keywords-1)
  10848. (length tail) 2)
  10849. org-todo-keywords-1)
  10850. (org-last org-todo-keywords-1))))
  10851. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  10852. (setq arg nil))) ;hack to fall back to cycling
  10853. (arg
  10854. ;; User or caller requests a specific state.
  10855. (cond
  10856. ((equal arg "") nil)
  10857. ((eq arg 'none) nil)
  10858. ((eq arg 'done) (or done-word (car org-done-keywords)))
  10859. ((eq arg 'nextset)
  10860. (or (car (cdr (member head org-todo-heads)))
  10861. (car org-todo-heads)))
  10862. ((eq arg 'previousset)
  10863. (let ((org-todo-heads (reverse org-todo-heads)))
  10864. (or (car (cdr (member head org-todo-heads)))
  10865. (car org-todo-heads))))
  10866. ((car (member arg org-todo-keywords-1)))
  10867. ((stringp arg)
  10868. (user-error "State `%s' not valid in this file" arg))
  10869. ((nth (1- (prefix-numeric-value arg))
  10870. org-todo-keywords-1))))
  10871. ((null member) (or head (car org-todo-keywords-1)))
  10872. ((equal this final-done-word) nil) ;-> make empty
  10873. ((null tail) nil) ;-> first entry
  10874. ((memq interpret '(type priority))
  10875. (if (eq this-command last-command)
  10876. (car tail)
  10877. (if (> (length tail) 0)
  10878. (or done-word (car org-done-keywords))
  10879. nil)))
  10880. (t
  10881. (car tail))))
  10882. (org-state (or
  10883. (run-hook-with-args-until-success
  10884. 'org-todo-get-default-hook org-state org-last-state)
  10885. org-state))
  10886. (next (if org-state (concat " " org-state " ") " "))
  10887. (change-plist (list :type 'todo-state-change :from this :to org-state
  10888. :position startpos))
  10889. dolog now-done-p)
  10890. (when org-blocker-hook
  10891. (let (org-blocked-by-checkboxes block-reason)
  10892. (setq org-last-todo-state-is-todo
  10893. (not (member this org-done-keywords)))
  10894. (unless (save-excursion
  10895. (save-match-data
  10896. (org-with-wide-buffer
  10897. (run-hook-with-args-until-failure
  10898. 'org-blocker-hook change-plist))))
  10899. (setq block-reason (if org-blocked-by-checkboxes
  10900. "contained checkboxes"
  10901. (format "\"%s\"" org-block-entry-blocking)))
  10902. (if (called-interactively-p 'interactive)
  10903. (user-error "TODO state change from %s to %s blocked (by %s)"
  10904. this org-state block-reason)
  10905. ;; Fail silently.
  10906. (message "TODO state change from %s to %s blocked (by %s)"
  10907. this org-state block-reason)
  10908. (throw 'exit nil)))))
  10909. (store-match-data match-data)
  10910. (replace-match next t t)
  10911. (cond ((equal this org-state)
  10912. (message "TODO state was already %s" (org-trim next)))
  10913. ((not (pos-visible-in-window-p hl-pos))
  10914. (message "TODO state changed to %s" (org-trim next))))
  10915. (unless head
  10916. (setq head (org-get-todo-sequence-head org-state)
  10917. ass (assoc head org-todo-kwd-alist)
  10918. interpret (nth 1 ass)
  10919. done-word (nth 3 ass)
  10920. final-done-word (nth 4 ass)))
  10921. (when (memq arg '(nextset previousset))
  10922. (message "Keyword-Set %d/%d: %s"
  10923. (- (length org-todo-sets) -1
  10924. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  10925. (length org-todo-sets)
  10926. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  10927. (setq org-last-todo-state-is-todo
  10928. (not (member org-state org-done-keywords)))
  10929. (setq now-done-p (and (member org-state org-done-keywords)
  10930. (not (member this org-done-keywords))))
  10931. (and logging (org-local-logging logging))
  10932. (when (and (or org-todo-log-states org-log-done)
  10933. (not (eq org-inhibit-logging t))
  10934. (not (memq arg '(nextset previousset))))
  10935. ;; We need to look at recording a time and note.
  10936. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  10937. (nth 2 (assoc this org-todo-log-states))))
  10938. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  10939. (setq dolog 'time))
  10940. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  10941. (and org-state
  10942. (member org-state org-not-done-keywords)
  10943. (not (member this org-not-done-keywords))))
  10944. ;; This is now a todo state and was not one before
  10945. ;; If there was a CLOSED time stamp, get rid of it.
  10946. (org-add-planning-info nil nil 'closed))
  10947. (when (and now-done-p org-log-done)
  10948. ;; It is now done, and it was not done before.
  10949. (org-add-planning-info 'closed (org-current-effective-time))
  10950. (when (and (not dolog) (eq 'note org-log-done))
  10951. (org-add-log-setup 'done org-state this 'note)))
  10952. (when (and org-state dolog)
  10953. ;; This is a non-nil state, and we need to log it.
  10954. (org-add-log-setup 'state org-state this dolog)))
  10955. ;; Fixup tag positioning.
  10956. (org-todo-trigger-tag-changes org-state)
  10957. (when org-auto-align-tags (org-align-tags))
  10958. (when org-provide-todo-statistics
  10959. (org-update-parent-todo-statistics))
  10960. (run-hooks 'org-after-todo-state-change-hook)
  10961. (when (and arg (not (member org-state org-done-keywords)))
  10962. (setq head (org-get-todo-sequence-head org-state)))
  10963. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  10964. ;; Do we need to trigger a repeat?
  10965. (when now-done-p
  10966. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  10967. ;; This is for the agenda, take a snapshot of the headline.
  10968. (save-match-data
  10969. (setq org-agenda-headline-snapshot-before-repeat
  10970. (org-get-heading))))
  10971. (org-auto-repeat-maybe org-state))
  10972. ;; Fixup cursor location if close to the keyword.
  10973. (when (and (outline-on-heading-p)
  10974. (not (bolp))
  10975. (save-excursion (beginning-of-line 1)
  10976. (looking-at org-todo-line-regexp))
  10977. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  10978. (goto-char (or (match-end 2) (match-end 1)))
  10979. (and (looking-at " ") (just-one-space)))
  10980. (when org-trigger-hook
  10981. (save-excursion
  10982. (run-hook-with-args 'org-trigger-hook change-plist)))
  10983. (when commentp (org-toggle-comment))))))))
  10984. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  10985. "Block turning an entry into a TODO, using the hierarchy.
  10986. This checks whether the current task should be blocked from state
  10987. changes. Such blocking occurs when:
  10988. 1. The task has children which are not all in a completed state.
  10989. 2. A task has a parent with the property :ORDERED:, and there
  10990. are siblings prior to the current task with incomplete
  10991. status.
  10992. 3. The parent of the task is blocked because it has siblings that should
  10993. be done first, or is child of a block grandparent TODO entry."
  10994. (if (not org-enforce-todo-dependencies)
  10995. t ; if locally turned off don't block
  10996. (catch 'dont-block
  10997. ;; If this is not a todo state change, or if this entry is already DONE,
  10998. ;; do not block
  10999. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11000. (member (plist-get change-plist :from)
  11001. (cons 'done org-done-keywords))
  11002. (member (plist-get change-plist :to)
  11003. (cons 'todo org-not-done-keywords))
  11004. (not (plist-get change-plist :to)))
  11005. (throw 'dont-block t))
  11006. ;; If this task has children, and any are undone, it's blocked
  11007. (save-excursion
  11008. (org-back-to-heading t)
  11009. (let ((this-level (funcall outline-level)))
  11010. (outline-next-heading)
  11011. (let ((child-level (funcall outline-level)))
  11012. (while (and (not (eobp))
  11013. (> child-level this-level))
  11014. ;; this todo has children, check whether they are all
  11015. ;; completed
  11016. (when (and (not (org-entry-is-done-p))
  11017. (org-entry-is-todo-p))
  11018. (setq org-block-entry-blocking (org-get-heading))
  11019. (throw 'dont-block nil))
  11020. (outline-next-heading)
  11021. (setq child-level (funcall outline-level))))))
  11022. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11023. ;; any previous siblings are undone, it's blocked
  11024. (save-excursion
  11025. (org-back-to-heading t)
  11026. (let* ((pos (point))
  11027. (parent-pos (and (org-up-heading-safe) (point)))
  11028. (case-fold-search nil))
  11029. (unless parent-pos (throw 'dont-block t)) ; no parent
  11030. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11031. (forward-line 1)
  11032. (re-search-forward org-not-done-heading-regexp pos t))
  11033. (setq org-block-entry-blocking (match-string 0))
  11034. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11035. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11036. (while t
  11037. (goto-char parent-pos)
  11038. (unless (looking-at org-not-done-heading-regexp)
  11039. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11040. (setq pos (point))
  11041. (setq parent-pos (and (org-up-heading-safe) (point)))
  11042. (unless parent-pos (throw 'dont-block t)) ; no parent
  11043. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11044. (forward-line 1)
  11045. (re-search-forward org-not-done-heading-regexp pos t)
  11046. (setq org-block-entry-blocking (org-get-heading)))
  11047. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11048. (defcustom org-track-ordered-property-with-tag nil
  11049. "Should the ORDERED property also be shown as a tag?
  11050. The ORDERED property decides if an entry should require subtasks to be
  11051. completed in sequence. Since a property is not very visible, setting
  11052. this option means that toggling the ORDERED property with the command
  11053. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11054. not relevant for the behavior, but it makes things more visible.
  11055. Note that toggling the tag with tags commands will not change the property
  11056. and therefore not influence behavior!
  11057. This can be t, meaning the tag ORDERED should be used, It can also be a
  11058. string to select a different tag for this task."
  11059. :group 'org-todo
  11060. :type '(choice
  11061. (const :tag "No tracking" nil)
  11062. (const :tag "Track with ORDERED tag" t)
  11063. (string :tag "Use other tag")))
  11064. (defun org-toggle-ordered-property ()
  11065. "Toggle the ORDERED property of the current entry.
  11066. For better visibility, you can track the value of this property with a tag.
  11067. See variable `org-track-ordered-property-with-tag'."
  11068. (interactive)
  11069. (let* ((t1 org-track-ordered-property-with-tag)
  11070. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11071. (save-excursion
  11072. (org-back-to-heading)
  11073. (if (org-entry-get nil "ORDERED")
  11074. (progn
  11075. (org-delete-property "ORDERED")
  11076. (and tag (org-toggle-tag tag 'off))
  11077. (message "Subtasks can be completed in arbitrary order"))
  11078. (org-entry-put nil "ORDERED" "t")
  11079. (and tag (org-toggle-tag tag 'on))
  11080. (message "Subtasks must be completed in sequence")))))
  11081. (defun org-block-todo-from-checkboxes (change-plist)
  11082. "Block turning an entry into a TODO, using checkboxes.
  11083. This checks whether the current task should be blocked from state
  11084. changes because there are unchecked boxes in this entry."
  11085. (if (not org-enforce-todo-checkbox-dependencies)
  11086. t ; if locally turned off don't block
  11087. (catch 'dont-block
  11088. ;; If this is not a todo state change, or if this entry is already DONE,
  11089. ;; do not block
  11090. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11091. (member (plist-get change-plist :from)
  11092. (cons 'done org-done-keywords))
  11093. (member (plist-get change-plist :to)
  11094. (cons 'todo org-not-done-keywords))
  11095. (not (plist-get change-plist :to)))
  11096. (throw 'dont-block t))
  11097. ;; If this task has checkboxes that are not checked, it's blocked
  11098. (save-excursion
  11099. (org-back-to-heading t)
  11100. (let ((beg (point)) end)
  11101. (outline-next-heading)
  11102. (setq end (point))
  11103. (goto-char beg)
  11104. (when (org-list-search-forward
  11105. (concat (org-item-beginning-re)
  11106. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11107. "\\[[- ]\\]")
  11108. end t)
  11109. (when (boundp 'org-blocked-by-checkboxes)
  11110. (setq org-blocked-by-checkboxes t))
  11111. (throw 'dont-block nil))))
  11112. t))) ; do not block
  11113. (defun org-entry-blocked-p ()
  11114. "Non-nil if entry at point is blocked."
  11115. (and (not (org-entry-get nil "NOBLOCKING"))
  11116. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11117. (not (run-hook-with-args-until-failure
  11118. 'org-blocker-hook
  11119. (list :type 'todo-state-change
  11120. :position (point)
  11121. :from 'todo
  11122. :to 'done)))))
  11123. (defun org-update-statistics-cookies (all)
  11124. "Update the statistics cookie, either from TODO or from checkboxes.
  11125. This should be called with the cursor in a line with a statistics
  11126. cookie. When called with a \\[universal-argument] prefix, update
  11127. all statistics cookies in the buffer."
  11128. (interactive "P")
  11129. (if all
  11130. (progn
  11131. (org-update-checkbox-count 'all)
  11132. (org-map-entries 'org-update-parent-todo-statistics))
  11133. (if (not (org-at-heading-p))
  11134. (org-update-checkbox-count)
  11135. (let ((pos (point-marker))
  11136. end l1 l2)
  11137. (ignore-errors (org-back-to-heading t))
  11138. (if (not (org-at-heading-p))
  11139. (org-update-checkbox-count)
  11140. (setq l1 (org-outline-level))
  11141. (setq end (save-excursion
  11142. (outline-next-heading)
  11143. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11144. (point)))
  11145. (if (and (save-excursion
  11146. (re-search-forward
  11147. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11148. (not (save-excursion (re-search-forward
  11149. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11150. (org-update-checkbox-count)
  11151. (if (and l2 (> l2 l1))
  11152. (progn
  11153. (goto-char end)
  11154. (org-update-parent-todo-statistics))
  11155. (goto-char pos)
  11156. (beginning-of-line 1)
  11157. (while (re-search-forward
  11158. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11159. (point-at-eol) t)
  11160. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11161. (goto-char pos)
  11162. (move-marker pos nil)))))
  11163. (defvar org-entry-property-inherited-from) ;; defined below
  11164. (defun org-update-parent-todo-statistics ()
  11165. "Update any statistics cookie in the parent of the current headline.
  11166. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11167. the entire subtree and this will travel up the hierarchy and update
  11168. statistics everywhere."
  11169. (let* ((prop (save-excursion (org-up-heading-safe)
  11170. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11171. (recursive (or (not org-hierarchical-todo-statistics)
  11172. (and prop (string-match "\\<recursive\\>" prop))))
  11173. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11174. 0))
  11175. (first t)
  11176. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11177. level ltoggle l1 new ndel
  11178. (cnt-all 0) (cnt-done 0) is-percent kwd
  11179. checkbox-beg cookie-present)
  11180. (catch 'exit
  11181. (save-excursion
  11182. (beginning-of-line 1)
  11183. (setq ltoggle (funcall outline-level))
  11184. ;; Three situations are to consider:
  11185. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11186. ;; to the top-level ancestor on the headline;
  11187. ;; 2. If parent has "recursive" property, repeat up to the
  11188. ;; headline setting that property, taking inheritance into
  11189. ;; account;
  11190. ;; 3. Else, move up to direct parent and proceed only once.
  11191. (while (and (setq level (org-up-heading-safe))
  11192. (or recursive first)
  11193. (>= (point) lim))
  11194. (setq first nil cookie-present nil)
  11195. (unless (and level
  11196. (not (string-match
  11197. "\\<checkbox\\>"
  11198. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11199. "")))))
  11200. (throw 'exit nil))
  11201. (while (re-search-forward box-re (point-at-eol) t)
  11202. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11203. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11204. (save-match-data
  11205. (unless (outline-next-heading) (throw 'exit nil))
  11206. (while (and (looking-at org-complex-heading-regexp)
  11207. (> (setq l1 (length (match-string 1))) level))
  11208. (setq kwd (and (or recursive (= l1 ltoggle))
  11209. (match-string 2)))
  11210. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11211. (and (eq org-provide-todo-statistics t)
  11212. (or (member kwd org-done-keywords)))
  11213. (and (listp org-provide-todo-statistics)
  11214. (stringp (car org-provide-todo-statistics))
  11215. (or (member kwd org-provide-todo-statistics)
  11216. (member kwd org-done-keywords)))
  11217. (and (listp org-provide-todo-statistics)
  11218. (listp (car org-provide-todo-statistics))
  11219. (or (member kwd (car org-provide-todo-statistics))
  11220. (and (member kwd org-done-keywords)
  11221. (member kwd (cadr org-provide-todo-statistics))))))
  11222. (setq cnt-all (1+ cnt-all))
  11223. (and (eq org-provide-todo-statistics t)
  11224. kwd
  11225. (setq cnt-all (1+ cnt-all))))
  11226. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11227. (member kwd org-done-keywords))
  11228. (and (listp org-provide-todo-statistics)
  11229. (listp (car org-provide-todo-statistics))
  11230. (member kwd org-done-keywords)
  11231. (member kwd (cadr org-provide-todo-statistics)))
  11232. (and (listp org-provide-todo-statistics)
  11233. (stringp (car org-provide-todo-statistics))
  11234. (member kwd org-done-keywords)))
  11235. (setq cnt-done (1+ cnt-done)))
  11236. (outline-next-heading)))
  11237. (setq new
  11238. (if is-percent
  11239. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11240. (max 1 cnt-all)))
  11241. (format "[%d/%d]" cnt-done cnt-all))
  11242. ndel (- (match-end 0) checkbox-beg))
  11243. (goto-char checkbox-beg)
  11244. (insert new)
  11245. (delete-region (point) (+ (point) ndel))
  11246. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11247. (when cookie-present
  11248. (run-hook-with-args 'org-after-todo-statistics-hook
  11249. cnt-done (- cnt-all cnt-done))))))
  11250. (run-hooks 'org-todo-statistics-hook)))
  11251. (defvar org-after-todo-statistics-hook nil
  11252. "Hook that is called after a TODO statistics cookie has been updated.
  11253. Each function is called with two arguments: the number of not-done entries
  11254. and the number of done entries.
  11255. For example, the following function, when added to this hook, will switch
  11256. an entry to DONE when all children are done, and back to TODO when new
  11257. entries are set to a TODO status. Note that this hook is only called
  11258. when there is a statistics cookie in the headline!
  11259. (defun org-summary-todo (n-done n-not-done)
  11260. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11261. (let (org-log-done org-log-states) ; turn off logging
  11262. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11263. ")
  11264. (defvar org-todo-statistics-hook nil
  11265. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11266. This hook runs even if there is no statistics cookie present, in which case
  11267. `org-after-todo-statistics-hook' would not run.")
  11268. (defun org-todo-trigger-tag-changes (state)
  11269. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11270. (let ((l org-todo-state-tags-triggers)
  11271. changes)
  11272. (when (or (not state) (equal state ""))
  11273. (setq changes (append changes (cdr (assoc "" l)))))
  11274. (when (and (stringp state) (> (length state) 0))
  11275. (setq changes (append changes (cdr (assoc state l)))))
  11276. (when (member state org-not-done-keywords)
  11277. (setq changes (append changes (cdr (assq 'todo l)))))
  11278. (when (member state org-done-keywords)
  11279. (setq changes (append changes (cdr (assq 'done l)))))
  11280. (dolist (c changes)
  11281. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11282. (defun org-local-logging (value)
  11283. "Get logging settings from a property VALUE."
  11284. ;; Directly set the variables, they are already local.
  11285. (setq org-log-done nil
  11286. org-log-repeat nil
  11287. org-todo-log-states nil)
  11288. (dolist (w (split-string value))
  11289. (let (a)
  11290. (cond
  11291. ((setq a (assoc w org-startup-options))
  11292. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11293. (set (nth 1 a) (nth 2 a))))
  11294. ((setq a (org-extract-log-state-settings w))
  11295. (and (member (car a) org-todo-keywords-1)
  11296. (push a org-todo-log-states)))))))
  11297. (defun org-get-todo-sequence-head (kwd)
  11298. "Return the head of the TODO sequence to which KWD belongs.
  11299. If KWD is not set, check if there is a text property remembering the
  11300. right sequence."
  11301. (let (p)
  11302. (cond
  11303. ((not kwd)
  11304. (or (get-text-property (point-at-bol) 'org-todo-head)
  11305. (progn
  11306. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11307. nil (point-at-eol)))
  11308. (get-text-property p 'org-todo-head))))
  11309. ((not (member kwd org-todo-keywords-1))
  11310. (car org-todo-keywords-1))
  11311. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11312. (defun org-fast-todo-selection ()
  11313. "Fast TODO keyword selection with single keys.
  11314. Returns the new TODO keyword, or nil if no state change should occur."
  11315. (let* ((fulltable org-todo-key-alist)
  11316. (done-keywords org-done-keywords) ;; needed for the faces.
  11317. (maxlen (apply 'max (mapcar
  11318. (lambda (x)
  11319. (if (stringp (car x)) (string-width (car x)) 0))
  11320. fulltable)))
  11321. (expert nil)
  11322. (fwidth (+ maxlen 3 1 3))
  11323. (ncol (/ (- (window-width) 4) fwidth))
  11324. tg cnt e c tbl
  11325. groups ingroup)
  11326. (save-excursion
  11327. (save-window-excursion
  11328. (if expert
  11329. (set-buffer (get-buffer-create " *Org todo*"))
  11330. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11331. (erase-buffer)
  11332. (setq-local org-done-keywords done-keywords)
  11333. (setq tbl fulltable cnt 0)
  11334. (while (setq e (pop tbl))
  11335. (cond
  11336. ((equal e '(:startgroup))
  11337. (push '() groups) (setq ingroup t)
  11338. (unless (= cnt 0)
  11339. (setq cnt 0)
  11340. (insert "\n"))
  11341. (insert "{ "))
  11342. ((equal e '(:endgroup))
  11343. (setq ingroup nil cnt 0)
  11344. (insert "}\n"))
  11345. ((equal e '(:newline))
  11346. (unless (= cnt 0)
  11347. (setq cnt 0)
  11348. (insert "\n")
  11349. (setq e (car tbl))
  11350. (while (equal (car tbl) '(:newline))
  11351. (insert "\n")
  11352. (setq tbl (cdr tbl)))))
  11353. (t
  11354. (setq tg (car e) c (cdr e))
  11355. (when ingroup (push tg (car groups)))
  11356. (setq tg (org-add-props tg nil 'face
  11357. (org-get-todo-face tg)))
  11358. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11359. (insert "[" c "] " tg (make-string
  11360. (- fwidth 4 (length tg)) ?\ ))
  11361. (when (= (setq cnt (1+ cnt)) ncol)
  11362. (insert "\n")
  11363. (when ingroup (insert " "))
  11364. (setq cnt 0)))))
  11365. (insert "\n")
  11366. (goto-char (point-min))
  11367. (unless expert (org-fit-window-to-buffer))
  11368. (message "[a-z..]:Set [SPC]:clear")
  11369. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11370. (cond
  11371. ((or (= c ?\C-g)
  11372. (and (= c ?q) (not (rassoc c fulltable))))
  11373. (setq quit-flag t))
  11374. ((= c ?\ ) nil)
  11375. ((setq e (rassoc c fulltable) tg (car e))
  11376. tg)
  11377. (t (setq quit-flag t)))))))
  11378. (defun org-entry-is-todo-p ()
  11379. (member (org-get-todo-state) org-not-done-keywords))
  11380. (defun org-entry-is-done-p ()
  11381. (member (org-get-todo-state) org-done-keywords))
  11382. (defun org-get-todo-state ()
  11383. "Return the TODO keyword of the current subtree."
  11384. (save-excursion
  11385. (org-back-to-heading t)
  11386. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11387. (match-end 2)
  11388. (match-string 2))))
  11389. (defun org-at-date-range-p (&optional inactive-ok)
  11390. "Non-nil if point is inside a date range.
  11391. When optional argument INACTIVE-OK is non-nil, also consider
  11392. inactive time ranges.
  11393. When this function returns a non-nil value, match data is set
  11394. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11395. on INACTIVE-OK."
  11396. (interactive)
  11397. (save-excursion
  11398. (catch 'exit
  11399. (let ((pos (point)))
  11400. (skip-chars-backward "^[<\r\n")
  11401. (skip-chars-backward "<[")
  11402. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11403. (>= (match-end 0) pos)
  11404. (throw 'exit t))
  11405. (skip-chars-backward "^<[\r\n")
  11406. (skip-chars-backward "<[")
  11407. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11408. (>= (match-end 0) pos)
  11409. (throw 'exit t)))
  11410. nil)))
  11411. (defun org-get-repeat (&optional timestamp)
  11412. "Check if there is a time-stamp with repeater in this entry.
  11413. Return the repeater, as a string, or nil. Also return nil when
  11414. this function is called before first heading.
  11415. When optional argument TIMESTAMP is a string, extract the
  11416. repeater from there instead."
  11417. (save-match-data
  11418. (cond (timestamp
  11419. (and (string-match org-repeat-re timestamp)
  11420. (match-string-no-properties 1 timestamp)))
  11421. ((org-before-first-heading-p) nil)
  11422. (t
  11423. (save-excursion
  11424. (org-back-to-heading t)
  11425. (let ((end (org-entry-end-position)))
  11426. (catch :repeat
  11427. (while (re-search-forward org-repeat-re end t)
  11428. (when (save-match-data (org-at-timestamp-p 'agenda))
  11429. (throw :repeat (match-string-no-properties 1)))))))))))
  11430. (defvar org-last-changed-timestamp)
  11431. (defvar org-last-inserted-timestamp)
  11432. (defvar org-log-post-message)
  11433. (defvar org-log-note-purpose)
  11434. (defvar org-log-note-how nil)
  11435. (defvar org-log-note-extra)
  11436. (defun org-auto-repeat-maybe (done-word)
  11437. "Check if the current headline contains a repeated time-stamp.
  11438. If yes, set TODO state back to what it was and change the base date
  11439. of repeating deadline/scheduled time stamps to new date.
  11440. This function is run automatically after each state change to a DONE state."
  11441. (let* ((repeat (org-get-repeat))
  11442. (aa (assoc org-last-state org-todo-kwd-alist))
  11443. (interpret (nth 1 aa))
  11444. (head (nth 2 aa))
  11445. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11446. (msg "Entry repeats: ")
  11447. (org-log-done nil)
  11448. (org-todo-log-states nil)
  11449. (end (copy-marker (org-entry-end-position))))
  11450. (unwind-protect
  11451. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11452. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11453. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11454. (and (stringp org-todo-repeat-to-state)
  11455. org-todo-repeat-to-state)
  11456. (and org-todo-repeat-to-state org-last-state))))
  11457. (org-todo (cond
  11458. ((and to-state (member to-state org-todo-keywords-1))
  11459. to-state)
  11460. ((eq interpret 'type) org-last-state)
  11461. (head)
  11462. (t 'none))))
  11463. (org-back-to-heading t)
  11464. (org-add-planning-info nil nil 'closed)
  11465. ;; When `org-log-repeat' is non-nil or entry contains
  11466. ;; a clock, set LAST_REPEAT property.
  11467. (when (or org-log-repeat
  11468. (catch :clock
  11469. (save-excursion
  11470. (while (re-search-forward org-clock-line-re end t)
  11471. (when (org-at-clock-log-p) (throw :clock t))))))
  11472. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11473. (org-time-stamp-format t t)
  11474. (current-time))))
  11475. (when org-log-repeat
  11476. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11477. (memq 'org-add-log-note post-command-hook))
  11478. ;; We are already setup for some record.
  11479. (when (eq org-log-repeat 'note)
  11480. ;; Make sure we take a note, not only a time stamp.
  11481. (setq org-log-note-how 'note))
  11482. ;; Set up for taking a record.
  11483. (org-add-log-setup 'state
  11484. (or done-word (car org-done-keywords))
  11485. org-last-state
  11486. org-log-repeat)))
  11487. (let ((planning-re (regexp-opt
  11488. (list org-scheduled-string org-deadline-string))))
  11489. (while (re-search-forward org-ts-regexp end t)
  11490. (let* ((ts (match-string 0))
  11491. (planning? (org-at-planning-p))
  11492. (type (if (not planning?) "Plain:"
  11493. (save-excursion
  11494. (re-search-backward
  11495. planning-re (line-beginning-position) t)
  11496. (match-string 0)))))
  11497. (cond
  11498. ;; Ignore fake time-stamps (e.g., within comments).
  11499. ((not (org-at-timestamp-p 'agenda)))
  11500. ;; Time-stamps without a repeater are usually
  11501. ;; skipped. However, a SCHEDULED time-stamp without
  11502. ;; one is removed, as they are no longer relevant.
  11503. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11504. ts))
  11505. (when (equal type org-scheduled-string)
  11506. (org-remove-timestamp-with-keyword type)))
  11507. (t
  11508. (let ((n (string-to-number (match-string 2 ts)))
  11509. (what (match-string 3 ts)))
  11510. (when (equal what "w") (setq n (* n 7) what "d"))
  11511. (when (and (equal what "h")
  11512. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11513. ts)))
  11514. (user-error
  11515. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11516. has been set"
  11517. n))
  11518. ;; Preparation, see if we need to modify the start
  11519. ;; date for the change.
  11520. (when (match-end 1)
  11521. (let ((time (save-match-data
  11522. (org-time-string-to-time ts))))
  11523. (cond
  11524. ((equal (match-string 1 ts) ".")
  11525. ;; Shift starting date to today
  11526. (org-timestamp-change
  11527. (- (org-today) (time-to-days time))
  11528. 'day))
  11529. ((equal (match-string 1 ts) "+")
  11530. (let ((nshiftmax 10)
  11531. (nshift 0))
  11532. (while (or (= nshift 0)
  11533. (not (time-less-p (current-time) time)))
  11534. (when (= (cl-incf nshift) nshiftmax)
  11535. (or (y-or-n-p
  11536. (format "%d repeater intervals were not \
  11537. enough to shift date past today. Continue? "
  11538. nshift))
  11539. (user-error "Abort")))
  11540. (org-timestamp-change n (cdr (assoc what whata)))
  11541. (org-in-regexp org-ts-regexp3)
  11542. (setq ts (match-string 1))
  11543. (setq time
  11544. (save-match-data
  11545. (org-time-string-to-time ts)))))
  11546. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11547. ;; Rematch, so that we have everything in place
  11548. ;; for the real shift.
  11549. (org-in-regexp org-ts-regexp3)
  11550. (setq ts (match-string 1))
  11551. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11552. ts)))))
  11553. (save-excursion
  11554. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11555. (setq msg
  11556. (concat
  11557. msg type " " org-last-changed-timestamp " "))))))))
  11558. (setq org-log-post-message msg)
  11559. (message "%s" msg))
  11560. (set-marker end nil))))
  11561. (defun org-show-todo-tree (arg)
  11562. "Make a compact tree which shows all headlines marked with TODO.
  11563. The tree will show the lines where the regexp matches, and all higher
  11564. headlines above the match.
  11565. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11566. With a numeric prefix N, construct a sparse tree for the Nth element
  11567. of `org-todo-keywords-1'."
  11568. (interactive "P")
  11569. (let ((case-fold-search nil)
  11570. (kwd-re
  11571. (cond ((null arg) org-not-done-regexp)
  11572. ((equal arg '(4))
  11573. (let ((kwd
  11574. (completing-read "Keyword (or KWD1|KWD2|...): "
  11575. (mapcar #'list org-todo-keywords-1))))
  11576. (concat "\\("
  11577. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11578. "\\)\\>")))
  11579. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11580. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11581. org-todo-keywords-1)))
  11582. (t (user-error "Invalid prefix argument: %s" arg)))))
  11583. (message "%d TODO entries found"
  11584. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11585. (defun org--deadline-or-schedule (arg type time)
  11586. "Insert DEADLINE or SCHEDULE information in current entry.
  11587. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  11588. `org-schedule' for information about ARG and TIME arguments."
  11589. (let* ((deadline? (eq type 'deadline))
  11590. (keyword (if deadline? org-deadline-string org-scheduled-string))
  11591. (log (if deadline? org-log-redeadline org-log-reschedule))
  11592. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  11593. (old-date-time (and old-date (org-time-string-to-time old-date)))
  11594. ;; Save repeater cookie from either TIME or current scheduled
  11595. ;; time stamp. We are going to insert it back at the end of
  11596. ;; the process.
  11597. (repeater (or (and (org-string-nw-p time)
  11598. ;; We use `org-repeat-re' because we need
  11599. ;; to tell the difference between a real
  11600. ;; repeater and a time delta, e.g. "+2d".
  11601. (string-match org-repeat-re time)
  11602. (match-string 1 time))
  11603. (and (org-string-nw-p old-date)
  11604. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  11605. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  11606. old-date)
  11607. (match-string 1 old-date)))))
  11608. (pcase arg
  11609. (`(4)
  11610. (if (not old-date)
  11611. (message (if deadline? "Entry had no deadline to remove"
  11612. "Entry was not scheduled"))
  11613. (when (and old-date log)
  11614. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  11615. nil old-date log))
  11616. (org-remove-timestamp-with-keyword keyword)
  11617. (message (if deadline? "Entry no longer has a deadline."
  11618. "Entry is no longer scheduled."))))
  11619. (`(16)
  11620. (save-excursion
  11621. (org-back-to-heading t)
  11622. (let ((regexp (if deadline? org-deadline-time-regexp
  11623. org-scheduled-time-regexp)))
  11624. (if (not (re-search-forward regexp (line-end-position 2) t))
  11625. (user-error (if deadline? "No deadline information to update"
  11626. "No scheduled information to update"))
  11627. (let* ((rpl0 (match-string 1))
  11628. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  11629. (msg (if deadline? "Warn starting from" "Delay until")))
  11630. (replace-match
  11631. (concat keyword
  11632. " <" rpl
  11633. (format " -%dd"
  11634. (abs (- (time-to-days
  11635. (save-match-data
  11636. (org-read-date
  11637. nil t nil msg old-date-time)))
  11638. (time-to-days old-date-time))))
  11639. ">") t t))))))
  11640. (_
  11641. (org-add-planning-info type time 'closed)
  11642. (when (and old-date
  11643. log
  11644. (not (equal old-date org-last-inserted-timestamp)))
  11645. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  11646. org-last-inserted-timestamp
  11647. old-date
  11648. log))
  11649. (when repeater
  11650. (save-excursion
  11651. (org-back-to-heading t)
  11652. (when (re-search-forward
  11653. (concat keyword " " org-last-inserted-timestamp)
  11654. (line-end-position 2)
  11655. t)
  11656. (goto-char (1- (match-end 0)))
  11657. (insert " " repeater)
  11658. (setq org-last-inserted-timestamp
  11659. (concat (substring org-last-inserted-timestamp 0 -1)
  11660. " " repeater
  11661. (substring org-last-inserted-timestamp -1))))))
  11662. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  11663. org-last-inserted-timestamp)))))
  11664. (defun org-deadline (arg &optional time)
  11665. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  11666. With one universal prefix argument, remove any deadline from the item.
  11667. With two universal prefix arguments, prompt for a warning delay.
  11668. With argument TIME, set the deadline at the corresponding date. TIME
  11669. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11670. (interactive "P")
  11671. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11672. (org-map-entries
  11673. (lambda () (org--deadline-or-schedule arg 'deadline time))
  11674. nil
  11675. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11676. 'region-start-level
  11677. 'region)
  11678. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11679. (org--deadline-or-schedule arg 'deadline time)))
  11680. (defun org-schedule (arg &optional time)
  11681. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  11682. With one universal prefix argument, remove any scheduling date from the item.
  11683. With two universal prefix arguments, prompt for a delay cookie.
  11684. With argument TIME, scheduled at the corresponding date. TIME can
  11685. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11686. (interactive "P")
  11687. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11688. (org-map-entries
  11689. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  11690. nil
  11691. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11692. 'region-start-level
  11693. 'region)
  11694. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11695. (org--deadline-or-schedule arg 'scheduled time)))
  11696. (defun org-get-scheduled-time (pom &optional inherit)
  11697. "Get the scheduled time as a time tuple, of a format suitable
  11698. for calling org-schedule with, or if there is no scheduling,
  11699. returns nil."
  11700. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  11701. (when time
  11702. (apply 'encode-time (org-parse-time-string time)))))
  11703. (defun org-get-deadline-time (pom &optional inherit)
  11704. "Get the deadline as a time tuple, of a format suitable for
  11705. calling org-deadline with, or if there is no scheduling, returns
  11706. nil."
  11707. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  11708. (when time
  11709. (apply 'encode-time (org-parse-time-string time)))))
  11710. (defun org-remove-timestamp-with-keyword (keyword)
  11711. "Remove all time stamps with KEYWORD in the current entry."
  11712. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  11713. beg)
  11714. (save-excursion
  11715. (org-back-to-heading t)
  11716. (setq beg (point))
  11717. (outline-next-heading)
  11718. (while (re-search-backward re beg t)
  11719. (replace-match "")
  11720. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  11721. (equal (char-before) ?\ ))
  11722. (backward-delete-char 1)
  11723. (when (string-match "^[ \t]*$" (buffer-substring
  11724. (point-at-bol) (point-at-eol)))
  11725. (delete-region (point-at-bol)
  11726. (min (point-max) (1+ (point-at-eol))))))))))
  11727. (defvar org-time-was-given) ; dynamically scoped parameter
  11728. (defvar org-end-time-was-given) ; dynamically scoped parameter
  11729. (defun org-at-planning-p ()
  11730. "Non-nil when point is on a planning info line."
  11731. ;; This is as accurate and faster than `org-element-at-point' since
  11732. ;; planning info location is fixed in the section.
  11733. (org-with-wide-buffer
  11734. (beginning-of-line)
  11735. (and (looking-at-p org-planning-line-re)
  11736. (eq (point)
  11737. (ignore-errors
  11738. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  11739. (org-back-to-heading t)
  11740. (org-with-limited-levels (org-back-to-heading t)))
  11741. (line-beginning-position 2))))))
  11742. (defun org-add-planning-info (what &optional time &rest remove)
  11743. "Insert new timestamp with keyword in the planning line.
  11744. WHAT indicates what kind of time stamp to add. It is a symbol
  11745. among `closed', `deadline', `scheduled' and nil. TIME indicates
  11746. the time to use. If none is given, the user is prompted for
  11747. a date. REMOVE indicates what kind of entries to remove. An old
  11748. WHAT entry will also be removed."
  11749. (let (org-time-was-given org-end-time-was-given default-time default-input)
  11750. (catch 'exit
  11751. (when (and (memq what '(scheduled deadline))
  11752. (or (not time)
  11753. (and (stringp time)
  11754. (string-match "^[-+]+[0-9]" time))))
  11755. ;; Try to get a default date/time from existing timestamp
  11756. (save-excursion
  11757. (org-back-to-heading t)
  11758. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  11759. (when (re-search-forward (if (eq what 'scheduled)
  11760. org-scheduled-time-regexp
  11761. org-deadline-time-regexp)
  11762. end t)
  11763. (setq ts (match-string 1)
  11764. default-time (apply 'encode-time (org-parse-time-string ts))
  11765. default-input (and ts (org-get-compact-tod ts)))))))
  11766. (when what
  11767. (setq time
  11768. (if (stringp time)
  11769. ;; This is a string (relative or absolute), set
  11770. ;; proper date.
  11771. (apply #'encode-time
  11772. (org-read-date-analyze
  11773. time default-time (decode-time default-time)))
  11774. ;; If necessary, get the time from the user
  11775. (or time (org-read-date nil 'to-time nil nil
  11776. default-time default-input)))))
  11777. (org-with-wide-buffer
  11778. (org-back-to-heading t)
  11779. (forward-line)
  11780. (unless (bolp) (insert "\n"))
  11781. (cond ((looking-at-p org-planning-line-re)
  11782. ;; Move to current indentation.
  11783. (skip-chars-forward " \t")
  11784. ;; Check if we have to remove something.
  11785. (dolist (type (if what (cons what remove) remove))
  11786. (save-excursion
  11787. (when (re-search-forward
  11788. (cl-case type
  11789. (closed org-closed-time-regexp)
  11790. (deadline org-deadline-time-regexp)
  11791. (scheduled org-scheduled-time-regexp)
  11792. (otherwise
  11793. (error "Invalid planning type: %s" type)))
  11794. (line-end-position) t)
  11795. ;; Delete until next keyword or end of line.
  11796. (delete-region
  11797. (match-beginning 0)
  11798. (if (re-search-forward org-keyword-time-not-clock-regexp
  11799. (line-end-position)
  11800. t)
  11801. (match-beginning 0)
  11802. (line-end-position))))))
  11803. ;; If there is nothing more to add and no more keyword
  11804. ;; is left, remove the line completely.
  11805. (if (and (looking-at-p "[ \t]*$") (not what))
  11806. (delete-region (line-beginning-position)
  11807. (line-beginning-position 2))
  11808. ;; If we removed last keyword, do not leave trailing
  11809. ;; white space at the end of line.
  11810. (let ((p (point)))
  11811. (save-excursion
  11812. (end-of-line)
  11813. (unless (= (skip-chars-backward " \t" p) 0)
  11814. (delete-region (point) (line-end-position)))))))
  11815. ((not what) (throw 'exit nil)) ; Nothing to do.
  11816. (t (insert-before-markers "\n")
  11817. (backward-char 1)
  11818. (when org-adapt-indentation
  11819. (indent-to-column (1+ (org-outline-level))))))
  11820. (when what
  11821. ;; Insert planning keyword.
  11822. (insert (cl-case what
  11823. (closed org-closed-string)
  11824. (deadline org-deadline-string)
  11825. (scheduled org-scheduled-string)
  11826. (otherwise (error "Invalid planning type: %s" what)))
  11827. " ")
  11828. ;; Insert associated timestamp.
  11829. (let ((ts (org-insert-time-stamp
  11830. time
  11831. (or org-time-was-given
  11832. (and (eq what 'closed) org-log-done-with-time))
  11833. (eq what 'closed)
  11834. nil nil (list org-end-time-was-given))))
  11835. (unless (eolp) (insert " "))
  11836. ts))))))
  11837. (defvar org-log-note-marker (make-marker)
  11838. "Marker pointing at the entry where the note is to be inserted.")
  11839. (defvar org-log-note-purpose nil)
  11840. (defvar org-log-note-state nil)
  11841. (defvar org-log-note-previous-state nil)
  11842. (defvar org-log-note-extra nil)
  11843. (defvar org-log-note-window-configuration nil)
  11844. (defvar org-log-note-return-to (make-marker))
  11845. (defvar org-log-note-effective-time nil
  11846. "Remembered current time so that dynamically scoped
  11847. `org-extend-today-until' affects timestamps in state change log")
  11848. (defvar org-log-post-message nil
  11849. "Message to be displayed after a log note has been stored.
  11850. The auto-repeater uses this.")
  11851. (defun org-add-note ()
  11852. "Add a note to the current entry.
  11853. This is done in the same way as adding a state change note."
  11854. (interactive)
  11855. (org-add-log-setup 'note))
  11856. (defun org-log-beginning (&optional create)
  11857. "Return expected start of log notes in current entry.
  11858. When optional argument CREATE is non-nil, the function creates
  11859. a drawer to store notes, if necessary. Returned position ignores
  11860. narrowing."
  11861. (org-with-wide-buffer
  11862. (let ((drawer (org-log-into-drawer)))
  11863. (cond
  11864. (drawer
  11865. (org-end-of-meta-data)
  11866. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  11867. (end (if (org-at-heading-p) (point)
  11868. (save-excursion (outline-next-heading) (point))))
  11869. (case-fold-search t))
  11870. (catch 'exit
  11871. ;; Try to find existing drawer.
  11872. (while (re-search-forward regexp end t)
  11873. (let ((element (org-element-at-point)))
  11874. (when (eq (org-element-type element) 'drawer)
  11875. (let ((cend (org-element-property :contents-end element)))
  11876. (when (and (not org-log-states-order-reversed) cend)
  11877. (goto-char cend)))
  11878. (throw 'exit nil))))
  11879. ;; No drawer found. Create one, if permitted.
  11880. (when create
  11881. (unless (bolp) (insert "\n"))
  11882. (let ((beg (point)))
  11883. (insert ":" drawer ":\n:END:\n")
  11884. (org-indent-region beg (point))
  11885. (org-flag-region
  11886. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  11887. (end-of-line -1)))))
  11888. (t
  11889. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  11890. (skip-chars-forward " \t\n")
  11891. (beginning-of-line)
  11892. (unless org-log-states-order-reversed
  11893. (org-skip-over-state-notes)
  11894. (skip-chars-backward " \t\n")
  11895. (forward-line)))))
  11896. (if (bolp) (point) (line-beginning-position 2))))
  11897. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  11898. "Set up the post command hook to take a note.
  11899. If this is about to TODO state change, the new state is expected in STATE.
  11900. HOW is an indicator what kind of note should be created.
  11901. EXTRA is additional text that will be inserted into the notes buffer."
  11902. (move-marker org-log-note-marker (point))
  11903. (setq org-log-note-purpose purpose
  11904. org-log-note-state state
  11905. org-log-note-previous-state prev-state
  11906. org-log-note-how how
  11907. org-log-note-extra extra
  11908. org-log-note-effective-time (org-current-effective-time))
  11909. (add-hook 'post-command-hook 'org-add-log-note 'append))
  11910. (defun org-skip-over-state-notes ()
  11911. "Skip past the list of State notes in an entry."
  11912. (when (ignore-errors (goto-char (org-in-item-p)))
  11913. (let* ((struct (org-list-struct))
  11914. (prevs (org-list-prevs-alist struct))
  11915. (regexp
  11916. (concat "[ \t]*- +"
  11917. (replace-regexp-in-string
  11918. " +" " +"
  11919. (org-replace-escapes
  11920. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  11921. `(("%d" . ,org-ts-regexp-inactive)
  11922. ("%D" . ,org-ts-regexp)
  11923. ("%s" . "\"\\S-+\"")
  11924. ("%S" . "\"\\S-+\"")
  11925. ("%t" . ,org-ts-regexp-inactive)
  11926. ("%T" . ,org-ts-regexp)
  11927. ("%u" . ".*?")
  11928. ("%U" . ".*?")))))))
  11929. (while (looking-at-p regexp)
  11930. (goto-char (or (org-list-get-next-item (point) struct prevs)
  11931. (org-list-get-item-end (point) struct)))))))
  11932. (defun org-add-log-note (&optional _purpose)
  11933. "Pop up a window for taking a note, and add this note later."
  11934. (remove-hook 'post-command-hook 'org-add-log-note)
  11935. (setq org-log-note-window-configuration (current-window-configuration))
  11936. (delete-other-windows)
  11937. (move-marker org-log-note-return-to (point))
  11938. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  11939. (goto-char org-log-note-marker)
  11940. (org-switch-to-buffer-other-window "*Org Note*")
  11941. (erase-buffer)
  11942. (if (memq org-log-note-how '(time state))
  11943. (org-store-log-note)
  11944. (let ((org-inhibit-startup t)) (org-mode))
  11945. (insert (format "# Insert note for %s.
  11946. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  11947. (cond
  11948. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  11949. ((eq org-log-note-purpose 'done) "closed todo item")
  11950. ((eq org-log-note-purpose 'state)
  11951. (format "state change from \"%s\" to \"%s\""
  11952. (or org-log-note-previous-state "")
  11953. (or org-log-note-state "")))
  11954. ((eq org-log-note-purpose 'reschedule)
  11955. "rescheduling")
  11956. ((eq org-log-note-purpose 'delschedule)
  11957. "no longer scheduled")
  11958. ((eq org-log-note-purpose 'redeadline)
  11959. "changing deadline")
  11960. ((eq org-log-note-purpose 'deldeadline)
  11961. "removing deadline")
  11962. ((eq org-log-note-purpose 'refile)
  11963. "refiling")
  11964. ((eq org-log-note-purpose 'note)
  11965. "this entry")
  11966. (t (error "This should not happen")))))
  11967. (when org-log-note-extra (insert org-log-note-extra))
  11968. (setq-local org-finish-function 'org-store-log-note)
  11969. (run-hooks 'org-log-buffer-setup-hook)))
  11970. (defvar org-note-abort nil) ; dynamically scoped
  11971. (defun org-store-log-note ()
  11972. "Finish taking a log note, and insert it to where it belongs."
  11973. (let ((txt (prog1 (buffer-string)
  11974. (kill-buffer)))
  11975. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  11976. lines)
  11977. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  11978. (setq txt (replace-match "" t t txt)))
  11979. (when (string-match "\\s-+\\'" txt)
  11980. (setq txt (replace-match "" t t txt)))
  11981. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  11982. (when (org-string-nw-p note)
  11983. (setq note
  11984. (org-replace-escapes
  11985. note
  11986. (list (cons "%u" (user-login-name))
  11987. (cons "%U" user-full-name)
  11988. (cons "%t" (format-time-string
  11989. (org-time-stamp-format 'long 'inactive)
  11990. org-log-note-effective-time))
  11991. (cons "%T" (format-time-string
  11992. (org-time-stamp-format 'long nil)
  11993. org-log-note-effective-time))
  11994. (cons "%d" (format-time-string
  11995. (org-time-stamp-format nil 'inactive)
  11996. org-log-note-effective-time))
  11997. (cons "%D" (format-time-string
  11998. (org-time-stamp-format nil nil)
  11999. org-log-note-effective-time))
  12000. (cons "%s" (cond
  12001. ((not org-log-note-state) "")
  12002. ((string-match-p org-ts-regexp
  12003. org-log-note-state)
  12004. (format "\"[%s]\""
  12005. (substring org-log-note-state 1 -1)))
  12006. (t (format "\"%s\"" org-log-note-state))))
  12007. (cons "%S"
  12008. (cond
  12009. ((not org-log-note-previous-state) "")
  12010. ((string-match-p org-ts-regexp
  12011. org-log-note-previous-state)
  12012. (format "\"[%s]\""
  12013. (substring
  12014. org-log-note-previous-state 1 -1)))
  12015. (t (format "\"%s\""
  12016. org-log-note-previous-state)))))))
  12017. (when lines (setq note (concat note " \\\\")))
  12018. (push note lines))
  12019. (when (and lines (not org-note-abort))
  12020. (with-current-buffer (marker-buffer org-log-note-marker)
  12021. (org-with-wide-buffer
  12022. ;; Find location for the new note.
  12023. (goto-char org-log-note-marker)
  12024. (set-marker org-log-note-marker nil)
  12025. ;; Note associated to a clock is to be located right after
  12026. ;; the clock. Do not move point.
  12027. (unless (eq org-log-note-purpose 'clock-out)
  12028. (goto-char (org-log-beginning t)))
  12029. ;; Make sure point is at the beginning of an empty line.
  12030. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12031. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12032. ;; In an existing list, add a new item at the top level.
  12033. ;; Otherwise, indent line like a regular one.
  12034. (let ((itemp (org-in-item-p)))
  12035. (if itemp
  12036. (indent-line-to
  12037. (let ((struct (save-excursion
  12038. (goto-char itemp) (org-list-struct))))
  12039. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12040. (org-indent-line)))
  12041. (insert (org-list-bullet-string "-") (pop lines))
  12042. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12043. (dolist (line lines)
  12044. (insert "\n")
  12045. (indent-line-to ind)
  12046. (insert line)))
  12047. (message "Note stored")
  12048. (org-back-to-heading t))
  12049. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12050. ;; from within `org-add-log-note' because `buffer-undo-list'
  12051. ;; is then modified outside of `org-with-remote-undo'.
  12052. (when (eq this-command 'org-agenda-todo)
  12053. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12054. ;; Don't add undo information when called from `org-agenda-todo'.
  12055. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12056. (set-window-configuration org-log-note-window-configuration)
  12057. (with-current-buffer (marker-buffer org-log-note-return-to)
  12058. (goto-char org-log-note-return-to))
  12059. (move-marker org-log-note-return-to nil)
  12060. (when org-log-post-message (message "%s" org-log-post-message))))
  12061. (defun org-remove-empty-drawer-at (pos)
  12062. "Remove an empty drawer at position POS.
  12063. POS may also be a marker."
  12064. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12065. (org-with-wide-buffer
  12066. (goto-char pos)
  12067. (let ((drawer (org-element-at-point)))
  12068. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12069. (not (org-element-property :contents-begin drawer)))
  12070. (delete-region (org-element-property :begin drawer)
  12071. (progn (goto-char (org-element-property :end drawer))
  12072. (skip-chars-backward " \r\t\n")
  12073. (forward-line)
  12074. (point))))))))
  12075. (defvar org-ts-type nil)
  12076. (defun org-sparse-tree (&optional arg type)
  12077. "Create a sparse tree, prompt for the details.
  12078. This command can create sparse trees. You first need to select the type
  12079. of match used to create the tree:
  12080. t Show all TODO entries.
  12081. T Show entries with a specific TODO keyword.
  12082. m Show entries selected by a tags/property match.
  12083. p Enter a property name and its value (both with completion on existing
  12084. names/values) and show entries with that property.
  12085. r Show entries matching a regular expression (`/' can be used as well).
  12086. b Show deadlines and scheduled items before a date.
  12087. a Show deadlines and scheduled items after a date.
  12088. d Show deadlines due within `org-deadline-warning-days'.
  12089. D Show deadlines and scheduled items between a date range."
  12090. (interactive "P")
  12091. (setq type (or type org-sparse-tree-default-date-type))
  12092. (setq org-ts-type type)
  12093. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12094. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12095. \[c]ycle through date types: %s"
  12096. (cl-case type
  12097. (all "all timestamps")
  12098. (scheduled "only scheduled")
  12099. (deadline "only deadline")
  12100. (active "only active timestamps")
  12101. (inactive "only inactive timestamps")
  12102. (closed "with a closed time-stamp")
  12103. (otherwise "scheduled/deadline")))
  12104. (let ((answer (read-char-exclusive)))
  12105. (cl-case answer
  12106. (?c
  12107. (org-sparse-tree
  12108. arg
  12109. (cadr
  12110. (memq type '(nil all scheduled deadline active inactive closed)))))
  12111. (?d (call-interactively 'org-check-deadlines))
  12112. (?b (call-interactively 'org-check-before-date))
  12113. (?a (call-interactively 'org-check-after-date))
  12114. (?D (call-interactively 'org-check-dates-range))
  12115. (?t (call-interactively 'org-show-todo-tree))
  12116. (?T (org-show-todo-tree '(4)))
  12117. (?m (call-interactively 'org-match-sparse-tree))
  12118. ((?p ?P)
  12119. (let* ((kwd (completing-read
  12120. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12121. (value (completing-read
  12122. "Value: " (mapcar #'list (org-property-values kwd)))))
  12123. (unless (string-match "\\`{.*}\\'" value)
  12124. (setq value (concat "\"" value "\"")))
  12125. (org-match-sparse-tree arg (concat kwd "=" value))))
  12126. ((?r ?R ?/) (call-interactively 'org-occur))
  12127. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12128. (defvar-local org-occur-highlights nil
  12129. "List of overlays used for occur matches.")
  12130. (defvar-local org-occur-parameters nil
  12131. "Parameters of the active org-occur calls.
  12132. This is a list, each call to org-occur pushes as cons cell,
  12133. containing the regular expression and the callback, onto the list.
  12134. The list can contain several entries if `org-occur' has been called
  12135. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12136. will only contain one set of parameters. When the highlights are
  12137. removed (for example with `C-c C-c', or with the next edit (depending
  12138. on `org-remove-highlights-with-change'), this variable is emptied
  12139. as well.")
  12140. (defun org-occur (regexp &optional keep-previous callback)
  12141. "Make a compact tree which shows all matches of REGEXP.
  12142. The tree will show the lines where the regexp matches, and any other context
  12143. defined in `org-show-context-detail', which see.
  12144. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12145. done by a previous call to `org-occur' will be kept, to allow stacking of
  12146. calls to this command.
  12147. Optional argument CALLBACK can be a function of no argument. In this case,
  12148. it is called with point at the end of the match, match data being set
  12149. accordingly. Current match is shown only if the return value is non-nil.
  12150. The function must neither move point nor alter narrowing."
  12151. (interactive "sRegexp: \nP")
  12152. (when (equal regexp "")
  12153. (user-error "Regexp cannot be empty"))
  12154. (unless keep-previous
  12155. (org-remove-occur-highlights nil nil t))
  12156. (push (cons regexp callback) org-occur-parameters)
  12157. (let ((cnt 0))
  12158. (save-excursion
  12159. (goto-char (point-min))
  12160. (when (or (not keep-previous) ; do not want to keep
  12161. (not org-occur-highlights)) ; no previous matches
  12162. ;; hide everything
  12163. (org-overview))
  12164. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12165. (isearch-no-upper-case-p regexp t)
  12166. org-occur-case-fold-search)))
  12167. (while (re-search-forward regexp nil t)
  12168. (when (or (not callback)
  12169. (save-match-data (funcall callback)))
  12170. (setq cnt (1+ cnt))
  12171. (when org-highlight-sparse-tree-matches
  12172. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12173. (org-show-context 'occur-tree)))))
  12174. (when org-remove-highlights-with-change
  12175. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12176. nil 'local))
  12177. (unless org-sparse-tree-open-archived-trees
  12178. (org-hide-archived-subtrees (point-min) (point-max)))
  12179. (run-hooks 'org-occur-hook)
  12180. (when (called-interactively-p 'interactive)
  12181. (message "%d match(es) for regexp %s" cnt regexp))
  12182. cnt))
  12183. (defun org-occur-next-match (&optional n _reset)
  12184. "Function for `next-error-function' to find sparse tree matches.
  12185. N is the number of matches to move, when negative move backwards.
  12186. This function always goes back to the starting point when no
  12187. match is found."
  12188. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12189. (search-func (if (< n 0)
  12190. 'previous-single-char-property-change
  12191. 'next-single-char-property-change))
  12192. (n (abs n))
  12193. (pos (point))
  12194. p1)
  12195. (catch 'exit
  12196. (while (setq p1 (funcall search-func (point) 'org-type))
  12197. (when (equal p1 limit)
  12198. (goto-char pos)
  12199. (user-error "No more matches"))
  12200. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12201. (setq n (1- n))
  12202. (when (= n 0)
  12203. (goto-char p1)
  12204. (throw 'exit (point))))
  12205. (goto-char p1))
  12206. (goto-char p1)
  12207. (user-error "No more matches"))))
  12208. (defun org-highlight-new-match (beg end)
  12209. "Highlight from BEG to END and mark the highlight is an occur headline."
  12210. (let ((ov (make-overlay beg end)))
  12211. (overlay-put ov 'face 'secondary-selection)
  12212. (overlay-put ov 'org-type 'org-occur)
  12213. (push ov org-occur-highlights)))
  12214. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12215. "Remove the occur highlights from the buffer.
  12216. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12217. from the `before-change-functions' in the current buffer."
  12218. (interactive)
  12219. (unless org-inhibit-highlight-removal
  12220. (mapc #'delete-overlay org-occur-highlights)
  12221. (setq org-occur-highlights nil)
  12222. (setq org-occur-parameters nil)
  12223. (unless noremove
  12224. (remove-hook 'before-change-functions
  12225. 'org-remove-occur-highlights 'local))))
  12226. ;;;; Priorities
  12227. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12228. "Regular expression matching the priority indicator.")
  12229. (defvar org-remove-priority-next-time nil)
  12230. (defun org-priority-up ()
  12231. "Increase the priority of the current item."
  12232. (interactive)
  12233. (org-priority 'up))
  12234. (defun org-priority-down ()
  12235. "Decrease the priority of the current item."
  12236. (interactive)
  12237. (org-priority 'down))
  12238. (defun org-priority (&optional action _show)
  12239. "Change the priority of an item.
  12240. ACTION can be `set', `up', `down', or a character."
  12241. (interactive "P")
  12242. (if (equal action '(4))
  12243. (org-show-priority)
  12244. (unless org-enable-priority-commands
  12245. (user-error "Priority commands are disabled"))
  12246. (setq action (or action 'set))
  12247. (let (current new news have remove)
  12248. (save-excursion
  12249. (org-back-to-heading t)
  12250. (when (looking-at org-priority-regexp)
  12251. (setq current (string-to-char (match-string 2))
  12252. have t))
  12253. (cond
  12254. ((eq action 'remove)
  12255. (setq remove t new ?\ ))
  12256. ((or (eq action 'set)
  12257. (integerp action))
  12258. (if (not (eq action 'set))
  12259. (setq new action)
  12260. (message "Priority %c-%c, SPC to remove: "
  12261. org-highest-priority org-lowest-priority)
  12262. (save-match-data
  12263. (setq new (read-char-exclusive))))
  12264. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12265. (= (upcase org-lowest-priority) org-lowest-priority))
  12266. (setq new (upcase new)))
  12267. (cond ((equal new ?\ ) (setq remove t))
  12268. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12269. (user-error "Priority must be between `%c' and `%c'"
  12270. org-highest-priority org-lowest-priority))))
  12271. ((eq action 'up)
  12272. (setq new (if have
  12273. (1- current) ; normal cycling
  12274. ;; last priority was empty
  12275. (if (eq last-command this-command)
  12276. org-lowest-priority ; wrap around empty to lowest
  12277. ;; default
  12278. (if org-priority-start-cycle-with-default
  12279. org-default-priority
  12280. (1- org-default-priority))))))
  12281. ((eq action 'down)
  12282. (setq new (if have
  12283. (1+ current) ; normal cycling
  12284. ;; last priority was empty
  12285. (if (eq last-command this-command)
  12286. org-highest-priority ; wrap around empty to highest
  12287. ;; default
  12288. (if org-priority-start-cycle-with-default
  12289. org-default-priority
  12290. (1+ org-default-priority))))))
  12291. (t (user-error "Invalid action")))
  12292. (when (or (< (upcase new) org-highest-priority)
  12293. (> (upcase new) org-lowest-priority))
  12294. (if (and (memq action '(up down))
  12295. (not have) (not (eq last-command this-command)))
  12296. ;; `new' is from default priority
  12297. (error
  12298. "The default can not be set, see `org-default-priority' why")
  12299. ;; normal cycling: `new' is beyond highest/lowest priority
  12300. ;; and is wrapped around to the empty priority
  12301. (setq remove t)))
  12302. (setq news (format "%c" new))
  12303. (if have
  12304. (if remove
  12305. (replace-match "" t t nil 1)
  12306. (replace-match news t t nil 2))
  12307. (if remove
  12308. (user-error "No priority cookie found in line")
  12309. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12310. (if (match-end 2)
  12311. (progn
  12312. (goto-char (match-end 2))
  12313. (insert " [#" news "]"))
  12314. (goto-char (match-beginning 3))
  12315. (insert "[#" news "] "))))
  12316. (org-align-tags))
  12317. (if remove
  12318. (message "Priority removed")
  12319. (message "Priority of current item set to %s" news)))))
  12320. (defun org-show-priority ()
  12321. "Show the priority of the current item.
  12322. This priority is composed of the main priority given with the [#A] cookies,
  12323. and by additional input from the age of a schedules or deadline entry."
  12324. (interactive)
  12325. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12326. (org-get-at-bol 'priority)
  12327. (save-excursion
  12328. (save-match-data
  12329. (beginning-of-line)
  12330. (and (looking-at org-heading-regexp)
  12331. (org-get-priority (match-string 0))))))))
  12332. (message "Priority is %d" (if pri pri -1000))))
  12333. (defun org-get-priority (s)
  12334. "Find priority cookie and return priority."
  12335. (save-match-data
  12336. (if (functionp org-get-priority-function)
  12337. (funcall org-get-priority-function)
  12338. (if (not (string-match org-priority-regexp s))
  12339. (* 1000 (- org-lowest-priority org-default-priority))
  12340. (* 1000 (- org-lowest-priority
  12341. (string-to-char (match-string 2 s))))))))
  12342. ;;;; Tags
  12343. (defvar org-agenda-archives-mode)
  12344. (defvar org-map-continue-from nil
  12345. "Position from where mapping should continue.
  12346. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12347. (defvar org-scanner-tags nil
  12348. "The current tag list while the tags scanner is running.")
  12349. (defvar org-trust-scanner-tags nil
  12350. "Should `org-get-tags' use the tags for the scanner.
  12351. This is for internal dynamical scoping only.
  12352. When this is non-nil, the function `org-get-tags' will return the value
  12353. of `org-scanner-tags' instead of building the list by itself. This
  12354. can lead to large speed-ups when the tags scanner is used in a file with
  12355. many entries, and when the list of tags is retrieved, for example to
  12356. obtain a list of properties. Building the tags list for each entry in such
  12357. a file becomes an N^2 operation - but with this variable set, it scales
  12358. as N.")
  12359. (defvar org--matcher-tags-todo-only nil)
  12360. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12361. "Scan headline tags with inheritance and produce output ACTION.
  12362. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12363. or `agenda' to produce an entry list for an agenda view. It can also be
  12364. a Lisp form or a function that should be called at each matched headline, in
  12365. this case the return value is a list of all return values from these calls.
  12366. MATCHER is a function accepting three arguments, returning
  12367. a non-nil value whenever a given set of tags qualifies a headline
  12368. for inclusion. See `org-make-tags-matcher' for more information.
  12369. As a special case, it can also be set to t (respectively nil) in
  12370. order to match all (respectively none) headline.
  12371. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  12372. included in the output.
  12373. START-LEVEL can be a string with asterisks, reducing the scope to
  12374. headlines matching this string."
  12375. (require 'org-agenda)
  12376. (let* ((re (concat "^"
  12377. (if start-level
  12378. ;; Get the correct level to match
  12379. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12380. org-outline-regexp)
  12381. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  12382. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  12383. (props (list 'face 'default
  12384. 'done-face 'org-agenda-done
  12385. 'undone-face 'default
  12386. 'mouse-face 'highlight
  12387. 'org-not-done-regexp org-not-done-regexp
  12388. 'org-todo-regexp org-todo-regexp
  12389. 'org-complex-heading-regexp org-complex-heading-regexp
  12390. 'help-echo
  12391. (format "mouse-2 or RET jump to Org file %S"
  12392. (abbreviate-file-name
  12393. (or (buffer-file-name (buffer-base-buffer))
  12394. (buffer-name (buffer-base-buffer)))))))
  12395. (org-map-continue-from nil)
  12396. lspos tags tags-list
  12397. (tags-alist (list (cons 0 org-file-tags)))
  12398. (llast 0) rtn rtn1 level category i txt
  12399. todo marker entry priority
  12400. ts-date ts-date-type ts-date-pair)
  12401. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12402. (setq action (list 'lambda nil action)))
  12403. (save-excursion
  12404. (goto-char (point-min))
  12405. (when (eq action 'sparse-tree)
  12406. (org-overview)
  12407. (org-remove-occur-highlights))
  12408. (while (let (case-fold-search)
  12409. (re-search-forward re nil t))
  12410. (setq org-map-continue-from nil)
  12411. (catch :skip
  12412. ;; Ignore closing parts of inline tasks.
  12413. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  12414. (throw :skip t))
  12415. (setq todo
  12416. ;; TODO: is the 1-2 difference a bug?
  12417. (when (match-end 1) (match-string-no-properties 2))
  12418. tags (when (match-end 4) (match-string-no-properties 4)))
  12419. (goto-char (setq lspos (match-beginning 0)))
  12420. (setq level (org-reduced-level (org-outline-level))
  12421. category (org-get-category))
  12422. (when (eq action 'agenda)
  12423. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12424. ts-date (car ts-date-pair)
  12425. ts-date-type (cdr ts-date-pair)))
  12426. (setq i llast llast level)
  12427. ;; remove tag lists from same and sublevels
  12428. (while (>= i level)
  12429. (when (setq entry (assoc i tags-alist))
  12430. (setq tags-alist (delete entry tags-alist)))
  12431. (setq i (1- i)))
  12432. ;; add the next tags
  12433. (when tags
  12434. (setq tags (org-split-string tags ":")
  12435. tags-alist
  12436. (cons (cons level tags) tags-alist)))
  12437. ;; compile tags for current headline
  12438. (setq tags-list
  12439. (if org-use-tag-inheritance
  12440. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12441. tags)
  12442. org-scanner-tags tags-list)
  12443. (when org-use-tag-inheritance
  12444. (setcdr (car tags-alist)
  12445. (mapcar (lambda (x)
  12446. (setq x (copy-sequence x))
  12447. (org-add-prop-inherited x))
  12448. (cdar tags-alist))))
  12449. (when (and tags org-use-tag-inheritance
  12450. (or (not (eq t org-use-tag-inheritance))
  12451. org-tags-exclude-from-inheritance))
  12452. ;; Selective inheritance, remove uninherited ones.
  12453. (setcdr (car tags-alist)
  12454. (org-remove-uninherited-tags (cdar tags-alist))))
  12455. (when (and
  12456. ;; eval matcher only when the todo condition is OK
  12457. (and (or (not todo-only) (member todo org-todo-keywords-1))
  12458. (if (functionp matcher)
  12459. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12460. (funcall matcher todo tags-list level))
  12461. matcher))
  12462. ;; Call the skipper, but return t if it does not
  12463. ;; skip, so that the `and' form continues evaluating.
  12464. (progn
  12465. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12466. t)
  12467. ;; Check if timestamps are deselecting this entry
  12468. (or (not todo-only)
  12469. (and (member todo org-todo-keywords-1)
  12470. (or (not org-agenda-tags-todo-honor-ignore-options)
  12471. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12472. ;; select this headline
  12473. (cond
  12474. ((eq action 'sparse-tree)
  12475. (and org-highlight-sparse-tree-matches
  12476. (org-get-heading) (match-end 0)
  12477. (org-highlight-new-match
  12478. (match-beginning 1) (match-end 1)))
  12479. (org-show-context 'tags-tree))
  12480. ((eq action 'agenda)
  12481. (setq txt (org-agenda-format-item
  12482. ""
  12483. (concat
  12484. (if (eq org-tags-match-list-sublevels 'indented)
  12485. (make-string (1- level) ?.) "")
  12486. (org-get-heading))
  12487. (make-string level ?\s)
  12488. category
  12489. tags-list)
  12490. priority (org-get-priority txt))
  12491. (goto-char lspos)
  12492. (setq marker (org-agenda-new-marker))
  12493. (org-add-props txt props
  12494. 'org-marker marker 'org-hd-marker marker 'org-category category
  12495. 'todo-state todo
  12496. 'ts-date ts-date
  12497. 'priority priority
  12498. 'type (concat "tagsmatch" ts-date-type))
  12499. (push txt rtn))
  12500. ((functionp action)
  12501. (setq org-map-continue-from nil)
  12502. (save-excursion
  12503. (setq rtn1 (funcall action))
  12504. (push rtn1 rtn)))
  12505. (t (user-error "Invalid action")))
  12506. ;; if we are to skip sublevels, jump to end of subtree
  12507. (unless org-tags-match-list-sublevels
  12508. (org-end-of-subtree t)
  12509. (backward-char 1))))
  12510. ;; Get the correct position from where to continue
  12511. (if org-map-continue-from
  12512. (goto-char org-map-continue-from)
  12513. (and (= (point) lspos) (end-of-line 1)))))
  12514. (when (and (eq action 'sparse-tree)
  12515. (not org-sparse-tree-open-archived-trees))
  12516. (org-hide-archived-subtrees (point-min) (point-max)))
  12517. (nreverse rtn)))
  12518. (defun org-remove-uninherited-tags (tags)
  12519. "Remove all tags that are not inherited from the list TAGS."
  12520. (cond
  12521. ((eq org-use-tag-inheritance t)
  12522. (if org-tags-exclude-from-inheritance
  12523. (org-delete-all org-tags-exclude-from-inheritance tags)
  12524. tags))
  12525. ((not org-use-tag-inheritance) nil)
  12526. ((stringp org-use-tag-inheritance)
  12527. (delq nil (mapcar
  12528. (lambda (x)
  12529. (if (and (string-match org-use-tag-inheritance x)
  12530. (not (member x org-tags-exclude-from-inheritance)))
  12531. x nil))
  12532. tags)))
  12533. ((listp org-use-tag-inheritance)
  12534. (delq nil (mapcar
  12535. (lambda (x)
  12536. (if (member x org-use-tag-inheritance) x nil))
  12537. tags)))))
  12538. (defun org-match-sparse-tree (&optional todo-only match)
  12539. "Create a sparse tree according to tags string MATCH.
  12540. MATCH is a string with match syntax. It can contain a selection
  12541. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  12542. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  12543. those. See the manual for details.
  12544. If optional argument TODO-ONLY is non-nil, only select lines that
  12545. are also TODO tasks."
  12546. (interactive "P")
  12547. (org-agenda-prepare-buffers (list (current-buffer)))
  12548. (let ((org--matcher-tags-todo-only todo-only))
  12549. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  12550. org--matcher-tags-todo-only)))
  12551. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  12552. (defvar org-cached-props nil)
  12553. (defun org-cached-entry-get (pom property)
  12554. (if (or (eq t org-use-property-inheritance)
  12555. (and (stringp org-use-property-inheritance)
  12556. (let ((case-fold-search t))
  12557. (string-match-p org-use-property-inheritance property)))
  12558. (and (listp org-use-property-inheritance)
  12559. (member-ignore-case property org-use-property-inheritance)))
  12560. ;; Caching is not possible, check it directly.
  12561. (org-entry-get pom property 'inherit)
  12562. ;; Get all properties, so we can do complicated checks easily.
  12563. (cdr (assoc-string property
  12564. (or org-cached-props
  12565. (setq org-cached-props (org-entry-properties pom)))
  12566. t))))
  12567. (defun org-global-tags-completion-table (&optional files)
  12568. "Return the list of all tags in all agenda buffer/files.
  12569. Optional FILES argument is a list of files which can be used
  12570. instead of the agenda files."
  12571. (save-excursion
  12572. (org-uniquify
  12573. (delq nil
  12574. (apply #'append
  12575. (mapcar
  12576. (lambda (file)
  12577. (set-buffer (find-file-noselect file))
  12578. (org--tag-add-to-alist
  12579. (org-get-buffer-tags)
  12580. (mapcar (lambda (x)
  12581. (and (stringp (car-safe x))
  12582. (list (car-safe x))))
  12583. org-current-tag-alist)))
  12584. (if (car-safe files) files
  12585. (org-agenda-files))))))))
  12586. (defun org-make-tags-matcher (match)
  12587. "Create the TAGS/TODO matcher form for the selection string MATCH.
  12588. Returns a cons of the selection string MATCH and a function
  12589. implementing the matcher.
  12590. The matcher is to be called at an Org entry, with point on the
  12591. headline, and returns non-nil if the entry matches the selection
  12592. string MATCH. It must be called with three arguments: the TODO
  12593. keyword at the entry (or nil if none), the list of all tags at
  12594. the entry including inherited ones and the reduced level of the
  12595. headline. Additionally, the category of the entry, if any, must
  12596. be specified as the text property `org-category' on the headline.
  12597. This function sets the variable `org--matcher-tags-todo-only' to
  12598. a non-nil value if the matcher restricts matching to TODO
  12599. entries, otherwise it is not touched.
  12600. See also `org-scan-tags'."
  12601. (unless match
  12602. ;; Get a new match request, with completion against the global
  12603. ;; tags table and the local tags in current buffer.
  12604. (let ((org-last-tags-completion-table
  12605. (org--tag-add-to-alist
  12606. (org-get-buffer-tags)
  12607. (org-global-tags-completion-table))))
  12608. (setq match
  12609. (completing-read
  12610. "Match: "
  12611. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  12612. (let ((match0 match)
  12613. (re (concat
  12614. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  12615. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  12616. "\\([<>=]\\{1,2\\}\\)"
  12617. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  12618. "\\|" org-tag-re "\\)"))
  12619. (start 0)
  12620. tagsmatch todomatch tagsmatcher todomatcher)
  12621. ;; Expand group tags.
  12622. (setq match (org-tags-expand match))
  12623. ;; Check if there is a TODO part of this match, which would be the
  12624. ;; part after a "/". To make sure that this slash is not part of
  12625. ;; a property value to be matched against, we also check that
  12626. ;; there is no / after that slash. First, find the last slash.
  12627. (let ((s 0))
  12628. (while (string-match "/+" match s)
  12629. (setq start (match-beginning 0))
  12630. (setq s (match-end 0))))
  12631. (if (and (string-match "/+" match start)
  12632. (not (string-match-p "\"" match start)))
  12633. ;; Match contains also a TODO-matching request.
  12634. (progn
  12635. (setq tagsmatch (substring match 0 (match-beginning 0)))
  12636. (setq todomatch (substring match (match-end 0)))
  12637. (when (string-prefix-p "!" todomatch)
  12638. (setq org--matcher-tags-todo-only t)
  12639. (setq todomatch (substring todomatch 1)))
  12640. (when (string-match "\\`\\s-*\\'" todomatch)
  12641. (setq todomatch nil)))
  12642. ;; Only matching tags.
  12643. (setq tagsmatch match)
  12644. (setq todomatch nil))
  12645. ;; Make the tags matcher.
  12646. (when (org-string-nw-p tagsmatch)
  12647. (let ((orlist nil)
  12648. (orterms (org-split-string tagsmatch "|"))
  12649. term)
  12650. (while (setq term (pop orterms))
  12651. (while (and (equal (substring term -1) "\\") orterms)
  12652. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  12653. (while (string-match re term)
  12654. (let* ((rest (substring term (match-end 0)))
  12655. (minus (and (match-end 1)
  12656. (equal (match-string 1 term) "-")))
  12657. (tag (save-match-data
  12658. (replace-regexp-in-string
  12659. "\\\\-" "-" (match-string 2 term))))
  12660. (regexp (eq (string-to-char tag) ?{))
  12661. (levelp (match-end 4))
  12662. (propp (match-end 5))
  12663. (mm
  12664. (cond
  12665. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  12666. (levelp
  12667. `(,(org-op-to-function (match-string 3 term))
  12668. level
  12669. ,(string-to-number (match-string 4 term))))
  12670. (propp
  12671. (let* ((gv (pcase (upcase (match-string 5 term))
  12672. ("CATEGORY"
  12673. '(get-text-property (point) 'org-category))
  12674. ("TODO" 'todo)
  12675. (p `(org-cached-entry-get nil ,p))))
  12676. (pv (match-string 7 term))
  12677. (regexp (eq (string-to-char pv) ?{))
  12678. (strp (eq (string-to-char pv) ?\"))
  12679. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  12680. (po (org-op-to-function (match-string 6 term)
  12681. (if timep 'time strp))))
  12682. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  12683. (when timep (setq pv (org-matcher-time pv)))
  12684. (cond ((and regexp (eq po '/=))
  12685. `(not (string-match ,pv (or ,gv ""))))
  12686. (regexp `(string-match ,pv (or ,gv "")))
  12687. (strp `(,po (or ,gv "") ,pv))
  12688. (t
  12689. `(,po
  12690. (string-to-number (or ,gv ""))
  12691. ,(string-to-number pv))))))
  12692. (t `(member ,tag tags-list)))))
  12693. (push (if minus `(not ,mm) mm) tagsmatcher)
  12694. (setq term rest)))
  12695. (push `(and ,@tagsmatcher) orlist)
  12696. (setq tagsmatcher nil))
  12697. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  12698. ;; Make the TODO matcher.
  12699. (when (org-string-nw-p todomatch)
  12700. (let ((orlist nil))
  12701. (dolist (term (org-split-string todomatch "|"))
  12702. (while (string-match re term)
  12703. (let* ((minus (and (match-end 1)
  12704. (equal (match-string 1 term) "-")))
  12705. (kwd (match-string 2 term))
  12706. (regexp (eq (string-to-char kwd) ?{))
  12707. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  12708. `(equal todo ,kwd))))
  12709. (push (if minus `(not ,mm) mm) todomatcher))
  12710. (setq term (substring term (match-end 0))))
  12711. (push (if (> (length todomatcher) 1)
  12712. (cons 'and todomatcher)
  12713. (car todomatcher))
  12714. orlist)
  12715. (setq todomatcher nil))
  12716. (setq todomatcher (cons 'or orlist))))
  12717. ;; Return the string and function of the matcher. If no
  12718. ;; tags-specific or todo-specific matcher exists, match
  12719. ;; everything.
  12720. (let ((matcher (if (and tagsmatcher todomatcher)
  12721. `(and ,tagsmatcher ,todomatcher)
  12722. (or tagsmatcher todomatcher t))))
  12723. (when org--matcher-tags-todo-only
  12724. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  12725. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  12726. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  12727. "Expand group tags in MATCH.
  12728. This replaces every group tag in MATCH with a regexp tag search.
  12729. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  12730. will be replaced like this:
  12731. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12732. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12733. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12734. Replacing by a regexp preserves the structure of the match.
  12735. E.g., this expansion
  12736. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  12737. will match anything tagged with \"Lab\" and \"Home\", or tagged
  12738. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  12739. A group tag in MATCH can contain regular expressions of its own.
  12740. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  12741. will be replaced like this:
  12742. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  12743. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  12744. assumed to be a single group tag, and the function will return
  12745. the list of tags in this group.
  12746. When DOWNCASE is non-nil, expand downcased TAGS."
  12747. (if org-group-tags
  12748. (let* ((case-fold-search t)
  12749. (stable org-mode-syntax-table)
  12750. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  12751. (taggroups (if downcased
  12752. (mapcar (lambda (tg) (mapcar #'downcase tg))
  12753. taggroups)
  12754. taggroups))
  12755. (taggroups-keys (mapcar #'car taggroups))
  12756. (return-match (if downcased (downcase match) match))
  12757. (count 0)
  12758. (work-already-expanded tags-already-expanded)
  12759. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  12760. ;; @ and _ are allowed as word-components in tags.
  12761. (modify-syntax-entry ?@ "w" stable)
  12762. (modify-syntax-entry ?_ "w" stable)
  12763. ;; Temporarily replace regexp-expressions in the match-expression.
  12764. (while (string-match "{.+?}" return-match)
  12765. (cl-incf count)
  12766. (push (match-string 0 return-match) regexps-in-match)
  12767. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  12768. (while (and taggroups-keys
  12769. (with-syntax-table stable
  12770. (string-match
  12771. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  12772. (regexp-opt taggroups-keys) "\\>\\)")
  12773. return-match)))
  12774. (let* ((dir (match-string 1 return-match))
  12775. (tag (match-string 2 return-match))
  12776. (tag (if downcased (downcase tag) tag)))
  12777. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  12778. (member tag tags-already-expanded))
  12779. (setq tags-in-group (assoc tag taggroups))
  12780. (push tag work-already-expanded)
  12781. ;; Recursively expand each tag in the group, if the tag hasn't
  12782. ;; already been expanded. Restore the match-data after all recursive calls.
  12783. (save-match-data
  12784. (let (tags-expanded)
  12785. (dolist (x (cdr tags-in-group))
  12786. (if (and (member x taggroups-keys)
  12787. (not (member x work-already-expanded)))
  12788. (setq tags-expanded
  12789. (delete-dups
  12790. (append
  12791. (org-tags-expand x t downcased
  12792. work-already-expanded)
  12793. tags-expanded)))
  12794. (setq tags-expanded
  12795. (append (list x) tags-expanded)))
  12796. (setq work-already-expanded
  12797. (delete-dups
  12798. (append tags-expanded
  12799. work-already-expanded))))
  12800. (setq tags-in-group
  12801. (delete-dups (cons (car tags-in-group)
  12802. tags-expanded)))))
  12803. ;; Filter tag-regexps from tags.
  12804. (setq regexp-in-group-escaped
  12805. (delq nil (mapcar (lambda (x)
  12806. (if (stringp x)
  12807. (and (equal "{" (substring x 0 1))
  12808. (equal "}" (substring x -1))
  12809. x)
  12810. x))
  12811. tags-in-group))
  12812. regexp-in-group
  12813. (mapcar (lambda (x)
  12814. (substring x 1 -1))
  12815. regexp-in-group-escaped)
  12816. tags-in-group
  12817. (delq nil (mapcar (lambda (x)
  12818. (if (stringp x)
  12819. (and (not (equal "{" (substring x 0 1)))
  12820. (not (equal "}" (substring x -1)))
  12821. x)
  12822. x))
  12823. tags-in-group)))
  12824. ;; If single-as-list, do no more in the while-loop.
  12825. (if (not single-as-list)
  12826. (progn
  12827. (when regexp-in-group
  12828. (setq regexp-in-group
  12829. (concat "\\|"
  12830. (mapconcat 'identity regexp-in-group
  12831. "\\|"))))
  12832. (setq tags-in-group
  12833. (concat dir
  12834. "{\\<"
  12835. (regexp-opt tags-in-group)
  12836. "\\>"
  12837. regexp-in-group
  12838. "}"))
  12839. (when (stringp tags-in-group)
  12840. (org-add-props tags-in-group '(grouptag t)))
  12841. (setq return-match
  12842. (replace-match tags-in-group t t return-match)))
  12843. (setq tags-in-group
  12844. (append regexp-in-group-escaped tags-in-group))))
  12845. (setq taggroups-keys (delete tag taggroups-keys))))
  12846. ;; Add the regular expressions back into the match-expression again.
  12847. (while regexps-in-match
  12848. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  12849. (pop regexps-in-match)
  12850. return-match t t))
  12851. (cl-decf count))
  12852. (if single-as-list
  12853. (if tags-in-group tags-in-group (list return-match))
  12854. return-match))
  12855. (if single-as-list
  12856. (list (if downcased (downcase match) match))
  12857. match)))
  12858. (defun org-op-to-function (op &optional stringp)
  12859. "Turn an operator into the appropriate function."
  12860. (setq op
  12861. (cond
  12862. ((equal op "<" ) '(< org-string< org-time<))
  12863. ((equal op ">" ) '(> org-string> org-time>))
  12864. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  12865. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  12866. ((member op '("=" "==")) '(= string= org-time=))
  12867. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  12868. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  12869. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  12870. (defvar org-tags-overlay (make-overlay 1 1))
  12871. (delete-overlay org-tags-overlay)
  12872. (defun org-add-prop-inherited (s)
  12873. (add-text-properties 0 (length s) '(inherited t) s)
  12874. s)
  12875. (defun org-toggle-tag (tag &optional onoff)
  12876. "Toggle the tag TAG for the current line.
  12877. If ONOFF is `on' or `off', don't toggle but set to this state."
  12878. (save-excursion
  12879. (org-back-to-heading t)
  12880. (let ((current
  12881. ;; Reverse the tags list so any new tag is appended to the
  12882. ;; current list of tags.
  12883. (nreverse (org-get-tags nil t)))
  12884. res)
  12885. (pcase onoff
  12886. (`off (setq current (delete tag current)))
  12887. ((or `on (guard (not (member tag current))))
  12888. (setq res t)
  12889. (cl-pushnew tag current :test #'equal))
  12890. (_ (setq current (delete tag current))))
  12891. (org-set-tags (nreverse current))
  12892. res)))
  12893. (defun org--align-tags-here (to-col)
  12894. "Align tags on the current headline to TO-COL.
  12895. Assume point is on a headline. Preserve point when aligning
  12896. tags."
  12897. (when (and (org-match-line org-tag-line-re)
  12898. (/= to-col (save-excursion ;nothing to do?
  12899. (goto-char (match-beginning 1)) (current-column))))
  12900. (let* ((shift (if (>= to-col 0) to-col
  12901. (- (abs to-col) (string-width (match-string 1)))))
  12902. (origin (point-marker))
  12903. (column (current-column))
  12904. (tags-start (match-beginning 1))
  12905. (blank-start (save-excursion
  12906. (goto-char tags-start)
  12907. (skip-chars-backward " \t")
  12908. (point)))
  12909. (in-blank? (and (> origin blank-start)
  12910. (<= origin tags-start))))
  12911. (delete-region blank-start tags-start)
  12912. (goto-char blank-start)
  12913. (let ((indent-tabs-mode nil)) (indent-to shift 1))
  12914. ;; Try to move back to original position. If point was in the
  12915. ;; blanks before the tags, ORIGIN marker is of no use because it
  12916. ;; now points to BLANK-START. Use COLUMN instead.
  12917. (if in-blank? (org-move-to-column column)
  12918. (goto-char origin)))))
  12919. (defun org-set-tags-command (&optional arg)
  12920. "Set the tags for the current visible entry.
  12921. When called with `\\[universal-argument]' prefix argument ARG, \
  12922. realign all tags
  12923. in the current buffer. If a region is active, set tags for
  12924. all headlines in the region.
  12925. This function is for interactive use only;
  12926. in Lisp code use `org-set-tags' instead."
  12927. (interactive "P")
  12928. (cond
  12929. (arg (org-align-tags t))
  12930. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12931. ;; Disable `org-loop-over-headlines-in-active-region' for
  12932. ;; successive calls.
  12933. (let (org-loop-over-headlines-in-active-region)
  12934. (org-map-entries
  12935. #'org-set-tags-command
  12936. nil
  12937. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12938. 'region-start-level
  12939. 'region)
  12940. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  12941. (t
  12942. (save-excursion
  12943. (org-back-to-heading)
  12944. (let* ((all-tags (org-get-tags))
  12945. (table (setq org-last-tags-completion-table
  12946. (org--tag-add-to-alist
  12947. (and org-complete-tags-always-offer-all-agenda-tags
  12948. (org-global-tags-completion-table
  12949. (org-agenda-files)))
  12950. (or org-current-tag-alist (org-get-buffer-tags)))))
  12951. (current-tags
  12952. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  12953. all-tags))
  12954. (inherited-tags
  12955. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  12956. all-tags))
  12957. (tags
  12958. (replace-regexp-in-string
  12959. ;; Ignore all forbidden characters in tags.
  12960. "[^[:alnum:]_@#%]+" ":"
  12961. (if (or (eq t org-use-fast-tag-selection)
  12962. (and org-use-fast-tag-selection
  12963. (delq nil (mapcar #'cdr table))))
  12964. (org-fast-tag-selection
  12965. current-tags
  12966. inherited-tags
  12967. table
  12968. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  12969. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  12970. (org-trim (completing-read
  12971. "Tags: "
  12972. #'org-tags-completion-function
  12973. nil nil (org-make-tag-string current-tags)
  12974. 'org-tags-history)))))))
  12975. (org-set-tags tags))))))
  12976. (defun org-align-tags (&optional all)
  12977. "Align tags in current entry.
  12978. When optional argument ALL is non-nil, align all tags in the
  12979. visible part of the buffer."
  12980. (let ((get-indent-column
  12981. (lambda ()
  12982. (let ((offset (if (bound-and-true-p org-indent-mode)
  12983. (* (1- org-indent-indentation-per-level)
  12984. (1- (org-current-level)))
  12985. 0)))
  12986. (+ org-tags-column
  12987. (if (> org-tags-column 0) (- offset) offset))))))
  12988. (if (and (not all) (org-at-heading-p))
  12989. (org--align-tags-here (funcall get-indent-column))
  12990. (save-excursion
  12991. (if all
  12992. (while (re-search-forward org-tag-line-re nil t)
  12993. (org--align-tags-here (funcall get-indent-column)))
  12994. (org-back-to-heading t)
  12995. (org--align-tags-here (funcall get-indent-column)))))))
  12996. (defun org-set-tags (tags)
  12997. "Set the tags of the current entry to TAGS, replacing current tags.
  12998. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  12999. If TAGS is nil or the empty string, all tags are removed.
  13000. This function assumes point is on a headline."
  13001. (org-with-wide-buffer
  13002. (let ((tags (pcase tags
  13003. ((pred listp) tags)
  13004. ((pred stringp) (split-string (org-trim tags) ":" t))
  13005. (_ (error "Invalid tag specification: %S" tags))))
  13006. (old-tags (org-get-tags nil t))
  13007. (change-flag nil))
  13008. (when (functionp org-tags-sort-function)
  13009. (setq tags (sort tags org-tags-sort-function)))
  13010. (unless (equal tags old-tags) (setq change-flag t))
  13011. ;; Delete previous tags and any trailing white space.
  13012. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  13013. (line-end-position)))
  13014. (skip-chars-backward " \t")
  13015. (delete-region (point) (line-end-position))
  13016. ;; Deleting white spaces may break an otherwise empty headline.
  13017. ;; Re-introduce one space in this case.
  13018. (unless (org-at-heading-p) (insert " "))
  13019. (when tags
  13020. (save-excursion (insert " " (org-make-tag-string tags)))
  13021. ;; When text is being inserted on an invisible region
  13022. ;; boundary, it can be inadvertently sucked into
  13023. ;; invisibility.
  13024. (unless (org-invisible-p (line-beginning-position))
  13025. (org-flag-region (point) (line-end-position) nil 'outline)))
  13026. ;; Align tags, if any.
  13027. (when tags (org-align-tags))
  13028. (when change-flag (run-hooks 'org-after-tags-change-hook)))))
  13029. (defun org-change-tag-in-region (beg end tag off)
  13030. "Add or remove TAG for each entry in the region.
  13031. This works in the agenda, and also in an Org buffer."
  13032. (interactive
  13033. (list (region-beginning) (region-end)
  13034. (let ((org-last-tags-completion-table
  13035. (if (derived-mode-p 'org-mode)
  13036. (org--tag-add-to-alist
  13037. (org-get-buffer-tags)
  13038. (org-global-tags-completion-table))
  13039. (org-global-tags-completion-table))))
  13040. (completing-read
  13041. "Tag: " 'org-tags-completion-function nil nil nil
  13042. 'org-tags-history))
  13043. (progn
  13044. (message "[s]et or [r]emove? ")
  13045. (equal (read-char-exclusive) ?r))))
  13046. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13047. (let ((agendap (equal major-mode 'org-agenda-mode))
  13048. l1 l2 m buf pos newhead (cnt 0))
  13049. (goto-char end)
  13050. (setq l2 (1- (org-current-line)))
  13051. (goto-char beg)
  13052. (setq l1 (org-current-line))
  13053. (cl-loop for l from l1 to l2 do
  13054. (org-goto-line l)
  13055. (setq m (get-text-property (point) 'org-hd-marker))
  13056. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13057. (and agendap m))
  13058. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13059. pos (if agendap m (point)))
  13060. (with-current-buffer buf
  13061. (save-excursion
  13062. (save-restriction
  13063. (goto-char pos)
  13064. (setq cnt (1+ cnt))
  13065. (org-toggle-tag tag (if off 'off 'on))
  13066. (setq newhead (org-get-heading)))))
  13067. (and agendap (org-agenda-change-all-lines newhead m))))
  13068. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13069. (defun org-tags-completion-function (string _predicate &optional flag)
  13070. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13071. (confirm (lambda (x) (stringp (car x)))))
  13072. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13073. (setq s1 (match-string 1 string)
  13074. s2 (match-string 2 string))
  13075. (setq s1 "" s2 string))
  13076. (cond
  13077. ((eq flag nil)
  13078. ;; try completion
  13079. (setq rtn (try-completion s2 ctable confirm))
  13080. (when (stringp rtn)
  13081. (setq rtn
  13082. (concat s1 s2 (substring rtn (length s2))
  13083. (if (and org-add-colon-after-tag-completion
  13084. (assoc rtn ctable))
  13085. ":" ""))))
  13086. rtn)
  13087. ((eq flag t)
  13088. ;; all-completions
  13089. (all-completions s2 ctable confirm))
  13090. ((eq flag 'lambda)
  13091. ;; exact match?
  13092. (assoc s2 ctable)))))
  13093. (defun org-fast-tag-insert (kwd tags face &optional end)
  13094. "Insert KDW, and the TAGS, the latter with face FACE.
  13095. Also insert END."
  13096. (insert (format "%-12s" (concat kwd ":"))
  13097. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13098. (or end "")))
  13099. (defun org-fast-tag-show-exit (flag)
  13100. (save-excursion
  13101. (org-goto-line 3)
  13102. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13103. (replace-match ""))
  13104. (when flag
  13105. (end-of-line 1)
  13106. (org-move-to-column (- (window-width) 19) t)
  13107. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13108. (defun org-set-current-tags-overlay (current prefix)
  13109. "Add an overlay to CURRENT tag with PREFIX."
  13110. (let ((s (org-make-tag-string current)))
  13111. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13112. (org-overlay-display org-tags-overlay (concat prefix s))))
  13113. (defvar org-last-tag-selection-key nil)
  13114. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13115. "Fast tag selection with single keys.
  13116. CURRENT is the current list of tags in the headline, INHERITED is the
  13117. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13118. possibly with grouping information. TODO-TABLE is a similar table with
  13119. TODO keywords, should these have keys assigned to them.
  13120. If the keys are nil, a-z are automatically assigned.
  13121. Returns the new tags string, or nil to not change the current settings."
  13122. (let* ((fulltable (append table todo-table))
  13123. (maxlen (if (null fulltable) 0
  13124. (apply #'max
  13125. (mapcar (lambda (x)
  13126. (if (stringp (car x)) (string-width (car x))
  13127. 0))
  13128. fulltable))))
  13129. (buf (current-buffer))
  13130. (expert (eq org-fast-tag-selection-single-key 'expert))
  13131. (buffer-tags nil)
  13132. (fwidth (+ maxlen 3 1 3))
  13133. (ncol (/ (- (window-width) 4) fwidth))
  13134. (i-face 'org-done)
  13135. (c-face 'org-todo)
  13136. tg cnt e c char c1 c2 ntable tbl rtn
  13137. ov-start ov-end ov-prefix
  13138. (exit-after-next org-fast-tag-selection-single-key)
  13139. (done-keywords org-done-keywords)
  13140. groups ingroup intaggroup)
  13141. (save-excursion
  13142. (beginning-of-line)
  13143. (if (looking-at org-tag-line-re)
  13144. (setq ov-start (match-beginning 1)
  13145. ov-end (match-end 1)
  13146. ov-prefix "")
  13147. (setq ov-start (1- (point-at-eol))
  13148. ov-end (1+ ov-start))
  13149. (skip-chars-forward "^\n\r")
  13150. (setq ov-prefix
  13151. (concat
  13152. (buffer-substring (1- (point)) (point))
  13153. (if (> (current-column) org-tags-column)
  13154. " "
  13155. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13156. (move-overlay org-tags-overlay ov-start ov-end)
  13157. (save-window-excursion
  13158. (if expert
  13159. (set-buffer (get-buffer-create " *Org tags*"))
  13160. (delete-other-windows)
  13161. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13162. (org-switch-to-buffer-other-window " *Org tags*"))
  13163. (erase-buffer)
  13164. (setq-local org-done-keywords done-keywords)
  13165. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13166. (org-fast-tag-insert "Current" current c-face "\n\n")
  13167. (org-fast-tag-show-exit exit-after-next)
  13168. (org-set-current-tags-overlay current ov-prefix)
  13169. (setq tbl fulltable char ?a cnt 0)
  13170. (while (setq e (pop tbl))
  13171. (cond
  13172. ((eq (car e) :startgroup)
  13173. (push '() groups) (setq ingroup t)
  13174. (unless (zerop cnt)
  13175. (setq cnt 0)
  13176. (insert "\n"))
  13177. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13178. ((eq (car e) :endgroup)
  13179. (setq ingroup nil cnt 0)
  13180. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13181. ((eq (car e) :startgrouptag)
  13182. (setq intaggroup t)
  13183. (unless (zerop cnt)
  13184. (setq cnt 0)
  13185. (insert "\n"))
  13186. (insert "[ "))
  13187. ((eq (car e) :endgrouptag)
  13188. (setq intaggroup nil cnt 0)
  13189. (insert "]\n"))
  13190. ((equal e '(:newline))
  13191. (unless (zerop cnt)
  13192. (setq cnt 0)
  13193. (insert "\n")
  13194. (setq e (car tbl))
  13195. (while (equal (car tbl) '(:newline))
  13196. (insert "\n")
  13197. (setq tbl (cdr tbl)))))
  13198. ((equal e '(:grouptags)) (insert " : "))
  13199. (t
  13200. (setq tg (copy-sequence (car e)) c2 nil)
  13201. (if (cdr e)
  13202. (setq c (cdr e))
  13203. ;; automatically assign a character.
  13204. (setq c1 (string-to-char
  13205. (downcase (substring
  13206. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13207. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13208. (while (or (rassoc char ntable) (rassoc char table))
  13209. (setq char (1+ char)))
  13210. (setq c2 c1))
  13211. (setq c (or c2 char)))
  13212. (when ingroup (push tg (car groups)))
  13213. (setq tg (org-add-props tg nil 'face
  13214. (cond
  13215. ((not (assoc tg table))
  13216. (org-get-todo-face tg))
  13217. ((member tg current) c-face)
  13218. ((member tg inherited) i-face))))
  13219. (when (equal (caar tbl) :grouptags)
  13220. (org-add-props tg nil 'face 'org-tag-group))
  13221. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13222. (insert "[" c "] " tg (make-string
  13223. (- fwidth 4 (length tg)) ?\ ))
  13224. (push (cons tg c) ntable)
  13225. (when (= (cl-incf cnt) ncol)
  13226. (insert "\n")
  13227. (when (or ingroup intaggroup) (insert " "))
  13228. (setq cnt 0)))))
  13229. (setq ntable (nreverse ntable))
  13230. (insert "\n")
  13231. (goto-char (point-min))
  13232. (unless expert (org-fit-window-to-buffer))
  13233. (setq rtn
  13234. (catch 'exit
  13235. (while t
  13236. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  13237. (if (not groups) "no " "")
  13238. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13239. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13240. (setq org-last-tag-selection-key c)
  13241. (cond
  13242. ((= c ?\r) (throw 'exit t))
  13243. ((= c ?!)
  13244. (setq groups (not groups))
  13245. (goto-char (point-min))
  13246. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13247. ((= c ?\C-c)
  13248. (if (not expert)
  13249. (org-fast-tag-show-exit
  13250. (setq exit-after-next (not exit-after-next)))
  13251. (setq expert nil)
  13252. (delete-other-windows)
  13253. (set-window-buffer (split-window-vertically) " *Org tags*")
  13254. (org-switch-to-buffer-other-window " *Org tags*")
  13255. (org-fit-window-to-buffer)))
  13256. ((or (= c ?\C-g)
  13257. (and (= c ?q) (not (rassoc c ntable))))
  13258. (delete-overlay org-tags-overlay)
  13259. (setq quit-flag t))
  13260. ((= c ?\ )
  13261. (setq current nil)
  13262. (when exit-after-next (setq exit-after-next 'now)))
  13263. ((= c ?\t)
  13264. (condition-case nil
  13265. (setq tg (completing-read
  13266. "Tag: "
  13267. (or buffer-tags
  13268. (with-current-buffer buf
  13269. (setq buffer-tags
  13270. (org-get-buffer-tags))))))
  13271. (quit (setq tg "")))
  13272. (when (string-match "\\S-" tg)
  13273. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13274. (if (member tg current)
  13275. (setq current (delete tg current))
  13276. (push tg current)))
  13277. (when exit-after-next (setq exit-after-next 'now)))
  13278. ((setq e (rassoc c todo-table) tg (car e))
  13279. (with-current-buffer buf
  13280. (save-excursion (org-todo tg)))
  13281. (when exit-after-next (setq exit-after-next 'now)))
  13282. ((setq e (rassoc c ntable) tg (car e))
  13283. (if (member tg current)
  13284. (setq current (delete tg current))
  13285. (cl-loop for g in groups do
  13286. (when (member tg g)
  13287. (dolist (x g) (setq current (delete x current)))))
  13288. (push tg current))
  13289. (when exit-after-next (setq exit-after-next 'now))))
  13290. ;; Create a sorted list
  13291. (setq current
  13292. (sort current
  13293. (lambda (a b)
  13294. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13295. (when (eq exit-after-next 'now) (throw 'exit t))
  13296. (goto-char (point-min))
  13297. (beginning-of-line 2)
  13298. (delete-region (point) (point-at-eol))
  13299. (org-fast-tag-insert "Current" current c-face)
  13300. (org-set-current-tags-overlay current ov-prefix)
  13301. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  13302. (while (re-search-forward tag-re nil t)
  13303. (let ((tag (match-string 1)))
  13304. (add-text-properties
  13305. (match-beginning 1) (match-end 1)
  13306. (list 'face
  13307. (cond
  13308. ((member tag current) c-face)
  13309. ((member tag inherited) i-face)
  13310. (t (get-text-property (match-beginning 1) '
  13311. face))))))))
  13312. (goto-char (point-min)))))
  13313. (delete-overlay org-tags-overlay)
  13314. (if rtn
  13315. (mapconcat 'identity current ":")
  13316. nil))))
  13317. (defun org-make-tag-string (tags)
  13318. "Return string associated to TAGS.
  13319. TAGS is a list of strings."
  13320. (if (null tags) ""
  13321. (format ":%s:" (mapconcat #'identity tags ":"))))
  13322. (defun org--get-local-tags ()
  13323. "Return list of tags for the current headline.
  13324. Assume point is at the beginning of the headline."
  13325. (and (looking-at org-tag-line-re)
  13326. (split-string (match-string-no-properties 2) ":" t)))
  13327. (defun org-get-tags (&optional pos local)
  13328. "Get the list of tags specified in the current headline.
  13329. When argument POS is non-nil, retrieve tags for headline at POS.
  13330. Accoring to `org-use-tags-inheritance', tags may be inherited
  13331. from parent headlines, and from the whole document, through
  13332. `org-file-tags'. However, when optional argument LOCAL is
  13333. non-nil, only return tags really specified in the considered
  13334. headline.
  13335. Inherited tags have the `inherited' text property."
  13336. (if (and org-trust-scanner-tags
  13337. (or (not pos) (eq pos (point)))
  13338. (not local))
  13339. org-scanner-tags
  13340. (org-with-point-at (or pos (point))
  13341. (unless (org-before-first-heading-p)
  13342. (org-back-to-heading t)
  13343. (let ((tags (org--get-local-tags)))
  13344. (if (or local (not org-use-tag-inheritance)) tags
  13345. (while (org-up-heading-safe)
  13346. (setq tags (append (mapcar #'org-add-prop-inherited
  13347. (org--get-local-tags))
  13348. tags)))
  13349. (org-remove-uninherited-tags
  13350. (delete-dups (append org-file-tags tags)))))))))
  13351. (defun org-get-buffer-tags ()
  13352. "Get a table of all tags used in the buffer, for completion."
  13353. (org-with-point-at 1
  13354. (let (tags)
  13355. (while (re-search-forward org-tag-line-re nil t)
  13356. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  13357. tags)))
  13358. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  13359. ;;;; The mapping API
  13360. (defvar org-agenda-skip-comment-trees)
  13361. (defvar org-agenda-skip-function)
  13362. (defun org-map-entries (func &optional match scope &rest skip)
  13363. "Call FUNC at each headline selected by MATCH in SCOPE.
  13364. FUNC is a function or a lisp form. The function will be called without
  13365. arguments, with the cursor positioned at the beginning of the headline.
  13366. The return values of all calls to the function will be collected and
  13367. returned as a list.
  13368. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13369. does not need to preserve point. After evaluation, the cursor will be
  13370. moved to the end of the line (presumably of the headline of the
  13371. processed entry) and search continues from there. Under some
  13372. circumstances, this may not produce the wanted results. For example,
  13373. if you have removed (e.g. archived) the current (sub)tree it could
  13374. mean that the next entry will be skipped entirely. In such cases, you
  13375. can specify the position from where search should continue by making
  13376. FUNC set the variable `org-map-continue-from' to the desired buffer
  13377. position.
  13378. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13379. Only headlines that are matched by this query will be considered during
  13380. the iteration. When MATCH is nil or t, all headlines will be
  13381. visited by the iteration.
  13382. SCOPE determines the scope of this command. It can be any of:
  13383. nil The current buffer, respecting the restriction if any
  13384. tree The subtree started with the entry at point
  13385. region The entries within the active region, if any
  13386. region-start-level
  13387. The entries within the active region, but only those at
  13388. the same level than the first one.
  13389. file The current buffer, without restriction
  13390. file-with-archives
  13391. The current buffer, and any archives associated with it
  13392. agenda All agenda files
  13393. agenda-with-archives
  13394. All agenda files with any archive files associated with them
  13395. \(file1 file2 ...)
  13396. If this is a list, all files in the list will be scanned
  13397. The remaining args are treated as settings for the skipping facilities of
  13398. the scanner. The following items can be given here:
  13399. archive skip trees with the archive tag
  13400. comment skip trees with the COMMENT keyword
  13401. function or Emacs Lisp form:
  13402. will be used as value for `org-agenda-skip-function', so
  13403. whenever the function returns a position, FUNC will not be
  13404. called for that entry and search will continue from the
  13405. position returned
  13406. If your function needs to retrieve the tags including inherited tags
  13407. at the *current* entry, you can use the value of the variable
  13408. `org-scanner-tags' which will be much faster than getting the value
  13409. with `org-get-tags'. If your function gets properties with
  13410. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  13411. to t around the call to `org-entry-properties' to get the same speedup.
  13412. Note that if your function moves around to retrieve tags and properties at
  13413. a *different* entry, you cannot use these techniques."
  13414. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  13415. (not (org-region-active-p)))
  13416. (let* ((org-agenda-archives-mode nil) ; just to make sure
  13417. (org-agenda-skip-archived-trees (memq 'archive skip))
  13418. (org-agenda-skip-comment-trees (memq 'comment skip))
  13419. (org-agenda-skip-function
  13420. (car (org-delete-all '(comment archive) skip)))
  13421. (org-tags-match-list-sublevels t)
  13422. (start-level (eq scope 'region-start-level))
  13423. matcher res
  13424. org-todo-keywords-for-agenda
  13425. org-done-keywords-for-agenda
  13426. org-todo-keyword-alist-for-agenda
  13427. org-tag-alist-for-agenda
  13428. org--matcher-tags-todo-only)
  13429. (cond
  13430. ((eq match t) (setq matcher t))
  13431. ((eq match nil) (setq matcher t))
  13432. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  13433. (save-excursion
  13434. (save-restriction
  13435. (cond ((eq scope 'tree)
  13436. (org-back-to-heading t)
  13437. (org-narrow-to-subtree)
  13438. (setq scope nil))
  13439. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  13440. (org-region-active-p))
  13441. ;; If needed, set start-level to a string like "2"
  13442. (when start-level
  13443. (save-excursion
  13444. (goto-char (region-beginning))
  13445. (unless (org-at-heading-p) (outline-next-heading))
  13446. (setq start-level (org-current-level))))
  13447. (narrow-to-region (region-beginning)
  13448. (save-excursion
  13449. (goto-char (region-end))
  13450. (unless (and (bolp) (org-at-heading-p))
  13451. (outline-next-heading))
  13452. (point)))
  13453. (setq scope nil)))
  13454. (if (not scope)
  13455. (progn
  13456. (org-agenda-prepare-buffers
  13457. (and buffer-file-name (list buffer-file-name)))
  13458. (setq res
  13459. (org-scan-tags
  13460. func matcher org--matcher-tags-todo-only start-level)))
  13461. ;; Get the right scope
  13462. (cond
  13463. ((and scope (listp scope) (symbolp (car scope)))
  13464. (setq scope (eval scope)))
  13465. ((eq scope 'agenda)
  13466. (setq scope (org-agenda-files t)))
  13467. ((eq scope 'agenda-with-archives)
  13468. (setq scope (org-agenda-files t))
  13469. (setq scope (org-add-archive-files scope)))
  13470. ((eq scope 'file)
  13471. (setq scope (and buffer-file-name (list buffer-file-name))))
  13472. ((eq scope 'file-with-archives)
  13473. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  13474. (org-agenda-prepare-buffers scope)
  13475. (dolist (file scope)
  13476. (with-current-buffer (org-find-base-buffer-visiting file)
  13477. (org-with-wide-buffer
  13478. (goto-char (point-min))
  13479. (setq res
  13480. (append
  13481. res
  13482. (org-scan-tags
  13483. func matcher org--matcher-tags-todo-only)))))))))
  13484. res)))
  13485. ;;; Properties API
  13486. (defconst org-special-properties
  13487. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  13488. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  13489. "The special properties valid in Org mode.
  13490. These are properties that are not defined in the property drawer,
  13491. but in some other way.")
  13492. (defconst org-default-properties
  13493. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  13494. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  13495. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  13496. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  13497. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  13498. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  13499. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  13500. "Some properties that are used by Org mode for various purposes.
  13501. Being in this list makes sure that they are offered for completion.")
  13502. (defun org--valid-property-p (property)
  13503. "Non nil when string PROPERTY is a valid property name."
  13504. (not
  13505. (or (equal property "")
  13506. (string-match-p "\\s-" property))))
  13507. (defun org--update-property-plist (key val props)
  13508. "Associate KEY to VAL in alist PROPS.
  13509. Modifications are made by side-effect. Return new alist."
  13510. (let* ((appending (string= (substring key -1) "+"))
  13511. (key (if appending (substring key 0 -1) key))
  13512. (old (assoc-string key props t)))
  13513. (if (not old) (cons (cons key val) props)
  13514. (setcdr old (if appending (concat (cdr old) " " val) val))
  13515. props)))
  13516. (defun org-get-property-block (&optional beg force)
  13517. "Return the (beg . end) range of the body of the property drawer.
  13518. BEG is the beginning of the current subtree, or of the part
  13519. before the first headline. If it is not given, it will be found.
  13520. If the drawer does not exist, create it if FORCE is non-nil, or
  13521. return nil."
  13522. (org-with-wide-buffer
  13523. (when beg (goto-char beg))
  13524. (unless (org-before-first-heading-p)
  13525. (let ((beg (cond (beg)
  13526. ((or (not (featurep 'org-inlinetask))
  13527. (org-inlinetask-in-task-p))
  13528. (org-back-to-heading t))
  13529. (t (org-with-limited-levels (org-back-to-heading t))))))
  13530. (forward-line)
  13531. (when (looking-at-p org-planning-line-re) (forward-line))
  13532. (cond ((looking-at org-property-drawer-re)
  13533. (forward-line)
  13534. (cons (point) (progn (goto-char (match-end 0))
  13535. (line-beginning-position))))
  13536. (force
  13537. (goto-char beg)
  13538. (org-insert-property-drawer)
  13539. (let ((pos (save-excursion (search-forward ":END:")
  13540. (line-beginning-position))))
  13541. (cons pos pos))))))))
  13542. (defun org-at-property-p ()
  13543. "Non-nil when point is inside a property drawer.
  13544. See `org-property-re' for match data, if applicable."
  13545. (save-excursion
  13546. (beginning-of-line)
  13547. (and (looking-at org-property-re)
  13548. (let ((property-drawer (save-match-data (org-get-property-block))))
  13549. (and property-drawer
  13550. (>= (point) (car property-drawer))
  13551. (< (point) (cdr property-drawer)))))))
  13552. (defun org-property-action ()
  13553. "Do an action on properties."
  13554. (interactive)
  13555. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  13556. (let ((c (read-char-exclusive)))
  13557. (cl-case c
  13558. (?s (call-interactively #'org-set-property))
  13559. (?d (call-interactively #'org-delete-property))
  13560. (?D (call-interactively #'org-delete-property-globally))
  13561. (?c (call-interactively #'org-compute-property-at-point))
  13562. (otherwise (user-error "No such property action %c" c)))))
  13563. (defun org-inc-effort ()
  13564. "Increment the value of the effort property in the current entry."
  13565. (interactive)
  13566. (org-set-effort t))
  13567. (defvar org-clock-effort) ; Defined in org-clock.el.
  13568. (defvar org-clock-current-task) ; Defined in org-clock.el.
  13569. (defun org-set-effort (&optional increment value)
  13570. "Set the effort property of the current entry.
  13571. If INCREMENT is non-nil, set the property to the next allowed
  13572. value. Otherwise, if optional argument VALUE is provided, use
  13573. it. Eventually, prompt for the new value if none of the previous
  13574. variables is set."
  13575. (interactive "P")
  13576. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  13577. (current (org-entry-get nil org-effort-property))
  13578. (value
  13579. (cond
  13580. (increment
  13581. (unless allowed (user-error "Allowed effort values are not set"))
  13582. (or (cl-caadr (member (list current) allowed))
  13583. (user-error "Unknown value %S among allowed values" current)))
  13584. (value
  13585. (if (stringp value) value
  13586. (error "Invalid effort value: %S" value)))
  13587. (t
  13588. (let ((must-match
  13589. (and allowed
  13590. (not (get-text-property 0 'org-unrestricted
  13591. (caar allowed))))))
  13592. (completing-read "Effort: " allowed nil must-match))))))
  13593. (unless (equal current value)
  13594. (org-entry-put nil org-effort-property value))
  13595. (org-refresh-property '((effort . identity)
  13596. (effort-minutes . org-duration-to-minutes))
  13597. value)
  13598. (when (equal (org-get-heading t t t t)
  13599. (bound-and-true-p org-clock-current-task))
  13600. (setq org-clock-effort (org-get-at-bol 'effort))
  13601. (org-clock-update-mode-line))
  13602. (message "%s is now %s" org-effort-property value)))
  13603. (defun org-entry-properties (&optional pom which)
  13604. "Get all properties of the current entry.
  13605. When POM is a buffer position, get all properties from the entry
  13606. there instead.
  13607. This includes the TODO keyword, the tags, time strings for
  13608. deadline, scheduled, and clocking, and any additional properties
  13609. defined in the entry.
  13610. If WHICH is nil or `all', get all properties. If WHICH is
  13611. `special' or `standard', only get that subclass. If WHICH is
  13612. a string, only get that property.
  13613. Return value is an alist. Keys are properties, as upcased
  13614. strings."
  13615. (org-with-point-at pom
  13616. (when (and (derived-mode-p 'org-mode)
  13617. (ignore-errors (org-back-to-heading t)))
  13618. (catch 'exit
  13619. (let* ((beg (point))
  13620. (specific (and (stringp which) (upcase which)))
  13621. (which (cond ((not specific) which)
  13622. ((member specific org-special-properties) 'special)
  13623. (t 'standard)))
  13624. props)
  13625. ;; Get the special properties, like TODO and TAGS.
  13626. (when (memq which '(nil all special))
  13627. (when (or (not specific) (string= specific "CLOCKSUM"))
  13628. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  13629. (when clocksum
  13630. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  13631. props)))
  13632. (when specific (throw 'exit props)))
  13633. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  13634. (let ((clocksumt (get-text-property (point)
  13635. :org-clock-minutes-today)))
  13636. (when clocksumt
  13637. (push (cons "CLOCKSUM_T"
  13638. (org-duration-from-minutes clocksumt))
  13639. props)))
  13640. (when specific (throw 'exit props)))
  13641. (when (or (not specific) (string= specific "ITEM"))
  13642. (let ((case-fold-search nil))
  13643. (when (looking-at org-complex-heading-regexp)
  13644. (push (cons "ITEM"
  13645. (let ((title (match-string-no-properties 4)))
  13646. (if (org-string-nw-p title)
  13647. (org-remove-tabs title)
  13648. "")))
  13649. props)))
  13650. (when specific (throw 'exit props)))
  13651. (when (or (not specific) (string= specific "TODO"))
  13652. (let ((case-fold-search nil))
  13653. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  13654. (push (cons "TODO" (match-string-no-properties 2)) props)))
  13655. (when specific (throw 'exit props)))
  13656. (when (or (not specific) (string= specific "PRIORITY"))
  13657. (push (cons "PRIORITY"
  13658. (if (looking-at org-priority-regexp)
  13659. (match-string-no-properties 2)
  13660. (char-to-string org-default-priority)))
  13661. props)
  13662. (when specific (throw 'exit props)))
  13663. (when (or (not specific) (string= specific "FILE"))
  13664. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  13665. props)
  13666. (when specific (throw 'exit props)))
  13667. (when (or (not specific) (string= specific "TAGS"))
  13668. (let ((tags (org-get-tags nil t)))
  13669. (when tags
  13670. (push (cons "TAGS" (org-make-tag-string tags))
  13671. props)))
  13672. (when specific (throw 'exit props)))
  13673. (when (or (not specific) (string= specific "ALLTAGS"))
  13674. (let ((tags (org-get-tags)))
  13675. (when tags
  13676. (push (cons "ALLTAGS" (org-make-tag-string tags))
  13677. props)))
  13678. (when specific (throw 'exit props)))
  13679. (when (or (not specific) (string= specific "BLOCKED"))
  13680. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  13681. (when specific (throw 'exit props)))
  13682. (when (or (not specific)
  13683. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  13684. (forward-line)
  13685. (when (looking-at-p org-planning-line-re)
  13686. (end-of-line)
  13687. (let ((bol (line-beginning-position))
  13688. ;; Backward compatibility: time keywords used to
  13689. ;; be configurable (before 8.3). Make sure we
  13690. ;; get the correct keyword.
  13691. (key-assoc `(("CLOSED" . ,org-closed-string)
  13692. ("DEADLINE" . ,org-deadline-string)
  13693. ("SCHEDULED" . ,org-scheduled-string))))
  13694. (dolist (pair (if specific (list (assoc specific key-assoc))
  13695. key-assoc))
  13696. (save-excursion
  13697. (when (search-backward (cdr pair) bol t)
  13698. (goto-char (match-end 0))
  13699. (skip-chars-forward " \t")
  13700. (and (looking-at org-ts-regexp-both)
  13701. (push (cons (car pair)
  13702. (match-string-no-properties 0))
  13703. props)))))))
  13704. (when specific (throw 'exit props)))
  13705. (when (or (not specific)
  13706. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  13707. (let ((find-ts
  13708. (lambda (end ts)
  13709. ;; Fix next time-stamp before END. TS is the
  13710. ;; list of time-stamps found so far.
  13711. (let ((ts ts)
  13712. (regexp (cond
  13713. ((string= specific "TIMESTAMP")
  13714. org-ts-regexp)
  13715. ((string= specific "TIMESTAMP_IA")
  13716. org-ts-regexp-inactive)
  13717. ((assoc "TIMESTAMP_IA" ts)
  13718. org-ts-regexp)
  13719. ((assoc "TIMESTAMP" ts)
  13720. org-ts-regexp-inactive)
  13721. (t org-ts-regexp-both))))
  13722. (catch 'next
  13723. (while (re-search-forward regexp end t)
  13724. (backward-char)
  13725. (let ((object (org-element-context)))
  13726. ;; Accept to match timestamps in node
  13727. ;; properties, too.
  13728. (when (memq (org-element-type object)
  13729. '(node-property timestamp))
  13730. (let ((type
  13731. (org-element-property :type object)))
  13732. (cond
  13733. ((and (memq type '(active active-range))
  13734. (not (equal specific "TIMESTAMP_IA")))
  13735. (unless (assoc "TIMESTAMP" ts)
  13736. (push (cons "TIMESTAMP"
  13737. (org-element-property
  13738. :raw-value object))
  13739. ts)
  13740. (when specific (throw 'exit ts))))
  13741. ((and (memq type '(inactive inactive-range))
  13742. (not (string= specific "TIMESTAMP")))
  13743. (unless (assoc "TIMESTAMP_IA" ts)
  13744. (push (cons "TIMESTAMP_IA"
  13745. (org-element-property
  13746. :raw-value object))
  13747. ts)
  13748. (when specific (throw 'exit ts))))))
  13749. ;; Both timestamp types are found,
  13750. ;; move to next part.
  13751. (when (= (length ts) 2) (throw 'next ts)))))
  13752. ts)))))
  13753. (goto-char beg)
  13754. ;; First look for timestamps within headline.
  13755. (let ((ts (funcall find-ts (line-end-position) nil)))
  13756. (if (= (length ts) 2) (setq props (nconc ts props))
  13757. ;; Then find timestamps in the section, skipping
  13758. ;; planning line.
  13759. (let ((end (save-excursion (outline-next-heading))))
  13760. (forward-line)
  13761. (when (looking-at-p org-planning-line-re) (forward-line))
  13762. (setq props (nconc (funcall find-ts end ts) props))))))))
  13763. ;; Get the standard properties, like :PROP:.
  13764. (when (memq which '(nil all standard))
  13765. ;; If we are looking after a specific property, delegate
  13766. ;; to `org-entry-get', which is faster. However, make an
  13767. ;; exception for "CATEGORY", since it can be also set
  13768. ;; through keywords (i.e. #+CATEGORY).
  13769. (if (and specific (not (equal specific "CATEGORY")))
  13770. (let ((value (org-entry-get beg specific nil t)))
  13771. (throw 'exit (and value (list (cons specific value)))))
  13772. (let ((range (org-get-property-block beg)))
  13773. (when range
  13774. (let ((end (cdr range)) seen-base)
  13775. (goto-char (car range))
  13776. ;; Unlike to `org--update-property-plist', we
  13777. ;; handle the case where base values is found
  13778. ;; after its extension. We also forbid standard
  13779. ;; properties to be named as special properties.
  13780. (while (re-search-forward org-property-re end t)
  13781. (let* ((key (upcase (match-string-no-properties 2)))
  13782. (extendp (string-match-p "\\+\\'" key))
  13783. (key-base (if extendp (substring key 0 -1) key))
  13784. (value (match-string-no-properties 3)))
  13785. (cond
  13786. ((member-ignore-case key-base org-special-properties))
  13787. (extendp
  13788. (setq props
  13789. (org--update-property-plist key value props)))
  13790. ((member key seen-base))
  13791. (t (push key seen-base)
  13792. (let ((p (assoc-string key props t)))
  13793. (if p (setcdr p (concat value " " (cdr p)))
  13794. (push (cons key value) props))))))))))))
  13795. (unless (assoc "CATEGORY" props)
  13796. (push (cons "CATEGORY" (org-get-category beg)) props)
  13797. (when (string= specific "CATEGORY") (throw 'exit props)))
  13798. ;; Return value.
  13799. props)))))
  13800. (defun org--property-local-values (property literal-nil)
  13801. "Return value for PROPERTY in current entry.
  13802. Value is a list whose car is the base value for PROPERTY and cdr
  13803. a list of accumulated values. Return nil if neither is found in
  13804. the entry. Also return nil when PROPERTY is set to \"nil\",
  13805. unless LITERAL-NIL is non-nil."
  13806. (let ((range (org-get-property-block)))
  13807. (when range
  13808. (goto-char (car range))
  13809. (let* ((case-fold-search t)
  13810. (end (cdr range))
  13811. (value
  13812. ;; Base value.
  13813. (save-excursion
  13814. (let ((v (and (re-search-forward
  13815. (org-re-property property nil t) end t)
  13816. (match-string-no-properties 3))))
  13817. (list (if literal-nil v (org-not-nil v)))))))
  13818. ;; Find additional values.
  13819. (let* ((property+ (org-re-property (concat property "+") nil t)))
  13820. (while (re-search-forward property+ end t)
  13821. (push (match-string-no-properties 3) value)))
  13822. ;; Return final values.
  13823. (and (not (equal value '(nil))) (nreverse value))))))
  13824. (defun org--property-global-value (property literal-nil)
  13825. "Return value for PROPERTY in current buffer.
  13826. Return value is a string. Return nil if property is not set
  13827. globally. Also return nil when PROPERTY is set to \"nil\",
  13828. unless LITERAL-NIL is non-nil."
  13829. (let ((global
  13830. (cdr (or (assoc-string property org-file-properties t)
  13831. (assoc-string property org-global-properties t)
  13832. (assoc-string property org-global-properties-fixed t)))))
  13833. (if literal-nil global (org-not-nil global))))
  13834. (defun org-entry-get (pom property &optional inherit literal-nil)
  13835. "Get value of PROPERTY for entry or content at point-or-marker POM.
  13836. If INHERIT is non-nil and the entry does not have the property,
  13837. then also check higher levels of the hierarchy. If INHERIT is
  13838. the symbol `selective', use inheritance only if the setting in
  13839. `org-use-property-inheritance' selects PROPERTY for inheritance.
  13840. If the property is present but empty, the return value is the
  13841. empty string. If the property is not present at all, nil is
  13842. returned. In any other case, return the value as a string.
  13843. Search is case-insensitive.
  13844. If LITERAL-NIL is set, return the string value \"nil\" as
  13845. a string, do not interpret it as the list atom nil. This is used
  13846. for inheritance when a \"nil\" value can supersede a non-nil
  13847. value higher up the hierarchy."
  13848. (org-with-point-at pom
  13849. (cond
  13850. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  13851. ;; We need a special property. Use `org-entry-properties' to
  13852. ;; retrieve it, but specify the wanted property.
  13853. (cdr (assoc-string property (org-entry-properties nil property))))
  13854. ((and inherit
  13855. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  13856. (org-entry-get-with-inheritance property literal-nil))
  13857. (t
  13858. (let* ((local (org--property-local-values property literal-nil))
  13859. (value (and local (mapconcat #'identity (delq nil local) " "))))
  13860. (if literal-nil value (org-not-nil value)))))))
  13861. (defun org-property-or-variable-value (var &optional inherit)
  13862. "Check if there is a property fixing the value of VAR.
  13863. If yes, return this value. If not, return the current value of the variable."
  13864. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  13865. (if (and prop (stringp prop) (string-match "\\S-" prop))
  13866. (read prop)
  13867. (symbol-value var))))
  13868. (defun org-entry-delete (pom property)
  13869. "Delete PROPERTY from entry at point-or-marker POM.
  13870. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  13871. non-nil when a property was removed."
  13872. (org-with-point-at pom
  13873. (pcase (org-get-property-block)
  13874. (`(,begin . ,origin)
  13875. (let* ((end (copy-marker origin))
  13876. (re (org-re-property
  13877. (concat (regexp-quote property) "\\+?") t t)))
  13878. (goto-char begin)
  13879. (while (re-search-forward re end t)
  13880. (delete-region (match-beginning 0) (line-beginning-position 2)))
  13881. ;; If drawer is empty, remove it altogether.
  13882. (when (= begin end)
  13883. (delete-region (line-beginning-position 0)
  13884. (line-beginning-position 2)))
  13885. ;; Return non-nil if some property was removed.
  13886. (prog1 (/= end origin) (set-marker end nil))))
  13887. (_ nil))))
  13888. ;; Multi-values properties are properties that contain multiple values
  13889. ;; These values are assumed to be single words, separated by whitespace.
  13890. (defun org-entry-add-to-multivalued-property (pom property value)
  13891. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  13892. (let* ((old (org-entry-get pom property))
  13893. (values (and old (split-string old))))
  13894. (setq value (org-entry-protect-space value))
  13895. (unless (member value values)
  13896. (setq values (append values (list value)))
  13897. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13898. (defun org-entry-remove-from-multivalued-property (pom property value)
  13899. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  13900. (let* ((old (org-entry-get pom property))
  13901. (values (and old (split-string old))))
  13902. (setq value (org-entry-protect-space value))
  13903. (when (member value values)
  13904. (setq values (delete value values))
  13905. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13906. (defun org-entry-member-in-multivalued-property (pom property value)
  13907. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  13908. (let* ((old (org-entry-get pom property))
  13909. (values (and old (split-string old))))
  13910. (setq value (org-entry-protect-space value))
  13911. (member value values)))
  13912. (defun org-entry-get-multivalued-property (pom property)
  13913. "Return a list of values in a multivalued property."
  13914. (let* ((value (org-entry-get pom property))
  13915. (values (and value (split-string value))))
  13916. (mapcar #'org-entry-restore-space values)))
  13917. (defun org-entry-put-multivalued-property (pom property &rest values)
  13918. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  13919. VALUES should be a list of strings. Spaces will be protected."
  13920. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  13921. (let* ((value (org-entry-get pom property))
  13922. (values (and value (split-string value))))
  13923. (mapcar #'org-entry-restore-space values)))
  13924. (defun org-entry-protect-space (s)
  13925. "Protect spaces and newline in string S."
  13926. (while (string-match " " s)
  13927. (setq s (replace-match "%20" t t s)))
  13928. (while (string-match "\n" s)
  13929. (setq s (replace-match "%0A" t t s)))
  13930. s)
  13931. (defun org-entry-restore-space (s)
  13932. "Restore spaces and newline in string S."
  13933. (while (string-match "%20" s)
  13934. (setq s (replace-match " " t t s)))
  13935. (while (string-match "%0A" s)
  13936. (setq s (replace-match "\n" t t s)))
  13937. s)
  13938. (defvar org-entry-property-inherited-from (make-marker)
  13939. "Marker pointing to the entry from where a property was inherited.
  13940. Each call to `org-entry-get-with-inheritance' will set this marker to the
  13941. location of the entry where the inheritance search matched. If there was
  13942. no match, the marker will point nowhere.
  13943. Note that also `org-entry-get' calls this function, if the INHERIT flag
  13944. is set.")
  13945. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  13946. "Get PROPERTY of entry or content at point, search higher levels if needed.
  13947. The search will stop at the first ancestor which has the property defined.
  13948. If the value found is \"nil\", return nil to show that the property
  13949. should be considered as undefined (this is the meaning of nil here).
  13950. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  13951. (move-marker org-entry-property-inherited-from nil)
  13952. (org-with-wide-buffer
  13953. (let (value)
  13954. (catch 'exit
  13955. (while t
  13956. (let ((v (org--property-local-values property literal-nil)))
  13957. (when v
  13958. (setq value
  13959. (concat (mapconcat #'identity (delq nil v) " ")
  13960. (and value " ")
  13961. value)))
  13962. (cond
  13963. ((car v)
  13964. (org-back-to-heading t)
  13965. (move-marker org-entry-property-inherited-from (point))
  13966. (throw 'exit nil))
  13967. ((org-up-heading-safe))
  13968. (t
  13969. (let ((global (org--property-global-value property literal-nil)))
  13970. (cond ((not global))
  13971. (value (setq value (concat global " " value)))
  13972. (t (setq value global))))
  13973. (throw 'exit nil))))))
  13974. (if literal-nil value (org-not-nil value)))))
  13975. (defvar org-property-changed-functions nil
  13976. "Hook called when the value of a property has changed.
  13977. Each hook function should accept two arguments, the name of the property
  13978. and the new value.")
  13979. (defun org-entry-put (pom property value)
  13980. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  13981. If the value is nil, it is converted to the empty string. If it
  13982. is not a string, an error is raised. Also raise an error on
  13983. invalid property names.
  13984. PROPERTY can be any regular property (see
  13985. `org-special-properties'). It can also be \"TODO\",
  13986. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  13987. For the last two properties, VALUE may have any of the special
  13988. values \"earlier\" and \"later\". The function then increases or
  13989. decreases scheduled or deadline date by one day."
  13990. (cond ((null value) (setq value ""))
  13991. ((not (stringp value)) (error "Properties values should be strings"))
  13992. ((not (org--valid-property-p property))
  13993. (user-error "Invalid property name: \"%s\"" property)))
  13994. (org-with-point-at pom
  13995. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  13996. (org-back-to-heading t)
  13997. (org-with-limited-levels (org-back-to-heading t)))
  13998. (let ((beg (point)))
  13999. (cond
  14000. ((equal property "TODO")
  14001. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14002. ((not (member value org-todo-keywords-1))
  14003. (user-error "\"%s\" is not a valid TODO state" value)))
  14004. (org-todo value)
  14005. (org-align-tags))
  14006. ((equal property "PRIORITY")
  14007. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14008. (org-align-tags))
  14009. ((equal property "SCHEDULED")
  14010. (forward-line)
  14011. (if (and (looking-at-p org-planning-line-re)
  14012. (re-search-forward
  14013. org-scheduled-time-regexp (line-end-position) t))
  14014. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14015. ((string= value "later") (org-timestamp-change 1 'day))
  14016. ((string= value "") (org-schedule '(4)))
  14017. (t (org-schedule nil value)))
  14018. (if (member value '("earlier" "later" ""))
  14019. (call-interactively #'org-schedule)
  14020. (org-schedule nil value))))
  14021. ((equal property "DEADLINE")
  14022. (forward-line)
  14023. (if (and (looking-at-p org-planning-line-re)
  14024. (re-search-forward
  14025. org-deadline-time-regexp (line-end-position) t))
  14026. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14027. ((string= value "later") (org-timestamp-change 1 'day))
  14028. ((string= value "") (org-deadline '(4)))
  14029. (t (org-deadline nil value)))
  14030. (if (member value '("earlier" "later" ""))
  14031. (call-interactively #'org-deadline)
  14032. (org-deadline nil value))))
  14033. ((member property org-special-properties)
  14034. (error "The %s property cannot be set with `org-entry-put'" property))
  14035. (t
  14036. (let* ((range (org-get-property-block beg 'force))
  14037. (end (cdr range))
  14038. (case-fold-search t))
  14039. (goto-char (car range))
  14040. (if (re-search-forward (org-re-property property nil t) end t)
  14041. (progn (delete-region (match-beginning 0) (match-end 0))
  14042. (goto-char (match-beginning 0)))
  14043. (goto-char end)
  14044. (insert "\n")
  14045. (backward-char))
  14046. (insert ":" property ":")
  14047. (when value (insert " " value))
  14048. (org-indent-line)))))
  14049. (run-hook-with-args 'org-property-changed-functions property value)))
  14050. (defun org-buffer-property-keys (&optional specials defaults columns)
  14051. "Get all property keys in the current buffer.
  14052. When SPECIALS is non-nil, also list the special properties that
  14053. reflect things like tags and TODO state.
  14054. When DEFAULTS is non-nil, also include properties that has
  14055. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14056. DESCRIPTION, LOCATION, and LOGGING and others.
  14057. When COLUMNS in non-nil, also include property names given in
  14058. COLUMN formats in the current buffer."
  14059. (let ((case-fold-search t)
  14060. (props (append
  14061. (and specials org-special-properties)
  14062. (and defaults (cons org-effort-property org-default-properties))
  14063. nil)))
  14064. (org-with-wide-buffer
  14065. (goto-char (point-min))
  14066. (while (re-search-forward org-property-start-re nil t)
  14067. (catch :skip
  14068. (let ((range (org-get-property-block)))
  14069. (unless range (throw :skip nil))
  14070. (goto-char (car range))
  14071. (let ((begin (car range))
  14072. (end (cdr range)))
  14073. ;; Make sure that found property block is not located
  14074. ;; before current point, as it would generate an infloop.
  14075. ;; It can happen, for example, in the following
  14076. ;; situation:
  14077. ;;
  14078. ;; * Headline
  14079. ;; :PROPERTIES:
  14080. ;; ...
  14081. ;; :END:
  14082. ;; *************** Inlinetask
  14083. ;; #+BEGIN_EXAMPLE
  14084. ;; :PROPERTIES:
  14085. ;; #+END_EXAMPLE
  14086. ;;
  14087. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  14088. (while (< (point) end)
  14089. (let ((p (progn (looking-at org-property-re)
  14090. (match-string-no-properties 2))))
  14091. ;; Only add true property name, not extension symbol.
  14092. (push (if (not (string-match-p "\\+\\'" p)) p
  14093. (substring p 0 -1))
  14094. props))
  14095. (forward-line))))
  14096. (outline-next-heading)))
  14097. (when columns
  14098. (goto-char (point-min))
  14099. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14100. (let ((element (org-element-at-point)))
  14101. (when (memq (org-element-type element) '(keyword node-property))
  14102. (let ((value (org-element-property :value element))
  14103. (start 0))
  14104. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  14105. \\(?:{[^}]+}\\)?"
  14106. value start)
  14107. (setq start (match-end 0))
  14108. (let ((p (match-string-no-properties 1 value)))
  14109. (unless (member-ignore-case p org-special-properties)
  14110. (push p props))))))))))
  14111. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14112. (defun org-property-values (key)
  14113. "List all non-nil values of property KEY in current buffer."
  14114. (org-with-wide-buffer
  14115. (goto-char (point-min))
  14116. (let ((case-fold-search t)
  14117. (re (org-re-property key))
  14118. values)
  14119. (while (re-search-forward re nil t)
  14120. (push (org-entry-get (point) key) values))
  14121. (delete-dups values))))
  14122. (defun org-insert-property-drawer ()
  14123. "Insert a property drawer into the current entry."
  14124. (org-with-wide-buffer
  14125. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14126. (org-back-to-heading t)
  14127. (org-with-limited-levels (org-back-to-heading t)))
  14128. (forward-line)
  14129. (when (looking-at-p org-planning-line-re) (forward-line))
  14130. (unless (looking-at-p org-property-drawer-re)
  14131. ;; Make sure we start editing a line from current entry, not from
  14132. ;; next one. It prevents extending text properties or overlays
  14133. ;; belonging to the latter.
  14134. (when (bolp) (backward-char))
  14135. (let ((begin (1+ (point)))
  14136. (inhibit-read-only t))
  14137. (insert "\n:PROPERTIES:\n:END:")
  14138. (when (eobp) (insert "\n"))
  14139. (org-indent-region begin (point))))))
  14140. (defun org-insert-drawer (&optional arg drawer)
  14141. "Insert a drawer at point.
  14142. When optional argument ARG is non-nil, insert a property drawer.
  14143. Optional argument DRAWER, when non-nil, is a string representing
  14144. drawer's name. Otherwise, the user is prompted for a name.
  14145. If a region is active, insert the drawer around that region
  14146. instead.
  14147. Point is left between drawer's boundaries."
  14148. (interactive "P")
  14149. (let* ((drawer (if arg "PROPERTIES"
  14150. (or drawer (read-from-minibuffer "Drawer: ")))))
  14151. (cond
  14152. ;; With C-u, fall back on `org-insert-property-drawer'
  14153. (arg (org-insert-property-drawer))
  14154. ;; Check validity of suggested drawer's name.
  14155. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14156. (user-error "Invalid drawer name"))
  14157. ;; With an active region, insert a drawer at point.
  14158. ((not (org-region-active-p))
  14159. (progn
  14160. (unless (bolp) (insert "\n"))
  14161. (insert (format ":%s:\n\n:END:\n" drawer))
  14162. (forward-line -2)))
  14163. ;; Otherwise, insert the drawer at point
  14164. (t
  14165. (let ((rbeg (region-beginning))
  14166. (rend (copy-marker (region-end))))
  14167. (unwind-protect
  14168. (progn
  14169. (goto-char rbeg)
  14170. (beginning-of-line)
  14171. (when (save-excursion
  14172. (re-search-forward org-outline-regexp-bol rend t))
  14173. (user-error "Drawers cannot contain headlines"))
  14174. ;; Position point at the beginning of the first
  14175. ;; non-blank line in region. Insert drawer's opening
  14176. ;; there, then indent it.
  14177. (org-skip-whitespace)
  14178. (beginning-of-line)
  14179. (insert ":" drawer ":\n")
  14180. (forward-line -1)
  14181. (indent-for-tab-command)
  14182. ;; Move point to the beginning of the first blank line
  14183. ;; after the last non-blank line in region. Insert
  14184. ;; drawer's closing, then indent it.
  14185. (goto-char rend)
  14186. (skip-chars-backward " \r\t\n")
  14187. (insert "\n:END:")
  14188. (deactivate-mark t)
  14189. (indent-for-tab-command)
  14190. (unless (eolp) (insert "\n")))
  14191. ;; Clear marker, whatever the outcome of insertion is.
  14192. (set-marker rend nil)))))))
  14193. (defvar org-property-set-functions-alist nil
  14194. "Property set function alist.
  14195. Each entry should have the following format:
  14196. (PROPERTY . READ-FUNCTION)
  14197. The read function will be called with the same argument as
  14198. `org-completing-read'.")
  14199. (defun org-set-property-function (property)
  14200. "Get the function that should be used to set PROPERTY.
  14201. This is computed according to `org-property-set-functions-alist'."
  14202. (or (cdr (assoc property org-property-set-functions-alist))
  14203. 'org-completing-read))
  14204. (defun org-read-property-value (property)
  14205. "Read PROPERTY value from user."
  14206. (let* ((completion-ignore-case t)
  14207. (allowed (org-property-get-allowed-values nil property 'table))
  14208. (cur (org-entry-get nil property))
  14209. (prompt (concat property " value"
  14210. (if (and cur (string-match "\\S-" cur))
  14211. (concat " [" cur "]") "") ": "))
  14212. (set-function (org-set-property-function property))
  14213. (val (if allowed
  14214. (funcall set-function prompt allowed nil
  14215. (not (get-text-property 0 'org-unrestricted
  14216. (caar allowed))))
  14217. (funcall set-function prompt
  14218. (mapcar 'list (org-property-values property))
  14219. nil nil "" nil cur))))
  14220. (org-trim val)))
  14221. (defvar org-last-set-property nil)
  14222. (defvar org-last-set-property-value nil)
  14223. (defun org-read-property-name ()
  14224. "Read a property name."
  14225. (let ((completion-ignore-case t)
  14226. (default-prop (or (and (org-at-property-p)
  14227. (match-string-no-properties 2))
  14228. org-last-set-property)))
  14229. (org-completing-read
  14230. (concat "Property"
  14231. (if default-prop (concat " [" default-prop "]") "")
  14232. ": ")
  14233. (mapcar #'list (org-buffer-property-keys nil t t))
  14234. nil nil nil nil default-prop)))
  14235. (defun org-set-property-and-value (use-last)
  14236. "Allow to set [PROPERTY]: [value] direction from prompt.
  14237. When use-default, don't even ask, just use the last
  14238. \"[PROPERTY]: [value]\" string from the history."
  14239. (interactive "P")
  14240. (let* ((completion-ignore-case t)
  14241. (pv (or (and use-last org-last-set-property-value)
  14242. (org-completing-read
  14243. "Enter a \"[Property]: [value]\" pair: "
  14244. nil nil nil nil nil
  14245. org-last-set-property-value)))
  14246. prop val)
  14247. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14248. (setq prop (match-string 1 pv)
  14249. val (match-string 2 pv))
  14250. (org-set-property prop val))))
  14251. (defun org-set-property (property value)
  14252. "In the current entry, set PROPERTY to VALUE.
  14253. When called interactively, this will prompt for a property name, offering
  14254. completion on existing and default properties. And then it will prompt
  14255. for a value, offering completion either on allowed values (via an inherited
  14256. xxx_ALL property) or on existing values in other instances of this property
  14257. in the current file.
  14258. Throw an error when trying to set a property with an invalid name."
  14259. (interactive (list nil nil))
  14260. (let ((property (or property (org-read-property-name))))
  14261. ;; `org-entry-put' also makes the following check, but this one
  14262. ;; avoids polluting `org-last-set-property' and
  14263. ;; `org-last-set-property-value' needlessly.
  14264. (unless (org--valid-property-p property)
  14265. (user-error "Invalid property name: \"%s\"" property))
  14266. (let ((value (or value (org-read-property-value property)))
  14267. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14268. (setq org-last-set-property property)
  14269. (setq org-last-set-property-value (concat property ": " value))
  14270. ;; Possibly postprocess the inserted value:
  14271. (when fn (setq value (funcall fn value)))
  14272. (unless (equal (org-entry-get nil property) value)
  14273. (org-entry-put nil property value)))))
  14274. (defun org-find-property (property &optional value)
  14275. "Find first entry in buffer that sets PROPERTY.
  14276. When optional argument VALUE is non-nil, only consider an entry
  14277. if it contains PROPERTY set to this value. If PROPERTY should be
  14278. explicitly set to nil, use string \"nil\" for VALUE.
  14279. Return position where the entry begins, or nil if there is no
  14280. such entry. If narrowing is in effect, only search the visible
  14281. part of the buffer."
  14282. (save-excursion
  14283. (goto-char (point-min))
  14284. (let ((case-fold-search t)
  14285. (re (org-re-property property nil (not value) value)))
  14286. (catch 'exit
  14287. (while (re-search-forward re nil t)
  14288. (when (if value (org-at-property-p)
  14289. (org-entry-get (point) property nil t))
  14290. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14291. (defun org-delete-property (property)
  14292. "In the current entry, delete PROPERTY."
  14293. (interactive
  14294. (let* ((completion-ignore-case t)
  14295. (cat (org-entry-get (point) "CATEGORY"))
  14296. (props0 (org-entry-properties nil 'standard))
  14297. (props (if cat props0
  14298. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14299. (prop (if (< 1 (length props))
  14300. (completing-read "Property: " props nil t)
  14301. (caar props))))
  14302. (list prop)))
  14303. (if (not property)
  14304. (message "No property to delete in this entry")
  14305. (org-entry-delete nil property)
  14306. (message "Property \"%s\" deleted" property)))
  14307. (defun org-delete-property-globally (property)
  14308. "Remove PROPERTY globally, from all entries.
  14309. This function ignores narrowing, if any."
  14310. (interactive
  14311. (let* ((completion-ignore-case t)
  14312. (prop (completing-read
  14313. "Globally remove property: "
  14314. (mapcar #'list (org-buffer-property-keys)))))
  14315. (list prop)))
  14316. (org-with-wide-buffer
  14317. (goto-char (point-min))
  14318. (let ((count 0)
  14319. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14320. (while (re-search-forward re nil t)
  14321. (when (org-entry-delete (point) property) (cl-incf count)))
  14322. (message "Property \"%s\" removed from %d entries" property count))))
  14323. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14324. (defun org-compute-property-at-point ()
  14325. "Compute the property at point.
  14326. This looks for an enclosing column format, extracts the operator and
  14327. then applies it to the property in the column format's scope."
  14328. (interactive)
  14329. (unless (org-at-property-p)
  14330. (user-error "Not at a property"))
  14331. (let ((prop (match-string-no-properties 2)))
  14332. (org-columns-get-format-and-top-level)
  14333. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14334. (user-error "No operator defined for property %s" prop))
  14335. (org-columns-compute prop)))
  14336. (defvar org-property-allowed-value-functions nil
  14337. "Hook for functions supplying allowed values for a specific property.
  14338. The functions must take a single argument, the name of the property, and
  14339. return a flat list of allowed values. If \":ETC\" is one of
  14340. the values, this means that these values are intended as defaults for
  14341. completion, but that other values should be allowed too.
  14342. The functions must return nil if they are not responsible for this
  14343. property.")
  14344. (defun org-property-get-allowed-values (pom property &optional table)
  14345. "Get allowed values for the property PROPERTY.
  14346. When TABLE is non-nil, return an alist that can directly be used for
  14347. completion."
  14348. (let (vals)
  14349. (cond
  14350. ((equal property "TODO")
  14351. (setq vals (org-with-point-at pom
  14352. (append org-todo-keywords-1 '("")))))
  14353. ((equal property "PRIORITY")
  14354. (let ((n org-lowest-priority))
  14355. (while (>= n org-highest-priority)
  14356. (push (char-to-string n) vals)
  14357. (setq n (1- n)))))
  14358. ((equal property "CATEGORY"))
  14359. ((member property org-special-properties))
  14360. ((setq vals (run-hook-with-args-until-success
  14361. 'org-property-allowed-value-functions property)))
  14362. (t
  14363. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14364. (when (and vals (string-match "\\S-" vals))
  14365. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14366. (setq vals (mapcar (lambda (x)
  14367. (cond ((stringp x) x)
  14368. ((numberp x) (number-to-string x))
  14369. ((symbolp x) (symbol-name x))
  14370. (t "???")))
  14371. vals)))))
  14372. (when (member ":ETC" vals)
  14373. (setq vals (remove ":ETC" vals))
  14374. (org-add-props (car vals) '(org-unrestricted t)))
  14375. (if table (mapcar 'list vals) vals)))
  14376. (defun org-property-previous-allowed-value (&optional _previous)
  14377. "Switch to the next allowed value for this property."
  14378. (interactive)
  14379. (org-property-next-allowed-value t))
  14380. (defun org-property-next-allowed-value (&optional previous)
  14381. "Switch to the next allowed value for this property."
  14382. (interactive)
  14383. (unless (org-at-property-p)
  14384. (user-error "Not at a property"))
  14385. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  14386. (key (match-string 2))
  14387. (value (match-string 3))
  14388. (allowed (or (org-property-get-allowed-values (point) key)
  14389. (and (member value '("[ ]" "[-]" "[X]"))
  14390. '("[ ]" "[X]"))))
  14391. (heading (save-match-data (nth 4 (org-heading-components))))
  14392. nval)
  14393. (unless allowed
  14394. (user-error "Allowed values for this property have not been defined"))
  14395. (when previous (setq allowed (reverse allowed)))
  14396. (when (member value allowed)
  14397. (setq nval (car (cdr (member value allowed)))))
  14398. (setq nval (or nval (car allowed)))
  14399. (when (equal nval value)
  14400. (user-error "Only one allowed value for this property"))
  14401. (org-at-property-p)
  14402. (replace-match (concat " :" key ": " nval) t t)
  14403. (org-indent-line)
  14404. (beginning-of-line 1)
  14405. (skip-chars-forward " \t")
  14406. (when (equal prop org-effort-property)
  14407. (org-refresh-property
  14408. '((effort . identity)
  14409. (effort-minutes . org-duration-to-minutes))
  14410. nval)
  14411. (when (string= org-clock-current-task heading)
  14412. (setq org-clock-effort nval)
  14413. (org-clock-update-mode-line)))
  14414. (run-hook-with-args 'org-property-changed-functions key nval)))
  14415. (defun org-find-olp (path &optional this-buffer)
  14416. "Return a marker pointing to the entry at outline path OLP.
  14417. If anything goes wrong, throw an error.
  14418. You can wrap this call to catch the error like this:
  14419. (condition-case msg
  14420. (org-mobile-locate-entry (match-string 4))
  14421. (error (nth 1 msg)))
  14422. The return value will then be either a string with the error message,
  14423. or a marker if everything is OK.
  14424. If THIS-BUFFER is set, the outline path does not contain a file,
  14425. only headings."
  14426. (let* ((file (if this-buffer buffer-file-name (pop path)))
  14427. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  14428. (level 1)
  14429. (lmin 1)
  14430. (lmax 1)
  14431. end found flevel)
  14432. (unless buffer (error "File not found :%s" file))
  14433. (with-current-buffer buffer
  14434. (unless (derived-mode-p 'org-mode)
  14435. (error "Buffer %s needs to be in Org mode" buffer))
  14436. (org-with-wide-buffer
  14437. (goto-char (point-min))
  14438. (dolist (heading path)
  14439. (let ((re (format org-complex-heading-regexp-format
  14440. (regexp-quote heading)))
  14441. (cnt 0))
  14442. (while (re-search-forward re end t)
  14443. (setq level (- (match-end 1) (match-beginning 1)))
  14444. (when (and (>= level lmin) (<= level lmax))
  14445. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  14446. (when (= cnt 0)
  14447. (error "Heading not found on level %d: %s" lmax heading))
  14448. (when (> cnt 1)
  14449. (error "Heading not unique on level %d: %s" lmax heading))
  14450. (goto-char found)
  14451. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  14452. (setq end (save-excursion (org-end-of-subtree t t)))))
  14453. (when (org-at-heading-p)
  14454. (point-marker))))))
  14455. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  14456. "Find node HEADING in BUFFER.
  14457. Return a marker to the heading if it was found, or nil if not.
  14458. If POS-ONLY is set, return just the position instead of a marker.
  14459. The heading text must match exact, but it may have a TODO keyword,
  14460. a priority cookie and tags in the standard locations."
  14461. (with-current-buffer (or buffer (current-buffer))
  14462. (org-with-wide-buffer
  14463. (goto-char (point-min))
  14464. (let (case-fold-search)
  14465. (when (re-search-forward
  14466. (format org-complex-heading-regexp-format
  14467. (regexp-quote heading)) nil t)
  14468. (if pos-only
  14469. (match-beginning 0)
  14470. (move-marker (make-marker) (match-beginning 0))))))))
  14471. (defun org-find-exact-heading-in-directory (heading &optional dir)
  14472. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  14473. When the target headline is found, return a marker to this location."
  14474. (let ((files (directory-files (or dir default-directory)
  14475. t "\\`[^.#].*\\.org\\'"))
  14476. visiting m buffer)
  14477. (catch 'found
  14478. (dolist (file files)
  14479. (message "trying %s" file)
  14480. (setq visiting (org-find-base-buffer-visiting file))
  14481. (setq buffer (or visiting (find-file-noselect file)))
  14482. (setq m (org-find-exact-headline-in-buffer
  14483. heading buffer))
  14484. (when (and (not m) (not visiting)) (kill-buffer buffer))
  14485. (and m (throw 'found m))))))
  14486. (defun org-find-entry-with-id (ident)
  14487. "Locate the entry that contains the ID property with exact value IDENT.
  14488. IDENT can be a string, a symbol or a number, this function will search for
  14489. the string representation of it.
  14490. Return the position where this entry starts, or nil if there is no such entry."
  14491. (interactive "sID: ")
  14492. (let ((id (cond
  14493. ((stringp ident) ident)
  14494. ((symbolp ident) (symbol-name ident))
  14495. ((numberp ident) (number-to-string ident))
  14496. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  14497. (org-with-wide-buffer (org-find-property "ID" id))))
  14498. ;;;; Timestamps
  14499. (defvar org-last-changed-timestamp nil)
  14500. (defvar org-last-inserted-timestamp nil
  14501. "The last time stamp inserted with `org-insert-time-stamp'.")
  14502. (defun org-time-stamp (arg &optional inactive)
  14503. "Prompt for a date/time and insert a time stamp.
  14504. If the user specifies a time like HH:MM or if this command is
  14505. called with at least one prefix argument, the time stamp contains
  14506. the date and the time. Otherwise, only the date is included.
  14507. All parts of a date not specified by the user are filled in from
  14508. the timestamp at point, if any, or the current date/time
  14509. otherwise.
  14510. If there is already a timestamp at the cursor, it is replaced.
  14511. With two universal prefix arguments, insert an active timestamp
  14512. with the current time without prompting the user.
  14513. When called from lisp, the timestamp is inactive if INACTIVE is
  14514. non-nil."
  14515. (interactive "P")
  14516. (let* ((ts (cond
  14517. ((org-at-date-range-p t)
  14518. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  14519. ((org-at-timestamp-p 'lax) (match-string 0))))
  14520. ;; Default time is either the timestamp at point or today.
  14521. ;; When entering a range, only the range start is considered.
  14522. (default-time (if (not ts) (current-time)
  14523. (apply #'encode-time (org-parse-time-string ts))))
  14524. (default-input (and ts (org-get-compact-tod ts)))
  14525. (repeater (and ts
  14526. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  14527. (match-string 0 ts)))
  14528. org-time-was-given
  14529. org-end-time-was-given
  14530. (time
  14531. (and (if (equal arg '(16)) (current-time)
  14532. ;; Preserve `this-command' and `last-command'.
  14533. (let ((this-command this-command)
  14534. (last-command last-command))
  14535. (org-read-date
  14536. arg 'totime nil nil default-time default-input
  14537. inactive))))))
  14538. (cond
  14539. ((and ts
  14540. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  14541. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  14542. (insert "--")
  14543. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  14544. (ts
  14545. ;; Make sure we're on a timestamp. When in the middle of a date
  14546. ;; range, move arbitrarily to range end.
  14547. (unless (org-at-timestamp-p 'lax)
  14548. (skip-chars-forward "-")
  14549. (org-at-timestamp-p 'lax))
  14550. (replace-match "")
  14551. (setq org-last-changed-timestamp
  14552. (org-insert-time-stamp
  14553. time (or org-time-was-given arg)
  14554. inactive nil nil (list org-end-time-was-given)))
  14555. (when repeater
  14556. (backward-char)
  14557. (insert " " repeater)
  14558. (setq org-last-changed-timestamp
  14559. (concat (substring org-last-inserted-timestamp 0 -1)
  14560. " " repeater ">")))
  14561. (message "Timestamp updated"))
  14562. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  14563. (t (org-insert-time-stamp
  14564. time (or org-time-was-given arg) inactive nil nil
  14565. (list org-end-time-was-given))))))
  14566. ;; FIXME: can we use this for something else, like computing time differences?
  14567. (defun org-get-compact-tod (s)
  14568. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  14569. (let* ((t1 (match-string 1 s))
  14570. (h1 (string-to-number (match-string 2 s)))
  14571. (m1 (string-to-number (match-string 3 s)))
  14572. (t2 (and (match-end 4) (match-string 5 s)))
  14573. (h2 (and t2 (string-to-number (match-string 6 s))))
  14574. (m2 (and t2 (string-to-number (match-string 7 s))))
  14575. dh dm)
  14576. (if (not t2)
  14577. t1
  14578. (setq dh (- h2 h1) dm (- m2 m1))
  14579. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  14580. (concat t1 "+" (number-to-string dh)
  14581. (and (/= 0 dm) (format ":%02d" dm)))))))
  14582. (defun org-time-stamp-inactive (&optional arg)
  14583. "Insert an inactive time stamp.
  14584. An inactive time stamp is enclosed in square brackets instead of angle
  14585. brackets. It is inactive in the sense that it does not trigger agenda entries,
  14586. does not link to the calendar and cannot be changed with the S-cursor keys.
  14587. So these are more for recording a certain time/date.
  14588. If the user specifies a time like HH:MM or if this command is called with
  14589. at least one prefix argument, the time stamp contains the date and the time.
  14590. Otherwise, only the date is included.
  14591. When called with two universal prefix arguments, insert an active time stamp
  14592. with the current time without prompting the user."
  14593. (interactive "P")
  14594. (org-time-stamp arg 'inactive))
  14595. (defvar org-date-ovl (make-overlay 1 1))
  14596. (overlay-put org-date-ovl 'face 'org-date-selected)
  14597. (delete-overlay org-date-ovl)
  14598. (defvar org-ans1) ; dynamically scoped parameter
  14599. (defvar org-ans2) ; dynamically scoped parameter
  14600. (defvar org-plain-time-of-day-regexp) ; defined below
  14601. (defvar org-overriding-default-time nil) ; dynamically scoped
  14602. (defvar org-read-date-overlay nil)
  14603. (defvar org-dcst nil) ; dynamically scoped
  14604. (defvar org-read-date-history nil)
  14605. (defvar org-read-date-final-answer nil)
  14606. (defvar org-read-date-analyze-futurep nil)
  14607. (defvar org-read-date-analyze-forced-year nil)
  14608. (defvar org-read-date-inactive)
  14609. (defvar org-read-date-minibuffer-local-map
  14610. (let* ((map (make-sparse-keymap)))
  14611. (set-keymap-parent map minibuffer-local-map)
  14612. (org-defkey map (kbd ".")
  14613. (lambda () (interactive)
  14614. ;; Are we at the beginning of the prompt?
  14615. (if (looking-back "^[^:]+: "
  14616. (let ((inhibit-field-text-motion t))
  14617. (line-beginning-position)))
  14618. (org-eval-in-calendar '(calendar-goto-today))
  14619. (insert "."))))
  14620. (org-defkey map (kbd "C-.")
  14621. (lambda () (interactive)
  14622. (org-eval-in-calendar '(calendar-goto-today))))
  14623. (org-defkey map (kbd "M-S-<left>")
  14624. (lambda () (interactive)
  14625. (org-eval-in-calendar '(calendar-backward-month 1))))
  14626. (org-defkey map (kbd "ESC S-<left>")
  14627. (lambda () (interactive)
  14628. (org-eval-in-calendar '(calendar-backward-month 1))))
  14629. (org-defkey map (kbd "M-S-<right>")
  14630. (lambda () (interactive)
  14631. (org-eval-in-calendar '(calendar-forward-month 1))))
  14632. (org-defkey map (kbd "ESC S-<right>")
  14633. (lambda () (interactive)
  14634. (org-eval-in-calendar '(calendar-forward-month 1))))
  14635. (org-defkey map (kbd "M-S-<up>")
  14636. (lambda () (interactive)
  14637. (org-eval-in-calendar '(calendar-backward-year 1))))
  14638. (org-defkey map (kbd "ESC S-<up>")
  14639. (lambda () (interactive)
  14640. (org-eval-in-calendar '(calendar-backward-year 1))))
  14641. (org-defkey map (kbd "M-S-<down>")
  14642. (lambda () (interactive)
  14643. (org-eval-in-calendar '(calendar-forward-year 1))))
  14644. (org-defkey map (kbd "ESC S-<down>")
  14645. (lambda () (interactive)
  14646. (org-eval-in-calendar '(calendar-forward-year 1))))
  14647. (org-defkey map (kbd "S-<up>")
  14648. (lambda () (interactive)
  14649. (org-eval-in-calendar '(calendar-backward-week 1))))
  14650. (org-defkey map (kbd "S-<down>")
  14651. (lambda () (interactive)
  14652. (org-eval-in-calendar '(calendar-forward-week 1))))
  14653. (org-defkey map (kbd "S-<left>")
  14654. (lambda () (interactive)
  14655. (org-eval-in-calendar '(calendar-backward-day 1))))
  14656. (org-defkey map (kbd "S-<right>")
  14657. (lambda () (interactive)
  14658. (org-eval-in-calendar '(calendar-forward-day 1))))
  14659. (org-defkey map (kbd "!")
  14660. (lambda () (interactive)
  14661. (org-eval-in-calendar '(diary-view-entries))
  14662. (message "")))
  14663. (org-defkey map (kbd ">")
  14664. (lambda () (interactive)
  14665. (org-eval-in-calendar '(calendar-scroll-left 1))))
  14666. (org-defkey map (kbd "<")
  14667. (lambda () (interactive)
  14668. (org-eval-in-calendar '(calendar-scroll-right 1))))
  14669. (org-defkey map (kbd "C-v")
  14670. (lambda () (interactive)
  14671. (org-eval-in-calendar
  14672. '(calendar-scroll-left-three-months 1))))
  14673. (org-defkey map (kbd "M-v")
  14674. (lambda () (interactive)
  14675. (org-eval-in-calendar
  14676. '(calendar-scroll-right-three-months 1))))
  14677. map)
  14678. "Keymap for minibuffer commands when using `org-read-date'.")
  14679. (defvar org-def)
  14680. (defvar org-defdecode)
  14681. (defvar org-with-time)
  14682. (defvar calendar-setup) ; Dynamically scoped.
  14683. (defun org-read-date (&optional with-time to-time from-string prompt
  14684. default-time default-input inactive)
  14685. "Read a date, possibly a time, and make things smooth for the user.
  14686. The prompt will suggest to enter an ISO date, but you can also enter anything
  14687. which will at least partially be understood by `parse-time-string'.
  14688. Unrecognized parts of the date will default to the current day, month, year,
  14689. hour and minute. If this command is called to replace a timestamp at point,
  14690. or to enter the second timestamp of a range, the default time is taken
  14691. from the existing stamp. Furthermore, the command prefers the future,
  14692. so if you are giving a date where the year is not given, and the day-month
  14693. combination is already past in the current year, it will assume you
  14694. mean next year. For details, see the manual. A few examples:
  14695. 3-2-5 --> 2003-02-05
  14696. feb 15 --> currentyear-02-15
  14697. 2/15 --> currentyear-02-15
  14698. sep 12 9 --> 2009-09-12
  14699. 12:45 --> today 12:45
  14700. 22 sept 0:34 --> currentyear-09-22 0:34
  14701. 12 --> currentyear-currentmonth-12
  14702. Fri --> nearest Friday after today
  14703. -Tue --> last Tuesday
  14704. etc.
  14705. Furthermore you can specify a relative date by giving, as the *first* thing
  14706. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  14707. change in days weeks, months, years.
  14708. With a single plus or minus, the date is relative to today. With a double
  14709. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  14710. +4d --> four days from today
  14711. +4 --> same as above
  14712. +2w --> two weeks from today
  14713. ++5 --> five days from default date
  14714. The function understands only English month and weekday abbreviations.
  14715. While prompting, a calendar is popped up - you can also select the
  14716. date with the mouse (button 1). The calendar shows a period of three
  14717. months. To scroll it to other months, use the keys `>' and `<'.
  14718. If you don't like the calendar, turn it off with
  14719. (setq org-read-date-popup-calendar nil)
  14720. With optional argument TO-TIME, the date will immediately be converted
  14721. to an internal time.
  14722. With an optional argument WITH-TIME, the prompt will suggest to
  14723. also insert a time. Note that when WITH-TIME is not set, you can
  14724. still enter a time, and this function will inform the calling routine
  14725. about this change. The calling routine may then choose to change the
  14726. format used to insert the time stamp into the buffer to include the time.
  14727. With optional argument FROM-STRING, read from this string instead from
  14728. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  14729. the time/date that is used for everything that is not specified by the
  14730. user."
  14731. (require 'parse-time)
  14732. (let* ((org-with-time with-time)
  14733. (org-time-stamp-rounding-minutes
  14734. (if (equal org-with-time '(16))
  14735. '(0 0)
  14736. org-time-stamp-rounding-minutes))
  14737. (org-dcst org-display-custom-times)
  14738. (ct (org-current-time))
  14739. (org-def (or org-overriding-default-time default-time ct))
  14740. (org-defdecode (decode-time org-def))
  14741. (cur-frame (selected-frame))
  14742. (mouse-autoselect-window nil) ; Don't let the mouse jump
  14743. (calendar-setup
  14744. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  14745. (calendar-move-hook nil)
  14746. (calendar-view-diary-initially-flag nil)
  14747. (calendar-view-holidays-initially-flag nil)
  14748. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  14749. ;; Rationalize `org-def' and `org-defdecode', if required.
  14750. (when (< (nth 2 org-defdecode) org-extend-today-until)
  14751. (setf (nth 2 org-defdecode) -1)
  14752. (setf (nth 1 org-defdecode) 59)
  14753. (setq org-def (apply #'encode-time org-defdecode))
  14754. (setq org-defdecode (decode-time org-def)))
  14755. (let* ((timestr (format-time-string
  14756. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  14757. org-def))
  14758. (prompt (concat (if prompt (concat prompt " ") "")
  14759. (format "Date+time [%s]: " timestr))))
  14760. (cond
  14761. (from-string (setq ans from-string))
  14762. (org-read-date-popup-calendar
  14763. (save-excursion
  14764. (save-window-excursion
  14765. (calendar)
  14766. (when (eq calendar-setup 'calendar-only)
  14767. (setq cal-frame
  14768. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  14769. (select-frame cal-frame))
  14770. (org-eval-in-calendar '(setq cursor-type nil) t)
  14771. (unwind-protect
  14772. (progn
  14773. (calendar-forward-day (- (time-to-days org-def)
  14774. (calendar-absolute-from-gregorian
  14775. (calendar-current-date))))
  14776. (org-eval-in-calendar nil t)
  14777. (let* ((old-map (current-local-map))
  14778. (map (copy-keymap calendar-mode-map))
  14779. (minibuffer-local-map
  14780. (copy-keymap org-read-date-minibuffer-local-map)))
  14781. (org-defkey map (kbd "RET") 'org-calendar-select)
  14782. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  14783. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  14784. (unwind-protect
  14785. (progn
  14786. (use-local-map map)
  14787. (setq org-read-date-inactive inactive)
  14788. (add-hook 'post-command-hook 'org-read-date-display)
  14789. (setq org-ans0
  14790. (read-string prompt
  14791. default-input
  14792. 'org-read-date-history
  14793. nil))
  14794. ;; org-ans0: from prompt
  14795. ;; org-ans1: from mouse click
  14796. ;; org-ans2: from calendar motion
  14797. (setq ans
  14798. (concat org-ans0 " " (or org-ans1 org-ans2))))
  14799. (remove-hook 'post-command-hook 'org-read-date-display)
  14800. (use-local-map old-map)
  14801. (when org-read-date-overlay
  14802. (delete-overlay org-read-date-overlay)
  14803. (setq org-read-date-overlay nil)))))
  14804. (bury-buffer "*Calendar*")
  14805. (when cal-frame
  14806. (delete-frame cal-frame)
  14807. (select-frame-set-input-focus cur-frame))))))
  14808. (t ; Naked prompt only
  14809. (unwind-protect
  14810. (setq ans (read-string prompt default-input
  14811. 'org-read-date-history timestr))
  14812. (when org-read-date-overlay
  14813. (delete-overlay org-read-date-overlay)
  14814. (setq org-read-date-overlay nil))))))
  14815. (setq final (org-read-date-analyze ans org-def org-defdecode))
  14816. (when org-read-date-analyze-forced-year
  14817. (message "Year was forced into %s"
  14818. (if org-read-date-force-compatible-dates
  14819. "compatible range (1970-2037)"
  14820. "range representable on this machine"))
  14821. (ding))
  14822. ;; One round trip to get rid of 34th of August and stuff like that....
  14823. (setq final (decode-time (apply 'encode-time final)))
  14824. (setq org-read-date-final-answer ans)
  14825. (if to-time
  14826. (apply 'encode-time final)
  14827. (if (and (boundp 'org-time-was-given) org-time-was-given)
  14828. (format "%04d-%02d-%02d %02d:%02d"
  14829. (nth 5 final) (nth 4 final) (nth 3 final)
  14830. (nth 2 final) (nth 1 final))
  14831. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  14832. (defun org-read-date-display ()
  14833. "Display the current date prompt interpretation in the minibuffer."
  14834. (when org-read-date-display-live
  14835. (when org-read-date-overlay
  14836. (delete-overlay org-read-date-overlay))
  14837. (when (minibufferp (current-buffer))
  14838. (save-excursion
  14839. (end-of-line 1)
  14840. (while (not (equal (buffer-substring
  14841. (max (point-min) (- (point) 4)) (point))
  14842. " "))
  14843. (insert " ")))
  14844. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  14845. " " (or org-ans1 org-ans2)))
  14846. (org-end-time-was-given nil)
  14847. (f (org-read-date-analyze ans org-def org-defdecode))
  14848. (fmts (if org-dcst
  14849. org-time-stamp-custom-formats
  14850. org-time-stamp-formats))
  14851. (fmt (if (or org-with-time
  14852. (and (boundp 'org-time-was-given) org-time-was-given))
  14853. (cdr fmts)
  14854. (car fmts)))
  14855. (txt (format-time-string fmt (apply 'encode-time f)))
  14856. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  14857. (txt (concat "=> " txt)))
  14858. (when (and org-end-time-was-given
  14859. (string-match org-plain-time-of-day-regexp txt))
  14860. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  14861. org-end-time-was-given
  14862. (substring txt (match-end 0)))))
  14863. (when org-read-date-analyze-futurep
  14864. (setq txt (concat txt " (=>F)")))
  14865. (setq org-read-date-overlay
  14866. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  14867. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  14868. (defun org-read-date-analyze (ans def defdecode)
  14869. "Analyze the combined answer of the date prompt."
  14870. ;; FIXME: cleanup and comment
  14871. ;; Pass `current-time' result to `decode-time' (instead of calling
  14872. ;; without arguments) so that only `current-time' has to be
  14873. ;; overridden in tests.
  14874. (let ((org-def def)
  14875. (org-defdecode defdecode)
  14876. (nowdecode (decode-time (current-time)))
  14877. delta deltan deltaw deltadef year month day
  14878. hour minute second wday pm h2 m2 tl wday1
  14879. iso-year iso-weekday iso-week iso-date futurep kill-year)
  14880. (setq org-read-date-analyze-futurep nil
  14881. org-read-date-analyze-forced-year nil)
  14882. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  14883. (setq ans "+0"))
  14884. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  14885. (setq ans (replace-match "" t t ans)
  14886. deltan (car delta)
  14887. deltaw (nth 1 delta)
  14888. deltadef (nth 2 delta)))
  14889. ;; Check if there is an iso week date in there. If yes, store the
  14890. ;; info and postpone interpreting it until the rest of the parsing
  14891. ;; is done.
  14892. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  14893. (setq iso-year (when (match-end 1)
  14894. (org-small-year-to-year
  14895. (string-to-number (match-string 1 ans))))
  14896. iso-weekday (when (match-end 3)
  14897. (string-to-number (match-string 3 ans)))
  14898. iso-week (string-to-number (match-string 2 ans)))
  14899. (setq ans (replace-match "" t t ans)))
  14900. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  14901. (when (string-match
  14902. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  14903. (setq year (if (match-end 2)
  14904. (string-to-number (match-string 2 ans))
  14905. (progn (setq kill-year t)
  14906. (string-to-number (format-time-string "%Y"))))
  14907. month (string-to-number (match-string 3 ans))
  14908. day (string-to-number (match-string 4 ans)))
  14909. (setq year (org-small-year-to-year year))
  14910. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14911. t nil ans)))
  14912. ;; Help matching dotted european dates
  14913. (when (string-match
  14914. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  14915. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  14916. (setq kill-year t)
  14917. (string-to-number (format-time-string "%Y")))
  14918. day (string-to-number (match-string 1 ans))
  14919. month (string-to-number (match-string 2 ans))
  14920. ans (replace-match (format "%04d-%02d-%02d" year month day)
  14921. t nil ans)))
  14922. ;; Help matching american dates, like 5/30 or 5/30/7
  14923. (when (string-match
  14924. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  14925. (setq year (if (match-end 4)
  14926. (string-to-number (match-string 4 ans))
  14927. (progn (setq kill-year t)
  14928. (string-to-number (format-time-string "%Y"))))
  14929. month (string-to-number (match-string 1 ans))
  14930. day (string-to-number (match-string 2 ans)))
  14931. (setq year (org-small-year-to-year year))
  14932. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14933. t nil ans)))
  14934. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  14935. ;; If there is a time with am/pm, and *no* time without it, we convert
  14936. ;; so that matching will be successful.
  14937. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  14938. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  14939. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  14940. (setq hour (string-to-number (match-string 1 ans))
  14941. minute (if (match-end 3)
  14942. (string-to-number (match-string 3 ans))
  14943. 0)
  14944. pm (equal ?p
  14945. (string-to-char (downcase (match-string 4 ans)))))
  14946. (if (and (= hour 12) (not pm))
  14947. (setq hour 0)
  14948. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  14949. (setq ans (replace-match (format "%02d:%02d" hour minute)
  14950. t t ans))))
  14951. ;; Check if a time range is given as a duration
  14952. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  14953. (setq hour (string-to-number (match-string 1 ans))
  14954. h2 (+ hour (string-to-number (match-string 3 ans)))
  14955. minute (string-to-number (match-string 2 ans))
  14956. m2 (+ minute (if (match-end 5) (string-to-number
  14957. (match-string 5 ans))0)))
  14958. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  14959. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  14960. t t ans)))
  14961. ;; Check if there is a time range
  14962. (when (boundp 'org-end-time-was-given)
  14963. (setq org-time-was-given nil)
  14964. (when (and (string-match org-plain-time-of-day-regexp ans)
  14965. (match-end 8))
  14966. (setq org-end-time-was-given (match-string 8 ans))
  14967. (setq ans (concat (substring ans 0 (match-beginning 7))
  14968. (substring ans (match-end 7))))))
  14969. (setq tl (parse-time-string ans)
  14970. day (or (nth 3 tl) (nth 3 org-defdecode))
  14971. month
  14972. (cond ((nth 4 tl))
  14973. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  14974. ;; Day was specified. Make sure DAY+MONTH
  14975. ;; combination happens in the future.
  14976. ((nth 3 tl)
  14977. (setq futurep t)
  14978. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  14979. (nth 4 nowdecode)))
  14980. (t (nth 4 org-defdecode)))
  14981. year
  14982. (cond ((and (not kill-year) (nth 5 tl)))
  14983. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  14984. ;; Month was guessed in the future and is at least
  14985. ;; equal to NOWDECODE's. Fix year accordingly.
  14986. (futurep
  14987. (if (or (> month (nth 4 nowdecode))
  14988. (>= day (nth 3 nowdecode)))
  14989. (nth 5 nowdecode)
  14990. (1+ (nth 5 nowdecode))))
  14991. ;; Month was specified. Make sure MONTH+YEAR
  14992. ;; combination happens in the future.
  14993. ((nth 4 tl)
  14994. (setq futurep t)
  14995. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  14996. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  14997. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  14998. (t (nth 5 nowdecode))))
  14999. (t (nth 5 org-defdecode)))
  15000. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15001. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15002. second (or (nth 0 tl) 0)
  15003. wday (nth 6 tl))
  15004. (when (and (eq org-read-date-prefer-future 'time)
  15005. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15006. (equal day (nth 3 nowdecode))
  15007. (equal month (nth 4 nowdecode))
  15008. (equal year (nth 5 nowdecode))
  15009. (nth 2 tl)
  15010. (or (< (nth 2 tl) (nth 2 nowdecode))
  15011. (and (= (nth 2 tl) (nth 2 nowdecode))
  15012. (nth 1 tl)
  15013. (< (nth 1 tl) (nth 1 nowdecode)))))
  15014. (setq day (1+ day)
  15015. futurep t))
  15016. ;; Special date definitions below
  15017. (cond
  15018. (iso-week
  15019. ;; There was an iso week
  15020. (require 'cal-iso)
  15021. (setq futurep nil)
  15022. (setq year (or iso-year year)
  15023. day (or iso-weekday wday 1)
  15024. wday nil ; to make sure that the trigger below does not match
  15025. iso-date (calendar-gregorian-from-absolute
  15026. (calendar-iso-to-absolute
  15027. (list iso-week day year))))
  15028. ; FIXME: Should we also push ISO weeks into the future?
  15029. ; (when (and org-read-date-prefer-future
  15030. ; (not iso-year)
  15031. ; (< (calendar-absolute-from-gregorian iso-date)
  15032. ; (time-to-days (current-time))))
  15033. ; (setq year (1+ year)
  15034. ; iso-date (calendar-gregorian-from-absolute
  15035. ; (calendar-iso-to-absolute
  15036. ; (list iso-week day year)))))
  15037. (setq month (car iso-date)
  15038. year (nth 2 iso-date)
  15039. day (nth 1 iso-date)))
  15040. (deltan
  15041. (setq futurep nil)
  15042. (unless deltadef
  15043. ;; Pass `current-time' result to `decode-time' (instead of
  15044. ;; calling without arguments) so that only `current-time' has
  15045. ;; to be overridden in tests.
  15046. (let ((now (decode-time (current-time))))
  15047. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15048. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15049. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15050. ((equal deltaw "m") (setq month (+ month deltan)))
  15051. ((equal deltaw "y") (setq year (+ year deltan)))))
  15052. ((and wday (not (nth 3 tl)))
  15053. ;; Weekday was given, but no day, so pick that day in the week
  15054. ;; on or after the derived date.
  15055. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15056. (unless (equal wday wday1)
  15057. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15058. (when (and (boundp 'org-time-was-given)
  15059. (nth 2 tl))
  15060. (setq org-time-was-given t))
  15061. (when (< year 100) (setq year (+ 2000 year)))
  15062. ;; Check of the date is representable
  15063. (if org-read-date-force-compatible-dates
  15064. (progn
  15065. (when (< year 1970)
  15066. (setq year 1970 org-read-date-analyze-forced-year t))
  15067. (when (> year 2037)
  15068. (setq year 2037 org-read-date-analyze-forced-year t)))
  15069. (condition-case nil
  15070. (ignore (encode-time second minute hour day month year))
  15071. (error
  15072. (setq year (nth 5 org-defdecode))
  15073. (setq org-read-date-analyze-forced-year t))))
  15074. (setq org-read-date-analyze-futurep futurep)
  15075. (list second minute hour day month year)))
  15076. (defvar parse-time-weekdays)
  15077. (defun org-read-date-get-relative (s today default)
  15078. "Check string S for special relative date string.
  15079. TODAY and DEFAULT are internal times, for today and for a default.
  15080. Return shift list (N what def-flag)
  15081. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15082. N is the number of WHATs to shift.
  15083. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15084. the DEFAULT date rather than TODAY."
  15085. (require 'parse-time)
  15086. (when (and
  15087. (string-match
  15088. (concat
  15089. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15090. "\\([0-9]+\\)?"
  15091. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15092. "\\([ \t]\\|$\\)") s)
  15093. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15094. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15095. (string-to-char (substring (match-string 1 s) -1))
  15096. ?+))
  15097. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15098. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15099. (what (if (match-end 3) (match-string 3 s) "d"))
  15100. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15101. (date (if rel default today))
  15102. (wday (nth 6 (decode-time date)))
  15103. delta)
  15104. (if wday1
  15105. (progn
  15106. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15107. (when (= delta 0) (setq delta 7))
  15108. (when (= dir ?-)
  15109. (setq delta (- delta 7))
  15110. (when (= delta 0) (setq delta -7)))
  15111. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15112. (list delta "d" rel))
  15113. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15114. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15115. "Turn a user-specified date into the internal representation.
  15116. The internal representation needed by the calendar is (month day year).
  15117. This is a wrapper to handle the brain-dead convention in calendar that
  15118. user function argument order change dependent on argument order."
  15119. (pcase calendar-date-style
  15120. (`american (list arg1 arg2 arg3))
  15121. (`european (list arg2 arg1 arg3))
  15122. (`iso (list arg2 arg3 arg1))))
  15123. (defun org-eval-in-calendar (form &optional keepdate)
  15124. "Eval FORM in the calendar window and return to current window.
  15125. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15126. (let ((sf (selected-frame))
  15127. (sw (selected-window)))
  15128. (select-window (get-buffer-window "*Calendar*" t))
  15129. (eval form)
  15130. (when (and (not keepdate) (calendar-cursor-to-date))
  15131. (let* ((date (calendar-cursor-to-date))
  15132. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15133. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15134. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15135. (select-window sw)
  15136. (select-frame-set-input-focus sf)))
  15137. (defun org-calendar-select ()
  15138. "Return to `org-read-date' with the date currently selected.
  15139. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15140. (interactive)
  15141. (when (calendar-cursor-to-date)
  15142. (let* ((date (calendar-cursor-to-date))
  15143. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15144. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15145. (when (active-minibuffer-window) (exit-minibuffer))))
  15146. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15147. "Insert a date stamp for the date given by the internal TIME.
  15148. See `format-time-string' for the format of TIME.
  15149. WITH-HM means use the stamp format that includes the time of the day.
  15150. INACTIVE means use square brackets instead of angular ones, so that the
  15151. stamp will not contribute to the agenda.
  15152. PRE and POST are optional strings to be inserted before and after the
  15153. stamp.
  15154. The command returns the inserted time stamp."
  15155. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15156. stamp)
  15157. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15158. (insert-before-markers (or pre ""))
  15159. (when (listp extra)
  15160. (setq extra (car extra))
  15161. (if (and (stringp extra)
  15162. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15163. (setq extra (format "-%02d:%02d"
  15164. (string-to-number (match-string 1 extra))
  15165. (string-to-number (match-string 2 extra))))
  15166. (setq extra nil)))
  15167. (when extra
  15168. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15169. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15170. (insert-before-markers (or post ""))
  15171. (setq org-last-inserted-timestamp stamp)))
  15172. (defun org-toggle-time-stamp-overlays ()
  15173. "Toggle the use of custom time stamp formats."
  15174. (interactive)
  15175. (setq org-display-custom-times (not org-display-custom-times))
  15176. (unless org-display-custom-times
  15177. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15178. (while (setq p (next-single-property-change p 'display))
  15179. (when (and (get-text-property p 'display)
  15180. (eq (get-text-property p 'face) 'org-date))
  15181. (remove-text-properties
  15182. p (setq p (next-single-property-change p 'display))
  15183. '(display t))))
  15184. (set-buffer-modified-p bmp)))
  15185. (org-restart-font-lock)
  15186. (setq org-table-may-need-update t)
  15187. (if org-display-custom-times
  15188. (message "Time stamps are overlaid with custom format")
  15189. (message "Time stamp overlays removed")))
  15190. (defun org-display-custom-time (beg end)
  15191. "Overlay modified time stamp format over timestamp between BEG and END."
  15192. (let* ((ts (buffer-substring beg end))
  15193. t1 with-hm tf time str (off 0))
  15194. (save-match-data
  15195. (setq t1 (org-parse-time-string ts t))
  15196. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15197. (setq off (- (match-end 0) (match-beginning 0)))))
  15198. (setq end (- end off))
  15199. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  15200. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15201. time (org-fix-decoded-time t1)
  15202. str (org-add-props
  15203. (format-time-string
  15204. (substring tf 1 -1) (apply 'encode-time time))
  15205. nil 'mouse-face 'highlight))
  15206. (put-text-property beg end 'display str)))
  15207. (defun org-fix-decoded-time (time)
  15208. "Set 0 instead of nil for the first 6 elements of time.
  15209. Don't touch the rest."
  15210. (let ((n 0))
  15211. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15212. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15213. "Difference between TIMESTAMP-STRING and now in days.
  15214. If SECONDS is non-nil, return the difference in seconds."
  15215. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15216. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15217. (funcall fdiff (current-time)))))
  15218. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15219. "Is the time in TIMESTAMP-STRING close to the current date?"
  15220. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15221. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15222. (not (org-entry-is-done-p))))
  15223. (defun org-get-wdays (ts &optional delay zero-delay)
  15224. "Get the deadline lead time appropriate for timestring TS.
  15225. When DELAY is non-nil, get the delay time for scheduled items
  15226. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15227. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15228. don't try to find the delay cookie in the scheduled timestamp."
  15229. (let ((tv (if delay org-scheduled-delay-days
  15230. org-deadline-warning-days)))
  15231. (cond
  15232. ((or (and delay (< tv 0))
  15233. (and delay zero-delay (<= tv 0))
  15234. (and (not delay) (<= tv 0)))
  15235. ;; Enforce this value no matter what
  15236. (- tv))
  15237. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15238. ;; lead time is specified.
  15239. (floor (* (string-to-number (match-string 1 ts))
  15240. (cdr (assoc (match-string 2 ts)
  15241. '(("d" . 1) ("w" . 7)
  15242. ("m" . 30.4) ("y" . 365.25)
  15243. ("h" . 0.041667)))))))
  15244. ;; go for the default.
  15245. (t tv))))
  15246. (defun org-calendar-select-mouse (ev)
  15247. "Return to `org-read-date' with the date currently selected.
  15248. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15249. (interactive "e")
  15250. (mouse-set-point ev)
  15251. (when (calendar-cursor-to-date)
  15252. (let* ((date (calendar-cursor-to-date))
  15253. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15254. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15255. (when (active-minibuffer-window) (exit-minibuffer))))
  15256. (defun org-check-deadlines (ndays)
  15257. "Check if there are any deadlines due or past due.
  15258. A deadline is considered due if it happens within `org-deadline-warning-days'
  15259. days from today's date. If the deadline appears in an entry marked DONE,
  15260. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15261. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15262. are shown."
  15263. (interactive "P")
  15264. (let* ((org-warn-days
  15265. (cond
  15266. ((equal ndays '(4)) 100000)
  15267. (ndays (prefix-numeric-value ndays))
  15268. (t (abs org-deadline-warning-days))))
  15269. (case-fold-search nil)
  15270. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15271. (callback
  15272. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15273. (message "%d deadlines past-due or due within %d days"
  15274. (org-occur regexp nil callback)
  15275. org-warn-days)))
  15276. (defsubst org-re-timestamp (type)
  15277. "Return a regexp for timestamp TYPE.
  15278. Allowed values for TYPE are:
  15279. all: all timestamps
  15280. active: only active timestamps (<...>)
  15281. inactive: only inactive timestamps ([...])
  15282. scheduled: only scheduled timestamps
  15283. deadline: only deadline timestamps
  15284. closed: only closed time-stamps
  15285. When TYPE is nil, fall back on returning a regexp that matches
  15286. both scheduled and deadline timestamps."
  15287. (cl-case type
  15288. (all org-ts-regexp-both)
  15289. (active org-ts-regexp)
  15290. (inactive org-ts-regexp-inactive)
  15291. (scheduled org-scheduled-time-regexp)
  15292. (deadline org-deadline-time-regexp)
  15293. (closed org-closed-time-regexp)
  15294. (otherwise
  15295. (concat "\\<"
  15296. (regexp-opt (list org-deadline-string org-scheduled-string))
  15297. " *<\\([^>]+\\)>"))))
  15298. (defun org-check-before-date (d)
  15299. "Check if there are deadlines or scheduled entries before date D."
  15300. (interactive (list (org-read-date)))
  15301. (let* ((case-fold-search nil)
  15302. (regexp (org-re-timestamp org-ts-type))
  15303. (ts-type org-ts-type)
  15304. (callback
  15305. (lambda ()
  15306. (let ((match (match-string 1)))
  15307. (and (if (memq ts-type '(active inactive all))
  15308. (eq (org-element-type (save-excursion
  15309. (backward-char)
  15310. (org-element-context)))
  15311. 'timestamp)
  15312. (org-at-planning-p))
  15313. (time-less-p
  15314. (org-time-string-to-time match)
  15315. (org-time-string-to-time d)))))))
  15316. (message "%d entries before %s"
  15317. (org-occur regexp nil callback)
  15318. d)))
  15319. (defun org-check-after-date (d)
  15320. "Check if there are deadlines or scheduled entries after date D."
  15321. (interactive (list (org-read-date)))
  15322. (let* ((case-fold-search nil)
  15323. (regexp (org-re-timestamp org-ts-type))
  15324. (ts-type org-ts-type)
  15325. (callback
  15326. (lambda ()
  15327. (let ((match (match-string 1)))
  15328. (and (if (memq ts-type '(active inactive all))
  15329. (eq (org-element-type (save-excursion
  15330. (backward-char)
  15331. (org-element-context)))
  15332. 'timestamp)
  15333. (org-at-planning-p))
  15334. (not (time-less-p
  15335. (org-time-string-to-time match)
  15336. (org-time-string-to-time d))))))))
  15337. (message "%d entries after %s"
  15338. (org-occur regexp nil callback)
  15339. d)))
  15340. (defun org-check-dates-range (start-date end-date)
  15341. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15342. (interactive (list (org-read-date nil nil nil "Range starts")
  15343. (org-read-date nil nil nil "Range end")))
  15344. (let ((case-fold-search nil)
  15345. (regexp (org-re-timestamp org-ts-type))
  15346. (callback
  15347. (let ((type org-ts-type))
  15348. (lambda ()
  15349. (let ((match (match-string 1)))
  15350. (and
  15351. (if (memq type '(active inactive all))
  15352. (eq (org-element-type (save-excursion
  15353. (backward-char)
  15354. (org-element-context)))
  15355. 'timestamp)
  15356. (org-at-planning-p))
  15357. (not (time-less-p
  15358. (org-time-string-to-time match)
  15359. (org-time-string-to-time start-date)))
  15360. (time-less-p
  15361. (org-time-string-to-time match)
  15362. (org-time-string-to-time end-date))))))))
  15363. (message "%d entries between %s and %s"
  15364. (org-occur regexp nil callback) start-date end-date)))
  15365. (defun org-evaluate-time-range (&optional to-buffer)
  15366. "Evaluate a time range by computing the difference between start and end.
  15367. Normally the result is just printed in the echo area, but with prefix arg
  15368. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15369. If the time range is actually in a table, the result is inserted into the
  15370. next column.
  15371. For time difference computation, a year is assumed to be exactly 365
  15372. days in order to avoid rounding problems."
  15373. (interactive "P")
  15374. (or
  15375. (org-clock-update-time-maybe)
  15376. (save-excursion
  15377. (unless (org-at-date-range-p t)
  15378. (goto-char (point-at-bol))
  15379. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  15380. (unless (org-at-date-range-p t)
  15381. (user-error "Not at a time-stamp range, and none found in current line")))
  15382. (let* ((ts1 (match-string 1))
  15383. (ts2 (match-string 2))
  15384. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  15385. (match-end (match-end 0))
  15386. (time1 (org-time-string-to-time ts1))
  15387. (time2 (org-time-string-to-time ts2))
  15388. (t1 (float-time time1))
  15389. (t2 (float-time time2))
  15390. (diff (abs (- t2 t1)))
  15391. (negative (< (- t2 t1) 0))
  15392. ;; (ys (floor (* 365 24 60 60)))
  15393. (ds (* 24 60 60))
  15394. (hs (* 60 60))
  15395. (fy "%dy %dd %02d:%02d")
  15396. (fy1 "%dy %dd")
  15397. (fd "%dd %02d:%02d")
  15398. (fd1 "%dd")
  15399. (fh "%02d:%02d")
  15400. y d h m align)
  15401. (if havetime
  15402. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15403. y 0
  15404. d (floor (/ diff ds)) diff (mod diff ds)
  15405. h (floor (/ diff hs)) diff (mod diff hs)
  15406. m (floor (/ diff 60)))
  15407. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15408. y 0
  15409. d (floor (+ (/ diff ds) 0.5))
  15410. h 0 m 0))
  15411. (if (not to-buffer)
  15412. (message "%s" (org-make-tdiff-string y d h m))
  15413. (if (org-at-table-p)
  15414. (progn
  15415. (goto-char match-end)
  15416. (setq align t)
  15417. (and (looking-at " *|") (goto-char (match-end 0))))
  15418. (goto-char match-end))
  15419. (when (looking-at
  15420. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  15421. (replace-match ""))
  15422. (when negative (insert " -"))
  15423. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  15424. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  15425. (insert " " (format fh h m))))
  15426. (when align (org-table-align))
  15427. (message "Time difference inserted")))))
  15428. (defun org-make-tdiff-string (y d h m)
  15429. (let ((fmt "")
  15430. (l nil))
  15431. (when (> y 0)
  15432. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  15433. (push y l))
  15434. (when (> d 0)
  15435. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  15436. (push d l))
  15437. (when (> h 0)
  15438. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  15439. (push h l))
  15440. (when (> m 0)
  15441. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  15442. (push m l))
  15443. (apply 'format fmt (nreverse l))))
  15444. (defun org-time-string-to-time (s)
  15445. "Convert timestamp string S into internal time."
  15446. (apply #'encode-time (org-parse-time-string s)))
  15447. (defun org-time-string-to-seconds (s)
  15448. "Convert a timestamp string S into a number of seconds."
  15449. (float-time (org-time-string-to-time s)))
  15450. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  15451. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  15452. "Convert time stamp S to an absolute day number.
  15453. If DAYNR in non-nil, and there is a specifier for a cyclic time
  15454. stamp, get the closest date to DAYNR. If PREFER is
  15455. `past' (respectively `future') return a date past (respectively
  15456. after) or equal to DAYNR.
  15457. POS is the location of time stamp S, as a buffer position in
  15458. BUFFER.
  15459. Diary sexp timestamps are matched against DAYNR, when non-nil.
  15460. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  15461. signaled."
  15462. (cond
  15463. ((string-match "\\`%%\\((.*)\\)" s)
  15464. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  15465. ;; only able to match individual dates. If it fails, raise an
  15466. ;; error.
  15467. (if (and daynr
  15468. (org-diary-sexp-entry
  15469. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  15470. daynr
  15471. (signal 'org-diary-sexp-no-match (list s))))
  15472. (daynr (org-closest-date s daynr prefer))
  15473. (t (time-to-days
  15474. (condition-case errdata
  15475. (apply #'encode-time (org-parse-time-string s))
  15476. (error (error "Bad timestamp `%s'%s\nError was: %s"
  15477. s
  15478. (if (not (and buffer pos)) ""
  15479. (format-message " at %d in buffer `%s'" pos buffer))
  15480. (cdr errdata))))))))
  15481. (defun org-days-to-iso-week (days)
  15482. "Return the iso week number."
  15483. (require 'cal-iso)
  15484. (car (calendar-iso-from-absolute days)))
  15485. (defun org-small-year-to-year (year)
  15486. "Convert 2-digit years into 4-digit years.
  15487. YEAR is expanded into one of the 30 next years, if possible, or
  15488. into a past one. Any year larger than 99 is returned unchanged."
  15489. (if (>= year 100) year
  15490. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  15491. (century (/ current 100))
  15492. (offset (- year (% current 100))))
  15493. (cond ((> offset 30) (+ (* (1- century) 100) year))
  15494. ((> offset -70) (+ (* century 100) year))
  15495. (t (+ (* (1+ century) 100) year))))))
  15496. (defun org-time-from-absolute (d)
  15497. "Return the time corresponding to date D.
  15498. D may be an absolute day number, or a calendar-type list (month day year)."
  15499. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  15500. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  15501. (defvar org-agenda-current-date)
  15502. (defun org-calendar-holiday ()
  15503. "List of holidays, for Diary display in Org mode."
  15504. (require 'holidays)
  15505. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  15506. (and hl (mapconcat #'identity hl "; "))))
  15507. (defun org-diary-sexp-entry (sexp entry d)
  15508. "Process a SEXP diary ENTRY for date D."
  15509. (require 'diary-lib)
  15510. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  15511. ;; dynamically.
  15512. (let* ((sexp `(let ((entry ,entry)
  15513. (date ',d))
  15514. ,(car (read-from-string sexp))))
  15515. (result (if calendar-debug-sexp (eval sexp)
  15516. (condition-case nil
  15517. (eval sexp)
  15518. (error
  15519. (beep)
  15520. (message "Bad sexp at line %d in %s: %s"
  15521. (org-current-line)
  15522. (buffer-file-name) sexp)
  15523. (sleep-for 2))))))
  15524. (cond ((stringp result) (split-string result "; "))
  15525. ((and (consp result)
  15526. (not (consp (cdr result)))
  15527. (stringp (cdr result))) (cdr result))
  15528. ((and (consp result)
  15529. (stringp (car result))) result)
  15530. (result entry))))
  15531. (defun org-diary-to-ical-string (frombuf)
  15532. "Get iCalendar entries from diary entries in buffer FROMBUF.
  15533. This uses the icalendar.el library."
  15534. (let* ((tmpdir temporary-file-directory)
  15535. (tmpfile (make-temp-name
  15536. (expand-file-name "orgics" tmpdir)))
  15537. buf rtn b e)
  15538. (with-current-buffer frombuf
  15539. (icalendar-export-region (point-min) (point-max) tmpfile)
  15540. (setq buf (find-buffer-visiting tmpfile))
  15541. (set-buffer buf)
  15542. (goto-char (point-min))
  15543. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  15544. (setq b (match-beginning 0)))
  15545. (goto-char (point-max))
  15546. (when (re-search-backward "^END:VEVENT" nil t)
  15547. (setq e (match-end 0)))
  15548. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  15549. (kill-buffer buf)
  15550. (delete-file tmpfile)
  15551. rtn))
  15552. (defun org-closest-date (start current prefer)
  15553. "Return closest date to CURRENT starting from START.
  15554. CURRENT and START are both time stamps.
  15555. When PREFER is `past', return a date that is either CURRENT or
  15556. past. When PREFER is `future', return a date that is either
  15557. CURRENT or future.
  15558. Only time stamps with a repeater are modified. Any other time
  15559. stamp stay unchanged. In any case, return value is an absolute
  15560. day number."
  15561. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  15562. ;; No repeater. Do not shift time stamp.
  15563. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15564. (let ((value (string-to-number (match-string 1 start)))
  15565. (type (match-string 2 start)))
  15566. (if (= 0 value)
  15567. ;; Repeater with a 0-value is considered as void.
  15568. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15569. (let* ((base (org-date-to-gregorian start))
  15570. (target (org-date-to-gregorian current))
  15571. (sday (calendar-absolute-from-gregorian base))
  15572. (cday (calendar-absolute-from-gregorian target))
  15573. n1 n2)
  15574. ;; If START is already past CURRENT, just return START.
  15575. (if (<= cday sday) sday
  15576. ;; Compute closest date before (N1) and closest date past
  15577. ;; (N2) CURRENT.
  15578. (pcase type
  15579. ("h"
  15580. (let ((missing-hours
  15581. (mod (+ (- (* 24 (- cday sday))
  15582. (nth 2 (org-parse-time-string start)))
  15583. org-extend-today-until)
  15584. value)))
  15585. (setf n1 (if (= missing-hours 0) cday
  15586. (- cday (1+ (/ missing-hours 24)))))
  15587. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  15588. ((or "d" "w")
  15589. (let ((value (if (equal type "w") (* 7 value) value)))
  15590. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  15591. (setf n2 (+ n1 value))))
  15592. ("m"
  15593. (let* ((add-months
  15594. (lambda (d n)
  15595. ;; Add N months to gregorian date D, i.e.,
  15596. ;; a list (MONTH DAY YEAR). Return a valid
  15597. ;; gregorian date.
  15598. (let ((m (+ (nth 0 d) n)))
  15599. (list (mod m 12)
  15600. (nth 1 d)
  15601. (+ (/ m 12) (nth 2 d))))))
  15602. (months ; Complete months to TARGET.
  15603. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  15604. (- (nth 0 target) (nth 0 base))
  15605. ;; If START's day is greater than
  15606. ;; TARGET's, remove incomplete month.
  15607. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  15608. value)
  15609. value))
  15610. (before (funcall add-months base months)))
  15611. (setf n1 (calendar-absolute-from-gregorian before))
  15612. (setf n2
  15613. (calendar-absolute-from-gregorian
  15614. (funcall add-months before value)))))
  15615. (_
  15616. (let* ((d (nth 1 base))
  15617. (m (nth 0 base))
  15618. (y (nth 2 base))
  15619. (years ; Complete years to TARGET.
  15620. (* (/ (- (nth 2 target)
  15621. y
  15622. ;; If START's month and day are
  15623. ;; greater than TARGET's, remove
  15624. ;; incomplete year.
  15625. (if (or (> (nth 0 target) m)
  15626. (and (= (nth 0 target) m)
  15627. (> (nth 1 target) d)))
  15628. 0
  15629. 1))
  15630. value)
  15631. value))
  15632. (before (list m d (+ y years))))
  15633. (setf n1 (calendar-absolute-from-gregorian before))
  15634. (setf n2 (calendar-absolute-from-gregorian
  15635. (list m d (+ (nth 2 before) value)))))))
  15636. ;; Handle PREFER parameter, if any.
  15637. (cond
  15638. ((eq prefer 'past) (if (= cday n2) n2 n1))
  15639. ((eq prefer 'future) (if (= cday n1) n1 n2))
  15640. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  15641. (defun org-date-to-gregorian (d)
  15642. "Turn any specification of date D into a Gregorian date for the calendar."
  15643. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  15644. ((and (listp d) (= (length d) 3)) d)
  15645. ((stringp d)
  15646. (let ((d (org-parse-time-string d)))
  15647. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  15648. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  15649. (defun org-timestamp-up (&optional arg)
  15650. "Increase the date item at the cursor by one.
  15651. If the cursor is on the year, change the year. If it is on the month,
  15652. the day or the time, change that. If the cursor is on the enclosing
  15653. bracket, change the timestamp type.
  15654. With prefix ARG, change by that many units."
  15655. (interactive "p")
  15656. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  15657. (defun org-timestamp-down (&optional arg)
  15658. "Decrease the date item at the cursor by one.
  15659. If the cursor is on the year, change the year. If it is on the month,
  15660. the day or the time, change that. If the cursor is on the enclosing
  15661. bracket, change the timestamp type.
  15662. With prefix ARG, change by that many units."
  15663. (interactive "p")
  15664. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  15665. (defun org-timestamp-up-day (&optional arg)
  15666. "Increase the date in the time stamp by one day.
  15667. With prefix ARG, change that many days."
  15668. (interactive "p")
  15669. (if (and (not (org-at-timestamp-p 'lax))
  15670. (org-at-heading-p))
  15671. (org-todo 'up)
  15672. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  15673. (defun org-timestamp-down-day (&optional arg)
  15674. "Decrease the date in the time stamp by one day.
  15675. With prefix ARG, change that many days."
  15676. (interactive "p")
  15677. (if (and (not (org-at-timestamp-p 'lax))
  15678. (org-at-heading-p))
  15679. (org-todo 'down)
  15680. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  15681. (defun org-at-timestamp-p (&optional extended)
  15682. "Non-nil if point is inside a timestamp.
  15683. By default, the function only consider syntactically valid active
  15684. timestamps. However, the caller may have a broader definition
  15685. for timestamps. As a consequence, optional argument EXTENDED can
  15686. be set to the following values
  15687. `inactive'
  15688. Include also syntactically valid inactive timestamps.
  15689. `agenda'
  15690. Include timestamps allowed in Agenda, i.e., those in
  15691. properties drawers, planning lines and clock lines.
  15692. `lax'
  15693. Ignore context. The function matches any part of the
  15694. document looking like a timestamp. This includes comments,
  15695. example blocks...
  15696. For backward-compatibility with Org 9.0, every other non-nil
  15697. value is equivalent to `inactive'.
  15698. When at a timestamp, return the position of the point as a symbol
  15699. among `bracket', `after', `year', `month', `hour', `minute',
  15700. `day' or a number of character from the last know part of the
  15701. time stamp.
  15702. When matching, the match groups are the following:
  15703. group 1: year
  15704. group 2: month
  15705. group 3: day number
  15706. group 4: day name
  15707. group 5: hours, if any
  15708. group 6: minutes, if any"
  15709. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  15710. (pos (point))
  15711. (match?
  15712. (let ((boundaries (org-in-regexp regexp)))
  15713. (save-match-data
  15714. (cond ((null boundaries) nil)
  15715. ((eq extended 'lax) t)
  15716. (t
  15717. (or (and (eq extended 'agenda)
  15718. (or (org-at-planning-p)
  15719. (org-at-property-p)
  15720. (and (bound-and-true-p
  15721. org-agenda-include-inactive-timestamps)
  15722. (org-at-clock-log-p))))
  15723. (eq 'timestamp
  15724. (save-excursion
  15725. (when (= pos (cdr boundaries)) (forward-char -1))
  15726. (org-element-type (org-element-context)))))))))))
  15727. (cond
  15728. ((not match?) nil)
  15729. ((= pos (match-beginning 0)) 'bracket)
  15730. ;; Distinguish location right before the closing bracket from
  15731. ;; right after it.
  15732. ((= pos (1- (match-end 0))) 'bracket)
  15733. ((= pos (match-end 0)) 'after)
  15734. ((org-pos-in-match-range pos 2) 'year)
  15735. ((org-pos-in-match-range pos 3) 'month)
  15736. ((org-pos-in-match-range pos 7) 'hour)
  15737. ((org-pos-in-match-range pos 8) 'minute)
  15738. ((or (org-pos-in-match-range pos 4)
  15739. (org-pos-in-match-range pos 5)) 'day)
  15740. ((and (> pos (or (match-end 8) (match-end 5)))
  15741. (< pos (match-end 0)))
  15742. (- pos (or (match-end 8) (match-end 5))))
  15743. (t 'day))))
  15744. (defun org-toggle-timestamp-type ()
  15745. "Toggle the type (<active> or [inactive]) of a time stamp."
  15746. (interactive)
  15747. (when (org-at-timestamp-p 'lax)
  15748. (let ((beg (match-beginning 0)) (end (match-end 0))
  15749. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  15750. (save-excursion
  15751. (goto-char beg)
  15752. (while (re-search-forward "[][<>]" end t)
  15753. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  15754. t t)))
  15755. (message "Timestamp is now %sactive"
  15756. (if (equal (char-after beg) ?<) "" "in")))))
  15757. (defun org-at-clock-log-p ()
  15758. "Non-nil if point is on a clock log line."
  15759. (and (org-match-line org-clock-line-re)
  15760. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  15761. (defvar org-clock-history) ; defined in org-clock.el
  15762. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  15763. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  15764. "Change the date in the time stamp at point.
  15765. The date will be changed by N times WHAT. WHAT can be `day', `month',
  15766. `year', `minute', `second'. If WHAT is not given, the cursor position
  15767. in the timestamp determines what will be changed.
  15768. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  15769. (let ((origin (point))
  15770. (timestamp? (org-at-timestamp-p 'lax))
  15771. origin-cat
  15772. with-hm inactive
  15773. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  15774. extra rem
  15775. ts time time0 fixnext clrgx)
  15776. (unless timestamp? (user-error "Not at a timestamp"))
  15777. (if (and (not what) (eq timestamp? 'bracket))
  15778. (org-toggle-timestamp-type)
  15779. ;; Point isn't on brackets. Remember the part of the time-stamp
  15780. ;; the point was in. Indeed, size of time-stamps may change,
  15781. ;; but point must be kept in the same category nonetheless.
  15782. (setq origin-cat timestamp?)
  15783. (when (and (not what) (not (eq timestamp? 'day))
  15784. org-display-custom-times
  15785. (get-text-property (point) 'display)
  15786. (not (get-text-property (1- (point)) 'display)))
  15787. (setq timestamp? 'day))
  15788. (setq timestamp? (or what timestamp?)
  15789. inactive (= (char-after (match-beginning 0)) ?\[)
  15790. ts (match-string 0))
  15791. (replace-match "")
  15792. (when (string-match
  15793. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  15794. ts)
  15795. (setq extra (match-string 1 ts))
  15796. (when suppress-tmp-delay
  15797. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  15798. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  15799. (setq with-hm t))
  15800. (setq time0 (org-parse-time-string ts))
  15801. (when (and updown
  15802. (eq timestamp? 'minute)
  15803. (not current-prefix-arg))
  15804. ;; This looks like s-up and s-down. Change by one rounding step.
  15805. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  15806. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  15807. (setcar (cdr time0) (+ (nth 1 time0)
  15808. (if (> n 0) (- rem) (- dm rem))))))
  15809. (setq time
  15810. (apply #'encode-time
  15811. (or (car time0) 0)
  15812. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  15813. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  15814. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  15815. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  15816. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  15817. (nthcdr 6 time0)))
  15818. (when (and (memq timestamp? '(hour minute))
  15819. extra
  15820. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  15821. (setq extra (org-modify-ts-extra
  15822. extra
  15823. (if (eq timestamp? 'hour) 2 5)
  15824. n dm)))
  15825. (when (integerp timestamp?)
  15826. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  15827. (when (eq what 'calendar)
  15828. (let ((cal-date (org-get-date-from-calendar)))
  15829. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  15830. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  15831. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  15832. (setcar time0 (or (car time0) 0))
  15833. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  15834. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  15835. (setq time (apply 'encode-time time0))))
  15836. ;; Insert the new time-stamp, and ensure point stays in the same
  15837. ;; category as before (i.e. not after the last position in that
  15838. ;; category).
  15839. (let ((pos (point)))
  15840. ;; Stay before inserted string. `save-excursion' is of no use.
  15841. (setq org-last-changed-timestamp
  15842. (org-insert-time-stamp time with-hm inactive nil nil extra))
  15843. (goto-char pos))
  15844. (save-match-data
  15845. (looking-at org-ts-regexp3)
  15846. (goto-char
  15847. (pcase origin-cat
  15848. ;; `day' category ends before `hour' if any, or at the end
  15849. ;; of the day name.
  15850. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  15851. (`hour (min (match-end 7) origin))
  15852. (`minute (min (1- (match-end 8)) origin))
  15853. ((pred integerp) (min (1- (match-end 0)) origin))
  15854. ;; Point was right after the time-stamp. However, the
  15855. ;; time-stamp length might have changed, so refer to
  15856. ;; (match-end 0) instead.
  15857. (`after (match-end 0))
  15858. ;; `year' and `month' have both fixed size: point couldn't
  15859. ;; have moved into another part.
  15860. (_ origin))))
  15861. ;; Update clock if on a CLOCK line.
  15862. (org-clock-update-time-maybe)
  15863. ;; Maybe adjust the closest clock in `org-clock-history'
  15864. (when org-clock-adjust-closest
  15865. (if (not (and (org-at-clock-log-p)
  15866. (< 1 (length (delq nil (mapcar 'marker-position
  15867. org-clock-history))))))
  15868. (message "No clock to adjust")
  15869. (cond ((save-excursion ; fix previous clock?
  15870. (re-search-backward org-ts-regexp0 nil t)
  15871. (looking-back (concat org-clock-string " \\[")
  15872. (line-beginning-position)))
  15873. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  15874. ((save-excursion ; fix next clock?
  15875. (re-search-backward org-ts-regexp0 nil t)
  15876. (looking-at (concat org-ts-regexp0 "\\] =>")))
  15877. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  15878. (save-window-excursion
  15879. ;; Find closest clock to point, adjust the previous/next one in history
  15880. (let* ((p (save-excursion (org-back-to-heading t)))
  15881. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  15882. (clfixnth
  15883. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  15884. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  15885. (if (not clfixpos)
  15886. (message "No clock to adjust")
  15887. (save-excursion
  15888. (org-goto-marker-or-bmk clfixpos)
  15889. (org-show-subtree)
  15890. (when (re-search-forward clrgx nil t)
  15891. (goto-char (match-beginning 1))
  15892. (let (org-clock-adjust-closest)
  15893. (org-timestamp-change n timestamp? updown))
  15894. (message "Clock adjusted in %s for heading: %s"
  15895. (file-name-nondirectory (buffer-file-name))
  15896. (org-get-heading t t)))))))))
  15897. ;; Try to recenter the calendar window, if any.
  15898. (when (and org-calendar-follow-timestamp-change
  15899. (get-buffer-window "*Calendar*" t)
  15900. (memq timestamp? '(day month year)))
  15901. (org-recenter-calendar (time-to-days time))))))
  15902. (defun org-modify-ts-extra (s pos n dm)
  15903. "Change the different parts of the lead-time and repeat fields in timestamp."
  15904. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  15905. ng h m new rem)
  15906. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  15907. (cond
  15908. ((or (org-pos-in-match-range pos 2)
  15909. (org-pos-in-match-range pos 3))
  15910. (setq m (string-to-number (match-string 3 s))
  15911. h (string-to-number (match-string 2 s)))
  15912. (if (org-pos-in-match-range pos 2)
  15913. (setq h (+ h n))
  15914. (setq n (* dm (with-no-warnings (signum n))))
  15915. (unless (= 0 (setq rem (% m dm)))
  15916. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  15917. (setq m (+ m n)))
  15918. (when (< m 0) (setq m (+ m 60) h (1- h)))
  15919. (when (> m 59) (setq m (- m 60) h (1+ h)))
  15920. (setq h (mod h 24))
  15921. (setq ng 1 new (format "-%02d:%02d" h m)))
  15922. ((org-pos-in-match-range pos 6)
  15923. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  15924. ((org-pos-in-match-range pos 5)
  15925. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  15926. ((org-pos-in-match-range pos 9)
  15927. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  15928. ((org-pos-in-match-range pos 8)
  15929. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  15930. (when ng
  15931. (setq s (concat
  15932. (substring s 0 (match-beginning ng))
  15933. new
  15934. (substring s (match-end ng))))))
  15935. s))
  15936. (defun org-recenter-calendar (d)
  15937. "If the calendar is visible, recenter it to date D."
  15938. (let ((cwin (get-buffer-window "*Calendar*" t)))
  15939. (when cwin
  15940. (let ((calendar-move-hook nil))
  15941. (with-selected-window cwin
  15942. (calendar-goto-date
  15943. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  15944. (defun org-goto-calendar (&optional arg)
  15945. "Go to the Emacs calendar at the current date.
  15946. If there is a time stamp in the current line, go to that date.
  15947. A prefix ARG can be used to force the current date."
  15948. (interactive "P")
  15949. (let ((calendar-move-hook nil)
  15950. (calendar-view-holidays-initially-flag nil)
  15951. (calendar-view-diary-initially-flag nil)
  15952. diff)
  15953. (when (or (org-at-timestamp-p 'lax)
  15954. (org-match-line (concat ".*" org-ts-regexp)))
  15955. (let ((d1 (time-to-days (current-time)))
  15956. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  15957. (setq diff (- d2 d1))))
  15958. (calendar)
  15959. (calendar-goto-today)
  15960. (when (and diff (not arg)) (calendar-forward-day diff))))
  15961. (defun org-get-date-from-calendar ()
  15962. "Return a list (month day year) of date at point in calendar."
  15963. (with-current-buffer "*Calendar*"
  15964. (save-match-data
  15965. (calendar-cursor-to-date))))
  15966. (defun org-date-from-calendar ()
  15967. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  15968. If there is already a time stamp at the cursor position, update it."
  15969. (interactive)
  15970. (if (org-at-timestamp-p 'lax)
  15971. (org-timestamp-change 0 'calendar)
  15972. (let ((cal-date (org-get-date-from-calendar)))
  15973. (org-insert-time-stamp
  15974. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  15975. (defcustom org-effort-durations
  15976. `(("min" . 1)
  15977. ("h" . 60)
  15978. ("d" . ,(* 60 8))
  15979. ("w" . ,(* 60 8 5))
  15980. ("m" . ,(* 60 8 5 4))
  15981. ("y" . ,(* 60 8 5 40)))
  15982. "Conversion factor to minutes for an effort modifier.
  15983. Each entry has the form (MODIFIER . MINUTES).
  15984. In an effort string, a number followed by MODIFIER is multiplied
  15985. by the specified number of MINUTES to obtain an effort in
  15986. minutes.
  15987. For example, if the value of this variable is ((\"hours\" . 60)), then an
  15988. effort string \"2hours\" is equivalent to 120 minutes."
  15989. :group 'org-agenda
  15990. :version "26.1"
  15991. :package-version '(Org . "8.3")
  15992. :type '(alist :key-type (string :tag "Modifier")
  15993. :value-type (number :tag "Minutes")))
  15994. (defcustom org-image-actual-width t
  15995. "Should we use the actual width of images when inlining them?
  15996. When set to t, always use the image width.
  15997. When set to a number, use imagemagick (when available) to set
  15998. the image's width to this value.
  15999. When set to a number in a list, try to get the width from any
  16000. #+ATTR.* keyword if it matches a width specification like
  16001. #+ATTR_HTML: :width 300px
  16002. and fall back on that number if none is found.
  16003. When set to nil, try to get the width from an #+ATTR.* keyword
  16004. and fall back on the original width if none is found.
  16005. This requires Emacs >= 24.1, build with imagemagick support."
  16006. :group 'org-appearance
  16007. :version "24.4"
  16008. :package-version '(Org . "8.0")
  16009. :type '(choice
  16010. (const :tag "Use the image width" t)
  16011. (integer :tag "Use a number of pixels")
  16012. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16013. (const :tag "Use #+ATTR* or don't resize" nil)))
  16014. (defcustom org-agenda-inhibit-startup nil
  16015. "Inhibit startup when preparing agenda buffers.
  16016. When this variable is t, the initialization of the Org agenda
  16017. buffers is inhibited: e.g. the visibility state is not set, the
  16018. tables are not re-aligned, etc."
  16019. :type 'boolean
  16020. :version "24.3"
  16021. :group 'org-agenda)
  16022. (defcustom org-agenda-ignore-properties nil
  16023. "Avoid updating text properties when building the agenda.
  16024. Properties are used to prepare buffers for effort estimates,
  16025. appointments, statistics and subtree-local categories.
  16026. If you don't use these in the agenda, you can add them to this
  16027. list and agenda building will be a bit faster.
  16028. The value is a list, with zero or more of the symbols `effort', `appt',
  16029. `stats' or `category'."
  16030. :type '(set :greedy t
  16031. (const effort)
  16032. (const appt)
  16033. (const stats)
  16034. (const category))
  16035. :version "26.1"
  16036. :package-version '(Org . "8.3")
  16037. :group 'org-agenda)
  16038. ;;;; Files
  16039. (defun org-save-all-org-buffers ()
  16040. "Save all Org buffers without user confirmation."
  16041. (interactive)
  16042. (message "Saving all Org buffers...")
  16043. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16044. (when (featurep 'org-id) (org-id-locations-save))
  16045. (message "Saving all Org buffers... done"))
  16046. (defun org-revert-all-org-buffers ()
  16047. "Revert all Org buffers.
  16048. Prompt for confirmation when there are unsaved changes.
  16049. Be sure you know what you are doing before letting this function
  16050. overwrite your changes.
  16051. This function is useful in a setup where one tracks Org files
  16052. with a version control system, to revert on one machine after pulling
  16053. changes from another. I believe the procedure must be like this:
  16054. 1. M-x org-save-all-org-buffers
  16055. 2. Pull changes from the other machine, resolve conflicts
  16056. 3. M-x org-revert-all-org-buffers"
  16057. (interactive)
  16058. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16059. (user-error "Abort"))
  16060. (save-excursion
  16061. (save-window-excursion
  16062. (dolist (b (buffer-list))
  16063. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16064. (with-current-buffer b buffer-file-name))
  16065. (pop-to-buffer-same-window b)
  16066. (revert-buffer t 'no-confirm)))
  16067. (when (and (featurep 'org-id) org-id-track-globally)
  16068. (org-id-locations-load)))))
  16069. ;;;; Agenda files
  16070. ;;;###autoload
  16071. (defun org-switchb (&optional arg)
  16072. "Switch between Org buffers.
  16073. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16074. With `\\[universal-argument] \\[universal-argument]' \
  16075. prefix, restrict available buffers to agenda files."
  16076. (interactive "P")
  16077. (let ((blist (org-buffer-list
  16078. (cond ((equal arg '(4)) 'files)
  16079. ((equal arg '(16)) 'agenda)))))
  16080. (pop-to-buffer-same-window
  16081. (completing-read "Org buffer: "
  16082. (mapcar #'list (mapcar #'buffer-name blist))
  16083. nil t))))
  16084. (defun org-buffer-list (&optional predicate exclude-tmp)
  16085. "Return a list of Org buffers.
  16086. PREDICATE can be `export', `files' or `agenda'.
  16087. export restrict the list to Export buffers.
  16088. files restrict the list to buffers visiting Org files.
  16089. agenda restrict the list to buffers visiting agenda files.
  16090. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16091. (let* ((bfn nil)
  16092. (agenda-files (and (eq predicate 'agenda)
  16093. (mapcar 'file-truename (org-agenda-files t))))
  16094. (filter
  16095. (cond
  16096. ((eq predicate 'files)
  16097. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16098. ((eq predicate 'export)
  16099. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16100. ((eq predicate 'agenda)
  16101. (lambda (b)
  16102. (with-current-buffer b
  16103. (and (derived-mode-p 'org-mode)
  16104. (setq bfn (buffer-file-name b))
  16105. (member (file-truename bfn) agenda-files)))))
  16106. (t (lambda (b) (with-current-buffer b
  16107. (or (derived-mode-p 'org-mode)
  16108. (string-match "\\*Org .*Export"
  16109. (buffer-name b)))))))))
  16110. (delq nil
  16111. (mapcar
  16112. (lambda(b)
  16113. (if (and (funcall filter b)
  16114. (or (not exclude-tmp)
  16115. (not (string-match "tmp" (buffer-name b)))))
  16116. b
  16117. nil))
  16118. (buffer-list)))))
  16119. (defun org-agenda-files (&optional unrestricted archives)
  16120. "Get the list of agenda files.
  16121. Optional UNRESTRICTED means return the full list even if a restriction
  16122. is currently in place.
  16123. When ARCHIVES is t, include all archive files that are really being
  16124. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16125. `org-agenda-archives-mode' is t."
  16126. (let ((files
  16127. (cond
  16128. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16129. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16130. ((listp org-agenda-files) org-agenda-files)
  16131. (t (error "Invalid value of `org-agenda-files'")))))
  16132. (setq files (apply 'append
  16133. (mapcar (lambda (f)
  16134. (if (file-directory-p f)
  16135. (directory-files
  16136. f t org-agenda-file-regexp)
  16137. (list f)))
  16138. files)))
  16139. (when org-agenda-skip-unavailable-files
  16140. (setq files (delq nil
  16141. (mapcar (function
  16142. (lambda (file)
  16143. (and (file-readable-p file) file)))
  16144. files))))
  16145. (when (or (eq archives t)
  16146. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16147. (setq files (org-add-archive-files files)))
  16148. files))
  16149. (defun org-agenda-file-p (&optional file)
  16150. "Return non-nil, if FILE is an agenda file.
  16151. If FILE is omitted, use the file associated with the current
  16152. buffer."
  16153. (let ((fname (or file (buffer-file-name))))
  16154. (and fname
  16155. (member (file-truename fname)
  16156. (mapcar #'file-truename (org-agenda-files t))))))
  16157. (defun org-edit-agenda-file-list ()
  16158. "Edit the list of agenda files.
  16159. Depending on setup, this either uses customize to edit the variable
  16160. `org-agenda-files', or it visits the file that is holding the list. In the
  16161. latter case, the buffer is set up in a way that saving it automatically kills
  16162. the buffer and restores the previous window configuration."
  16163. (interactive)
  16164. (if (stringp org-agenda-files)
  16165. (let ((cw (current-window-configuration)))
  16166. (find-file org-agenda-files)
  16167. (setq-local org-window-configuration cw)
  16168. (add-hook 'after-save-hook
  16169. (lambda ()
  16170. (set-window-configuration
  16171. (prog1 org-window-configuration
  16172. (kill-buffer (current-buffer))))
  16173. (org-install-agenda-files-menu)
  16174. (message "New agenda file list installed"))
  16175. nil 'local)
  16176. (message "%s" (substitute-command-keys
  16177. "Edit list and finish with \\[save-buffer]")))
  16178. (customize-variable 'org-agenda-files)))
  16179. (defun org-store-new-agenda-file-list (list)
  16180. "Set new value for the agenda file list and save it correctly."
  16181. (if (stringp org-agenda-files)
  16182. (let ((fe (org-read-agenda-file-list t)) b u)
  16183. (while (setq b (find-buffer-visiting org-agenda-files))
  16184. (kill-buffer b))
  16185. (with-temp-file org-agenda-files
  16186. (insert
  16187. (mapconcat
  16188. (lambda (f) ;; Keep un-expanded entries.
  16189. (if (setq u (assoc f fe))
  16190. (cdr u)
  16191. f))
  16192. list "\n")
  16193. "\n")))
  16194. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16195. (org-insert-mode-line-in-empty-file nil))
  16196. (setq org-agenda-files list)
  16197. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16198. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16199. "Read the list of agenda files from a file.
  16200. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16201. filenames, used by `org-store-new-agenda-file-list' to write back
  16202. un-expanded file names."
  16203. (when (file-directory-p org-agenda-files)
  16204. (error "`org-agenda-files' cannot be a single directory"))
  16205. (when (stringp org-agenda-files)
  16206. (with-temp-buffer
  16207. (insert-file-contents org-agenda-files)
  16208. (mapcar
  16209. (lambda (f)
  16210. (let ((e (expand-file-name (substitute-in-file-name f)
  16211. org-directory)))
  16212. (if pair-with-expansion
  16213. (cons e f)
  16214. e)))
  16215. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16216. ;;;###autoload
  16217. (defun org-cycle-agenda-files ()
  16218. "Cycle through the files in `org-agenda-files'.
  16219. If the current buffer visits an agenda file, find the next one in the list.
  16220. If the current buffer does not, find the first agenda file."
  16221. (interactive)
  16222. (let* ((fs (or (org-agenda-files t)
  16223. (user-error "No agenda files")))
  16224. (files (copy-sequence fs))
  16225. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16226. file)
  16227. (when tcf
  16228. (while (and (setq file (pop files))
  16229. (not (equal (file-truename file) tcf)))))
  16230. (find-file (car (or files fs)))
  16231. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16232. (defun org-agenda-file-to-front (&optional to-end)
  16233. "Move/add the current file to the top of the agenda file list.
  16234. If the file is not present in the list, it is added to the front. If it is
  16235. present, it is moved there. With optional argument TO-END, add/move to the
  16236. end of the list."
  16237. (interactive "P")
  16238. (let ((org-agenda-skip-unavailable-files nil)
  16239. (file-alist (mapcar (lambda (x)
  16240. (cons (file-truename x) x))
  16241. (org-agenda-files t)))
  16242. (ctf (file-truename
  16243. (or buffer-file-name
  16244. (user-error "Please save the current buffer to a file"))))
  16245. x had)
  16246. (setq x (assoc ctf file-alist) had x)
  16247. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16248. (if to-end
  16249. (setq file-alist (append (delq x file-alist) (list x)))
  16250. (setq file-alist (cons x (delq x file-alist))))
  16251. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16252. (org-install-agenda-files-menu)
  16253. (message "File %s to %s of agenda file list"
  16254. (if had "moved" "added") (if to-end "end" "front"))))
  16255. (defun org-remove-file (&optional file)
  16256. "Remove current file from the list of files in variable `org-agenda-files'.
  16257. These are the files which are being checked for agenda entries.
  16258. Optional argument FILE means use this file instead of the current."
  16259. (interactive)
  16260. (let* ((org-agenda-skip-unavailable-files nil)
  16261. (file (or file buffer-file-name
  16262. (user-error "Current buffer does not visit a file")))
  16263. (true-file (file-truename file))
  16264. (afile (abbreviate-file-name file))
  16265. (files (delq nil (mapcar
  16266. (lambda (x)
  16267. (unless (equal true-file
  16268. (file-truename x))
  16269. x))
  16270. (org-agenda-files t)))))
  16271. (if (not (= (length files) (length (org-agenda-files t))))
  16272. (progn
  16273. (org-store-new-agenda-file-list files)
  16274. (org-install-agenda-files-menu)
  16275. (message "Removed from Org Agenda list: %s" afile))
  16276. (message "File was not in list: %s (not removed)" afile))))
  16277. (defun org-file-menu-entry (file)
  16278. (vector file (list 'find-file file) t))
  16279. (defun org-check-agenda-file (file)
  16280. "Make sure FILE exists. If not, ask user what to do."
  16281. (unless (file-exists-p file)
  16282. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16283. (abbreviate-file-name file))
  16284. (let ((r (downcase (read-char-exclusive))))
  16285. (cond
  16286. ((equal r ?r)
  16287. (org-remove-file file)
  16288. (throw 'nextfile t))
  16289. (t (user-error "Abort"))))))
  16290. (defun org-get-agenda-file-buffer (file)
  16291. "Get an agenda buffer visiting FILE.
  16292. If the buffer needs to be created, add it to the list of buffers
  16293. which might be released later."
  16294. (let ((buf (org-find-base-buffer-visiting file)))
  16295. (if buf
  16296. buf ; just return it
  16297. ;; Make a new buffer and remember it
  16298. (setq buf (find-file-noselect file))
  16299. (when buf (push buf org-agenda-new-buffers))
  16300. buf)))
  16301. (defun org-release-buffers (blist)
  16302. "Release all buffers in list, asking the user for confirmation when needed.
  16303. When a buffer is unmodified, it is just killed. When modified, it is saved
  16304. \(if the user agrees) and then killed."
  16305. (let (file)
  16306. (dolist (buf blist)
  16307. (setq file (buffer-file-name buf))
  16308. (when (and (buffer-modified-p buf)
  16309. file
  16310. (y-or-n-p (format "Save file %s? " file)))
  16311. (with-current-buffer buf (save-buffer)))
  16312. (kill-buffer buf))))
  16313. (defun org-agenda-prepare-buffers (files)
  16314. "Create buffers for all agenda files, protect archived trees and comments."
  16315. (interactive)
  16316. (let ((pa '(:org-archived t))
  16317. (pc '(:org-comment t))
  16318. (pall '(:org-archived t :org-comment t))
  16319. (inhibit-read-only t)
  16320. (org-inhibit-startup org-agenda-inhibit-startup)
  16321. (rea (org-make-tag-string (list org-archive-tag)))
  16322. re pos)
  16323. (setq org-tag-alist-for-agenda nil
  16324. org-tag-groups-alist-for-agenda nil)
  16325. (save-excursion
  16326. (save-restriction
  16327. (dolist (file files)
  16328. (catch 'nextfile
  16329. (if (bufferp file)
  16330. (set-buffer file)
  16331. (org-check-agenda-file file)
  16332. (set-buffer (org-get-agenda-file-buffer file)))
  16333. (widen)
  16334. (org-set-regexps-and-options 'tags-only)
  16335. (setq pos (point))
  16336. (or (memq 'category org-agenda-ignore-properties)
  16337. (org-refresh-category-properties))
  16338. (or (memq 'stats org-agenda-ignore-properties)
  16339. (org-refresh-stats-properties))
  16340. (or (memq 'effort org-agenda-ignore-properties)
  16341. (org-refresh-effort-properties))
  16342. (or (memq 'appt org-agenda-ignore-properties)
  16343. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16344. (setq org-todo-keywords-for-agenda
  16345. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16346. (setq org-done-keywords-for-agenda
  16347. (append org-done-keywords-for-agenda org-done-keywords))
  16348. (setq org-todo-keyword-alist-for-agenda
  16349. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16350. (setq org-tag-alist-for-agenda
  16351. (org--tag-add-to-alist
  16352. org-tag-alist-for-agenda
  16353. org-current-tag-alist))
  16354. ;; Merge current file's tag groups into global
  16355. ;; `org-tag-groups-alist-for-agenda'.
  16356. (when org-group-tags
  16357. (dolist (alist org-tag-groups-alist)
  16358. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  16359. (if old
  16360. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  16361. (push alist org-tag-groups-alist-for-agenda)))))
  16362. (with-silent-modifications
  16363. (save-excursion
  16364. (remove-text-properties (point-min) (point-max) pall)
  16365. (when org-agenda-skip-archived-trees
  16366. (goto-char (point-min))
  16367. (while (re-search-forward rea nil t)
  16368. (when (org-at-heading-p t)
  16369. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  16370. (goto-char (point-min))
  16371. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  16372. (while (re-search-forward re nil t)
  16373. (when (save-match-data (org-in-commented-heading-p t))
  16374. (add-text-properties
  16375. (match-beginning 0) (org-end-of-subtree t) pc)))))
  16376. (goto-char pos)))))
  16377. (setq org-todo-keywords-for-agenda
  16378. (org-uniquify org-todo-keywords-for-agenda))
  16379. (setq org-todo-keyword-alist-for-agenda
  16380. (org-uniquify org-todo-keyword-alist-for-agenda))))
  16381. ;;;; CDLaTeX minor mode
  16382. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  16383. "Keymap for the minor `org-cdlatex-mode'.")
  16384. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  16385. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  16386. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  16387. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  16388. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  16389. (defvar org-cdlatex-texmathp-advice-is-done nil
  16390. "Flag remembering if we have applied the advice to texmathp already.")
  16391. (define-minor-mode org-cdlatex-mode
  16392. "Toggle the minor `org-cdlatex-mode'.
  16393. This mode supports entering LaTeX environment and math in LaTeX fragments
  16394. in Org mode.
  16395. \\{org-cdlatex-mode-map}"
  16396. nil " OCDL" nil
  16397. (when org-cdlatex-mode
  16398. (require 'cdlatex)
  16399. (run-hooks 'cdlatex-mode-hook)
  16400. (cdlatex-compute-tables))
  16401. (unless org-cdlatex-texmathp-advice-is-done
  16402. (setq org-cdlatex-texmathp-advice-is-done t)
  16403. (defadvice texmathp (around org-math-always-on activate)
  16404. "Always return t in Org buffers.
  16405. This is because we want to insert math symbols without dollars even outside
  16406. the LaTeX math segments. If Org mode thinks that point is actually inside
  16407. an embedded LaTeX fragment, let `texmathp' do its job.
  16408. `\\[org-cdlatex-mode-map]'"
  16409. (interactive)
  16410. (let (p)
  16411. (cond
  16412. ((not (derived-mode-p 'org-mode)) ad-do-it)
  16413. ((eq this-command 'cdlatex-math-symbol)
  16414. (setq ad-return-value t
  16415. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  16416. (t
  16417. (let ((p (org-inside-LaTeX-fragment-p)))
  16418. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  16419. (setq ad-return-value t
  16420. texmathp-why '("Org mode embedded math" . 0))
  16421. (when p ad-do-it)))))))))
  16422. (defun turn-on-org-cdlatex ()
  16423. "Unconditionally turn on `org-cdlatex-mode'."
  16424. (org-cdlatex-mode 1))
  16425. (defun org-try-cdlatex-tab ()
  16426. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  16427. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  16428. - inside a LaTeX fragment, or
  16429. - after the first word in a line, where an abbreviation expansion could
  16430. insert a LaTeX environment."
  16431. (when org-cdlatex-mode
  16432. (cond
  16433. ;; Before any word on the line: No expansion possible.
  16434. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  16435. ;; Just after first word on the line: Expand it. Make sure it
  16436. ;; cannot happen on headlines, though.
  16437. ((save-excursion
  16438. (skip-chars-backward "a-zA-Z0-9*")
  16439. (skip-chars-backward " \t")
  16440. (and (bolp) (not (org-at-heading-p))))
  16441. (cdlatex-tab) t)
  16442. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  16443. (defun org-cdlatex-underscore-caret (&optional _arg)
  16444. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  16445. Revert to the normal definition outside of these fragments."
  16446. (interactive "P")
  16447. (if (org-inside-LaTeX-fragment-p)
  16448. (call-interactively 'cdlatex-sub-superscript)
  16449. (let (org-cdlatex-mode)
  16450. (call-interactively (key-binding (vector last-input-event))))))
  16451. (defun org-cdlatex-math-modify (&optional _arg)
  16452. "Execute `cdlatex-math-modify' in LaTeX fragments.
  16453. Revert to the normal definition outside of these fragments."
  16454. (interactive "P")
  16455. (if (org-inside-LaTeX-fragment-p)
  16456. (call-interactively 'cdlatex-math-modify)
  16457. (let (org-cdlatex-mode)
  16458. (call-interactively (key-binding (vector last-input-event))))))
  16459. (defun org-cdlatex-environment-indent (&optional environment item)
  16460. "Execute `cdlatex-environment' and indent the inserted environment.
  16461. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  16462. The inserted environment is indented to current indentation
  16463. unless point is at the beginning of the line, in which the
  16464. environment remains unintended."
  16465. (interactive)
  16466. ;; cdlatex-environment always return nil. Therefore, capture output
  16467. ;; first and determine if an environment was selected.
  16468. (let* ((beg (point-marker))
  16469. (end (copy-marker (point) t))
  16470. (inserted (progn
  16471. (ignore-errors (cdlatex-environment environment item))
  16472. (< beg end)))
  16473. ;; Figure out how many lines to move forward after the
  16474. ;; environment has been inserted.
  16475. (lines (when inserted
  16476. (save-excursion
  16477. (- (cl-loop while (< beg (point))
  16478. with x = 0
  16479. do (forward-line -1)
  16480. (cl-incf x)
  16481. finally return x)
  16482. (if (progn (goto-char beg)
  16483. (and (progn (skip-chars-forward " \t") (eolp))
  16484. (progn (skip-chars-backward " \t") (bolp))))
  16485. 1 0)))))
  16486. (env (org-trim (delete-and-extract-region beg end))))
  16487. (when inserted
  16488. ;; Get indentation of next line unless at column 0.
  16489. (let ((ind (if (bolp) 0
  16490. (save-excursion
  16491. (org-return-indent)
  16492. (prog1 (org-get-indentation)
  16493. (when (progn (skip-chars-forward " \t") (eolp))
  16494. (delete-region beg (point)))))))
  16495. (bol (progn (skip-chars-backward " \t") (bolp))))
  16496. ;; Insert a newline before environment unless at column zero
  16497. ;; to "escape" the current line. Insert a newline if
  16498. ;; something is one the same line as \end{ENVIRONMENT}.
  16499. (insert
  16500. (concat (unless bol "\n") env
  16501. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  16502. (unless (zerop ind)
  16503. (save-excursion
  16504. (goto-char beg)
  16505. (while (< (point) end)
  16506. (unless (eolp) (indent-line-to ind))
  16507. (forward-line))))
  16508. (goto-char beg)
  16509. (forward-line lines)
  16510. (indent-line-to ind)))
  16511. (set-marker beg nil)
  16512. (set-marker end nil)))
  16513. ;;;; LaTeX fragments
  16514. (defun org-inside-LaTeX-fragment-p ()
  16515. "Test if point is inside a LaTeX fragment.
  16516. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  16517. sequence appearing also before point.
  16518. Even though the matchers for math are configurable, this function assumes
  16519. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  16520. delimiters are skipped when they have been removed by customization.
  16521. The return value is nil, or a cons cell with the delimiter and the
  16522. position of this delimiter.
  16523. This function does a reasonably good job, but can locally be fooled by
  16524. for example currency specifications. For example it will assume being in
  16525. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  16526. fragments that are properly closed, but during editing, we have to live
  16527. with the uncertainty caused by missing closing delimiters. This function
  16528. looks only before point, not after."
  16529. (catch 'exit
  16530. (let ((pos (point))
  16531. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  16532. (lim (save-excursion (org-backward-paragraph) (point)))
  16533. dd-on str (start 0) m re)
  16534. (goto-char pos)
  16535. (when dodollar
  16536. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  16537. re (nth 1 (assoc "$" org-latex-regexps)))
  16538. (while (string-match re str start)
  16539. (cond
  16540. ((= (match-end 0) (length str))
  16541. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  16542. ((= (match-end 0) (- (length str) 5))
  16543. (throw 'exit nil))
  16544. (t (setq start (match-end 0))))))
  16545. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  16546. (goto-char pos)
  16547. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  16548. (and (match-beginning 2) (throw 'exit nil))
  16549. ;; count $$
  16550. (while (re-search-backward "\\$\\$" lim t)
  16551. (setq dd-on (not dd-on)))
  16552. (goto-char pos)
  16553. (when dd-on (cons "$$" m))))))
  16554. (defun org-inside-latex-macro-p ()
  16555. "Is point inside a LaTeX macro or its arguments?"
  16556. (save-match-data
  16557. (org-in-regexp
  16558. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  16559. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  16560. "Build an overlay between BEG and END using IMAGE file.
  16561. Argument IMAGETYPE is the extension of the displayed image,
  16562. as a string. It defaults to \"png\"."
  16563. (let ((ov (make-overlay beg end))
  16564. (imagetype (or (intern imagetype) 'png)))
  16565. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  16566. (overlay-put ov 'evaporate t)
  16567. (overlay-put ov
  16568. 'modification-hooks
  16569. (list (lambda (o _flag _beg _end &optional _l)
  16570. (delete-overlay o))))
  16571. (overlay-put ov
  16572. 'display
  16573. (list 'image :type imagetype :file image :ascent 'center))))
  16574. (defun org--list-latex-overlays (&optional beg end)
  16575. "List all Org LaTeX overlays in current buffer.
  16576. Limit to overlays between BEG and END when those are provided."
  16577. (cl-remove-if-not
  16578. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  16579. (overlays-in (or beg (point-min)) (or end (point-max)))))
  16580. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  16581. "Remove all overlays with LaTeX fragment images in current buffer.
  16582. When optional arguments BEG and END are non-nil, remove all
  16583. overlays between them instead. Return a non-nil value when some
  16584. overlays were removed, nil otherwise."
  16585. (let ((overlays (org--list-latex-overlays beg end)))
  16586. (mapc #'delete-overlay overlays)
  16587. overlays))
  16588. (defun org-toggle-latex-fragment (&optional arg)
  16589. "Preview the LaTeX fragment at point, or all locally or globally.
  16590. If the cursor is on a LaTeX fragment, create the image and overlay
  16591. it over the source code, if there is none. Remove it otherwise.
  16592. If there is no fragment at point, display all fragments in the
  16593. current section.
  16594. With prefix ARG, preview or clear image for all fragments in the
  16595. current subtree or in the whole buffer when used before the first
  16596. headline. With a prefix ARG `\\[universal-argument] \
  16597. \\[universal-argument]' preview or clear images
  16598. for all fragments in the buffer."
  16599. (interactive "P")
  16600. (when (display-graphic-p)
  16601. (catch 'exit
  16602. (save-excursion
  16603. (let (beg end msg)
  16604. (cond
  16605. ((or (equal arg '(16))
  16606. (and (equal arg '(4))
  16607. (org-with-limited-levels (org-before-first-heading-p))))
  16608. (if (org-remove-latex-fragment-image-overlays)
  16609. (progn (message "LaTeX fragments images removed from buffer")
  16610. (throw 'exit nil))
  16611. (setq msg "Creating images for buffer...")))
  16612. ((equal arg '(4))
  16613. (org-with-limited-levels (org-back-to-heading t))
  16614. (setq beg (point))
  16615. (setq end (progn (org-end-of-subtree t) (point)))
  16616. (if (org-remove-latex-fragment-image-overlays beg end)
  16617. (progn
  16618. (message "LaTeX fragment images removed from subtree")
  16619. (throw 'exit nil))
  16620. (setq msg "Creating images for subtree...")))
  16621. ((let ((datum (org-element-context)))
  16622. (when (memq (org-element-type datum)
  16623. '(latex-environment latex-fragment))
  16624. (setq beg (org-element-property :begin datum))
  16625. (setq end (org-element-property :end datum))
  16626. (if (org-remove-latex-fragment-image-overlays beg end)
  16627. (progn (message "LaTeX fragment image removed")
  16628. (throw 'exit nil))
  16629. (setq msg "Creating image...")))))
  16630. (t
  16631. (org-with-limited-levels
  16632. (setq beg (if (org-at-heading-p) (line-beginning-position)
  16633. (outline-previous-heading)
  16634. (point)))
  16635. (setq end (progn (outline-next-heading) (point)))
  16636. (if (org-remove-latex-fragment-image-overlays beg end)
  16637. (progn
  16638. (message "LaTeX fragment images removed from section")
  16639. (throw 'exit nil))
  16640. (setq msg "Creating images for section...")))))
  16641. (let ((file (buffer-file-name (buffer-base-buffer))))
  16642. (org-format-latex
  16643. (concat org-preview-latex-image-directory "org-ltximg")
  16644. beg end
  16645. ;; Emacs cannot overlay images from remote hosts. Create
  16646. ;; it in `temporary-file-directory' instead.
  16647. (if (or (not file) (file-remote-p file))
  16648. temporary-file-directory
  16649. default-directory)
  16650. 'overlays msg 'forbuffer org-preview-latex-default-process))
  16651. (message (concat msg "done")))))))
  16652. (defun org-format-latex
  16653. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  16654. "Replace LaTeX fragments with links to an image.
  16655. The function takes care of creating the replacement image.
  16656. Only consider fragments between BEG and END when those are
  16657. provided.
  16658. When optional argument OVERLAYS is non-nil, display the image on
  16659. top of the fragment instead of replacing it.
  16660. PROCESSING-TYPE is the conversion method to use, as a symbol.
  16661. Some of the options can be changed using the variable
  16662. `org-format-latex-options', which see."
  16663. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  16664. (unless (eq processing-type 'verbatim)
  16665. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  16666. (cnt 0)
  16667. checkdir-flag)
  16668. (goto-char (or beg (point-min)))
  16669. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  16670. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  16671. (overlay-recenter (or end (point-max))))
  16672. (while (re-search-forward math-regexp end t)
  16673. (unless (and overlays
  16674. (eq (get-char-property (point) 'org-overlay-type)
  16675. 'org-latex-overlay))
  16676. (let* ((context (org-element-context))
  16677. (type (org-element-type context)))
  16678. (when (memq type '(latex-environment latex-fragment))
  16679. (let ((block-type (eq type 'latex-environment))
  16680. (value (org-element-property :value context))
  16681. (beg (org-element-property :begin context))
  16682. (end (save-excursion
  16683. (goto-char (org-element-property :end context))
  16684. (skip-chars-backward " \r\t\n")
  16685. (point))))
  16686. (cond
  16687. ((eq processing-type 'mathjax)
  16688. ;; Prepare for MathJax processing.
  16689. (if (not (string-match "\\`\\$\\$?" value))
  16690. (goto-char end)
  16691. (delete-region beg end)
  16692. (if (string= (match-string 0 value) "$$")
  16693. (insert "\\[" (substring value 2 -2) "\\]")
  16694. (insert "\\(" (substring value 1 -1) "\\)"))))
  16695. ((assq processing-type org-preview-latex-process-alist)
  16696. ;; Process to an image.
  16697. (cl-incf cnt)
  16698. (goto-char beg)
  16699. (let* ((processing-info
  16700. (cdr (assq processing-type org-preview-latex-process-alist)))
  16701. (face (face-at-point))
  16702. ;; Get the colors from the face at point.
  16703. (fg
  16704. (let ((color (plist-get org-format-latex-options
  16705. :foreground)))
  16706. (if (and forbuffer (eq color 'auto))
  16707. (face-attribute face :foreground nil 'default)
  16708. color)))
  16709. (bg
  16710. (let ((color (plist-get org-format-latex-options
  16711. :background)))
  16712. (if (and forbuffer (eq color 'auto))
  16713. (face-attribute face :background nil 'default)
  16714. color)))
  16715. (hash (sha1 (prin1-to-string
  16716. (list org-format-latex-header
  16717. org-latex-default-packages-alist
  16718. org-latex-packages-alist
  16719. org-format-latex-options
  16720. forbuffer value fg bg))))
  16721. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  16722. (absprefix (expand-file-name prefix dir))
  16723. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  16724. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  16725. (sep (and block-type "\n\n"))
  16726. (link (concat sep "[[file:" linkfile "]]" sep))
  16727. (options
  16728. (org-combine-plists
  16729. org-format-latex-options
  16730. `(:foreground ,fg :background ,bg))))
  16731. (when msg (message msg cnt))
  16732. (unless checkdir-flag ; Ensure the directory exists.
  16733. (setq checkdir-flag t)
  16734. (let ((todir (file-name-directory absprefix)))
  16735. (unless (file-directory-p todir)
  16736. (make-directory todir t))))
  16737. (unless (file-exists-p movefile)
  16738. (org-create-formula-image
  16739. value movefile options forbuffer processing-type))
  16740. (if overlays
  16741. (progn
  16742. (dolist (o (overlays-in beg end))
  16743. (when (eq (overlay-get o 'org-overlay-type)
  16744. 'org-latex-overlay)
  16745. (delete-overlay o)))
  16746. (org--format-latex-make-overlay beg end movefile imagetype)
  16747. (goto-char end))
  16748. (delete-region beg end)
  16749. (insert
  16750. (org-add-props link
  16751. (list 'org-latex-src
  16752. (replace-regexp-in-string "\"" "" value)
  16753. 'org-latex-src-embed-type
  16754. (if block-type 'paragraph 'character)))))))
  16755. ((eq processing-type 'mathml)
  16756. ;; Process to MathML.
  16757. (unless (org-format-latex-mathml-available-p)
  16758. (user-error "LaTeX to MathML converter not configured"))
  16759. (cl-incf cnt)
  16760. (when msg (message msg cnt))
  16761. (goto-char beg)
  16762. (delete-region beg end)
  16763. (insert (org-format-latex-as-mathml
  16764. value block-type prefix dir)))
  16765. (t
  16766. (error "Unknown conversion process %s for LaTeX fragments"
  16767. processing-type)))))))))))
  16768. (defun org-create-math-formula (latex-frag &optional mathml-file)
  16769. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  16770. Use `org-latex-to-mathml-convert-command'. If the conversion is
  16771. sucessful, return the portion between \"<math...> </math>\"
  16772. elements otherwise return nil. When MATHML-FILE is specified,
  16773. write the results in to that file. When invoked as an
  16774. interactive command, prompt for LATEX-FRAG, with initial value
  16775. set to the current active region and echo the results for user
  16776. inspection."
  16777. (interactive (list (let ((frag (when (org-region-active-p)
  16778. (buffer-substring-no-properties
  16779. (region-beginning) (region-end)))))
  16780. (read-string "LaTeX Fragment: " frag nil frag))))
  16781. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  16782. (let* ((tmp-in-file
  16783. (let ((file (file-relative-name
  16784. (make-temp-name (expand-file-name "ltxmathml-in")))))
  16785. (write-region latex-frag nil file)
  16786. file))
  16787. (tmp-out-file (file-relative-name
  16788. (make-temp-name (expand-file-name "ltxmathml-out"))))
  16789. (cmd (format-spec
  16790. org-latex-to-mathml-convert-command
  16791. `((?j . ,(and org-latex-to-mathml-jar-file
  16792. (shell-quote-argument
  16793. (expand-file-name
  16794. org-latex-to-mathml-jar-file))))
  16795. (?I . ,(shell-quote-argument tmp-in-file))
  16796. (?i . ,latex-frag)
  16797. (?o . ,(shell-quote-argument tmp-out-file)))))
  16798. mathml shell-command-output)
  16799. (when (called-interactively-p 'any)
  16800. (unless (org-format-latex-mathml-available-p)
  16801. (user-error "LaTeX to MathML converter not configured")))
  16802. (message "Running %s" cmd)
  16803. (setq shell-command-output (shell-command-to-string cmd))
  16804. (setq mathml
  16805. (when (file-readable-p tmp-out-file)
  16806. (with-current-buffer (find-file-noselect tmp-out-file t)
  16807. (goto-char (point-min))
  16808. (when (re-search-forward
  16809. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  16810. (regexp-quote
  16811. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  16812. nil t)
  16813. (prog1 (match-string 0) (kill-buffer))))))
  16814. (cond
  16815. (mathml
  16816. (setq mathml
  16817. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  16818. (when mathml-file
  16819. (write-region mathml nil mathml-file))
  16820. (when (called-interactively-p 'any)
  16821. (message mathml)))
  16822. ((message "LaTeX to MathML conversion failed")
  16823. (message shell-command-output)))
  16824. (delete-file tmp-in-file)
  16825. (when (file-exists-p tmp-out-file)
  16826. (delete-file tmp-out-file))
  16827. mathml))
  16828. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  16829. prefix &optional dir)
  16830. "Use `org-create-math-formula' but check local cache first."
  16831. (let* ((absprefix (expand-file-name prefix dir))
  16832. (print-length nil) (print-level nil)
  16833. (formula-id (concat
  16834. "formula-"
  16835. (sha1
  16836. (prin1-to-string
  16837. (list latex-frag
  16838. org-latex-to-mathml-convert-command)))))
  16839. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  16840. (formula-cache-dir (file-name-directory formula-cache)))
  16841. (unless (file-directory-p formula-cache-dir)
  16842. (make-directory formula-cache-dir t))
  16843. (unless (file-exists-p formula-cache)
  16844. (org-create-math-formula latex-frag formula-cache))
  16845. (if (file-exists-p formula-cache)
  16846. ;; Successful conversion. Return the link to MathML file.
  16847. (org-add-props
  16848. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  16849. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  16850. 'org-latex-src-embed-type (if latex-frag-type
  16851. 'paragraph 'character)))
  16852. ;; Failed conversion. Return the LaTeX fragment verbatim
  16853. latex-frag)))
  16854. (defun org--get-display-dpi ()
  16855. "Get the DPI of the display.
  16856. The function assumes that the display has the same pixel width in
  16857. the horizontal and vertical directions."
  16858. (if (display-graphic-p)
  16859. (round (/ (display-pixel-height)
  16860. (/ (display-mm-height) 25.4)))
  16861. (error "Attempt to calculate the dpi of a non-graphic display")))
  16862. (defun org-create-formula-image
  16863. (string tofile options buffer &optional processing-type)
  16864. "Create an image from LaTeX source using external processes.
  16865. The LaTeX STRING is saved to a temporary LaTeX file, then
  16866. converted to an image file by process PROCESSING-TYPE defined in
  16867. `org-preview-latex-process-alist'. A nil value defaults to
  16868. `org-preview-latex-default-process'.
  16869. The generated image file is eventually moved to TOFILE.
  16870. The OPTIONS argument controls the size, foreground color and
  16871. background color of the generated image.
  16872. When BUFFER non-nil, this function is used for LaTeX previewing.
  16873. Otherwise, it is used to deal with LaTeX snippets showed in
  16874. a HTML file."
  16875. (let* ((processing-type (or processing-type
  16876. org-preview-latex-default-process))
  16877. (processing-info
  16878. (cdr (assq processing-type org-preview-latex-process-alist)))
  16879. (programs (plist-get processing-info :programs))
  16880. (error-message (or (plist-get processing-info :message) ""))
  16881. (use-xcolor (plist-get processing-info :use-xcolor))
  16882. (image-input-type (plist-get processing-info :image-input-type))
  16883. (image-output-type (plist-get processing-info :image-output-type))
  16884. (post-clean (or (plist-get processing-info :post-clean)
  16885. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  16886. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  16887. (latex-header
  16888. (or (plist-get processing-info :latex-header)
  16889. (org-latex-make-preamble
  16890. (org-export-get-environment (org-export-get-backend 'latex))
  16891. org-format-latex-header
  16892. 'snippet)))
  16893. (latex-compiler (plist-get processing-info :latex-compiler))
  16894. (image-converter (plist-get processing-info :image-converter))
  16895. (tmpdir temporary-file-directory)
  16896. (texfilebase (make-temp-name
  16897. (expand-file-name "orgtex" tmpdir)))
  16898. (texfile (concat texfilebase ".tex"))
  16899. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  16900. '(1.0 . 1.0)))
  16901. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  16902. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  16903. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  16904. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  16905. "Black"))
  16906. (bg (or (plist-get options (if buffer :background :html-background))
  16907. "Transparent"))
  16908. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  16909. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  16910. (dolist (program programs)
  16911. (org-check-external-command program error-message))
  16912. (if use-xcolor
  16913. (progn (if (eq fg 'default)
  16914. (setq fg (org-latex-color :foreground))
  16915. (setq fg (org-latex-color-format fg)))
  16916. (if (eq bg 'default)
  16917. (setq bg (org-latex-color :background))
  16918. (setq bg (org-latex-color-format
  16919. (if (string= bg "Transparent") "white" bg))))
  16920. (with-temp-file texfile
  16921. (insert latex-header)
  16922. (insert "\n\\begin{document}\n"
  16923. "\\definecolor{fg}{rgb}{" fg "}\n"
  16924. "\\definecolor{bg}{rgb}{" bg "}\n"
  16925. "\n\\pagecolor{bg}\n"
  16926. "\n{\\color{fg}\n"
  16927. string
  16928. "\n}\n"
  16929. "\n\\end{document}\n")))
  16930. (if (eq fg 'default)
  16931. (setq fg (org-dvipng-color :foreground))
  16932. (unless (string= fg "Transparent")
  16933. (setq fg (org-dvipng-color-format fg))))
  16934. (if (eq bg 'default)
  16935. (setq bg (org-dvipng-color :background))
  16936. (unless (string= bg "Transparent")
  16937. (setq bg (org-dvipng-color-format bg))))
  16938. (with-temp-file texfile
  16939. (insert latex-header)
  16940. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  16941. (let* ((err-msg (format "Please adjust `%s' part of \
  16942. `org-preview-latex-process-alist'."
  16943. processing-type))
  16944. (image-input-file
  16945. (org-compile-file
  16946. texfile latex-compiler image-input-type err-msg log-buf))
  16947. (image-output-file
  16948. (org-compile-file
  16949. image-input-file image-converter image-output-type err-msg log-buf
  16950. `((?F . ,(shell-quote-argument fg))
  16951. (?B . ,(shell-quote-argument bg))
  16952. (?D . ,(shell-quote-argument (format "%s" dpi)))
  16953. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  16954. (copy-file image-output-file tofile 'replace)
  16955. (dolist (e post-clean)
  16956. (when (file-exists-p (concat texfilebase e))
  16957. (delete-file (concat texfilebase e))))
  16958. image-output-file)))
  16959. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  16960. "Fill a LaTeX header template TPL.
  16961. In the template, the following place holders will be recognized:
  16962. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  16963. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  16964. [PACKAGES] \\usepackage statements for PKG
  16965. [NO-PACKAGES] do not include PKG
  16966. [EXTRA] the string EXTRA
  16967. [NO-EXTRA] do not include EXTRA
  16968. For backward compatibility, if both the positive and the negative place
  16969. holder is missing, the positive one (without the \"NO-\") will be
  16970. assumed to be present at the end of the template.
  16971. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  16972. EXTRA is a string.
  16973. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  16974. (let (rpl (end ""))
  16975. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  16976. (setq rpl (if (or (match-end 1) (not def-pkg))
  16977. "" (org-latex-packages-to-string def-pkg snippets-p t))
  16978. tpl (replace-match rpl t t tpl))
  16979. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  16980. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  16981. (setq rpl (if (or (match-end 1) (not pkg))
  16982. "" (org-latex-packages-to-string pkg snippets-p t))
  16983. tpl (replace-match rpl t t tpl))
  16984. (when pkg (setq end
  16985. (concat end "\n"
  16986. (org-latex-packages-to-string pkg snippets-p)))))
  16987. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  16988. (setq rpl (if (or (match-end 1) (not extra))
  16989. "" (concat extra "\n"))
  16990. tpl (replace-match rpl t t tpl))
  16991. (when (and extra (string-match "\\S-" extra))
  16992. (setq end (concat end "\n" extra))))
  16993. (if (string-match "\\S-" end)
  16994. (concat tpl "\n" end)
  16995. tpl)))
  16996. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  16997. "Turn an alist of packages into a string with the \\usepackage macros."
  16998. (setq pkg (mapconcat (lambda(p)
  16999. (cond
  17000. ((stringp p) p)
  17001. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17002. (format "%% Package %s omitted" (cadr p)))
  17003. ((equal "" (car p))
  17004. (format "\\usepackage{%s}" (cadr p)))
  17005. (t
  17006. (format "\\usepackage[%s]{%s}"
  17007. (car p) (cadr p)))))
  17008. pkg
  17009. "\n"))
  17010. (if newline (concat pkg "\n") pkg))
  17011. (defun org-dvipng-color (attr)
  17012. "Return a RGB color specification for dvipng."
  17013. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17014. (defun org-dvipng-color-format (color-name)
  17015. "Convert COLOR-NAME to a RGB color value for dvipng."
  17016. (apply #'format "rgb %s %s %s"
  17017. (mapcar 'org-normalize-color
  17018. (color-values color-name))))
  17019. (defun org-latex-color (attr)
  17020. "Return a RGB color for the LaTeX color package."
  17021. (org-latex-color-format (face-attribute 'default attr nil)))
  17022. (defun org-latex-color-format (color-name)
  17023. "Convert COLOR-NAME to a RGB color value."
  17024. (apply #'format "%s,%s,%s"
  17025. (mapcar 'org-normalize-color
  17026. (color-values color-name))))
  17027. (defun org-normalize-color (value)
  17028. "Return string to be used as color value for an RGB component."
  17029. (format "%g" (/ value 65535.0)))
  17030. ;; Image display
  17031. (defvar-local org-inline-image-overlays nil)
  17032. (defun org-toggle-inline-images (&optional include-linked)
  17033. "Toggle the display of inline images.
  17034. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17035. (interactive "P")
  17036. (if org-inline-image-overlays
  17037. (progn
  17038. (org-remove-inline-images)
  17039. (when (called-interactively-p 'interactive)
  17040. (message "Inline image display turned off")))
  17041. (org-display-inline-images include-linked)
  17042. (when (called-interactively-p 'interactive)
  17043. (message (if org-inline-image-overlays
  17044. (format "%d images displayed inline"
  17045. (length org-inline-image-overlays))
  17046. "No images to display inline")))))
  17047. (defun org-redisplay-inline-images ()
  17048. "Refresh the display of inline images."
  17049. (interactive)
  17050. (if (not org-inline-image-overlays)
  17051. (org-toggle-inline-images)
  17052. (org-toggle-inline-images)
  17053. (org-toggle-inline-images)))
  17054. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17055. "Display inline images.
  17056. An inline image is a link which follows either of these
  17057. conventions:
  17058. 1. Its path is a file with an extension matching return value
  17059. from `image-file-name-regexp' and it has no contents.
  17060. 2. Its description consists in a single link of the previous
  17061. type.
  17062. When optional argument INCLUDE-LINKED is non-nil, also links with
  17063. a text description part will be inlined. This can be nice for
  17064. a quick look at those images, but it does not reflect what
  17065. exported files will look like.
  17066. When optional argument REFRESH is non-nil, refresh existing
  17067. images between BEG and END. This will create new image displays
  17068. only if necessary. BEG and END default to the buffer
  17069. boundaries."
  17070. (interactive "P")
  17071. (when (display-graphic-p)
  17072. (unless refresh
  17073. (org-remove-inline-images)
  17074. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17075. (org-with-wide-buffer
  17076. (goto-char (or beg (point-min)))
  17077. (let* ((case-fold-search t)
  17078. (file-extension-re (image-file-name-regexp))
  17079. (link-abbrevs (mapcar #'car
  17080. (append org-link-abbrev-alist-local
  17081. org-link-abbrev-alist)))
  17082. ;; Check absolute, relative file names and explicit
  17083. ;; "file:" links. Also check link abbreviations since
  17084. ;; some might expand to "file" links.
  17085. (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
  17086. (if (not link-abbrevs) ""
  17087. (format "\\|\\(?:%s:\\)"
  17088. (regexp-opt link-abbrevs))))))
  17089. (while (re-search-forward file-types-re end t)
  17090. (let ((link (save-match-data (org-element-context))))
  17091. ;; Check if we're at an inline image, i.e., an image file
  17092. ;; link without a description (unless INCLUDE-LINKED is
  17093. ;; non-nil).
  17094. (when (and (equal "file" (org-element-property :type link))
  17095. (or include-linked
  17096. (null (org-element-contents link)))
  17097. (string-match-p file-extension-re
  17098. (org-element-property :path link)))
  17099. (let ((file (expand-file-name
  17100. (org-link-unescape
  17101. (org-element-property :path link)))))
  17102. (when (file-exists-p file)
  17103. (let ((width
  17104. ;; Apply `org-image-actual-width' specifications.
  17105. (cond
  17106. ((not (image-type-available-p 'imagemagick)) nil)
  17107. ((eq org-image-actual-width t) nil)
  17108. ((listp org-image-actual-width)
  17109. (or
  17110. ;; First try to find a width among
  17111. ;; attributes associated to the paragraph
  17112. ;; containing link.
  17113. (let ((paragraph
  17114. (let ((e link))
  17115. (while (and (setq e (org-element-property
  17116. :parent e))
  17117. (not (eq (org-element-type e)
  17118. 'paragraph))))
  17119. e)))
  17120. (when paragraph
  17121. (save-excursion
  17122. (goto-char (org-element-property :begin paragraph))
  17123. (when
  17124. (re-search-forward
  17125. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17126. (org-element-property
  17127. :post-affiliated paragraph)
  17128. t)
  17129. (string-to-number (match-string 1))))))
  17130. ;; Otherwise, fall-back to provided number.
  17131. (car org-image-actual-width)))
  17132. ((numberp org-image-actual-width)
  17133. org-image-actual-width)))
  17134. (old (get-char-property-and-overlay
  17135. (org-element-property :begin link)
  17136. 'org-image-overlay)))
  17137. (if (and (car-safe old) refresh)
  17138. (image-refresh (overlay-get (cdr old) 'display))
  17139. (let ((image (create-image file
  17140. (and width 'imagemagick)
  17141. nil
  17142. :width width)))
  17143. (when image
  17144. (let ((ov (make-overlay
  17145. (org-element-property :begin link)
  17146. (progn
  17147. (goto-char
  17148. (org-element-property :end link))
  17149. (skip-chars-backward " \t")
  17150. (point)))))
  17151. (overlay-put ov 'display image)
  17152. (overlay-put ov 'face 'default)
  17153. (overlay-put ov 'org-image-overlay t)
  17154. (overlay-put
  17155. ov 'modification-hooks
  17156. (list 'org-display-inline-remove-overlay))
  17157. (push ov org-inline-image-overlays)))))))))))))))
  17158. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17159. "Remove inline-display overlay if a corresponding region is modified."
  17160. (let ((inhibit-modification-hooks t))
  17161. (when (and ov after)
  17162. (delete ov org-inline-image-overlays)
  17163. (delete-overlay ov))))
  17164. (defun org-remove-inline-images ()
  17165. "Remove inline display of images."
  17166. (interactive)
  17167. (mapc #'delete-overlay org-inline-image-overlays)
  17168. (setq org-inline-image-overlays nil))
  17169. ;;; Key bindings
  17170. (defun org-remap (map &rest commands)
  17171. "In MAP, remap the functions given in COMMANDS.
  17172. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  17173. (let (new old)
  17174. (while commands
  17175. (setq old (pop commands) new (pop commands))
  17176. (org-defkey map (vector 'remap old) new))))
  17177. ;;;; Outline functions that can be remapped in Org
  17178. (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
  17179. (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
  17180. (define-key org-mode-map [remap outline-forward-same-level]
  17181. #'org-forward-heading-same-level)
  17182. (define-key org-mode-map [remap outline-backward-same-level]
  17183. #'org-backward-heading-same-level)
  17184. (define-key org-mode-map [remap outline-show-branches]
  17185. #'org-kill-note-or-show-branches)
  17186. (define-key org-mode-map [remap outline-promote] #'org-promote-subtree)
  17187. (define-key org-mode-map [remap outline-demote] #'org-demote-subtree)
  17188. (define-key org-mode-map [remap outline-insert-heading] #'org-ctrl-c-ret)
  17189. (define-key org-mode-map [remap outline-next-visible-heading]
  17190. #'org-next-visible-heading)
  17191. (define-key org-mode-map [remap outline-previous-visible-heading]
  17192. #'org-previous-visible-heading)
  17193. (define-key org-mode-map [remap show-children] #'org-show-children)
  17194. ;;;; Make `C-c C-x' a prefix key
  17195. (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
  17196. ;;;; TAB key with modifiers
  17197. (org-defkey org-mode-map (kbd "C-i") #'org-cycle)
  17198. (org-defkey org-mode-map (kbd "<tab>") #'org-cycle)
  17199. (org-defkey org-mode-map (kbd "C-<tab>") #'org-force-cycle-archived)
  17200. (org-defkey org-mode-map (kbd "M-<tab>") #'pcomplete)
  17201. (org-defkey org-mode-map (kbd "ESC <tab>") #'pcomplete)
  17202. (org-defkey org-mode-map (kbd "<S-iso-leftab>") #'org-shifttab)
  17203. (org-defkey org-mode-map (kbd "S-<tab>") #'org-shifttab)
  17204. (define-key org-mode-map (kbd "<backtab>") #'org-shifttab)
  17205. ;;;; RET key with modifiers
  17206. (org-defkey org-mode-map (kbd "S-<return>") #'org-table-copy-down)
  17207. (org-defkey org-mode-map (kbd "M-S-<return>") #'org-insert-todo-heading)
  17208. (org-defkey org-mode-map (kbd "ESC S-<return>") #'org-insert-todo-heading)
  17209. (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
  17210. (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
  17211. ;;;; Cursor keys with modifiers
  17212. (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
  17213. (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
  17214. (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
  17215. (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
  17216. (org-defkey org-mode-map (kbd "ESC <up>") #'org-metaup)
  17217. (org-defkey org-mode-map (kbd "M-<down>") #'org-metadown)
  17218. (org-defkey org-mode-map (kbd "ESC <down>") #'org-metadown)
  17219. (org-defkey org-mode-map (kbd "C-M-S-<right>") #'org-increase-number-at-point)
  17220. (org-defkey org-mode-map (kbd "C-M-S-<left>") #'org-decrease-number-at-point)
  17221. (org-defkey org-mode-map (kbd "M-S-<left>") #'org-shiftmetaleft)
  17222. (org-defkey org-mode-map (kbd "ESC S-<left>") #'org-shiftmetaleft)
  17223. (org-defkey org-mode-map (kbd "M-S-<right>") #'org-shiftmetaright)
  17224. (org-defkey org-mode-map (kbd "ESC S-<right>") #'org-shiftmetaright)
  17225. (org-defkey org-mode-map (kbd "M-S-<up>") #'org-shiftmetaup)
  17226. (org-defkey org-mode-map (kbd "ESC S-<up>") #'org-shiftmetaup)
  17227. (org-defkey org-mode-map (kbd "M-S-<down>") #'org-shiftmetadown)
  17228. (org-defkey org-mode-map (kbd "ESC S-<down>") #'org-shiftmetadown)
  17229. (org-defkey org-mode-map (kbd "S-<up>") #'org-shiftup)
  17230. (org-defkey org-mode-map (kbd "S-<down>") #'org-shiftdown)
  17231. (org-defkey org-mode-map (kbd "S-<left>") #'org-shiftleft)
  17232. (org-defkey org-mode-map (kbd "S-<right>") #'org-shiftright)
  17233. (org-defkey org-mode-map (kbd "C-S-<right>") #'org-shiftcontrolright)
  17234. (org-defkey org-mode-map (kbd "C-S-<left>") #'org-shiftcontrolleft)
  17235. (org-defkey org-mode-map (kbd "C-S-<up>") #'org-shiftcontrolup)
  17236. (org-defkey org-mode-map (kbd "C-S-<down>") #'org-shiftcontroldown)
  17237. ;;;; Babel keys
  17238. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  17239. (pcase-dolist (`(,key . ,def) org-babel-key-bindings)
  17240. (define-key org-babel-map key def))
  17241. ;;;; Extra keys for TTY access.
  17242. ;; We only set them when really needed because otherwise the
  17243. ;; menus don't show the simple keys
  17244. (when (or org-use-extra-keys (not window-system))
  17245. (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
  17246. (org-defkey org-mode-map (kbd "C-c C-x m") #'org-meta-return)
  17247. (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
  17248. (org-defkey org-mode-map (kbd "C-c C-x RET") #'org-meta-return)
  17249. (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
  17250. (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
  17251. (org-defkey org-mode-map (kbd "C-c C-x l") #'org-metaleft)
  17252. (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
  17253. (org-defkey org-mode-map (kbd "C-c C-x r") #'org-metaright)
  17254. (org-defkey org-mode-map (kbd "C-c C-x u") #'org-metaup)
  17255. (org-defkey org-mode-map (kbd "C-c C-x d") #'org-metadown)
  17256. (org-defkey org-mode-map (kbd "C-c C-x L") #'org-shiftmetaleft)
  17257. (org-defkey org-mode-map (kbd "C-c C-x R") #'org-shiftmetaright)
  17258. (org-defkey org-mode-map (kbd "C-c C-x U") #'org-shiftmetaup)
  17259. (org-defkey org-mode-map (kbd "C-c C-x D") #'org-shiftmetadown)
  17260. (org-defkey org-mode-map (kbd "C-c <up>") #'org-shiftup)
  17261. (org-defkey org-mode-map (kbd "C-c <down>") #'org-shiftdown)
  17262. (org-defkey org-mode-map (kbd "C-c <left>") #'org-shiftleft)
  17263. (org-defkey org-mode-map (kbd "C-c <right>") #'org-shiftright)
  17264. (org-defkey org-mode-map (kbd "C-c C-x <right>") #'org-shiftcontrolright)
  17265. (org-defkey org-mode-map (kbd "C-c C-x <left>") #'org-shiftcontrolleft))
  17266. ;;;; Narrow map
  17267. (org-defkey narrow-map "s" #'org-narrow-to-subtree)
  17268. (org-defkey narrow-map "b" #'org-narrow-to-block)
  17269. (org-defkey narrow-map "e" #'org-narrow-to-element)
  17270. ;;;; Remap usual Emacs bindings
  17271. (org-remap org-mode-map
  17272. 'self-insert-command 'org-self-insert-command
  17273. 'delete-char 'org-delete-char
  17274. 'delete-backward-char 'org-delete-backward-char
  17275. 'kill-line 'org-kill-line
  17276. 'open-line 'org-open-line
  17277. 'yank 'org-yank
  17278. 'comment-dwim 'org-comment-dwim
  17279. 'move-beginning-of-line 'org-beginning-of-line
  17280. 'move-end-of-line 'org-end-of-line
  17281. 'forward-paragraph 'org-forward-paragraph
  17282. 'backward-paragraph 'org-backward-paragraph
  17283. 'backward-sentence 'org-backward-sentence
  17284. 'forward-sentence 'org-forward-sentence
  17285. 'fill-paragraph 'org-fill-paragraph
  17286. 'delete-indentation 'org-delete-indentation
  17287. 'transpose-words 'org-transpose-words)
  17288. ;;;; All the other keys
  17289. (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
  17290. (org-defkey org-mode-map (kbd "C-c C-a") #'org-show-all)
  17291. (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
  17292. (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
  17293. (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
  17294. (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
  17295. (org-defkey org-mode-map (kbd "M-{") #'org-backward-element)
  17296. (org-defkey org-mode-map (kbd "ESC {") #'org-backward-element)
  17297. (org-defkey org-mode-map (kbd "C-c C-^") #'org-up-element)
  17298. (org-defkey org-mode-map (kbd "C-c C-_") #'org-down-element)
  17299. (org-defkey org-mode-map (kbd "C-c C-f") #'org-forward-heading-same-level)
  17300. (org-defkey org-mode-map (kbd "C-c C-b") #'org-backward-heading-same-level)
  17301. (org-defkey org-mode-map (kbd "C-c M-f") #'org-next-block)
  17302. (org-defkey org-mode-map (kbd "C-c M-b") #'org-previous-block)
  17303. (org-defkey org-mode-map (kbd "C-c $") #'org-archive-subtree)
  17304. (org-defkey org-mode-map (kbd "C-c C-x C-s") #'org-archive-subtree)
  17305. (org-defkey org-mode-map (kbd "C-c C-x C-a") #'org-archive-subtree-default)
  17306. (org-defkey org-mode-map (kbd "C-c C-x d") #'org-insert-drawer)
  17307. (org-defkey org-mode-map (kbd "C-c C-x a") #'org-toggle-archive-tag)
  17308. (org-defkey org-mode-map (kbd "C-c C-x A") #'org-archive-to-archive-sibling)
  17309. (org-defkey org-mode-map (kbd "C-c C-x b") #'org-tree-to-indirect-buffer)
  17310. (org-defkey org-mode-map (kbd "C-c C-x q") #'org-toggle-tags-groups)
  17311. (org-defkey org-mode-map (kbd "C-c C-j") #'org-goto)
  17312. (org-defkey org-mode-map (kbd "C-c C-t") #'org-todo)
  17313. (org-defkey org-mode-map (kbd "C-c C-q") #'org-set-tags-command)
  17314. (org-defkey org-mode-map (kbd "C-c C-s") #'org-schedule)
  17315. (org-defkey org-mode-map (kbd "C-c C-d") #'org-deadline)
  17316. (org-defkey org-mode-map (kbd "C-c ;") #'org-toggle-comment)
  17317. (org-defkey org-mode-map (kbd "C-c C-w") #'org-refile)
  17318. (org-defkey org-mode-map (kbd "C-c M-w") #'org-copy)
  17319. (org-defkey org-mode-map (kbd "C-c /") #'org-sparse-tree) ;minor-mode reserved
  17320. (org-defkey org-mode-map (kbd "C-c \\") #'org-match-sparse-tree) ;minor-mode r.
  17321. (org-defkey org-mode-map (kbd "C-c RET") #'org-ctrl-c-ret)
  17322. (org-defkey org-mode-map (kbd "C-c C-x c") #'org-clone-subtree-with-time-shift)
  17323. (org-defkey org-mode-map (kbd "C-c C-x v") #'org-copy-visible)
  17324. (org-defkey org-mode-map (kbd "C-<return>") #'org-insert-heading-respect-content)
  17325. (org-defkey org-mode-map (kbd "C-S-<return>") #'org-insert-todo-heading-respect-content)
  17326. (org-defkey org-mode-map (kbd "C-c C-x C-n") #'org-next-link)
  17327. (org-defkey org-mode-map (kbd "C-c C-x C-p") #'org-previous-link)
  17328. (org-defkey org-mode-map (kbd "C-c C-l") #'org-insert-link)
  17329. (org-defkey org-mode-map (kbd "C-c M-l") #'org-insert-last-stored-link)
  17330. (org-defkey org-mode-map (kbd "C-c C-M-l") #'org-insert-all-links)
  17331. (org-defkey org-mode-map (kbd "C-c C-o") #'org-open-at-point)
  17332. (org-defkey org-mode-map (kbd "C-c %") #'org-mark-ring-push)
  17333. (org-defkey org-mode-map (kbd "C-c &") #'org-mark-ring-goto)
  17334. (org-defkey org-mode-map (kbd "C-c C-z") #'org-add-note) ;alternative binding
  17335. (org-defkey org-mode-map (kbd "C-c .") #'org-time-stamp) ;minor-mode reserved
  17336. (org-defkey org-mode-map (kbd "C-c !") #'org-time-stamp-inactive) ;minor-mode r.
  17337. (org-defkey org-mode-map (kbd "C-c ,") #'org-priority) ;minor-mode reserved
  17338. (org-defkey org-mode-map (kbd "C-c C-y") #'org-evaluate-time-range)
  17339. (org-defkey org-mode-map (kbd "C-c >") #'org-goto-calendar)
  17340. (org-defkey org-mode-map (kbd "C-c <") #'org-date-from-calendar)
  17341. (org-defkey org-mode-map (kbd "C-,") #'org-cycle-agenda-files)
  17342. (org-defkey org-mode-map (kbd "C-'") #'org-cycle-agenda-files)
  17343. (org-defkey org-mode-map (kbd "C-c [") #'org-agenda-file-to-front)
  17344. (org-defkey org-mode-map (kbd "C-c ]") #'org-remove-file)
  17345. (org-defkey org-mode-map (kbd "C-c C-x <") #'org-agenda-set-restriction-lock)
  17346. (org-defkey org-mode-map (kbd "C-c C-x >") #'org-agenda-remove-restriction-lock)
  17347. (org-defkey org-mode-map (kbd "C-c -") #'org-ctrl-c-minus)
  17348. (org-defkey org-mode-map (kbd "C-c *") #'org-ctrl-c-star)
  17349. (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
  17350. (org-defkey org-mode-map (kbd "C-c ^") #'org-sort)
  17351. (org-defkey org-mode-map (kbd "C-c C-c") #'org-ctrl-c-ctrl-c)
  17352. (org-defkey org-mode-map (kbd "C-c C-k") #'org-kill-note-or-show-branches)
  17353. (org-defkey org-mode-map (kbd "C-c #") #'org-update-statistics-cookies)
  17354. (org-defkey org-mode-map (kbd "RET") #'org-return)
  17355. (org-defkey org-mode-map (kbd "C-j") #'org-return-indent)
  17356. (org-defkey org-mode-map (kbd "C-c ?") #'org-table-field-info)
  17357. (org-defkey org-mode-map (kbd "C-c SPC") #'org-table-blank-field)
  17358. (org-defkey org-mode-map (kbd "C-c +") #'org-table-sum)
  17359. (org-defkey org-mode-map (kbd "C-c =") #'org-table-eval-formula)
  17360. (org-defkey org-mode-map (kbd "C-c '") #'org-edit-special)
  17361. (org-defkey org-mode-map (kbd "C-c `") #'org-table-edit-field)
  17362. (org-defkey org-mode-map (kbd "C-c \" a") #'orgtbl-ascii-plot)
  17363. (org-defkey org-mode-map (kbd "C-c \" g") #'org-plot/gnuplot)
  17364. (org-defkey org-mode-map (kbd "C-c |") #'org-table-create-or-convert-from-region)
  17365. (org-defkey org-mode-map (kbd "C-#") #'org-table-rotate-recalc-marks)
  17366. (org-defkey org-mode-map (kbd "C-c ~") #'org-table-create-with-table.el)
  17367. (org-defkey org-mode-map (kbd "C-c C-a") #'org-attach)
  17368. (org-defkey org-mode-map (kbd "C-c }") #'org-table-toggle-coordinate-overlays)
  17369. (org-defkey org-mode-map (kbd "C-c {") #'org-table-toggle-formula-debugger)
  17370. (org-defkey org-mode-map (kbd "C-c C-e") #'org-export-dispatch)
  17371. (org-defkey org-mode-map (kbd "C-c :") #'org-toggle-fixed-width)
  17372. (org-defkey org-mode-map (kbd "C-c C-x C-f") #'org-emphasize)
  17373. (org-defkey org-mode-map (kbd "C-c C-x f") #'org-footnote-action)
  17374. (org-defkey org-mode-map (kbd "C-c @") #'org-mark-subtree)
  17375. (org-defkey org-mode-map (kbd "M-h") #'org-mark-element)
  17376. (org-defkey org-mode-map (kbd "ESC h") #'org-mark-element)
  17377. (org-defkey org-mode-map (kbd "C-c C-*") #'org-list-make-subtree)
  17378. (org-defkey org-mode-map (kbd "C-c C-x C-w") #'org-cut-special)
  17379. (org-defkey org-mode-map (kbd "C-c C-x M-w") #'org-copy-special)
  17380. (org-defkey org-mode-map (kbd "C-c C-x C-y") #'org-paste-special)
  17381. (org-defkey org-mode-map (kbd "C-c C-x C-t") #'org-toggle-time-stamp-overlays)
  17382. (org-defkey org-mode-map (kbd "C-c C-x C-i") #'org-clock-in)
  17383. (org-defkey org-mode-map (kbd "C-c C-x C-x") #'org-clock-in-last)
  17384. (org-defkey org-mode-map (kbd "C-c C-x C-z") #'org-resolve-clocks)
  17385. (org-defkey org-mode-map (kbd "C-c C-x C-o") #'org-clock-out)
  17386. (org-defkey org-mode-map (kbd "C-c C-x C-j") #'org-clock-goto)
  17387. (org-defkey org-mode-map (kbd "C-c C-x C-q") #'org-clock-cancel)
  17388. (org-defkey org-mode-map (kbd "C-c C-x C-d") #'org-clock-display)
  17389. (org-defkey org-mode-map (kbd "C-c C-x C-r") #'org-clock-report)
  17390. (org-defkey org-mode-map (kbd "C-c C-x C-u") #'org-dblock-update)
  17391. (org-defkey org-mode-map (kbd "C-c C-x C-l") #'org-toggle-latex-fragment)
  17392. (org-defkey org-mode-map (kbd "C-c C-x C-v") #'org-toggle-inline-images)
  17393. (org-defkey org-mode-map (kbd "C-c C-x C-M-v") #'org-redisplay-inline-images)
  17394. (org-defkey org-mode-map (kbd "C-c C-x \\") #'org-toggle-pretty-entities)
  17395. (org-defkey org-mode-map (kbd "C-c C-x C-b") #'org-toggle-checkbox)
  17396. (org-defkey org-mode-map (kbd "C-c C-x p") #'org-set-property)
  17397. (org-defkey org-mode-map (kbd "C-c C-x P") #'org-set-property-and-value)
  17398. (org-defkey org-mode-map (kbd "C-c C-x e") #'org-set-effort)
  17399. (org-defkey org-mode-map (kbd "C-c C-x E") #'org-inc-effort)
  17400. (org-defkey org-mode-map (kbd "C-c C-x o") #'org-toggle-ordered-property)
  17401. (org-defkey org-mode-map (kbd "C-c C-x i") #'org-columns-insert-dblock)
  17402. (org-defkey org-mode-map (kbd "C-c C-,") #'org-insert-structure-template)
  17403. (org-defkey org-mode-map (kbd "C-c C-x .") #'org-timer)
  17404. (org-defkey org-mode-map (kbd "C-c C-x -") #'org-timer-item)
  17405. (org-defkey org-mode-map (kbd "C-c C-x 0") #'org-timer-start)
  17406. (org-defkey org-mode-map (kbd "C-c C-x _") #'org-timer-stop)
  17407. (org-defkey org-mode-map (kbd "C-c C-x ;") #'org-timer-set-timer)
  17408. (org-defkey org-mode-map (kbd "C-c C-x ,") #'org-timer-pause-or-continue)
  17409. (define-key org-mode-map (kbd "C-c C-x C-c") #'org-columns)
  17410. (define-key org-mode-map (kbd "C-c C-x !") #'org-reload)
  17411. (define-key org-mode-map (kbd "C-c C-x g") #'org-feed-update-all)
  17412. (define-key org-mode-map (kbd "C-c C-x G") #'org-feed-goto-inbox)
  17413. (define-key org-mode-map (kbd "C-c C-x [") #'org-reftex-citation)
  17414. ;;; Speed commands
  17415. (defconst org-speed-commands-default
  17416. '(
  17417. ("Outline Navigation")
  17418. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  17419. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  17420. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  17421. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  17422. ("F" . org-next-block)
  17423. ("B" . org-previous-block)
  17424. ("u" . (org-speed-move-safe 'outline-up-heading))
  17425. ("j" . org-goto)
  17426. ("g" . (org-refile t))
  17427. ("Outline Visibility")
  17428. ("c" . org-cycle)
  17429. ("C" . org-shifttab)
  17430. (" " . org-display-outline-path)
  17431. ("s" . org-toggle-narrow-to-subtree)
  17432. ("k" . org-cut-subtree)
  17433. ("=" . org-columns)
  17434. ("Outline Structure Editing")
  17435. ("U" . org-metaup)
  17436. ("D" . org-metadown)
  17437. ("r" . org-metaright)
  17438. ("l" . org-metaleft)
  17439. ("R" . org-shiftmetaright)
  17440. ("L" . org-shiftmetaleft)
  17441. ("i" . (progn (forward-char 1) (call-interactively
  17442. 'org-insert-heading-respect-content)))
  17443. ("^" . org-sort)
  17444. ("w" . org-refile)
  17445. ("a" . org-archive-subtree-default-with-confirmation)
  17446. ("@" . org-mark-subtree)
  17447. ("#" . org-toggle-comment)
  17448. ("Clock Commands")
  17449. ("I" . org-clock-in)
  17450. ("O" . org-clock-out)
  17451. ("Meta Data Editing")
  17452. ("t" . org-todo)
  17453. ("," . (org-priority))
  17454. ("0" . (org-priority ?\ ))
  17455. ("1" . (org-priority ?A))
  17456. ("2" . (org-priority ?B))
  17457. ("3" . (org-priority ?C))
  17458. (":" . org-set-tags-command)
  17459. ("e" . org-set-effort)
  17460. ("E" . org-inc-effort)
  17461. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  17462. (org-entry-put (point) "APPT_WARNTIME" m)))
  17463. ("Agenda Views etc")
  17464. ("v" . org-agenda)
  17465. ("/" . org-sparse-tree)
  17466. ("Misc")
  17467. ("o" . org-open-at-point)
  17468. ("?" . org-speed-command-help)
  17469. ("<" . (org-agenda-set-restriction-lock 'subtree))
  17470. (">" . (org-agenda-remove-restriction-lock))
  17471. )
  17472. "The default speed commands.")
  17473. (defun org-print-speed-command (e)
  17474. (if (> (length (car e)) 1)
  17475. (progn
  17476. (princ "\n")
  17477. (princ (car e))
  17478. (princ "\n")
  17479. (princ (make-string (length (car e)) ?-))
  17480. (princ "\n"))
  17481. (princ (car e))
  17482. (princ " ")
  17483. (if (symbolp (cdr e))
  17484. (princ (symbol-name (cdr e)))
  17485. (prin1 (cdr e)))
  17486. (princ "\n")))
  17487. (defun org-speed-command-help ()
  17488. "Show the available speed commands."
  17489. (interactive)
  17490. (if (not org-use-speed-commands)
  17491. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  17492. (with-output-to-temp-buffer "*Help*"
  17493. (princ "User-defined Speed commands\n===========================\n")
  17494. (mapc #'org-print-speed-command org-speed-commands-user)
  17495. (princ "\n")
  17496. (princ "Built-in Speed commands\n=======================\n")
  17497. (mapc #'org-print-speed-command org-speed-commands-default))
  17498. (with-current-buffer "*Help*"
  17499. (setq truncate-lines t))))
  17500. (defun org-speed-move-safe (cmd)
  17501. "Execute CMD, but make sure that the cursor always ends up in a headline.
  17502. If not, return to the original position and throw an error."
  17503. (interactive)
  17504. (let ((pos (point)))
  17505. (call-interactively cmd)
  17506. (unless (and (bolp) (org-at-heading-p))
  17507. (goto-char pos)
  17508. (error "Boundary reached while executing %s" cmd))))
  17509. (defvar org-self-insert-command-undo-counter 0)
  17510. (defvar org-table-auto-blank-field) ; defined in org-table.el
  17511. (defvar org-speed-command nil)
  17512. (defun org-speed-command-activate (keys)
  17513. "Hook for activating single-letter speed commands.
  17514. `org-speed-commands-default' specifies a minimal command set.
  17515. Use `org-speed-commands-user' for further customization."
  17516. (when (or (and (bolp) (looking-at org-outline-regexp))
  17517. (and (functionp org-use-speed-commands)
  17518. (funcall org-use-speed-commands)))
  17519. (cdr (assoc keys (append org-speed-commands-user
  17520. org-speed-commands-default)))))
  17521. (defun org-babel-speed-command-activate (keys)
  17522. "Hook for activating single-letter code block commands."
  17523. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  17524. (cdr (assoc keys org-babel-key-bindings))))
  17525. (defcustom org-speed-command-hook
  17526. '(org-speed-command-activate org-babel-speed-command-activate)
  17527. "Hook for activating speed commands at strategic locations.
  17528. Hook functions are called in sequence until a valid handler is
  17529. found.
  17530. Each hook takes a single argument, a user-pressed command key
  17531. which is also a `self-insert-command' from the global map.
  17532. Within the hook, examine the cursor position and the command key
  17533. and return nil or a valid handler as appropriate. Handler could
  17534. be one of an interactive command, a function, or a form.
  17535. Set `org-use-speed-commands' to non-nil value to enable this
  17536. hook. The default setting is `org-speed-command-activate'."
  17537. :group 'org-structure
  17538. :version "24.1"
  17539. :type 'hook)
  17540. (defun org-self-insert-command (N)
  17541. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  17542. If the cursor is in a table looking at whitespace, the whitespace is
  17543. overwritten, and the table is not marked as requiring realignment."
  17544. (interactive "p")
  17545. (org-check-before-invisible-edit 'insert)
  17546. (cond
  17547. ((and org-use-speed-commands
  17548. (let ((kv (this-command-keys-vector)))
  17549. (setq org-speed-command
  17550. (run-hook-with-args-until-success
  17551. 'org-speed-command-hook
  17552. (make-string 1 (aref kv (1- (length kv))))))))
  17553. (cond
  17554. ((commandp org-speed-command)
  17555. (setq this-command org-speed-command)
  17556. (call-interactively org-speed-command))
  17557. ((functionp org-speed-command)
  17558. (funcall org-speed-command))
  17559. ((and org-speed-command (listp org-speed-command))
  17560. (eval org-speed-command))
  17561. (t (let (org-use-speed-commands)
  17562. (call-interactively 'org-self-insert-command)))))
  17563. ((and
  17564. (= N 1)
  17565. (not (org-region-active-p))
  17566. (org-at-table-p)
  17567. (progn
  17568. ;; Check if we blank the field, and if that triggers align.
  17569. (and (featurep 'org-table)
  17570. org-table-auto-blank-field
  17571. (memq last-command
  17572. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  17573. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  17574. ;; Got extra space, this field does not determine
  17575. ;; column width.
  17576. (let (org-table-may-need-update) (org-table-blank-field))
  17577. ;; No extra space, this field may determine column
  17578. ;; width.
  17579. (org-table-blank-field)))
  17580. t)
  17581. (looking-at "[^|\n]* |"))
  17582. ;; There is room for insertion without re-aligning the table.
  17583. (self-insert-command N)
  17584. (org-table-with-shrunk-field
  17585. (save-excursion
  17586. (skip-chars-forward "^|")
  17587. ;; Do not delete last space, which is
  17588. ;; `org-table-separator-space', but the regular space before
  17589. ;; it.
  17590. (delete-region (- (point) 2) (1- (point))))))
  17591. (t
  17592. (setq org-table-may-need-update t)
  17593. (self-insert-command N)
  17594. (org-fix-tags-on-the-fly)
  17595. (when org-self-insert-cluster-for-undo
  17596. (if (not (eq last-command 'org-self-insert-command))
  17597. (setq org-self-insert-command-undo-counter 1)
  17598. (if (>= org-self-insert-command-undo-counter 20)
  17599. (setq org-self-insert-command-undo-counter 1)
  17600. (and (> org-self-insert-command-undo-counter 0)
  17601. buffer-undo-list (listp buffer-undo-list)
  17602. (not (cadr buffer-undo-list)) ; remove nil entry
  17603. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  17604. (setq org-self-insert-command-undo-counter
  17605. (1+ org-self-insert-command-undo-counter))))))))
  17606. (defun org-check-before-invisible-edit (kind)
  17607. "Check is editing if kind KIND would be dangerous with invisible text around.
  17608. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  17609. ;; First, try to get out of here as quickly as possible, to reduce overhead
  17610. (when (and org-catch-invisible-edits
  17611. (or (not (boundp 'visible-mode)) (not visible-mode))
  17612. (or (get-char-property (point) 'invisible)
  17613. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  17614. ;; OK, we need to take a closer look. Do not consider
  17615. ;; invisibility obtained through text properties (e.g., link
  17616. ;; fontification), as it cannot be toggled.
  17617. (let* ((invisible-at-point
  17618. (pcase (get-char-property-and-overlay (point) 'invisible)
  17619. (`(,_ . ,(and (pred overlayp) o)) o)))
  17620. ;; Assume that point cannot land in the middle of an
  17621. ;; overlay, or between two overlays.
  17622. (invisible-before-point
  17623. (and (not invisible-at-point)
  17624. (not (bobp))
  17625. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  17626. (`(,_ . ,(and (pred overlayp) o)) o))))
  17627. (border-and-ok-direction
  17628. (or
  17629. ;; Check if we are acting predictably before invisible
  17630. ;; text.
  17631. (and invisible-at-point
  17632. (memq kind '(insert delete-backward)))
  17633. ;; Check if we are acting predictably after invisible text
  17634. ;; This works not well, and I have turned it off. It seems
  17635. ;; better to always show and stop after invisible text.
  17636. ;; (and (not invisible-at-point) invisible-before-point
  17637. ;; (memq kind '(insert delete)))
  17638. )))
  17639. (when (or invisible-at-point invisible-before-point)
  17640. (when (eq org-catch-invisible-edits 'error)
  17641. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  17642. (if (and org-custom-properties-overlays
  17643. (y-or-n-p "Display invisible properties in this buffer? "))
  17644. (org-toggle-custom-properties-visibility)
  17645. ;; Make the area visible
  17646. (save-excursion
  17647. (when invisible-before-point
  17648. (goto-char
  17649. (previous-single-char-property-change (point) 'invisible)))
  17650. ;; Remove whatever overlay is currently making yet-to-be
  17651. ;; edited text invisible. Also remove nested invisibility
  17652. ;; related overlays.
  17653. (delete-overlay (or invisible-at-point invisible-before-point))
  17654. (let ((origin (if invisible-at-point (point) (1- (point)))))
  17655. (while (pcase (get-char-property-and-overlay origin 'invisible)
  17656. (`(,_ . ,(and (pred overlayp) o))
  17657. (delete-overlay o)
  17658. t)))))
  17659. (cond
  17660. ((eq org-catch-invisible-edits 'show)
  17661. ;; That's it, we do the edit after showing
  17662. (message
  17663. "Unfolding invisible region around point before editing")
  17664. (sit-for 1))
  17665. ((and (eq org-catch-invisible-edits 'smart)
  17666. border-and-ok-direction)
  17667. (message "Unfolding invisible region around point before editing"))
  17668. (t
  17669. ;; Don't do the edit, make the user repeat it in full visibility
  17670. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  17671. (defun org-fix-tags-on-the-fly ()
  17672. "Align tags in headline at point.
  17673. Unlike `org-align-tags', this function does nothing if point is
  17674. either not currently on a tagged headline or on a tag."
  17675. (when (and (org-match-line org-tag-line-re)
  17676. (< (point) (match-beginning 1)))
  17677. (org-align-tags)))
  17678. (defun org-delete-backward-char (N)
  17679. "Like `delete-backward-char', insert whitespace at field end in tables.
  17680. When deleting backwards, in tables this function will insert whitespace in
  17681. front of the next \"|\" separator, to keep the table aligned. The table will
  17682. still be marked for re-alignment if the field did fill the entire column,
  17683. because, in this case the deletion might narrow the column."
  17684. (interactive "p")
  17685. (save-match-data
  17686. (org-check-before-invisible-edit 'delete-backward)
  17687. (if (and (= N 1)
  17688. (not overwrite-mode)
  17689. (not (org-region-active-p))
  17690. (not (eq (char-before) ?|))
  17691. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  17692. (looking-at-p ".*?|")
  17693. (org-at-table-p))
  17694. (progn (forward-char -1) (org-delete-char 1))
  17695. (backward-delete-char N)
  17696. (org-fix-tags-on-the-fly))))
  17697. (defun org-delete-char (N)
  17698. "Like `delete-char', but insert whitespace at field end in tables.
  17699. When deleting characters, in tables this function will insert whitespace in
  17700. front of the next \"|\" separator, to keep the table aligned. The table will
  17701. still be marked for re-alignment if the field did fill the entire column,
  17702. because, in this case the deletion might narrow the column."
  17703. (interactive "p")
  17704. (save-match-data
  17705. (org-check-before-invisible-edit 'delete)
  17706. (cond
  17707. ((or (/= N 1)
  17708. (eq (char-after) ?|)
  17709. (save-excursion (skip-chars-backward " \t") (bolp))
  17710. (not (org-at-table-p)))
  17711. (delete-char N)
  17712. (org-fix-tags-on-the-fly))
  17713. ((looking-at ".\\(.*?\\)|")
  17714. (let* ((update? org-table-may-need-update)
  17715. (noalign (looking-at-p ".*? |")))
  17716. (delete-char 1)
  17717. (org-table-with-shrunk-field
  17718. (save-excursion
  17719. ;; Last space is `org-table-separator-space', so insert
  17720. ;; a regular one before it instead.
  17721. (goto-char (- (match-end 0) 2))
  17722. (insert " ")))
  17723. ;; If there were two spaces at the end, this field does not
  17724. ;; determine the width of the column.
  17725. (when noalign (setq org-table-may-need-update update?))))
  17726. (t
  17727. (delete-char N)))))
  17728. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  17729. (put 'org-self-insert-command 'delete-selection
  17730. (lambda ()
  17731. (not (run-hook-with-args-until-success
  17732. 'self-insert-uses-region-functions))))
  17733. (put 'orgtbl-self-insert-command 'delete-selection
  17734. (lambda ()
  17735. (not (run-hook-with-args-until-success
  17736. 'self-insert-uses-region-functions))))
  17737. (put 'org-delete-char 'delete-selection 'supersede)
  17738. (put 'org-delete-backward-char 'delete-selection 'supersede)
  17739. (put 'org-yank 'delete-selection 'yank)
  17740. ;; Make `flyspell-mode' delay after some commands
  17741. (put 'org-self-insert-command 'flyspell-delayed t)
  17742. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  17743. (put 'org-delete-char 'flyspell-delayed t)
  17744. (put 'org-delete-backward-char 'flyspell-delayed t)
  17745. ;; Make pabbrev-mode expand after Org mode commands
  17746. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  17747. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  17748. (defun org-transpose-words ()
  17749. "Transpose words for Org.
  17750. This uses the `org-mode-transpose-word-syntax-table' syntax
  17751. table, which interprets characters in `org-emphasis-alist' as
  17752. word constituents."
  17753. (interactive)
  17754. (with-syntax-table org-mode-transpose-word-syntax-table
  17755. (call-interactively 'transpose-words)))
  17756. (defvar org-ctrl-c-ctrl-c-hook nil
  17757. "Hook for functions attaching themselves to `C-c C-c'.
  17758. This can be used to add additional functionality to the C-c C-c
  17759. key which executes context-dependent commands. This hook is run
  17760. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  17761. run after the last test.
  17762. Each function will be called with no arguments. The function
  17763. must check if the context is appropriate for it to act. If yes,
  17764. it should do its thing and then return a non-nil value. If the
  17765. context is wrong, just do nothing and return nil.")
  17766. (defvar org-ctrl-c-ctrl-c-final-hook nil
  17767. "Hook for functions attaching themselves to `C-c C-c'.
  17768. This can be used to add additional functionality to the C-c C-c
  17769. key which executes context-dependent commands. This hook is run
  17770. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  17771. before the first test.
  17772. Each function will be called with no arguments. The function
  17773. must check if the context is appropriate for it to act. If yes,
  17774. it should do its thing and then return a non-nil value. If the
  17775. context is wrong, just do nothing and return nil.")
  17776. (defvar org-tab-first-hook nil
  17777. "Hook for functions to attach themselves to TAB.
  17778. See `org-ctrl-c-ctrl-c-hook' for more information.
  17779. This hook runs as the first action when TAB is pressed, even before
  17780. `org-cycle' messes around with the `outline-regexp' to cater for
  17781. inline tasks and plain list item folding.
  17782. If any function in this hook returns t, any other actions that
  17783. would have been caused by TAB (such as table field motion or visibility
  17784. cycling) will not occur.")
  17785. (defvar org-tab-after-check-for-table-hook nil
  17786. "Hook for functions to attach themselves to TAB.
  17787. See `org-ctrl-c-ctrl-c-hook' for more information.
  17788. This hook runs after it has been established that the cursor is not in a
  17789. table, but before checking if the cursor is in a headline or if global cycling
  17790. should be done.
  17791. If any function in this hook returns t, not other actions like visibility
  17792. cycling will be done.")
  17793. (defvar org-tab-after-check-for-cycling-hook nil
  17794. "Hook for functions to attach themselves to TAB.
  17795. See `org-ctrl-c-ctrl-c-hook' for more information.
  17796. This hook runs after it has been established that not table field motion and
  17797. not visibility should be done because of current context. This is probably
  17798. the place where a package like yasnippets can hook in.")
  17799. (defvar org-tab-before-tab-emulation-hook nil
  17800. "Hook for functions to attach themselves to TAB.
  17801. See `org-ctrl-c-ctrl-c-hook' for more information.
  17802. This hook runs after every other options for TAB have been exhausted, but
  17803. before indentation and \t insertion takes place.")
  17804. (defvar org-metaleft-hook nil
  17805. "Hook for functions attaching themselves to `M-left'.
  17806. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17807. (defvar org-metaright-hook nil
  17808. "Hook for functions attaching themselves to `M-right'.
  17809. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17810. (defvar org-metaup-hook nil
  17811. "Hook for functions attaching themselves to `M-up'.
  17812. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17813. (defvar org-metadown-hook nil
  17814. "Hook for functions attaching themselves to `M-down'.
  17815. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17816. (defvar org-shiftmetaleft-hook nil
  17817. "Hook for functions attaching themselves to `M-S-left'.
  17818. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17819. (defvar org-shiftmetaright-hook nil
  17820. "Hook for functions attaching themselves to `M-S-right'.
  17821. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17822. (defvar org-shiftmetaup-hook nil
  17823. "Hook for functions attaching themselves to `M-S-up'.
  17824. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17825. (defvar org-shiftmetadown-hook nil
  17826. "Hook for functions attaching themselves to `M-S-down'.
  17827. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17828. (defvar org-metareturn-hook nil
  17829. "Hook for functions attaching themselves to `M-RET'.
  17830. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17831. (defvar org-shiftup-hook nil
  17832. "Hook for functions attaching themselves to `S-up'.
  17833. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17834. (defvar org-shiftup-final-hook nil
  17835. "Hook for functions attaching themselves to `S-up'.
  17836. This one runs after all other options except shift-select have been excluded.
  17837. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17838. (defvar org-shiftdown-hook nil
  17839. "Hook for functions attaching themselves to `S-down'.
  17840. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17841. (defvar org-shiftdown-final-hook nil
  17842. "Hook for functions attaching themselves to `S-down'.
  17843. This one runs after all other options except shift-select have been excluded.
  17844. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17845. (defvar org-shiftleft-hook nil
  17846. "Hook for functions attaching themselves to `S-left'.
  17847. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17848. (defvar org-shiftleft-final-hook nil
  17849. "Hook for functions attaching themselves to `S-left'.
  17850. This one runs after all other options except shift-select have been excluded.
  17851. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17852. (defvar org-shiftright-hook nil
  17853. "Hook for functions attaching themselves to `S-right'.
  17854. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17855. (defvar org-shiftright-final-hook nil
  17856. "Hook for functions attaching themselves to `S-right'.
  17857. This one runs after all other options except shift-select have been excluded.
  17858. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17859. (defun org-modifier-cursor-error ()
  17860. "Throw an error, a modified cursor command was applied in wrong context."
  17861. (user-error "This command is active in special context like tables, headlines or items"))
  17862. (defun org-shiftselect-error ()
  17863. "Throw an error because Shift-Cursor command was applied in wrong context."
  17864. (if (and (boundp 'shift-select-mode) shift-select-mode)
  17865. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  17866. (user-error "This command works only in special context like headlines or timestamps")))
  17867. (defun org-call-for-shift-select (cmd)
  17868. (let ((this-command-keys-shift-translated t))
  17869. (call-interactively cmd)))
  17870. (defun org-shifttab (&optional arg)
  17871. "Global visibility cycling or move to previous table field.
  17872. Call `org-table-previous-field' within a table.
  17873. When ARG is nil, cycle globally through visibility states.
  17874. When ARG is a numeric prefix, show contents of this level."
  17875. (interactive "P")
  17876. (cond
  17877. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  17878. ((integerp arg)
  17879. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  17880. (message "Content view to level: %d" arg)
  17881. (org-content (prefix-numeric-value arg2))
  17882. (org-cycle-show-empty-lines t)
  17883. (setq org-cycle-global-status 'overview)))
  17884. (t (call-interactively 'org-global-cycle))))
  17885. (defun org-shiftmetaleft ()
  17886. "Promote subtree or delete table column.
  17887. Calls `org-promote-subtree', `org-outdent-item-tree', or
  17888. `org-table-delete-column', depending on context. See the
  17889. individual commands for more information."
  17890. (interactive)
  17891. (cond
  17892. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  17893. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  17894. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  17895. ((if (not (org-region-active-p)) (org-at-item-p)
  17896. (save-excursion (goto-char (region-beginning))
  17897. (org-at-item-p)))
  17898. (call-interactively 'org-outdent-item-tree))
  17899. (t (org-modifier-cursor-error))))
  17900. (defun org-shiftmetaright ()
  17901. "Demote subtree or insert table column.
  17902. Calls `org-demote-subtree', `org-indent-item-tree', or
  17903. `org-table-insert-column', depending on context. See the
  17904. individual commands for more information."
  17905. (interactive)
  17906. (cond
  17907. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  17908. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  17909. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  17910. ((if (not (org-region-active-p)) (org-at-item-p)
  17911. (save-excursion (goto-char (region-beginning))
  17912. (org-at-item-p)))
  17913. (call-interactively 'org-indent-item-tree))
  17914. (t (org-modifier-cursor-error))))
  17915. (defun org-shiftmetaup (&optional _arg)
  17916. "Drag the line at point up.
  17917. In a table, kill the current row.
  17918. On a clock timestamp, update the value of the timestamp like `S-<up>'
  17919. but also adjust the previous clocked item in the clock history.
  17920. Everywhere else, drag the line at point up."
  17921. (interactive "P")
  17922. (cond
  17923. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  17924. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  17925. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17926. (call-interactively 'org-timestamp-up)))
  17927. (t (call-interactively 'org-drag-line-backward))))
  17928. (defun org-shiftmetadown (&optional _arg)
  17929. "Drag the line at point down.
  17930. In a table, insert an empty row at the current line.
  17931. On a clock timestamp, update the value of the timestamp like `S-<down>'
  17932. but also adjust the previous clocked item in the clock history.
  17933. Everywhere else, drag the line at point down."
  17934. (interactive "P")
  17935. (cond
  17936. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  17937. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  17938. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17939. (call-interactively 'org-timestamp-down)))
  17940. (t (call-interactively 'org-drag-line-forward))))
  17941. (defsubst org-hidden-tree-error ()
  17942. (user-error
  17943. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  17944. (defun org-metaleft (&optional _arg)
  17945. "Promote heading, list item at point or move table column left.
  17946. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  17947. depending on context. With no specific context, calls the Emacs
  17948. default `backward-word'. See the individual commands for more
  17949. information.
  17950. This function runs the hook `org-metaleft-hook' as a first step,
  17951. and returns at first non-nil value."
  17952. (interactive "P")
  17953. (cond
  17954. ((run-hook-with-args-until-success 'org-metaleft-hook))
  17955. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  17956. ((org-with-limited-levels
  17957. (or (org-at-heading-p)
  17958. (and (org-region-active-p)
  17959. (save-excursion
  17960. (goto-char (region-beginning))
  17961. (org-at-heading-p)))))
  17962. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  17963. (call-interactively 'org-do-promote))
  17964. ;; At an inline task.
  17965. ((org-at-heading-p)
  17966. (call-interactively 'org-inlinetask-promote))
  17967. ((or (org-at-item-p)
  17968. (and (org-region-active-p)
  17969. (save-excursion
  17970. (goto-char (region-beginning))
  17971. (org-at-item-p))))
  17972. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  17973. (call-interactively 'org-outdent-item))
  17974. (t (call-interactively 'backward-word))))
  17975. (defun org-metaright (&optional _arg)
  17976. "Demote heading, list item at point or move table column right.
  17977. In front of a drawer or a block keyword, indent it correctly.
  17978. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  17979. `org-indent-drawer' or `org-indent-block' depending on context.
  17980. With no specific context, calls the Emacs default `forward-word'.
  17981. See the individual commands for more information.
  17982. This function runs the hook `org-metaright-hook' as a first step,
  17983. and returns at first non-nil value."
  17984. (interactive "P")
  17985. (cond
  17986. ((run-hook-with-args-until-success 'org-metaright-hook))
  17987. ((org-at-table-p) (call-interactively 'org-table-move-column))
  17988. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  17989. ((org-at-block-p) (call-interactively 'org-indent-block))
  17990. ((org-with-limited-levels
  17991. (or (org-at-heading-p)
  17992. (and (org-region-active-p)
  17993. (save-excursion
  17994. (goto-char (region-beginning))
  17995. (org-at-heading-p)))))
  17996. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  17997. (call-interactively 'org-do-demote))
  17998. ;; At an inline task.
  17999. ((org-at-heading-p)
  18000. (call-interactively 'org-inlinetask-demote))
  18001. ((or (org-at-item-p)
  18002. (and (org-region-active-p)
  18003. (save-excursion
  18004. (goto-char (region-beginning))
  18005. (org-at-item-p))))
  18006. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18007. (call-interactively 'org-indent-item))
  18008. (t (call-interactively 'forward-word))))
  18009. (defun org-check-for-hidden (what)
  18010. "Check if there are hidden headlines/items in the current visual line.
  18011. WHAT can be either `headlines' or `items'. If the current line is
  18012. an outline or item heading and it has a folded subtree below it,
  18013. this function returns t, nil otherwise."
  18014. (let ((re (cond
  18015. ((eq what 'headlines) org-outline-regexp-bol)
  18016. ((eq what 'items) (org-item-beginning-re))
  18017. (t (error "This should not happen"))))
  18018. beg end)
  18019. (save-excursion
  18020. (catch 'exit
  18021. (unless (org-region-active-p)
  18022. (setq beg (point-at-bol))
  18023. (beginning-of-line 2)
  18024. (while (and (not (eobp)) ;; this is like `next-line'
  18025. (get-char-property (1- (point)) 'invisible))
  18026. (beginning-of-line 2))
  18027. (setq end (point))
  18028. (goto-char beg)
  18029. (goto-char (point-at-eol))
  18030. (setq end (max end (point)))
  18031. (while (re-search-forward re end t)
  18032. (when (get-char-property (match-beginning 0) 'invisible)
  18033. (throw 'exit t))))
  18034. nil))))
  18035. (defun org-metaup (&optional _arg)
  18036. "Move subtree up or move table row up.
  18037. Calls `org-move-subtree-up' or `org-table-move-row' or
  18038. `org-move-item-up', depending on context. See the individual commands
  18039. for more information."
  18040. (interactive "P")
  18041. (cond
  18042. ((run-hook-with-args-until-success 'org-metaup-hook))
  18043. ((org-region-active-p)
  18044. (let* ((a (min (region-beginning) (region-end)))
  18045. (b (1- (max (region-beginning) (region-end))))
  18046. (c (save-excursion (goto-char a)
  18047. (move-beginning-of-line 0)))
  18048. (d (save-excursion (goto-char a)
  18049. (move-end-of-line 0) (point))))
  18050. (transpose-regions a b c d)
  18051. (goto-char c)))
  18052. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18053. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18054. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18055. (t (org-drag-element-backward))))
  18056. (defun org-metadown (&optional _arg)
  18057. "Move subtree down or move table row down.
  18058. Calls `org-move-subtree-down' or `org-table-move-row' or
  18059. `org-move-item-down', depending on context. See the individual
  18060. commands for more information."
  18061. (interactive "P")
  18062. (cond
  18063. ((run-hook-with-args-until-success 'org-metadown-hook))
  18064. ((org-region-active-p)
  18065. (let* ((a (min (region-beginning) (region-end)))
  18066. (b (max (region-beginning) (region-end)))
  18067. (c (save-excursion (goto-char b)
  18068. (move-beginning-of-line 1)))
  18069. (d (save-excursion (goto-char b)
  18070. (move-end-of-line 1) (1+ (point)))))
  18071. (transpose-regions a b c d)
  18072. (goto-char d)))
  18073. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18074. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18075. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18076. (t (org-drag-element-forward))))
  18077. (defun org-shiftup (&optional arg)
  18078. "Increase item in timestamp or increase priority of current headline.
  18079. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18080. depending on context. See the individual commands for more information."
  18081. (interactive "P")
  18082. (cond
  18083. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18084. ((and org-support-shift-select (org-region-active-p))
  18085. (org-call-for-shift-select 'previous-line))
  18086. ((org-at-timestamp-p 'lax)
  18087. (call-interactively (if org-edit-timestamp-down-means-later
  18088. 'org-timestamp-down 'org-timestamp-up)))
  18089. ((and (not (eq org-support-shift-select 'always))
  18090. org-enable-priority-commands
  18091. (org-at-heading-p))
  18092. (call-interactively 'org-priority-up))
  18093. ((and (not org-support-shift-select) (org-at-item-p))
  18094. (call-interactively 'org-previous-item))
  18095. ((org-clocktable-try-shift 'up arg))
  18096. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18097. (org-support-shift-select
  18098. (org-call-for-shift-select 'previous-line))
  18099. (t (org-shiftselect-error))))
  18100. (defun org-shiftdown (&optional arg)
  18101. "Decrease item in timestamp or decrease priority of current headline.
  18102. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18103. depending on context. See the individual commands for more information."
  18104. (interactive "P")
  18105. (cond
  18106. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18107. ((and org-support-shift-select (org-region-active-p))
  18108. (org-call-for-shift-select 'next-line))
  18109. ((org-at-timestamp-p 'lax)
  18110. (call-interactively (if org-edit-timestamp-down-means-later
  18111. 'org-timestamp-up 'org-timestamp-down)))
  18112. ((and (not (eq org-support-shift-select 'always))
  18113. org-enable-priority-commands
  18114. (org-at-heading-p))
  18115. (call-interactively 'org-priority-down))
  18116. ((and (not org-support-shift-select) (org-at-item-p))
  18117. (call-interactively 'org-next-item))
  18118. ((org-clocktable-try-shift 'down arg))
  18119. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18120. (org-support-shift-select
  18121. (org-call-for-shift-select 'next-line))
  18122. (t (org-shiftselect-error))))
  18123. (defun org-shiftright (&optional arg)
  18124. "Cycle the thing at point or in the current line, depending on context.
  18125. Depending on context, this does one of the following:
  18126. - switch a timestamp at point one day into the future
  18127. - on a headline, switch to the next TODO keyword.
  18128. - on an item, switch entire list to the next bullet type
  18129. - on a property line, switch to the next allowed value
  18130. - on a clocktable definition line, move time block into the future"
  18131. (interactive "P")
  18132. (cond
  18133. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18134. ((and org-support-shift-select (org-region-active-p))
  18135. (org-call-for-shift-select 'forward-char))
  18136. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  18137. ((and (not (eq org-support-shift-select 'always))
  18138. (org-at-heading-p))
  18139. (let ((org-inhibit-logging
  18140. (not org-treat-S-cursor-todo-selection-as-state-change))
  18141. (org-inhibit-blocking
  18142. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18143. (org-call-with-arg 'org-todo 'right)))
  18144. ((or (and org-support-shift-select
  18145. (not (eq org-support-shift-select 'always))
  18146. (org-at-item-bullet-p))
  18147. (and (not org-support-shift-select) (org-at-item-p)))
  18148. (org-call-with-arg 'org-cycle-list-bullet nil))
  18149. ((and (not (eq org-support-shift-select 'always))
  18150. (org-at-property-p))
  18151. (call-interactively 'org-property-next-allowed-value))
  18152. ((org-clocktable-try-shift 'right arg))
  18153. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18154. (org-support-shift-select
  18155. (org-call-for-shift-select 'forward-char))
  18156. (t (org-shiftselect-error))))
  18157. (defun org-shiftleft (&optional arg)
  18158. "Cycle the thing at point or in the current line, depending on context.
  18159. Depending on context, this does one of the following:
  18160. - switch a timestamp at point one day into the past
  18161. - on a headline, switch to the previous TODO keyword.
  18162. - on an item, switch entire list to the previous bullet type
  18163. - on a property line, switch to the previous allowed value
  18164. - on a clocktable definition line, move time block into the past"
  18165. (interactive "P")
  18166. (cond
  18167. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18168. ((and org-support-shift-select (org-region-active-p))
  18169. (org-call-for-shift-select 'backward-char))
  18170. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  18171. ((and (not (eq org-support-shift-select 'always))
  18172. (org-at-heading-p))
  18173. (let ((org-inhibit-logging
  18174. (not org-treat-S-cursor-todo-selection-as-state-change))
  18175. (org-inhibit-blocking
  18176. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18177. (org-call-with-arg 'org-todo 'left)))
  18178. ((or (and org-support-shift-select
  18179. (not (eq org-support-shift-select 'always))
  18180. (org-at-item-bullet-p))
  18181. (and (not org-support-shift-select) (org-at-item-p)))
  18182. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  18183. ((and (not (eq org-support-shift-select 'always))
  18184. (org-at-property-p))
  18185. (call-interactively 'org-property-previous-allowed-value))
  18186. ((org-clocktable-try-shift 'left arg))
  18187. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  18188. (org-support-shift-select
  18189. (org-call-for-shift-select 'backward-char))
  18190. (t (org-shiftselect-error))))
  18191. (defun org-shiftcontrolright ()
  18192. "Switch to next TODO set."
  18193. (interactive)
  18194. (cond
  18195. ((and org-support-shift-select (org-region-active-p))
  18196. (org-call-for-shift-select 'forward-word))
  18197. ((and (not (eq org-support-shift-select 'always))
  18198. (org-at-heading-p))
  18199. (org-call-with-arg 'org-todo 'nextset))
  18200. (org-support-shift-select
  18201. (org-call-for-shift-select 'forward-word))
  18202. (t (org-shiftselect-error))))
  18203. (defun org-shiftcontrolleft ()
  18204. "Switch to previous TODO set."
  18205. (interactive)
  18206. (cond
  18207. ((and org-support-shift-select (org-region-active-p))
  18208. (org-call-for-shift-select 'backward-word))
  18209. ((and (not (eq org-support-shift-select 'always))
  18210. (org-at-heading-p))
  18211. (org-call-with-arg 'org-todo 'previousset))
  18212. (org-support-shift-select
  18213. (org-call-for-shift-select 'backward-word))
  18214. (t (org-shiftselect-error))))
  18215. (defun org-shiftcontrolup (&optional n)
  18216. "Change timestamps synchronously up in CLOCK log lines.
  18217. Optional argument N tells to change by that many units."
  18218. (interactive "P")
  18219. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18220. (let (org-support-shift-select)
  18221. (org-clock-timestamps-up n))
  18222. (user-error "Not at a clock log")))
  18223. (defun org-shiftcontroldown (&optional n)
  18224. "Change timestamps synchronously down in CLOCK log lines.
  18225. Optional argument N tells to change by that many units."
  18226. (interactive "P")
  18227. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18228. (let (org-support-shift-select)
  18229. (org-clock-timestamps-down n))
  18230. (user-error "Not at a clock log")))
  18231. (defun org-increase-number-at-point (&optional inc)
  18232. "Increment the number at point.
  18233. With an optional prefix numeric argument INC, increment using
  18234. this numeric value."
  18235. (interactive "p")
  18236. (if (not (number-at-point))
  18237. (user-error "Not on a number")
  18238. (unless inc (setq inc 1))
  18239. (let ((pos (point))
  18240. (beg (skip-chars-backward "-+^/*0-9eE."))
  18241. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  18242. (setq nap (buffer-substring-no-properties
  18243. (+ pos beg) (+ pos beg end)))
  18244. (delete-region (+ pos beg) (+ pos beg end))
  18245. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  18246. (when (org-at-table-p)
  18247. (org-table-align)
  18248. (org-table-end-of-field 1))))
  18249. (defun org-decrease-number-at-point (&optional inc)
  18250. "Decrement the number at point.
  18251. With an optional prefix numeric argument INC, decrement using
  18252. this numeric value."
  18253. (interactive "p")
  18254. (org-increase-number-at-point (- (or inc 1))))
  18255. (defun org-ctrl-c-ret ()
  18256. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  18257. (interactive)
  18258. (cond
  18259. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  18260. (t (call-interactively 'org-insert-heading))))
  18261. (defun org-find-visible ()
  18262. (let ((s (point)))
  18263. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18264. (get-char-property s 'invisible)))
  18265. s))
  18266. (defun org-find-invisible ()
  18267. (let ((s (point)))
  18268. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18269. (not (get-char-property s 'invisible))))
  18270. s))
  18271. (defun org-copy-visible (beg end)
  18272. "Copy the visible parts of the region."
  18273. (interactive "r")
  18274. (let ((result ""))
  18275. (while (/= beg end)
  18276. (when (get-char-property beg 'invisible)
  18277. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  18278. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  18279. (setq result (concat result (buffer-substring beg next)))
  18280. (setq beg next)))
  18281. (kill-new result)
  18282. (message "Visible strings have been copied to the kill ring.")))
  18283. (defun org-copy-special ()
  18284. "Copy region in table or copy current subtree.
  18285. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  18286. context. See the individual commands for more information."
  18287. (interactive)
  18288. (call-interactively
  18289. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  18290. (defun org-cut-special ()
  18291. "Cut region in table or cut current subtree.
  18292. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  18293. context. See the individual commands for more information."
  18294. (interactive)
  18295. (call-interactively
  18296. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  18297. (defun org-paste-special (arg)
  18298. "Paste rectangular region into table, or past subtree relative to level.
  18299. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  18300. See the individual commands for more information."
  18301. (interactive "P")
  18302. (if (org-at-table-p)
  18303. (org-table-paste-rectangle)
  18304. (org-paste-subtree arg)))
  18305. (defun org-edit-special (&optional arg)
  18306. "Call a special editor for the element at point.
  18307. When at a table, call the formula editor with `org-table-edit-formulas'.
  18308. When in a source code block, call `org-edit-src-code'.
  18309. When in a fixed-width region, call `org-edit-fixed-width-region'.
  18310. When in an export block, call `org-edit-export-block'.
  18311. When in a LaTeX environment, call `org-edit-latex-environment'.
  18312. When at an #+INCLUDE keyword, visit the included file.
  18313. When at a footnote reference, call `org-edit-footnote-reference'
  18314. On a link, call `ffap' to visit the link at point.
  18315. Otherwise, return a user error."
  18316. (interactive "P")
  18317. (let ((element (org-element-at-point)))
  18318. (barf-if-buffer-read-only)
  18319. (pcase (org-element-type element)
  18320. (`src-block
  18321. (if (not arg) (org-edit-src-code)
  18322. (let* ((info (org-babel-get-src-block-info))
  18323. (lang (nth 0 info))
  18324. (params (nth 2 info))
  18325. (session (cdr (assq :session params))))
  18326. (if (not session) (org-edit-src-code)
  18327. ;; At a src-block with a session and function called with
  18328. ;; an ARG: switch to the buffer related to the inferior
  18329. ;; process.
  18330. (switch-to-buffer
  18331. (funcall (intern (concat "org-babel-prep-session:" lang))
  18332. session params))))))
  18333. (`keyword
  18334. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  18335. (org-open-link-from-string
  18336. (format "[[%s]]"
  18337. (expand-file-name
  18338. (let ((value (org-element-property :value element)))
  18339. (cond ((org-file-url-p value)
  18340. (user-error "The file is specified as a URL, cannot be edited"))
  18341. ((not (org-string-nw-p value))
  18342. (user-error "No file to edit"))
  18343. ((string-match "\\`\"\\(.*?\\)\"" value)
  18344. (match-string 1 value))
  18345. ((string-match "\\`[^ \t\"]\\S-*" value)
  18346. (match-string 0 value))
  18347. (t (user-error "No valid file specified")))))))
  18348. (user-error "No special environment to edit here")))
  18349. (`table
  18350. (if (eq (org-element-property :type element) 'table.el)
  18351. (org-edit-table.el)
  18352. (call-interactively 'org-table-edit-formulas)))
  18353. ;; Only Org tables contain `table-row' type elements.
  18354. (`table-row (call-interactively 'org-table-edit-formulas))
  18355. (`example-block (org-edit-src-code))
  18356. (`export-block (org-edit-export-block))
  18357. (`fixed-width (org-edit-fixed-width-region))
  18358. (`latex-environment (org-edit-latex-environment))
  18359. (_
  18360. ;; No notable element at point. Though, we may be at a link or
  18361. ;; a footnote reference, which are objects. Thus, scan deeper.
  18362. (let ((context (org-element-context element)))
  18363. (pcase (org-element-type context)
  18364. (`footnote-reference (org-edit-footnote-reference))
  18365. (`inline-src-block (org-edit-inline-src-code))
  18366. (`link (call-interactively #'ffap))
  18367. (_ (user-error "No special environment to edit here"))))))))
  18368. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  18369. (defun org-ctrl-c-ctrl-c (&optional arg)
  18370. "Set tags in headline, or update according to changed information at point.
  18371. This command does many different things, depending on context:
  18372. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  18373. this is what we do.
  18374. - If the cursor is on a statistics cookie, update it.
  18375. - If the cursor is in a headline, prompt for tags and insert them
  18376. into the current line, aligned to `org-tags-column'. When called
  18377. with prefix arg, realign all tags in the current buffer.
  18378. - If the cursor is in one of the special #+KEYWORD lines, this
  18379. triggers scanning the buffer for these lines and updating the
  18380. information.
  18381. - If the cursor is inside a table, realign the table. This command
  18382. works even if the automatic table editor has been turned off.
  18383. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  18384. the entire table.
  18385. - If the cursor is at a footnote reference or definition, jump to
  18386. the corresponding definition or references, respectively.
  18387. - If the cursor is a the beginning of a dynamic block, update it.
  18388. - If the current buffer is a capture buffer, close note and file it.
  18389. - If the cursor is on a <<<target>>>, update radio targets and
  18390. corresponding links in this buffer.
  18391. - If the cursor is on a numbered item in a plain list, renumber the
  18392. ordered list.
  18393. - If the cursor is on a checkbox, toggle it.
  18394. - If the cursor is on a code block, evaluate it. The variable
  18395. `org-confirm-babel-evaluate' can be used to control prompting
  18396. before code block evaluation, by default every code block
  18397. evaluation requires confirmation. Code block evaluation can be
  18398. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  18399. (interactive "P")
  18400. (cond
  18401. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  18402. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  18403. (org-remove-occur-highlights)
  18404. (message "Temporary highlights/overlays removed from current buffer"))
  18405. ((and (local-variable-p 'org-finish-function)
  18406. (fboundp org-finish-function))
  18407. (funcall org-finish-function))
  18408. ((org-babel-hash-at-point))
  18409. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  18410. (t
  18411. (let* ((context
  18412. (org-element-lineage
  18413. (org-element-context)
  18414. ;; Limit to supported contexts.
  18415. '(babel-call clock dynamic-block footnote-definition
  18416. footnote-reference inline-babel-call inline-src-block
  18417. inlinetask item keyword node-property paragraph
  18418. plain-list planning property-drawer radio-target
  18419. src-block statistics-cookie table table-cell table-row
  18420. timestamp)
  18421. t))
  18422. (type (org-element-type context)))
  18423. ;; For convenience: at the first line of a paragraph on the same
  18424. ;; line as an item, apply function on that item instead.
  18425. (when (eq type 'paragraph)
  18426. (let ((parent (org-element-property :parent context)))
  18427. (when (and (eq (org-element-type parent) 'item)
  18428. (= (line-beginning-position)
  18429. (org-element-property :begin parent)))
  18430. (setq context parent)
  18431. (setq type 'item))))
  18432. ;; Act according to type of element or object at point.
  18433. ;;
  18434. ;; Do nothing on a blank line, except if it is contained in
  18435. ;; a src block. Hence, we first check if point is in such
  18436. ;; a block and then if it is at a blank line.
  18437. (pcase type
  18438. ((or `inline-src-block `src-block)
  18439. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  18440. (org-babel-eval-wipe-error-buffer)
  18441. (org-babel-execute-src-block
  18442. current-prefix-arg (org-babel-get-src-block-info nil context))))
  18443. ((guard (org-match-line "[ \t]*$"))
  18444. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  18445. (user-error
  18446. (substitute-command-keys
  18447. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  18448. ((or `babel-call `inline-babel-call)
  18449. (let ((info (org-babel-lob-get-info context)))
  18450. (when info (org-babel-execute-src-block nil info))))
  18451. (`clock (org-clock-update-time-maybe))
  18452. (`dynamic-block
  18453. (save-excursion
  18454. (goto-char (org-element-property :post-affiliated context))
  18455. (org-update-dblock)))
  18456. (`footnote-definition
  18457. (goto-char (org-element-property :post-affiliated context))
  18458. (call-interactively 'org-footnote-action))
  18459. (`footnote-reference (call-interactively #'org-footnote-action))
  18460. ((or `headline `inlinetask)
  18461. (save-excursion (goto-char (org-element-property :begin context))
  18462. (call-interactively #'org-set-tags-command)))
  18463. (`item
  18464. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  18465. ;; unconditionally, whereas `C-u' will toggle its presence.
  18466. ;; Without a universal argument, if the item has a checkbox,
  18467. ;; toggle it. Otherwise repair the list.
  18468. (let* ((box (org-element-property :checkbox context))
  18469. (struct (org-element-property :structure context))
  18470. (old-struct (copy-tree struct))
  18471. (parents (org-list-parents-alist struct))
  18472. (prevs (org-list-prevs-alist struct))
  18473. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  18474. (org-list-set-checkbox
  18475. (org-element-property :begin context) struct
  18476. (cond ((equal arg '(16)) "[-]")
  18477. ((and (not box) (equal arg '(4))) "[ ]")
  18478. ((or (not box) (equal arg '(4))) nil)
  18479. ((eq box 'on) "[ ]")
  18480. (t "[X]")))
  18481. ;; Mimic `org-list-write-struct' but with grabbing a return
  18482. ;; value from `org-list-struct-fix-box'.
  18483. (org-list-struct-fix-ind struct parents 2)
  18484. (org-list-struct-fix-item-end struct)
  18485. (org-list-struct-fix-bul struct prevs)
  18486. (org-list-struct-fix-ind struct parents)
  18487. (let ((block-item
  18488. (org-list-struct-fix-box struct parents prevs orderedp)))
  18489. (if (and box (equal struct old-struct))
  18490. (if (equal arg '(16))
  18491. (message "Checkboxes already reset")
  18492. (user-error "Cannot toggle this checkbox: %s"
  18493. (if (eq box 'on)
  18494. "all subitems checked"
  18495. "unchecked subitems")))
  18496. (org-list-struct-apply-struct struct old-struct)
  18497. (org-update-checkbox-count-maybe))
  18498. (when block-item
  18499. (message "Checkboxes were removed due to empty box at line %d"
  18500. (org-current-line block-item))))))
  18501. (`keyword
  18502. (let ((org-inhibit-startup-visibility-stuff t)
  18503. (org-startup-align-all-tables nil))
  18504. (when (boundp 'org-table-coordinate-overlays)
  18505. (mapc #'delete-overlay org-table-coordinate-overlays)
  18506. (setq org-table-coordinate-overlays nil))
  18507. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  18508. (message "Local setup has been refreshed"))
  18509. (`plain-list
  18510. ;; At a plain list, with a double C-u argument, set
  18511. ;; checkboxes of each item to "[-]", whereas a single one
  18512. ;; will toggle their presence according to the state of the
  18513. ;; first item in the list. Without an argument, repair the
  18514. ;; list.
  18515. (let* ((begin (org-element-property :contents-begin context))
  18516. (struct (org-element-property :structure context))
  18517. (old-struct (copy-tree struct))
  18518. (first-box (save-excursion
  18519. (goto-char begin)
  18520. (looking-at org-list-full-item-re)
  18521. (match-string-no-properties 3)))
  18522. (new-box (cond ((equal arg '(16)) "[-]")
  18523. ((equal arg '(4)) (unless first-box "[ ]"))
  18524. ((equal first-box "[X]") "[ ]")
  18525. (t "[X]"))))
  18526. (cond
  18527. (arg
  18528. (dolist (pos
  18529. (org-list-get-all-items
  18530. begin struct (org-list-prevs-alist struct)))
  18531. (org-list-set-checkbox pos struct new-box)))
  18532. ((and first-box (eq (point) begin))
  18533. ;; For convenience, when point is at bol on the first
  18534. ;; item of the list and no argument is provided, simply
  18535. ;; toggle checkbox of that item, if any.
  18536. (org-list-set-checkbox begin struct new-box)))
  18537. (when (equal
  18538. (org-list-write-struct
  18539. struct (org-list-parents-alist struct) old-struct)
  18540. old-struct)
  18541. (message "Cannot update this checkbox"))
  18542. (org-update-checkbox-count-maybe)))
  18543. ((or `property-drawer `node-property)
  18544. (call-interactively #'org-property-action))
  18545. (`radio-target
  18546. (call-interactively #'org-update-radio-target-regexp))
  18547. (`statistics-cookie
  18548. (call-interactively #'org-update-statistics-cookies))
  18549. ((or `table `table-cell `table-row)
  18550. ;; At a table, recalculate every field and align it. Also
  18551. ;; send the table if necessary. If the table has
  18552. ;; a `table.el' type, just give up. At a table row or cell,
  18553. ;; maybe recalculate line but always align table.
  18554. (if (eq (org-element-property :type context) 'table.el)
  18555. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  18556. Use `\\[org-edit-special]' to edit table.el tables"))
  18557. (if (or (eq type 'table)
  18558. ;; Check if point is at a TBLFM line.
  18559. (and (eq type 'table-row)
  18560. (= (point) (org-element-property :end context))))
  18561. (save-excursion
  18562. (if (org-at-TBLFM-p)
  18563. (progn (require 'org-table)
  18564. (org-table-calc-current-TBLFM))
  18565. (goto-char (org-element-property :contents-begin context))
  18566. (org-call-with-arg 'org-table-recalculate (or arg t))
  18567. (orgtbl-send-table 'maybe)))
  18568. (org-table-maybe-eval-formula)
  18569. (cond (arg (call-interactively #'org-table-recalculate))
  18570. ((org-table-maybe-recalculate-line))
  18571. (t (org-table-align))))))
  18572. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  18573. (org-timestamp-change 0 'day))
  18574. ((and `nil (guard (org-at-heading-p)))
  18575. ;; When point is on an unsupported object type, we can miss
  18576. ;; the fact that it also is at a heading. Handle it here.
  18577. (call-interactively #'org-set-tags-command))
  18578. ((guard
  18579. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  18580. (_
  18581. (user-error
  18582. (substitute-command-keys
  18583. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  18584. (defun org-mode-restart ()
  18585. (interactive)
  18586. (let ((indent-status (bound-and-true-p org-indent-mode)))
  18587. (funcall major-mode)
  18588. (hack-local-variables)
  18589. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  18590. (org-indent-mode -1))
  18591. (org-reset-file-cache))
  18592. (message "%s restarted" major-mode))
  18593. (defun org-kill-note-or-show-branches ()
  18594. "Abort storing current note, or call `outline-show-branches'."
  18595. (interactive)
  18596. (if (not org-finish-function)
  18597. (save-excursion
  18598. (save-restriction
  18599. (org-narrow-to-subtree)
  18600. (org-flag-subtree t)
  18601. (call-interactively 'outline-show-branches)
  18602. (org-hide-archived-subtrees (point-min) (point-max))))
  18603. (let ((org-note-abort t))
  18604. (funcall org-finish-function))))
  18605. (defun org-delete-indentation (&optional arg)
  18606. "Join current line to previous and fix whitespace at join.
  18607. If previous line is a headline add to headline title. Otherwise
  18608. the function calls `delete-indentation'.
  18609. With a non-nil optional argument, join it to the following one."
  18610. (interactive "*P")
  18611. (if (save-excursion
  18612. (beginning-of-line (if arg 1 0))
  18613. (let ((case-fold-search nil))
  18614. (looking-at org-complex-heading-regexp)))
  18615. ;; At headline.
  18616. (let ((tags-column (when (match-beginning 5)
  18617. (save-excursion (goto-char (match-beginning 5))
  18618. (current-column))))
  18619. (string (concat " " (progn (when arg (forward-line 1))
  18620. (org-trim (delete-and-extract-region
  18621. (line-beginning-position)
  18622. (line-end-position)))))))
  18623. (unless (bobp) (delete-region (point) (1- (point))))
  18624. (goto-char (or (match-end 4)
  18625. (match-beginning 5)
  18626. (match-end 0)))
  18627. (skip-chars-backward " \t")
  18628. (save-excursion (insert string))
  18629. ;; Adjust alignment of tags.
  18630. (cond
  18631. ((not tags-column)) ;no tags
  18632. (org-auto-align-tags (org-align-tags))
  18633. (t (org--align-tags-here tags-column)))) ;preserve tags column
  18634. (delete-indentation arg)))
  18635. (defun org-open-line (n)
  18636. "Insert a new row in tables, call `open-line' elsewhere.
  18637. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  18638. As a special case, when a document starts with a table, allow to
  18639. call `open-line' on the very first character."
  18640. (interactive "*p")
  18641. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  18642. (org-table-insert-row)
  18643. (open-line n)))
  18644. (defun org-return (&optional indent)
  18645. "Goto next table row or insert a newline.
  18646. Calls `org-table-next-row' or `newline', depending on context.
  18647. When optional INDENT argument is non-nil, call
  18648. `newline-and-indent' instead of `newline'.
  18649. When `org-return-follows-link' is non-nil and point is on
  18650. a timestamp or a link, call `org-open-at-point'. However, it
  18651. will not happen if point is in a table or on a \"dead\"
  18652. object (e.g., within a comment). In these case, you need to use
  18653. `org-open-at-point' directly."
  18654. (interactive)
  18655. (let ((context (if org-return-follows-link (org-element-context)
  18656. (org-element-at-point))))
  18657. (cond
  18658. ;; In a table, call `org-table-next-row'. However, before first
  18659. ;; column or after last one, split the table.
  18660. ((or (and (eq (org-element-type context) 'table)
  18661. (>= (point) (org-element-property :contents-begin context))
  18662. (< (point) (org-element-property :contents-end context)))
  18663. (org-element-lineage context '(table-row table-cell) t))
  18664. (if (or (looking-at-p "[ \t]*$")
  18665. (save-excursion (skip-chars-backward " \t") (bolp)))
  18666. (insert "\n")
  18667. (org-table-justify-field-maybe)
  18668. (call-interactively #'org-table-next-row)))
  18669. ;; On a link or a timestamp, call `org-open-at-point' if
  18670. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  18671. ;; locations, e.g., in a comment, as `org-open-at-point'.
  18672. ((and org-return-follows-link
  18673. (or (and (eq 'link (org-element-type context))
  18674. ;; Ensure point is not on the white spaces after
  18675. ;; the link.
  18676. (let ((origin (point)))
  18677. (org-with-point-at (org-element-property :end context)
  18678. (skip-chars-backward " \t")
  18679. (> (point) origin))))
  18680. (org-in-regexp org-ts-regexp-both nil t)
  18681. (org-in-regexp org-tsr-regexp-both nil t)
  18682. (org-in-regexp org-any-link-re nil t)))
  18683. (call-interactively #'org-open-at-point))
  18684. ;; Insert newline in heading, but preserve tags.
  18685. ((and (not (bolp))
  18686. (save-excursion (beginning-of-line)
  18687. (let ((case-fold-search nil))
  18688. (looking-at org-complex-heading-regexp))))
  18689. ;; At headline. Split line. However, if point is on keyword,
  18690. ;; priority cookie or tags, do not break any of them: add
  18691. ;; a newline after the headline instead.
  18692. (let ((tags-column (and (match-beginning 5)
  18693. (save-excursion (goto-char (match-beginning 5))
  18694. (current-column))))
  18695. (string
  18696. (when (and (match-end 4) (org-point-in-group (point) 4))
  18697. (delete-and-extract-region (point) (match-end 4)))))
  18698. ;; Adjust tag alignment.
  18699. (cond
  18700. ((not (and tags-column string)))
  18701. (org-auto-align-tags (org-align-tags))
  18702. (t (org--align-tags-here tags-column))) ;preserve tags column
  18703. (end-of-line)
  18704. (org-show-entry)
  18705. (if indent (newline-and-indent) (newline))
  18706. (when string (save-excursion (insert (org-trim string))))))
  18707. ;; In a list, make sure indenting keeps trailing text within.
  18708. ((and indent
  18709. (not (eolp))
  18710. (org-element-lineage context '(item)))
  18711. (let ((trailing-data
  18712. (delete-and-extract-region (point) (line-end-position))))
  18713. (newline-and-indent)
  18714. (save-excursion (insert trailing-data))))
  18715. (t
  18716. ;; Do not auto-fill when point is in an Org property drawer.
  18717. (let ((auto-fill-function (and (not (org-at-property-p))
  18718. auto-fill-function)))
  18719. (if indent
  18720. (newline-and-indent)
  18721. (newline)))))))
  18722. (defun org-return-indent ()
  18723. "Goto next table row or insert a newline and indent.
  18724. Calls `org-table-next-row' or `newline-and-indent', depending on
  18725. context. See the individual commands for more information."
  18726. (interactive)
  18727. (org-return t))
  18728. (defun org-ctrl-c-tab (&optional _arg)
  18729. "Toggle columns width in a table, or show children.
  18730. Call `org-table-toggle-column-width' if point is in a table.
  18731. Otherwise, call `org-show-children'."
  18732. (interactive "p")
  18733. (call-interactively
  18734. (if (org-at-table-p) #'org-table-toggle-column-width
  18735. #'org-show-children)))
  18736. (defun org-ctrl-c-star ()
  18737. "Compute table, or change heading status of lines.
  18738. Calls `org-table-recalculate' or `org-toggle-heading',
  18739. depending on context."
  18740. (interactive)
  18741. (cond
  18742. ((org-at-table-p)
  18743. (call-interactively 'org-table-recalculate))
  18744. (t
  18745. ;; Convert all lines in region to list items
  18746. (call-interactively 'org-toggle-heading))))
  18747. (defun org-ctrl-c-minus ()
  18748. "Insert separator line in table or modify bullet status of line.
  18749. Also turns a plain line or a region of lines into list items.
  18750. Calls `org-table-insert-hline', `org-toggle-item', or
  18751. `org-cycle-list-bullet', depending on context."
  18752. (interactive)
  18753. (cond
  18754. ((org-at-table-p)
  18755. (call-interactively 'org-table-insert-hline))
  18756. ((org-region-active-p)
  18757. (call-interactively 'org-toggle-item))
  18758. ((org-in-item-p)
  18759. (call-interactively 'org-cycle-list-bullet))
  18760. (t
  18761. (call-interactively 'org-toggle-item))))
  18762. (defun org-toggle-heading (&optional nstars)
  18763. "Convert headings to normal text, or items or text to headings.
  18764. If there is no active region, only convert the current line.
  18765. With a `\\[universal-argument]' prefix, convert the whole list at
  18766. point into heading.
  18767. In a region:
  18768. - If the first non blank line is a headline, remove the stars
  18769. from all headlines in the region.
  18770. - If it is a normal line, turn each and every normal line (i.e.,
  18771. not an heading or an item) in the region into headings. If you
  18772. want to convert only the first line of this region, use one
  18773. universal prefix argument.
  18774. - If it is a plain list item, turn all plain list items into headings.
  18775. When converting a line into a heading, the number of stars is chosen
  18776. such that the lines become children of the current entry. However,
  18777. when a numeric prefix argument is given, its value determines the
  18778. number of stars to add."
  18779. (interactive "P")
  18780. (let ((skip-blanks
  18781. (function
  18782. ;; Return beginning of first non-blank line, starting from
  18783. ;; line at POS.
  18784. (lambda (pos)
  18785. (save-excursion
  18786. (goto-char pos)
  18787. (while (org-at-comment-p) (forward-line))
  18788. (skip-chars-forward " \r\t\n")
  18789. (point-at-bol)))))
  18790. beg end toggled)
  18791. ;; Determine boundaries of changes. If a universal prefix has
  18792. ;; been given, put the list in a region. If region ends at a bol,
  18793. ;; do not consider the last line to be in the region.
  18794. (when (and current-prefix-arg (org-at-item-p))
  18795. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  18796. (org-mark-element))
  18797. (if (org-region-active-p)
  18798. (setq beg (funcall skip-blanks (region-beginning))
  18799. end (copy-marker (save-excursion
  18800. (goto-char (region-end))
  18801. (if (bolp) (point) (point-at-eol)))))
  18802. (setq beg (funcall skip-blanks (point-at-bol))
  18803. end (copy-marker (point-at-eol))))
  18804. ;; Ensure inline tasks don't count as headings.
  18805. (org-with-limited-levels
  18806. (save-excursion
  18807. (goto-char beg)
  18808. (cond
  18809. ;; Case 1. Started at an heading: de-star headings.
  18810. ((org-at-heading-p)
  18811. (while (< (point) end)
  18812. (when (org-at-heading-p t)
  18813. (looking-at org-outline-regexp) (replace-match "")
  18814. (setq toggled t))
  18815. (forward-line)))
  18816. ;; Case 2. Started at an item: change items into headlines.
  18817. ;; One star will be added by `org-list-to-subtree'.
  18818. ((org-at-item-p)
  18819. (while (< (point) end)
  18820. (when (org-at-item-p)
  18821. ;; Pay attention to cases when region ends before list.
  18822. (let* ((struct (org-list-struct))
  18823. (list-end
  18824. (min (org-list-get-bottom-point struct) (1+ end))))
  18825. (save-restriction
  18826. (narrow-to-region (point) list-end)
  18827. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  18828. (setq toggled t))
  18829. (forward-line)))
  18830. ;; Case 3. Started at normal text: make every line an heading,
  18831. ;; skipping headlines and items.
  18832. (t (let* ((stars
  18833. (make-string
  18834. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  18835. (add-stars
  18836. (cond (nstars "") ; stars from prefix only
  18837. ((equal stars "") "*") ; before first heading
  18838. (org-odd-levels-only "**") ; inside heading, odd
  18839. (t "*"))) ; inside heading, oddeven
  18840. (rpl (concat stars add-stars " "))
  18841. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  18842. (while (< (point) (if (equal nstars '(4)) lend end))
  18843. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  18844. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  18845. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  18846. (forward-line)))))))
  18847. (unless toggled (message "Cannot toggle heading from here"))))
  18848. (defun org-meta-return (&optional arg)
  18849. "Insert a new heading or wrap a region in a table.
  18850. Calls `org-insert-heading', `org-insert-item' or
  18851. `org-table-wrap-region', depending on context. When called with
  18852. an argument, unconditionally call `org-insert-heading'."
  18853. (interactive "P")
  18854. (org-check-before-invisible-edit 'insert)
  18855. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  18856. (call-interactively (cond (arg #'org-insert-heading)
  18857. ((org-at-table-p) #'org-table-wrap-region)
  18858. ((org-in-item-p) #'org-insert-item)
  18859. (t #'org-insert-heading)))))
  18860. ;;; Menu entries
  18861. (defsubst org-in-subtree-not-table-p ()
  18862. "Are we in a subtree and not in a table?"
  18863. (and (not (org-before-first-heading-p))
  18864. (not (org-at-table-p))))
  18865. ;; Define the Org mode menus
  18866. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  18867. '("Tbl"
  18868. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  18869. ["Next Field" org-cycle (org-at-table-p)]
  18870. ["Previous Field" org-shifttab (org-at-table-p)]
  18871. ["Next Row" org-return (org-at-table-p)]
  18872. "--"
  18873. ["Blank Field" org-table-blank-field (org-at-table-p)]
  18874. ["Edit Field" org-table-edit-field (org-at-table-p)]
  18875. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  18876. "--"
  18877. ("Column"
  18878. ["Move Column Left" org-metaleft (org-at-table-p)]
  18879. ["Move Column Right" org-metaright (org-at-table-p)]
  18880. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  18881. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  18882. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  18883. ("Row"
  18884. ["Move Row Up" org-metaup (org-at-table-p)]
  18885. ["Move Row Down" org-metadown (org-at-table-p)]
  18886. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  18887. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  18888. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  18889. "--"
  18890. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  18891. ("Rectangle"
  18892. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  18893. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  18894. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  18895. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  18896. "--"
  18897. ("Calculate"
  18898. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  18899. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  18900. ["Edit Formulas" org-edit-special (org-at-table-p)]
  18901. "--"
  18902. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  18903. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  18904. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  18905. "--"
  18906. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  18907. "--"
  18908. ["Sum Column/Rectangle" org-table-sum
  18909. (or (org-at-table-p) (org-region-active-p))]
  18910. ["Which Column?" org-table-current-column (org-at-table-p)])
  18911. ["Debug Formulas"
  18912. org-table-toggle-formula-debugger
  18913. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  18914. ["Show Col/Row Numbers"
  18915. org-table-toggle-coordinate-overlays
  18916. :style toggle
  18917. :selected (bound-and-true-p org-table-overlay-coordinates)]
  18918. "--"
  18919. ["Create" org-table-create (not (org-at-table-p))]
  18920. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  18921. ["Import from File" org-table-import (not (org-at-table-p))]
  18922. ["Export to File" org-table-export (org-at-table-p)]
  18923. "--"
  18924. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  18925. "--"
  18926. ("Plot"
  18927. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  18928. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  18929. (easy-menu-define org-org-menu org-mode-map "Org menu"
  18930. '("Org"
  18931. ("Show/Hide"
  18932. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  18933. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  18934. ["Sparse Tree..." org-sparse-tree t]
  18935. ["Reveal Context" org-reveal t]
  18936. ["Show All" org-show-all t]
  18937. "--"
  18938. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  18939. "--"
  18940. ["New Heading" org-insert-heading t]
  18941. ("Navigate Headings"
  18942. ["Up" outline-up-heading t]
  18943. ["Next" outline-next-visible-heading t]
  18944. ["Previous" outline-previous-visible-heading t]
  18945. ["Next Same Level" outline-forward-same-level t]
  18946. ["Previous Same Level" outline-backward-same-level t]
  18947. "--"
  18948. ["Jump" org-goto t])
  18949. ("Edit Structure"
  18950. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  18951. "--"
  18952. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  18953. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  18954. "--"
  18955. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  18956. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  18957. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  18958. "--"
  18959. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  18960. "--"
  18961. ["Copy visible text" org-copy-visible t]
  18962. "--"
  18963. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  18964. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  18965. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  18966. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  18967. "--"
  18968. ["Sort Region/Children" org-sort t]
  18969. "--"
  18970. ["Convert to odd levels" org-convert-to-odd-levels t]
  18971. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  18972. ("Editing"
  18973. ["Emphasis..." org-emphasize t]
  18974. ["Edit Source Example" org-edit-special t]
  18975. "--"
  18976. ["Footnote new/jump" org-footnote-action t]
  18977. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  18978. ("Archive"
  18979. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  18980. "--"
  18981. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  18982. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  18983. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  18984. )
  18985. "--"
  18986. ("Hyperlinks"
  18987. ["Store Link (Global)" org-store-link t]
  18988. ["Find existing link to here" org-occur-link-in-agenda-files t]
  18989. ["Insert Link" org-insert-link t]
  18990. ["Follow Link" org-open-at-point t]
  18991. "--"
  18992. ["Next link" org-next-link t]
  18993. ["Previous link" org-previous-link t]
  18994. "--"
  18995. ["Descriptive Links"
  18996. org-toggle-link-display
  18997. :style radio
  18998. :selected org-descriptive-links
  18999. ]
  19000. ["Literal Links"
  19001. org-toggle-link-display
  19002. :style radio
  19003. :selected (not org-descriptive-links)])
  19004. "--"
  19005. ("TODO Lists"
  19006. ["TODO/DONE/-" org-todo t]
  19007. ("Select keyword"
  19008. ["Next keyword" org-shiftright (org-at-heading-p)]
  19009. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19010. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19011. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19012. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19013. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19014. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  19015. "--"
  19016. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19017. :selected org-enforce-todo-dependencies :style toggle :active t]
  19018. "Settings for tree at point"
  19019. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19020. :selected (org-entry-get nil "ORDERED")
  19021. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19022. ["Do Children parallel" org-toggle-ordered-property :style radio
  19023. :selected (not (org-entry-get nil "ORDERED"))
  19024. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19025. "--"
  19026. ["Set Priority" org-priority t]
  19027. ["Priority Up" org-shiftup t]
  19028. ["Priority Down" org-shiftdown t]
  19029. "--"
  19030. ["Get news from all feeds" org-feed-update-all t]
  19031. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19032. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19033. ("TAGS and Properties"
  19034. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19035. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19036. "--"
  19037. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19038. ["Column view of properties" org-columns t]
  19039. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19040. ("Dates and Scheduling"
  19041. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19042. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19043. ("Change Date"
  19044. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  19045. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  19046. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  19047. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  19048. ["Compute Time Range" org-evaluate-time-range t]
  19049. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19050. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19051. "--"
  19052. ["Custom time format" org-toggle-time-stamp-overlays
  19053. :style radio :selected org-display-custom-times]
  19054. "--"
  19055. ["Goto Calendar" org-goto-calendar t]
  19056. ["Date from Calendar" org-date-from-calendar t]
  19057. "--"
  19058. ["Start/Restart Timer" org-timer-start t]
  19059. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19060. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19061. ["Insert Timer String" org-timer t]
  19062. ["Insert Timer Item" org-timer-item t])
  19063. ("Logging work"
  19064. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19065. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19066. ["Clock out" org-clock-out t]
  19067. ["Clock cancel" org-clock-cancel t]
  19068. "--"
  19069. ["Mark as default task" org-clock-mark-default-task t]
  19070. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19071. ["Goto running clock" org-clock-goto t]
  19072. "--"
  19073. ["Display times" org-clock-display t]
  19074. ["Create clock table" org-clock-report t]
  19075. "--"
  19076. ["Record DONE time"
  19077. (progn (setq org-log-done (not org-log-done))
  19078. (message "Switching to %s will %s record a timestamp"
  19079. (car org-done-keywords)
  19080. (if org-log-done "automatically" "not")))
  19081. :style toggle :selected org-log-done])
  19082. "--"
  19083. ["Agenda Command..." org-agenda t]
  19084. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19085. ("File List for Agenda")
  19086. ("Special views current file"
  19087. ["TODO Tree" org-show-todo-tree t]
  19088. ["Check Deadlines" org-check-deadlines t]
  19089. ["Tags/Property tree" org-match-sparse-tree t])
  19090. "--"
  19091. ["Export/Publish..." org-export-dispatch t]
  19092. ("LaTeX"
  19093. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  19094. :style toggle :selected org-cdlatex-mode]
  19095. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19096. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19097. ["Modify math symbol" org-cdlatex-math-modify
  19098. (org-inside-LaTeX-fragment-p)]
  19099. ["Insert citation" org-reftex-citation t])
  19100. "--"
  19101. ("MobileOrg"
  19102. ["Push Files and Views" org-mobile-push t]
  19103. ["Get Captured and Flagged" org-mobile-pull t]
  19104. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
  19105. "--"
  19106. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19107. "--"
  19108. ("Documentation"
  19109. ["Show Version" org-version t]
  19110. ["Info Documentation" org-info t]
  19111. ["Browse Org News" org-browse-news t])
  19112. ("Customize"
  19113. ["Browse Org Group" org-customize t]
  19114. "--"
  19115. ["Expand This Menu" org-create-customize-menu
  19116. (fboundp 'customize-menu-create)])
  19117. ["Send bug report" org-submit-bug-report t]
  19118. "--"
  19119. ("Refresh/Reload"
  19120. ["Refresh setup current buffer" org-mode-restart t]
  19121. ["Reload Org (after update)" org-reload t]
  19122. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  19123. (defun org-info (&optional node)
  19124. "Read documentation for Org in the info system.
  19125. With optional NODE, go directly to that node."
  19126. (interactive)
  19127. (info (format "(org)%s" (or node ""))))
  19128. (defun org-browse-news ()
  19129. "Browse the news for the latest major release."
  19130. (interactive)
  19131. (browse-url "https://orgmode.org/Changes.html"))
  19132. ;;;###autoload
  19133. (defun org-submit-bug-report ()
  19134. "Submit a bug report on Org via mail.
  19135. Don't hesitate to report any problems or inaccurate documentation.
  19136. If you don't have setup sending mail from (X)Emacs, please copy the
  19137. output buffer into your mail program, as it gives us important
  19138. information about your Org version and configuration."
  19139. (interactive)
  19140. (require 'reporter)
  19141. (defvar reporter-prompt-for-summary-p)
  19142. (org-load-modules-maybe)
  19143. (org-require-autoloaded-modules)
  19144. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19145. (reporter-submit-bug-report
  19146. "emacs-orgmode@gnu.org"
  19147. (org-version nil 'full)
  19148. (let (list)
  19149. (save-window-excursion
  19150. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19151. (delete-other-windows)
  19152. (erase-buffer)
  19153. (insert "You are about to submit a bug report to the Org mailing list.
  19154. We would like to add your full Org and Outline configuration to the
  19155. bug report. This greatly simplifies the work of the maintainer and
  19156. other experts on the mailing list.
  19157. HOWEVER, some variables you have customized may contain private
  19158. information. The names of customers, colleagues, or friends, might
  19159. appear in the form of file names, tags, todo states, or search strings.
  19160. If you answer yes to the prompt, you might want to check and remove
  19161. such private information before sending the email.")
  19162. (add-text-properties (point-min) (point-max) '(face org-warning))
  19163. (when (yes-or-no-p "Include your Org configuration ")
  19164. (mapatoms
  19165. (lambda (v)
  19166. (and (boundp v)
  19167. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19168. (or (and (symbol-value v)
  19169. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19170. (and
  19171. (get v 'custom-type) (get v 'standard-value)
  19172. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19173. (push v list)))))
  19174. (kill-buffer (get-buffer "*Warn about privacy*"))
  19175. list))
  19176. nil nil
  19177. "Remember to cover the basics, that is, what you expected to happen and
  19178. what in fact did happen. You don't know how to make a good report? See
  19179. https://orgmode.org/manual/Feedback.html#Feedback
  19180. Your bug report will be posted to the Org mailing list.
  19181. ------------------------------------------------------------------------")
  19182. (save-excursion
  19183. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19184. (replace-match "\\1Bug: \\3 [\\2]")))))
  19185. (defun org-install-agenda-files-menu ()
  19186. (let ((bl (buffer-list)))
  19187. (save-excursion
  19188. (while bl
  19189. (set-buffer (pop bl))
  19190. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19191. (when (derived-mode-p 'org-mode)
  19192. (easy-menu-change
  19193. '("Org") "File List for Agenda"
  19194. (append
  19195. (list
  19196. ["Edit File List" (org-edit-agenda-file-list) t]
  19197. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19198. ["Remove Current File from List" org-remove-file t]
  19199. ["Cycle through agenda files" org-cycle-agenda-files t]
  19200. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19201. "--")
  19202. (mapcar 'org-file-menu-entry
  19203. ;; Prevent initialization from failing.
  19204. (ignore-errors (org-agenda-files t)))))))))
  19205. ;;;; Documentation
  19206. (defun org-require-autoloaded-modules ()
  19207. (interactive)
  19208. (mapc #'require
  19209. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19210. org-table org-timer)))
  19211. ;;;###autoload
  19212. (defun org-reload (&optional uncompiled)
  19213. "Reload all Org Lisp files.
  19214. With prefix arg UNCOMPILED, load the uncompiled versions."
  19215. (interactive "P")
  19216. (require 'loadhist)
  19217. (let* ((org-dir (org-find-library-dir "org"))
  19218. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  19219. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  19220. (remove-re (format "\\`%s\\'"
  19221. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  19222. (feats (delete-dups
  19223. (mapcar 'file-name-sans-extension
  19224. (mapcar 'file-name-nondirectory
  19225. (delq nil
  19226. (mapcar 'feature-file
  19227. features))))))
  19228. (lfeat (append
  19229. (sort
  19230. (setq feats
  19231. (delq nil (mapcar
  19232. (lambda (f)
  19233. (if (and (string-match feature-re f)
  19234. (not (string-match remove-re f)))
  19235. f nil))
  19236. feats)))
  19237. 'string-lessp)
  19238. (list "org-version" "org")))
  19239. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  19240. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  19241. load-uncore load-misses)
  19242. (setq load-misses
  19243. (delq 't
  19244. (mapcar (lambda (f)
  19245. (or (org-load-noerror-mustsuffix (concat org-dir f))
  19246. (and (string= org-dir contrib-dir)
  19247. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  19248. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  19249. (add-to-list 'load-uncore f 'append)
  19250. 't)
  19251. f))
  19252. lfeat)))
  19253. (when load-uncore
  19254. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  19255. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  19256. (if load-misses
  19257. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  19258. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  19259. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  19260. ;;;###autoload
  19261. (defun org-customize ()
  19262. "Call the customize function with org as argument."
  19263. (interactive)
  19264. (org-load-modules-maybe)
  19265. (org-require-autoloaded-modules)
  19266. (customize-browse 'org))
  19267. (defun org-create-customize-menu ()
  19268. "Create a full customization menu for Org mode, insert it into the menu."
  19269. (interactive)
  19270. (org-load-modules-maybe)
  19271. (org-require-autoloaded-modules)
  19272. (if (fboundp 'customize-menu-create)
  19273. (progn
  19274. (easy-menu-change
  19275. '("Org") "Customize"
  19276. `(["Browse Org group" org-customize t]
  19277. "--"
  19278. ,(customize-menu-create 'org)
  19279. ["Set" Custom-set t]
  19280. ["Save" Custom-save t]
  19281. ["Reset to Current" Custom-reset-current t]
  19282. ["Reset to Saved" Custom-reset-saved t]
  19283. ["Reset to Standard Settings" Custom-reset-standard t]))
  19284. (message "\"Org\"-menu now contains full customization menu"))
  19285. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  19286. ;;;; Miscellaneous stuff
  19287. ;;; Generally useful functions
  19288. (defun org-link-display-format (s)
  19289. "Replace links in string S with their description.
  19290. If there is no description, use the link target."
  19291. (save-match-data
  19292. (replace-regexp-in-string
  19293. org-bracket-link-analytic-regexp
  19294. (lambda (m)
  19295. (if (match-end 5) (match-string 5 m)
  19296. (concat (match-string 1 m) (match-string 3 m))))
  19297. s nil t)))
  19298. (defun org-toggle-link-display ()
  19299. "Toggle the literal or descriptive display of links."
  19300. (interactive)
  19301. (if org-descriptive-links
  19302. (progn (org-remove-from-invisibility-spec '(org-link))
  19303. (org-restart-font-lock)
  19304. (setq org-descriptive-links nil))
  19305. (progn (add-to-invisibility-spec '(org-link))
  19306. (org-restart-font-lock)
  19307. (setq org-descriptive-links t))))
  19308. (defun org-in-clocktable-p ()
  19309. "Check if the cursor is in a clocktable."
  19310. (let ((pos (point)) start)
  19311. (save-excursion
  19312. (end-of-line 1)
  19313. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  19314. (setq start (match-beginning 0))
  19315. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  19316. (>= (match-end 0) pos)
  19317. start))))
  19318. (defun org-in-verbatim-emphasis ()
  19319. (save-match-data
  19320. (and (org-in-regexp org-verbatim-re 2)
  19321. (>= (point) (match-beginning 3))
  19322. (<= (point) (match-end 4)))))
  19323. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  19324. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  19325. (if (and marker (marker-buffer marker)
  19326. (buffer-live-p (marker-buffer marker)))
  19327. (progn
  19328. (pop-to-buffer-same-window (marker-buffer marker))
  19329. (when (or (> marker (point-max)) (< marker (point-min)))
  19330. (widen))
  19331. (goto-char marker)
  19332. (org-show-context 'org-goto))
  19333. (if bookmark
  19334. (bookmark-jump bookmark)
  19335. (error "Cannot find location"))))
  19336. (defun org-quote-csv-field (s)
  19337. "Quote field for inclusion in CSV material."
  19338. (if (string-match "[\",]" s)
  19339. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  19340. s))
  19341. (defun org-force-self-insert (N)
  19342. "Needed to enforce self-insert under remapping."
  19343. (interactive "p")
  19344. (self-insert-command N))
  19345. (defun org-fill-template (template alist)
  19346. "Find each %key of ALIST in TEMPLATE and replace it."
  19347. (let ((case-fold-search nil))
  19348. (dolist (entry (sort (copy-sequence alist)
  19349. (lambda (a b) (< (length (car a)) (length (car b))))))
  19350. (setq template
  19351. (replace-regexp-in-string
  19352. (concat "%" (regexp-quote (car entry)))
  19353. (or (cdr entry) "") template t t)))
  19354. template))
  19355. (defun org-quote-vert (s)
  19356. "Replace \"|\" with \"\\vert\"."
  19357. (while (string-match "|" s)
  19358. (setq s (replace-match "\\vert" t t s)))
  19359. s)
  19360. (defun org-uuidgen-p (s)
  19361. "Is S an ID created by UUIDGEN?"
  19362. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  19363. (defun org-in-src-block-p (&optional inside)
  19364. "Whether point is in a code source block.
  19365. When INSIDE is non-nil, don't consider we are within a src block
  19366. when point is at #+BEGIN_SRC or #+END_SRC."
  19367. (let ((case-fold-search t))
  19368. (or (and (eq (get-char-property (point) 'src-block) t))
  19369. (and (not inside)
  19370. (save-match-data
  19371. (save-excursion
  19372. (beginning-of-line)
  19373. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  19374. (defun org-context ()
  19375. "Return a list of contexts of the current cursor position.
  19376. If several contexts apply, all are returned.
  19377. Each context entry is a list with a symbol naming the context, and
  19378. two positions indicating start and end of the context. Possible
  19379. contexts are:
  19380. :headline anywhere in a headline
  19381. :headline-stars on the leading stars in a headline
  19382. :todo-keyword on a TODO keyword (including DONE) in a headline
  19383. :tags on the TAGS in a headline
  19384. :priority on the priority cookie in a headline
  19385. :item on the first line of a plain list item
  19386. :item-bullet on the bullet/number of a plain list item
  19387. :checkbox on the checkbox in a plain list item
  19388. :table in an Org table
  19389. :table-special on a special filed in a table
  19390. :table-table in a table.el table
  19391. :clocktable in a clocktable
  19392. :src-block in a source block
  19393. :link on a hyperlink
  19394. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  19395. :target on a <<target>>
  19396. :radio-target on a <<<radio-target>>>
  19397. :latex-fragment on a LaTeX fragment
  19398. :latex-preview on a LaTeX fragment with overlaid preview image
  19399. This function expects the position to be visible because it uses font-lock
  19400. faces as a help to recognize the following contexts: :table-special, :link,
  19401. and :keyword."
  19402. (let* ((f (get-text-property (point) 'face))
  19403. (faces (if (listp f) f (list f)))
  19404. (case-fold-search t)
  19405. (p (point)) clist o)
  19406. ;; First the large context
  19407. (cond
  19408. ((org-at-heading-p t)
  19409. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  19410. (when (progn
  19411. (beginning-of-line 1)
  19412. (looking-at org-todo-line-tags-regexp))
  19413. (push (org-point-in-group p 1 :headline-stars) clist)
  19414. (push (org-point-in-group p 2 :todo-keyword) clist)
  19415. (push (org-point-in-group p 4 :tags) clist))
  19416. (goto-char p)
  19417. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  19418. (when (looking-at "\\[#[A-Z0-9]\\]")
  19419. (push (org-point-in-group p 0 :priority) clist)))
  19420. ((org-at-item-p)
  19421. (push (org-point-in-group p 2 :item-bullet) clist)
  19422. (push (list :item (point-at-bol)
  19423. (save-excursion (org-end-of-item) (point)))
  19424. clist)
  19425. (and (org-at-item-checkbox-p)
  19426. (push (org-point-in-group p 0 :checkbox) clist)))
  19427. ((org-at-table-p)
  19428. (push (list :table (org-table-begin) (org-table-end)) clist)
  19429. (when (memq 'org-formula faces)
  19430. (push (list :table-special
  19431. (previous-single-property-change p 'face)
  19432. (next-single-property-change p 'face)) clist)))
  19433. ((org-at-table-p 'any)
  19434. (push (list :table-table) clist)))
  19435. (goto-char p)
  19436. (let ((case-fold-search t))
  19437. ;; New the "medium" contexts: clocktables, source blocks
  19438. (cond ((org-in-clocktable-p)
  19439. (push (list :clocktable
  19440. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  19441. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  19442. (match-beginning 1))
  19443. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  19444. (match-end 0))) clist))
  19445. ((org-in-src-block-p)
  19446. (push (list :src-block
  19447. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  19448. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  19449. (match-beginning 1))
  19450. (and (search-forward "#+END_SRC" nil t)
  19451. (match-beginning 0))) clist))))
  19452. (goto-char p)
  19453. ;; Now the small context
  19454. (cond
  19455. ((org-at-timestamp-p)
  19456. (push (org-point-in-group p 0 :timestamp) clist))
  19457. ((memq 'org-link faces)
  19458. (push (list :link
  19459. (previous-single-property-change p 'face)
  19460. (next-single-property-change p 'face)) clist))
  19461. ((memq 'org-special-keyword faces)
  19462. (push (list :keyword
  19463. (previous-single-property-change p 'face)
  19464. (next-single-property-change p 'face)) clist))
  19465. ((org-at-target-p)
  19466. (push (org-point-in-group p 0 :target) clist)
  19467. (goto-char (1- (match-beginning 0)))
  19468. (when (looking-at org-radio-target-regexp)
  19469. (push (org-point-in-group p 0 :radio-target) clist))
  19470. (goto-char p))
  19471. ((setq o (cl-some
  19472. (lambda (o)
  19473. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  19474. o))
  19475. (overlays-at (point))))
  19476. (push (list :latex-fragment
  19477. (overlay-start o) (overlay-end o)) clist)
  19478. (push (list :latex-preview
  19479. (overlay-start o) (overlay-end o)) clist))
  19480. ((org-inside-LaTeX-fragment-p)
  19481. ;; FIXME: positions wrong.
  19482. (push (list :latex-fragment (point) (point)) clist)))
  19483. (setq clist (nreverse (delq nil clist)))
  19484. clist))
  19485. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  19486. "Non-nil when point is between matches of START-RE and END-RE.
  19487. Also return a non-nil value when point is on one of the matches.
  19488. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  19489. buffer positions. Default values are the positions of headlines
  19490. surrounding the point.
  19491. The functions returns a cons cell whose car (resp. cdr) is the
  19492. position before START-RE (resp. after END-RE)."
  19493. (save-match-data
  19494. (let ((pos (point))
  19495. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  19496. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  19497. beg end)
  19498. (save-excursion
  19499. ;; Point is on a block when on START-RE or if START-RE can be
  19500. ;; found before it...
  19501. (and (or (org-in-regexp start-re)
  19502. (re-search-backward start-re limit-up t))
  19503. (setq beg (match-beginning 0))
  19504. ;; ... and END-RE after it...
  19505. (goto-char (match-end 0))
  19506. (re-search-forward end-re limit-down t)
  19507. (> (setq end (match-end 0)) pos)
  19508. ;; ... without another START-RE in-between.
  19509. (goto-char (match-beginning 0))
  19510. (not (re-search-backward start-re (1+ beg) t))
  19511. ;; Return value.
  19512. (cons beg end))))))
  19513. (defun org-in-block-p (names)
  19514. "Non-nil when point belongs to a block whose name belongs to NAMES.
  19515. NAMES is a list of strings containing names of blocks.
  19516. Return first block name matched, or nil. Beware that in case of
  19517. nested blocks, the returned name may not belong to the closest
  19518. block from point."
  19519. (save-match-data
  19520. (catch 'exit
  19521. (let ((case-fold-search t)
  19522. (lim-up (save-excursion (outline-previous-heading)))
  19523. (lim-down (save-excursion (outline-next-heading))))
  19524. (dolist (name names)
  19525. (let ((n (regexp-quote name)))
  19526. (when (org-between-regexps-p
  19527. (concat "^[ \t]*#\\+begin_" n)
  19528. (concat "^[ \t]*#\\+end_" n)
  19529. lim-up lim-down)
  19530. (throw 'exit n)))))
  19531. nil)))
  19532. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  19533. "Call `multi-occur' with buffers for all agenda files."
  19534. (interactive "sOrg-files matching: ")
  19535. (let* ((files (org-agenda-files))
  19536. (tnames (mapcar #'file-truename files))
  19537. (extra org-agenda-text-search-extra-files))
  19538. (when (eq (car extra) 'agenda-archives)
  19539. (setq extra (cdr extra))
  19540. (setq files (org-add-archive-files files)))
  19541. (dolist (f extra)
  19542. (unless (member (file-truename f) tnames)
  19543. (unless (member f files) (setq files (append files (list f))))
  19544. (setq tnames (append tnames (list (file-truename f))))))
  19545. (multi-occur
  19546. (mapcar (lambda (x)
  19547. (with-current-buffer
  19548. ;; FIXME: Why not just (find-file-noselect x)?
  19549. ;; Is it to avoid the "revert buffer" prompt?
  19550. (or (get-file-buffer x) (find-file-noselect x))
  19551. (widen)
  19552. (current-buffer)))
  19553. files)
  19554. regexp)))
  19555. (add-hook 'occur-mode-find-occurrence-hook
  19556. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  19557. (defun org-occur-link-in-agenda-files ()
  19558. "Create a link and search for it in the agendas.
  19559. The link is not stored in `org-stored-links', it is just created
  19560. for the search purpose."
  19561. (interactive)
  19562. (let ((link (condition-case nil
  19563. (org-store-link nil)
  19564. (error "Unable to create a link to here"))))
  19565. (org-occur-in-agenda-files (regexp-quote link))))
  19566. (defun org-back-over-empty-lines ()
  19567. "Move backwards over whitespace, to the beginning of the first empty line.
  19568. Returns the number of empty lines passed."
  19569. (let ((pos (point)))
  19570. (if (cdr (assq 'heading org-blank-before-new-entry))
  19571. (skip-chars-backward " \t\n\r")
  19572. (unless (eobp)
  19573. (forward-line -1)))
  19574. (beginning-of-line 2)
  19575. (goto-char (min (point) pos))
  19576. (count-lines (point) pos)))
  19577. (defun org-replace-escapes (string table)
  19578. "Replace %-escapes in STRING with values in TABLE.
  19579. TABLE is an association list with keys like \"%a\" and string values.
  19580. The sequences in STRING may contain normal field width and padding information,
  19581. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  19582. so values can contain further %-escapes if they are define later in TABLE."
  19583. (let ((tbl (copy-alist table))
  19584. (case-fold-search nil)
  19585. (pchg 0)
  19586. re rpl)
  19587. (dolist (e tbl)
  19588. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  19589. (when (and (cdr e) (string-match re (cdr e)))
  19590. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  19591. (safe "SREF"))
  19592. (add-text-properties 0 3 (list 'sref sref) safe)
  19593. (setcdr e (replace-match safe t t (cdr e)))))
  19594. (while (string-match re string)
  19595. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  19596. (cdr e)))
  19597. (setq string (replace-match rpl t t string))))
  19598. (while (setq pchg (next-property-change pchg string))
  19599. (let ((sref (get-text-property pchg 'sref string)))
  19600. (when (and sref (string-match "SREF" string pchg))
  19601. (setq string (replace-match sref t t string)))))
  19602. string))
  19603. ;;; TODO: Only called once, from ox-odt which should probably use
  19604. ;;; org-export-inline-image-p or something.
  19605. (defun org-file-image-p (file)
  19606. "Return non-nil if FILE is an image."
  19607. (save-match-data
  19608. (string-match (image-file-name-regexp) file)))
  19609. (defun org-get-cursor-date (&optional with-time)
  19610. "Return the date at cursor in as a time.
  19611. This works in the calendar and in the agenda, anywhere else it just
  19612. returns the current time.
  19613. If WITH-TIME is non-nil, returns the time of the event at point (in
  19614. the agenda) or the current time of the day."
  19615. (let (date day defd tp hod mod)
  19616. (when with-time
  19617. (setq tp (get-text-property (point) 'time))
  19618. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  19619. (setq hod (string-to-number (match-string 1 tp))
  19620. mod (string-to-number (match-string 2 tp))))
  19621. (or tp (let ((now (decode-time)))
  19622. (setq hod (nth 2 now)
  19623. mod (nth 1 now)))))
  19624. (cond
  19625. ((eq major-mode 'calendar-mode)
  19626. (setq date (calendar-cursor-to-date)
  19627. defd (encode-time 0 (or mod 0) (or hod 0)
  19628. (nth 1 date) (nth 0 date) (nth 2 date))))
  19629. ((eq major-mode 'org-agenda-mode)
  19630. (setq day (get-text-property (point) 'day))
  19631. (when day
  19632. (setq date (calendar-gregorian-from-absolute day)
  19633. defd (encode-time 0 (or mod 0) (or hod 0)
  19634. (nth 1 date) (nth 0 date) (nth 2 date))))))
  19635. (or defd (current-time))))
  19636. (defun org-mark-subtree (&optional up)
  19637. "Mark the current subtree.
  19638. This puts point at the start of the current subtree, and mark at
  19639. the end. If a numeric prefix UP is given, move up into the
  19640. hierarchy of headlines by UP levels before marking the subtree."
  19641. (interactive "P")
  19642. (org-with-limited-levels
  19643. (cond ((org-at-heading-p) (beginning-of-line))
  19644. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  19645. (t (outline-previous-visible-heading 1))))
  19646. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  19647. (if (called-interactively-p 'any)
  19648. (call-interactively 'org-mark-element)
  19649. (org-mark-element)))
  19650. ;;; Indentation
  19651. (defvar org-element-greater-elements)
  19652. (defun org--get-expected-indentation (element contentsp)
  19653. "Expected indentation column for current line, according to ELEMENT.
  19654. ELEMENT is an element containing point. CONTENTSP is non-nil
  19655. when indentation is to be computed according to contents of
  19656. ELEMENT."
  19657. (let ((type (org-element-type element))
  19658. (start (org-element-property :begin element))
  19659. (post-affiliated (org-element-property :post-affiliated element)))
  19660. (org-with-wide-buffer
  19661. (cond
  19662. (contentsp
  19663. (cl-case type
  19664. ((diary-sexp footnote-definition) 0)
  19665. ((headline inlinetask nil)
  19666. (if (not org-adapt-indentation) 0
  19667. (let ((level (org-current-level)))
  19668. (if level (1+ level) 0))))
  19669. ((item plain-list) (org-list-item-body-column post-affiliated))
  19670. (t
  19671. (goto-char start)
  19672. (org-get-indentation))))
  19673. ((memq type '(headline inlinetask nil))
  19674. (if (org-match-line "[ \t]*$")
  19675. (org--get-expected-indentation element t)
  19676. 0))
  19677. ((memq type '(diary-sexp footnote-definition)) 0)
  19678. ;; First paragraph of a footnote definition or an item.
  19679. ;; Indent like parent.
  19680. ((< (line-beginning-position) start)
  19681. (org--get-expected-indentation
  19682. (org-element-property :parent element) t))
  19683. ;; At first line: indent according to previous sibling, if any,
  19684. ;; ignoring footnote definitions and inline tasks, or parent's
  19685. ;; contents.
  19686. ((= (line-beginning-position) start)
  19687. (catch 'exit
  19688. (while t
  19689. (if (= (point-min) start) (throw 'exit 0)
  19690. (goto-char (1- start))
  19691. (let* ((previous (org-element-at-point))
  19692. (parent previous))
  19693. (while (and parent (<= (org-element-property :end parent) start))
  19694. (setq previous parent
  19695. parent (org-element-property :parent parent)))
  19696. (cond
  19697. ((not previous) (throw 'exit 0))
  19698. ((> (org-element-property :end previous) start)
  19699. (throw 'exit (org--get-expected-indentation previous t)))
  19700. ((memq (org-element-type previous)
  19701. '(footnote-definition inlinetask))
  19702. (setq start (org-element-property :begin previous)))
  19703. (t (goto-char (org-element-property :begin previous))
  19704. (throw 'exit
  19705. (if (bolp) (org-get-indentation)
  19706. ;; At first paragraph in an item or
  19707. ;; a footnote definition.
  19708. (org--get-expected-indentation
  19709. (org-element-property :parent previous) t))))))))))
  19710. ;; Otherwise, move to the first non-blank line above.
  19711. (t
  19712. (beginning-of-line)
  19713. (let ((pos (point)))
  19714. (skip-chars-backward " \r\t\n")
  19715. (cond
  19716. ;; Two blank lines end a footnote definition or a plain
  19717. ;; list. When we indent an empty line after them, the
  19718. ;; containing list or footnote definition is over, so it
  19719. ;; qualifies as a previous sibling. Therefore, we indent
  19720. ;; like its first line.
  19721. ((and (memq type '(footnote-definition plain-list))
  19722. (> (count-lines (point) pos) 2))
  19723. (goto-char start)
  19724. (org-get-indentation))
  19725. ;; Line above is the first one of a paragraph at the
  19726. ;; beginning of an item or a footnote definition. Indent
  19727. ;; like parent.
  19728. ((< (line-beginning-position) start)
  19729. (org--get-expected-indentation
  19730. (org-element-property :parent element) t))
  19731. ;; Line above is the beginning of an element, i.e., point
  19732. ;; was originally on the blank lines between element's start
  19733. ;; and contents.
  19734. ((= (line-beginning-position) post-affiliated)
  19735. (org--get-expected-indentation element t))
  19736. ;; POS is after contents in a greater element. Indent like
  19737. ;; the beginning of the element.
  19738. ((and (memq type org-element-greater-elements)
  19739. (let ((cend (org-element-property :contents-end element)))
  19740. (and cend (<= cend pos))))
  19741. ;; As a special case, if point is at the end of a footnote
  19742. ;; definition or an item, indent like the very last element
  19743. ;; within. If that last element is an item, indent like
  19744. ;; its contents.
  19745. (if (memq type '(footnote-definition item plain-list))
  19746. (let ((last (org-element-at-point)))
  19747. (goto-char pos)
  19748. (org--get-expected-indentation
  19749. last (eq (org-element-type last) 'item)))
  19750. (goto-char start)
  19751. (org-get-indentation)))
  19752. ;; In any other case, indent like the current line.
  19753. (t (org-get-indentation)))))))))
  19754. (defun org--align-node-property ()
  19755. "Align node property at point.
  19756. Alignment is done according to `org-property-format', which see."
  19757. (when (save-excursion
  19758. (beginning-of-line)
  19759. (looking-at org-property-re))
  19760. (replace-match
  19761. (concat (match-string 4)
  19762. (org-trim
  19763. (format org-property-format (match-string 1) (match-string 3))))
  19764. t t)))
  19765. (defun org-indent-line ()
  19766. "Indent line depending on context.
  19767. Indentation is done according to the following rules:
  19768. - Footnote definitions, diary sexps, headlines and inline tasks
  19769. have to start at column 0.
  19770. - On the very first line of an element, consider, in order, the
  19771. next rules until one matches:
  19772. 1. If there's a sibling element before, ignoring footnote
  19773. definitions and inline tasks, indent like its first line.
  19774. 2. If element has a parent, indent like its contents. More
  19775. precisely, if parent is an item, indent after the
  19776. description part, if any, or the bullet (see
  19777. `org-list-description-max-indent'). Else, indent like
  19778. parent's first line.
  19779. 3. Otherwise, indent relatively to current level, if
  19780. `org-adapt-indentation' is non-nil, or to left margin.
  19781. - On a blank line at the end of an element, indent according to
  19782. the type of the element. More precisely
  19783. 1. If element is a plain list, an item, or a footnote
  19784. definition, indent like the very last element within.
  19785. 2. If element is a paragraph, indent like its last non blank
  19786. line.
  19787. 3. Otherwise, indent like its very first line.
  19788. - In the code part of a source block, use language major mode
  19789. to indent current line if `org-src-tab-acts-natively' is
  19790. non-nil. If it is nil, do nothing.
  19791. - Otherwise, indent like the first non-blank line above.
  19792. The function doesn't indent an item as it could break the whole
  19793. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  19794. `\\[org-shiftmetaright]'.
  19795. Also align node properties according to `org-property-format'."
  19796. (interactive)
  19797. (cond
  19798. ((org-at-heading-p) 'noindent)
  19799. (t
  19800. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  19801. (type (org-element-type element)))
  19802. (cond ((and (memq type '(plain-list item))
  19803. (= (line-beginning-position)
  19804. (org-element-property :post-affiliated element)))
  19805. 'noindent)
  19806. ((and (eq type 'latex-environment)
  19807. (>= (point) (org-element-property :post-affiliated element))
  19808. (< (point) (org-with-wide-buffer
  19809. (goto-char (org-element-property :end element))
  19810. (skip-chars-backward " \r\t\n")
  19811. (line-beginning-position 2))))
  19812. 'noindent)
  19813. ((and (eq type 'src-block)
  19814. org-src-tab-acts-natively
  19815. (> (line-beginning-position)
  19816. (org-element-property :post-affiliated element))
  19817. (< (line-beginning-position)
  19818. (org-with-wide-buffer
  19819. (goto-char (org-element-property :end element))
  19820. (skip-chars-backward " \r\t\n")
  19821. (line-beginning-position))))
  19822. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  19823. (t
  19824. (let ((column (org--get-expected-indentation element nil)))
  19825. ;; Preserve current column.
  19826. (if (<= (current-column) (current-indentation))
  19827. (indent-line-to column)
  19828. (save-excursion (indent-line-to column))))
  19829. ;; Align node property. Also preserve current column.
  19830. (when (eq type 'node-property)
  19831. (let ((column (current-column)))
  19832. (org--align-node-property)
  19833. (org-move-to-column column)))))))))
  19834. (defun org-indent-region (start end)
  19835. "Indent each non-blank line in the region.
  19836. Called from a program, START and END specify the region to
  19837. indent. The function will not indent contents of example blocks,
  19838. verse blocks and export blocks as leading white spaces are
  19839. assumed to be significant there."
  19840. (interactive "r")
  19841. (save-excursion
  19842. (goto-char start)
  19843. (skip-chars-forward " \r\t\n")
  19844. (unless (eobp) (beginning-of-line))
  19845. (let ((indent-to
  19846. (lambda (ind pos)
  19847. ;; Set IND as indentation for all lines between point and
  19848. ;; POS. Blank lines are ignored. Leave point after POS
  19849. ;; once done.
  19850. (let ((limit (copy-marker pos)))
  19851. (while (< (point) limit)
  19852. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  19853. (forward-line))
  19854. (set-marker limit nil))))
  19855. (end (copy-marker end)))
  19856. (while (< (point) end)
  19857. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  19858. (let* ((element (org-element-at-point))
  19859. (type (org-element-type element))
  19860. (element-end (copy-marker (org-element-property :end element)))
  19861. (ind (org--get-expected-indentation element nil)))
  19862. (cond
  19863. ;; Element indented as a single block. Example blocks
  19864. ;; preserving indentation are a special case since the
  19865. ;; "contents" must not be indented whereas the block
  19866. ;; boundaries can.
  19867. ((or (memq type '(export-block latex-environment))
  19868. (and (eq type 'example-block)
  19869. (not
  19870. (or org-src-preserve-indentation
  19871. (org-element-property :preserve-indent element)))))
  19872. (let ((offset (- ind (org-get-indentation))))
  19873. (unless (zerop offset)
  19874. (indent-rigidly (org-element-property :begin element)
  19875. (org-element-property :end element)
  19876. offset)))
  19877. (goto-char element-end))
  19878. ;; Elements indented line wise. Be sure to exclude
  19879. ;; example blocks (preserving indentation) and source
  19880. ;; blocks from this category as they are treated
  19881. ;; specially later.
  19882. ((or (memq type '(paragraph table table-row))
  19883. (not (or (org-element-property :contents-begin element)
  19884. (memq type '(example-block src-block)))))
  19885. (when (eq type 'node-property)
  19886. (org--align-node-property)
  19887. (beginning-of-line))
  19888. (funcall indent-to ind (min element-end end)))
  19889. ;; Elements consisting of three parts: before the
  19890. ;; contents, the contents, and after the contents. The
  19891. ;; contents are treated specially, according to the
  19892. ;; element type, or not indented at all. Other parts are
  19893. ;; indented as a single block.
  19894. (t
  19895. (let* ((post (copy-marker
  19896. (org-element-property :post-affiliated element)))
  19897. (cbeg
  19898. (copy-marker
  19899. (cond
  19900. ((not (org-element-property :contents-begin element))
  19901. ;; Fake contents for source blocks.
  19902. (org-with-wide-buffer
  19903. (goto-char post)
  19904. (line-beginning-position 2)))
  19905. ((memq type '(footnote-definition item plain-list))
  19906. ;; Contents in these elements could start on
  19907. ;; the same line as the beginning of the
  19908. ;; element. Make sure we start indenting
  19909. ;; from the second line.
  19910. (org-with-wide-buffer
  19911. (goto-char post)
  19912. (end-of-line)
  19913. (skip-chars-forward " \r\t\n")
  19914. (if (eobp) (point) (line-beginning-position))))
  19915. (t (org-element-property :contents-begin element)))))
  19916. (cend (copy-marker
  19917. (or (org-element-property :contents-end element)
  19918. ;; Fake contents for source blocks.
  19919. (org-with-wide-buffer
  19920. (goto-char element-end)
  19921. (skip-chars-backward " \r\t\n")
  19922. (line-beginning-position)))
  19923. t)))
  19924. ;; Do not change items indentation individually as it
  19925. ;; might break the list as a whole. On the other
  19926. ;; hand, when at a plain list, indent it as a whole.
  19927. (cond ((eq type 'plain-list)
  19928. (let ((offset (- ind (org-get-indentation))))
  19929. (unless (zerop offset)
  19930. (indent-rigidly (org-element-property :begin element)
  19931. (org-element-property :end element)
  19932. offset))
  19933. (goto-char cbeg)))
  19934. ((eq type 'item) (goto-char cbeg))
  19935. (t (funcall indent-to ind (min cbeg end))))
  19936. (when (< (point) end)
  19937. (cl-case type
  19938. ((example-block verse-block))
  19939. (src-block
  19940. ;; In a source block, indent source code
  19941. ;; according to language major mode, but only if
  19942. ;; `org-src-tab-acts-natively' is non-nil.
  19943. (when (and (< (point) end) org-src-tab-acts-natively)
  19944. (ignore-errors
  19945. (org-babel-do-in-edit-buffer
  19946. (indent-region (point-min) (point-max))))))
  19947. (t (org-indent-region (point) (min cend end))))
  19948. (goto-char (min cend end))
  19949. (when (< (point) end)
  19950. (funcall indent-to ind (min element-end end))))
  19951. (set-marker post nil)
  19952. (set-marker cbeg nil)
  19953. (set-marker cend nil))))
  19954. (set-marker element-end nil))))
  19955. (set-marker end nil))))
  19956. (defun org-indent-drawer ()
  19957. "Indent the drawer at point."
  19958. (interactive)
  19959. (unless (save-excursion
  19960. (beginning-of-line)
  19961. (looking-at-p org-drawer-regexp))
  19962. (user-error "Not at a drawer"))
  19963. (let ((element (org-element-at-point)))
  19964. (unless (memq (org-element-type element) '(drawer property-drawer))
  19965. (user-error "Not at a drawer"))
  19966. (org-with-wide-buffer
  19967. (org-indent-region (org-element-property :begin element)
  19968. (org-element-property :end element))))
  19969. (message "Drawer at point indented"))
  19970. (defun org-indent-block ()
  19971. "Indent the block at point."
  19972. (interactive)
  19973. (unless (save-excursion
  19974. (beginning-of-line)
  19975. (let ((case-fold-search t))
  19976. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  19977. (user-error "Not at a block"))
  19978. (let ((element (org-element-at-point)))
  19979. (unless (memq (org-element-type element)
  19980. '(comment-block center-block dynamic-block example-block
  19981. export-block quote-block special-block
  19982. src-block verse-block))
  19983. (user-error "Not at a block"))
  19984. (org-with-wide-buffer
  19985. (org-indent-region (org-element-property :begin element)
  19986. (org-element-property :end element))))
  19987. (message "Block at point indented"))
  19988. ;;; Filling
  19989. ;; We use our own fill-paragraph and auto-fill functions.
  19990. ;; `org-fill-paragraph' relies on adaptive filling and context
  19991. ;; checking. Appropriate `fill-prefix' is computed with
  19992. ;; `org-adaptive-fill-function'.
  19993. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  19994. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  19995. ;; `org-adaptive-fill-function' value. Internally,
  19996. ;; `org-comment-line-break-function' breaks the line.
  19997. ;; `org-setup-filling' installs filling and auto-filling related
  19998. ;; variables during `org-mode' initialization.
  19999. (defun org-setup-filling ()
  20000. (require 'org-element)
  20001. ;; Prevent auto-fill from inserting unwanted new items.
  20002. (when (boundp 'fill-nobreak-predicate)
  20003. (setq-local
  20004. fill-nobreak-predicate
  20005. (org-uniquify
  20006. (append fill-nobreak-predicate
  20007. '(org-fill-line-break-nobreak-p
  20008. org-fill-n-macro-as-item-nobreak-p
  20009. org-fill-paragraph-with-timestamp-nobreak-p)))))
  20010. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  20011. (setq-local paragraph-start paragraph-ending)
  20012. (setq-local paragraph-separate paragraph-ending))
  20013. (setq-local fill-paragraph-function 'org-fill-paragraph)
  20014. (setq-local auto-fill-inhibit-regexp nil)
  20015. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  20016. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  20017. (setq-local comment-line-break-function 'org-comment-line-break-function))
  20018. (defun org-fill-line-break-nobreak-p ()
  20019. "Non-nil when a new line at point would create an Org line break."
  20020. (save-excursion
  20021. (skip-chars-backward "[ \t]")
  20022. (skip-chars-backward "\\\\")
  20023. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  20024. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  20025. "Non-nil when a new line at point would split a timestamp."
  20026. (and (org-at-timestamp-p 'lax)
  20027. (not (looking-at org-ts-regexp-both))))
  20028. (defun org-fill-n-macro-as-item-nobreak-p ()
  20029. "Non-nil when a new line at point would create a new list."
  20030. ;; During export, a "n" macro followed by a dot or a closing
  20031. ;; parenthesis can end up being parsed as a new list item.
  20032. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  20033. (defvar orgtbl-line-start-regexp) ; From org-table.el
  20034. (defun org-adaptive-fill-function ()
  20035. "Compute a fill prefix for the current line.
  20036. Return fill prefix, as a string, or nil if current line isn't
  20037. meant to be filled. For convenience, if `adaptive-fill-regexp'
  20038. matches in paragraphs or comments, use it."
  20039. (org-with-wide-buffer
  20040. (unless (org-at-heading-p)
  20041. (let* ((p (line-beginning-position))
  20042. (element (save-excursion
  20043. (beginning-of-line)
  20044. (org-element-at-point)))
  20045. (type (org-element-type element))
  20046. (post-affiliated (org-element-property :post-affiliated element)))
  20047. (unless (< p post-affiliated)
  20048. (cl-case type
  20049. (comment
  20050. (save-excursion
  20051. (beginning-of-line)
  20052. (looking-at "[ \t]*")
  20053. (concat (match-string 0) "# ")))
  20054. (footnote-definition "")
  20055. ((item plain-list)
  20056. (make-string (org-list-item-body-column post-affiliated) ?\s))
  20057. (paragraph
  20058. ;; Fill prefix is usually the same as the current line,
  20059. ;; unless the paragraph is at the beginning of an item.
  20060. (let ((parent (org-element-property :parent element)))
  20061. (save-excursion
  20062. (beginning-of-line)
  20063. (cond ((eq (org-element-type parent) 'item)
  20064. (make-string (org-list-item-body-column
  20065. (org-element-property :begin parent))
  20066. ?\s))
  20067. ((and adaptive-fill-regexp
  20068. ;; Locally disable
  20069. ;; `adaptive-fill-function' to let
  20070. ;; `fill-context-prefix' handle
  20071. ;; `adaptive-fill-regexp' variable.
  20072. (let (adaptive-fill-function)
  20073. (fill-context-prefix
  20074. post-affiliated
  20075. (org-element-property :end element)))))
  20076. ((looking-at "[ \t]+") (match-string 0))
  20077. (t "")))))
  20078. (comment-block
  20079. ;; Only fill contents if P is within block boundaries.
  20080. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  20081. (forward-line)
  20082. (point)))
  20083. (cend (save-excursion
  20084. (goto-char (org-element-property :end element))
  20085. (skip-chars-backward " \r\t\n")
  20086. (line-beginning-position))))
  20087. (when (and (>= p cbeg) (< p cend))
  20088. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  20089. (match-string 0)
  20090. ""))))))))))
  20091. (defun org-fill-element (&optional justify)
  20092. "Fill element at point, when applicable.
  20093. This function only applies to comment blocks, comments, example
  20094. blocks and paragraphs. Also, as a special case, re-align table
  20095. when point is at one.
  20096. If JUSTIFY is non-nil (interactively, with prefix argument),
  20097. justify as well. If `sentence-end-double-space' is non-nil, then
  20098. period followed by one space does not end a sentence, so don't
  20099. break a line there. The variable `fill-column' controls the
  20100. width for filling.
  20101. For convenience, when point is at a plain list, an item or
  20102. a footnote definition, try to fill the first paragraph within."
  20103. (with-syntax-table org-mode-transpose-word-syntax-table
  20104. ;; Move to end of line in order to get the first paragraph within
  20105. ;; a plain list or a footnote definition.
  20106. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  20107. ;; First check if point is in a blank line at the beginning of
  20108. ;; the buffer. In that case, ignore filling.
  20109. (cl-case (org-element-type element)
  20110. ;; Use major mode filling function is src blocks.
  20111. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  20112. ;; Align Org tables, leave table.el tables as-is.
  20113. (table-row (org-table-align) t)
  20114. (table
  20115. (when (eq (org-element-property :type element) 'org)
  20116. (save-excursion
  20117. (goto-char (org-element-property :post-affiliated element))
  20118. (org-table-align)))
  20119. t)
  20120. (paragraph
  20121. ;; Paragraphs may contain `line-break' type objects.
  20122. (let ((beg (max (point-min)
  20123. (org-element-property :contents-begin element)))
  20124. (end (min (point-max)
  20125. (org-element-property :contents-end element))))
  20126. ;; Do nothing if point is at an affiliated keyword.
  20127. (if (< (line-end-position) beg) t
  20128. ;; Fill paragraph, taking line breaks into account.
  20129. (save-excursion
  20130. (goto-char beg)
  20131. (let ((cuts (list beg)))
  20132. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  20133. (when (eq 'line-break
  20134. (org-element-type
  20135. (save-excursion (backward-char)
  20136. (org-element-context))))
  20137. (push (point) cuts)))
  20138. (dolist (c (delq end cuts))
  20139. (fill-region-as-paragraph c end justify)
  20140. (setq end c))))
  20141. t)))
  20142. ;; Contents of `comment-block' type elements should be
  20143. ;; filled as plain text, but only if point is within block
  20144. ;; markers.
  20145. (comment-block
  20146. (let* ((case-fold-search t)
  20147. (beg (save-excursion
  20148. (goto-char (org-element-property :begin element))
  20149. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  20150. (forward-line)
  20151. (point)))
  20152. (end (save-excursion
  20153. (goto-char (org-element-property :end element))
  20154. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  20155. (line-beginning-position))))
  20156. (if (or (< (point) beg) (> (point) end)) t
  20157. (fill-region-as-paragraph
  20158. (save-excursion (end-of-line)
  20159. (re-search-backward "^[ \t]*$" beg 'move)
  20160. (line-beginning-position))
  20161. (save-excursion (beginning-of-line)
  20162. (re-search-forward "^[ \t]*$" end 'move)
  20163. (line-beginning-position))
  20164. justify))))
  20165. ;; Fill comments.
  20166. (comment
  20167. (let ((begin (org-element-property :post-affiliated element))
  20168. (end (org-element-property :end element)))
  20169. (when (and (>= (point) begin) (<= (point) end))
  20170. (let ((begin (save-excursion
  20171. (end-of-line)
  20172. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  20173. (progn (forward-line) (point))
  20174. begin)))
  20175. (end (save-excursion
  20176. (end-of-line)
  20177. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  20178. (1- (line-beginning-position))
  20179. (skip-chars-backward " \r\t\n")
  20180. (line-end-position)))))
  20181. ;; Do not fill comments when at a blank line.
  20182. (when (> end begin)
  20183. (let ((fill-prefix
  20184. (save-excursion
  20185. (beginning-of-line)
  20186. (looking-at "[ \t]*#")
  20187. (let ((comment-prefix (match-string 0)))
  20188. (goto-char (match-end 0))
  20189. (if (looking-at adaptive-fill-regexp)
  20190. (concat comment-prefix (match-string 0))
  20191. (concat comment-prefix " "))))))
  20192. (save-excursion
  20193. (fill-region-as-paragraph begin end justify))))))
  20194. t))
  20195. ;; Ignore every other element.
  20196. (otherwise t)))))
  20197. (defun org-fill-paragraph (&optional justify region)
  20198. "Fill element at point, when applicable.
  20199. This function only applies to comment blocks, comments, example
  20200. blocks and paragraphs. Also, as a special case, re-align table
  20201. when point is at one.
  20202. For convenience, when point is at a plain list, an item or
  20203. a footnote definition, try to fill the first paragraph within.
  20204. If JUSTIFY is non-nil (interactively, with prefix argument),
  20205. justify as well. If `sentence-end-double-space' is non-nil, then
  20206. period followed by one space does not end a sentence, so don't
  20207. break a line there. The variable `fill-column' controls the
  20208. width for filling.
  20209. The REGION argument is non-nil if called interactively; in that
  20210. case, if Transient Mark mode is enabled and the mark is active,
  20211. fill each of the elements in the active region, instead of just
  20212. filling the current element."
  20213. (interactive (progn
  20214. (barf-if-buffer-read-only)
  20215. (list (if current-prefix-arg 'full) t)))
  20216. (cond
  20217. ((and region transient-mark-mode mark-active
  20218. (not (eq (region-beginning) (region-end))))
  20219. (let ((origin (point-marker))
  20220. (start (region-beginning)))
  20221. (unwind-protect
  20222. (progn
  20223. (goto-char (region-end))
  20224. (while (> (point) start)
  20225. (org-backward-paragraph)
  20226. (org-fill-element justify)))
  20227. (goto-char origin)
  20228. (set-marker origin nil))))
  20229. (t (org-fill-element justify))))
  20230. (defun org-auto-fill-function ()
  20231. "Auto-fill function."
  20232. ;; Check if auto-filling is meaningful.
  20233. (let ((fc (current-fill-column)))
  20234. (when (and fc (> (current-column) fc))
  20235. (let* ((fill-prefix (org-adaptive-fill-function))
  20236. ;; Enforce empty fill prefix, if required. Otherwise, it
  20237. ;; will be computed again.
  20238. (adaptive-fill-mode (not (equal fill-prefix ""))))
  20239. (when fill-prefix (do-auto-fill))))))
  20240. (defun org-comment-line-break-function (&optional soft)
  20241. "Break line at point and indent, continuing comment if within one.
  20242. The inserted newline is marked hard if variable
  20243. `use-hard-newlines' is true, unless optional argument SOFT is
  20244. non-nil."
  20245. (if soft (insert-and-inherit ?\n) (newline 1))
  20246. (save-excursion (forward-char -1) (delete-horizontal-space))
  20247. (delete-horizontal-space)
  20248. (indent-to-left-margin)
  20249. (insert-before-markers-and-inherit fill-prefix))
  20250. ;;; Fixed Width Areas
  20251. (defun org-toggle-fixed-width ()
  20252. "Toggle fixed-width markup.
  20253. Add or remove fixed-width markup on current line, whenever it
  20254. makes sense. Return an error otherwise.
  20255. If a region is active and if it contains only fixed-width areas
  20256. or blank lines, remove all fixed-width markup in it. If the
  20257. region contains anything else, convert all non-fixed-width lines
  20258. to fixed-width ones.
  20259. Blank lines at the end of the region are ignored unless the
  20260. region only contains such lines."
  20261. (interactive)
  20262. (if (not (org-region-active-p))
  20263. ;; No region:
  20264. ;;
  20265. ;; Remove fixed width marker only in a fixed-with element.
  20266. ;;
  20267. ;; Add fixed width maker in paragraphs, in blank lines after
  20268. ;; elements or at the beginning of a headline or an inlinetask,
  20269. ;; and before any one-line elements (e.g., a clock).
  20270. (progn
  20271. (beginning-of-line)
  20272. (let* ((element (org-element-at-point))
  20273. (type (org-element-type element)))
  20274. (cond
  20275. ((and (eq type 'fixed-width)
  20276. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  20277. (replace-match
  20278. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  20279. ((and (memq type '(babel-call clock comment diary-sexp headline
  20280. horizontal-rule keyword paragraph
  20281. planning))
  20282. (<= (org-element-property :post-affiliated element) (point)))
  20283. (skip-chars-forward " \t")
  20284. (insert ": "))
  20285. ((and (looking-at-p "[ \t]*$")
  20286. (or (eq type 'inlinetask)
  20287. (save-excursion
  20288. (skip-chars-forward " \r\t\n")
  20289. (<= (org-element-property :end element) (point)))))
  20290. (delete-region (point) (line-end-position))
  20291. (org-indent-line)
  20292. (insert ": "))
  20293. (t (user-error "Cannot insert a fixed-width line here")))))
  20294. ;; Region active.
  20295. (let* ((begin (save-excursion
  20296. (goto-char (region-beginning))
  20297. (line-beginning-position)))
  20298. (end (copy-marker
  20299. (save-excursion
  20300. (goto-char (region-end))
  20301. (unless (eolp) (beginning-of-line))
  20302. (if (save-excursion (re-search-backward "\\S-" begin t))
  20303. (progn (skip-chars-backward " \r\t\n") (point))
  20304. (point)))))
  20305. (all-fixed-width-p
  20306. (catch 'not-all-p
  20307. (save-excursion
  20308. (goto-char begin)
  20309. (skip-chars-forward " \r\t\n")
  20310. (when (eobp) (throw 'not-all-p nil))
  20311. (while (< (point) end)
  20312. (let ((element (org-element-at-point)))
  20313. (if (eq (org-element-type element) 'fixed-width)
  20314. (goto-char (org-element-property :end element))
  20315. (throw 'not-all-p nil))))
  20316. t))))
  20317. (if all-fixed-width-p
  20318. (save-excursion
  20319. (goto-char begin)
  20320. (while (< (point) end)
  20321. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  20322. (replace-match
  20323. "" nil nil nil
  20324. (if (= (line-end-position) (match-end 0)) 0 1)))
  20325. (forward-line)))
  20326. (let ((min-ind (point-max)))
  20327. ;; Find minimum indentation across all lines.
  20328. (save-excursion
  20329. (goto-char begin)
  20330. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  20331. (setq min-ind 0)
  20332. (catch 'zerop
  20333. (while (< (point) end)
  20334. (unless (looking-at-p "[ \t]*$")
  20335. (let ((ind (org-get-indentation)))
  20336. (setq min-ind (min min-ind ind))
  20337. (when (zerop ind) (throw 'zerop t))))
  20338. (forward-line)))))
  20339. ;; Loop over all lines and add fixed-width markup everywhere
  20340. ;; but in fixed-width lines.
  20341. (save-excursion
  20342. (goto-char begin)
  20343. (while (< (point) end)
  20344. (cond
  20345. ((org-at-heading-p)
  20346. (insert ": ")
  20347. (forward-line)
  20348. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  20349. (insert ":")
  20350. (forward-line)))
  20351. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  20352. (let* ((element (org-element-at-point))
  20353. (element-end (org-element-property :end element)))
  20354. (if (eq (org-element-type element) 'fixed-width)
  20355. (progn (goto-char element-end)
  20356. (skip-chars-backward " \r\t\n")
  20357. (forward-line))
  20358. (let ((limit (min end element-end)))
  20359. (while (< (point) limit)
  20360. (org-move-to-column min-ind t)
  20361. (insert ": ")
  20362. (forward-line))))))
  20363. (t
  20364. (org-move-to-column min-ind t)
  20365. (insert ": ")
  20366. (forward-line)))))))
  20367. (set-marker end nil))))
  20368. ;;; Blocks
  20369. (defun org-block-map (function &optional start end)
  20370. "Call FUNCTION at the head of all source blocks in the current buffer.
  20371. Optional arguments START and END can be used to limit the range."
  20372. (let ((start (or start (point-min)))
  20373. (end (or end (point-max))))
  20374. (save-excursion
  20375. (goto-char start)
  20376. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  20377. (save-excursion
  20378. (save-match-data
  20379. (goto-char (match-beginning 0))
  20380. (funcall function)))))))
  20381. (defun org-next-block (arg &optional backward block-regexp)
  20382. "Jump to the next block.
  20383. With a prefix argument ARG, jump forward ARG many blocks.
  20384. When BACKWARD is non-nil, jump to the previous block.
  20385. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  20386. Match data is set according to this regexp when the function
  20387. returns.
  20388. Return point at beginning of the opening line of found block.
  20389. Throw an error if no block is found."
  20390. (interactive "p")
  20391. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  20392. (case-fold-search t)
  20393. (search-fn (if backward #'re-search-backward #'re-search-forward))
  20394. (count (or arg 1))
  20395. (origin (point))
  20396. last-element)
  20397. (if backward (beginning-of-line) (end-of-line))
  20398. (while (and (> count 0) (funcall search-fn re nil t))
  20399. (let ((element (save-excursion
  20400. (goto-char (match-beginning 0))
  20401. (save-match-data (org-element-at-point)))))
  20402. (when (and (memq (org-element-type element)
  20403. '(center-block comment-block dynamic-block
  20404. example-block export-block quote-block
  20405. special-block src-block verse-block))
  20406. (<= (match-beginning 0)
  20407. (org-element-property :post-affiliated element)))
  20408. (setq last-element element)
  20409. (cl-decf count))))
  20410. (if (= count 0)
  20411. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  20412. (save-match-data (org-show-context)))
  20413. (goto-char origin)
  20414. (user-error "No %s code blocks" (if backward "previous" "further")))))
  20415. (defun org-previous-block (arg &optional block-regexp)
  20416. "Jump to the previous block.
  20417. With a prefix argument ARG, jump backward ARG many source blocks.
  20418. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  20419. (interactive "p")
  20420. (org-next-block arg t block-regexp))
  20421. ;;; Comments
  20422. ;; Org comments syntax is quite complex. It requires the entire line
  20423. ;; to be just a comment. Also, even with the right syntax at the
  20424. ;; beginning of line, some elements (e.g., verse-block or
  20425. ;; example-block) don't accept comments. Usual Emacs comment commands
  20426. ;; cannot cope with those requirements. Therefore, Org replaces them.
  20427. ;; Org still relies on `comment-dwim', but cannot trust
  20428. ;; `comment-only-p'. So, `comment-region-function' and
  20429. ;; `uncomment-region-function' both point
  20430. ;; to`org-comment-or-uncomment-region'. Eventually,
  20431. ;; `org-insert-comment' takes care of insertion of comments at the
  20432. ;; beginning of line.
  20433. ;; `org-setup-comments-handling' install comments related variables
  20434. ;; during `org-mode' initialization.
  20435. (defun org-setup-comments-handling ()
  20436. (interactive)
  20437. (setq-local comment-use-syntax nil)
  20438. (setq-local comment-start "# ")
  20439. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  20440. (setq-local comment-insert-comment-function 'org-insert-comment)
  20441. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  20442. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  20443. (defun org-insert-comment ()
  20444. "Insert an empty comment above current line.
  20445. If the line is empty, insert comment at its beginning. When
  20446. point is within a source block, comment according to the related
  20447. major mode."
  20448. (if (let ((element (org-element-at-point)))
  20449. (and (eq (org-element-type element) 'src-block)
  20450. (< (save-excursion
  20451. (goto-char (org-element-property :post-affiliated element))
  20452. (line-end-position))
  20453. (point))
  20454. (> (save-excursion
  20455. (goto-char (org-element-property :end element))
  20456. (skip-chars-backward " \r\t\n")
  20457. (line-beginning-position))
  20458. (point))))
  20459. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  20460. (beginning-of-line)
  20461. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  20462. (open-line 1))
  20463. (org-indent-line)
  20464. (insert "# ")))
  20465. (defvar comment-empty-lines) ; From newcomment.el.
  20466. (defun org-comment-or-uncomment-region (beg end &rest _)
  20467. "Comment or uncomment each non-blank line in the region.
  20468. Uncomment each non-blank line between BEG and END if it only
  20469. contains commented lines. Otherwise, comment them. If region is
  20470. strictly within a source block, use appropriate comment syntax."
  20471. (if (let ((element (org-element-at-point)))
  20472. (and (eq (org-element-type element) 'src-block)
  20473. (< (save-excursion
  20474. (goto-char (org-element-property :post-affiliated element))
  20475. (line-end-position))
  20476. beg)
  20477. (>= (save-excursion
  20478. (goto-char (org-element-property :end element))
  20479. (skip-chars-backward " \r\t\n")
  20480. (line-beginning-position))
  20481. end)))
  20482. ;; Translate region boundaries for the Org buffer to the source
  20483. ;; buffer.
  20484. (let ((offset (- end beg)))
  20485. (save-excursion
  20486. (goto-char beg)
  20487. (org-babel-do-in-edit-buffer
  20488. (comment-or-uncomment-region (point) (+ offset (point))))))
  20489. (save-restriction
  20490. ;; Restrict region
  20491. (narrow-to-region (save-excursion (goto-char beg)
  20492. (skip-chars-forward " \r\t\n" end)
  20493. (line-beginning-position))
  20494. (save-excursion (goto-char end)
  20495. (skip-chars-backward " \r\t\n" beg)
  20496. (line-end-position)))
  20497. (let ((uncommentp
  20498. ;; UNCOMMENTP is non-nil when every non blank line between
  20499. ;; BEG and END is a comment.
  20500. (save-excursion
  20501. (goto-char (point-min))
  20502. (while (and (not (eobp))
  20503. (let ((element (org-element-at-point)))
  20504. (and (eq (org-element-type element) 'comment)
  20505. (goto-char (min (point-max)
  20506. (org-element-property
  20507. :end element)))))))
  20508. (eobp))))
  20509. (if uncommentp
  20510. ;; Only blank lines and comments in region: uncomment it.
  20511. (save-excursion
  20512. (goto-char (point-min))
  20513. (while (not (eobp))
  20514. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  20515. (replace-match "" nil nil nil 1))
  20516. (forward-line)))
  20517. ;; Comment each line in region.
  20518. (let ((min-indent (point-max)))
  20519. ;; First find the minimum indentation across all lines.
  20520. (save-excursion
  20521. (goto-char (point-min))
  20522. (while (and (not (eobp)) (not (zerop min-indent)))
  20523. (unless (looking-at "[ \t]*$")
  20524. (setq min-indent (min min-indent (current-indentation))))
  20525. (forward-line)))
  20526. ;; Then loop over all lines.
  20527. (save-excursion
  20528. (goto-char (point-min))
  20529. (while (not (eobp))
  20530. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  20531. ;; Don't get fooled by invisible text (e.g. link path)
  20532. ;; when moving to column MIN-INDENT.
  20533. (let ((buffer-invisibility-spec nil))
  20534. (org-move-to-column min-indent t))
  20535. (insert comment-start))
  20536. (forward-line)))))))))
  20537. (defun org-comment-dwim (_arg)
  20538. "Call the comment command you mean.
  20539. Call `org-toggle-comment' if on a heading, otherwise call
  20540. `comment-dwim', within a source edit buffer if needed."
  20541. (interactive "*P")
  20542. (cond ((org-at-heading-p)
  20543. (call-interactively #'org-toggle-comment))
  20544. ((org-in-src-block-p)
  20545. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  20546. (t (call-interactively #'comment-dwim))))
  20547. ;;; Timestamps API
  20548. ;; This section contains tools to operate on, or create, timestamp
  20549. ;; objects, as returned by, e.g. `org-element-context'.
  20550. (defun org-timestamp-from-string (s)
  20551. "Convert Org timestamp S, as a string, into a timestamp object.
  20552. Return nil if S is not a valid timestamp string."
  20553. (when (org-string-nw-p s)
  20554. (with-temp-buffer
  20555. (save-excursion (insert s))
  20556. (org-element-timestamp-parser))))
  20557. (defun org-timestamp-from-time (time &optional with-time inactive)
  20558. "Convert a time value into a timestamp object.
  20559. TIME is an Emacs internal time representation, as returned, e.g.,
  20560. by `current-time'.
  20561. When optional argument WITH-TIME is non-nil, return a timestamp
  20562. object with a time part, i.e., with hours and minutes.
  20563. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  20564. return an active timestamp."
  20565. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  20566. (org-element-create 'timestamp
  20567. (list :type (if inactive 'inactive 'active)
  20568. :year-start year
  20569. :month-start month
  20570. :day-start day
  20571. :hour-start (and with-time hour)
  20572. :minute-start (and with-time minute)))))
  20573. (defun org-timestamp-to-time (timestamp &optional end)
  20574. "Convert TIMESTAMP object into an Emacs internal time value.
  20575. Use end of date range or time range when END is non-nil.
  20576. Otherwise, use its start."
  20577. (apply #'encode-time
  20578. (cons 0
  20579. (mapcar
  20580. (lambda (prop) (or (org-element-property prop timestamp) 0))
  20581. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  20582. '(:minute-start :hour-start :day-start :month-start
  20583. :year-start))))))
  20584. (defun org-timestamp-has-time-p (timestamp)
  20585. "Non-nil when TIMESTAMP has a time specified."
  20586. (org-element-property :hour-start timestamp))
  20587. (defun org-timestamp-format (timestamp format &optional end utc)
  20588. "Format a TIMESTAMP object into a string.
  20589. FORMAT is a format specifier to be passed to
  20590. `format-time-string'.
  20591. When optional argument END is non-nil, use end of date-range or
  20592. time-range, if possible.
  20593. When optional argument UTC is non-nil, time is be expressed as
  20594. Universal Time."
  20595. (format-time-string format (org-timestamp-to-time timestamp end)
  20596. (and utc t)))
  20597. (defun org-timestamp-split-range (timestamp &optional end)
  20598. "Extract a TIMESTAMP object from a date or time range.
  20599. END, when non-nil, means extract the end of the range.
  20600. Otherwise, extract its start.
  20601. Return a new timestamp object."
  20602. (let ((type (org-element-property :type timestamp)))
  20603. (if (memq type '(active inactive diary)) timestamp
  20604. (let ((split-ts (org-element-copy timestamp)))
  20605. ;; Set new type.
  20606. (org-element-put-property
  20607. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  20608. ;; Copy start properties over end properties if END is
  20609. ;; non-nil. Otherwise, copy end properties over `start' ones.
  20610. (let ((p-alist '((:minute-start . :minute-end)
  20611. (:hour-start . :hour-end)
  20612. (:day-start . :day-end)
  20613. (:month-start . :month-end)
  20614. (:year-start . :year-end))))
  20615. (dolist (p-cell p-alist)
  20616. (org-element-put-property
  20617. split-ts
  20618. (funcall (if end #'car #'cdr) p-cell)
  20619. (org-element-property
  20620. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  20621. ;; Eventually refresh `:raw-value'.
  20622. (org-element-put-property split-ts :raw-value nil)
  20623. (org-element-put-property
  20624. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  20625. (defun org-timestamp-translate (timestamp &optional boundary)
  20626. "Translate TIMESTAMP object to custom format.
  20627. Format string is defined in `org-time-stamp-custom-formats',
  20628. which see.
  20629. When optional argument BOUNDARY is non-nil, it is either the
  20630. symbol `start' or `end'. In this case, only translate the
  20631. starting or ending part of TIMESTAMP if it is a date or time
  20632. range. Otherwise, translate both parts.
  20633. Return timestamp as-is if `org-display-custom-times' is nil or if
  20634. it has a `diary' type."
  20635. (let ((type (org-element-property :type timestamp)))
  20636. (if (or (not org-display-custom-times) (eq type 'diary))
  20637. (org-element-interpret-data timestamp)
  20638. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  20639. org-time-stamp-custom-formats)))
  20640. (if (and (not boundary) (memq type '(active-range inactive-range)))
  20641. (concat (org-timestamp-format timestamp fmt)
  20642. "--"
  20643. (org-timestamp-format timestamp fmt t))
  20644. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  20645. ;;; Other stuff
  20646. (defvar reftex-docstruct-symbol)
  20647. (defvar org--rds)
  20648. (defun org-reftex-citation ()
  20649. "Use reftex-citation to insert a citation into the buffer.
  20650. This looks for a line like
  20651. #+BIBLIOGRAPHY: foo plain option:-d
  20652. and derives from it that foo.bib is the bibliography file relevant
  20653. for this document. It then installs the necessary environment for RefTeX
  20654. to work in this buffer and calls `reftex-citation' to insert a citation
  20655. into the buffer.
  20656. Export of such citations to both LaTeX and HTML is handled by the contributed
  20657. package ox-bibtex by Taru Karttunen."
  20658. (interactive)
  20659. (let ((reftex-docstruct-symbol 'org--rds)
  20660. org--rds bib)
  20661. (org-with-wide-buffer
  20662. (let ((case-fold-search t)
  20663. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  20664. (if (not (save-excursion
  20665. (or (re-search-forward re nil t)
  20666. (re-search-backward re nil t))))
  20667. (user-error "No bibliography defined in file")
  20668. (setq bib (concat (match-string 1) ".bib")
  20669. org--rds (list (list 'bib bib))))))
  20670. (call-interactively 'reftex-citation)))
  20671. ;;;; Functions extending outline functionality
  20672. (defun org-beginning-of-line (&optional n)
  20673. "Go to the beginning of the current visible line.
  20674. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  20675. symbol `reversed', on the first attempt move to where the
  20676. headline text starts, and only move to beginning of line when the
  20677. cursor is already before the start of the text of the headline.
  20678. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  20679. start of the text on the second attempt.
  20680. With argument N not nil or 1, move forward N - 1 lines first."
  20681. (interactive "^p")
  20682. (let ((origin (point))
  20683. (special (pcase org-special-ctrl-a/e
  20684. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  20685. deactivate-mark)
  20686. ;; First move to a visible line.
  20687. (if (bound-and-true-p visual-line-mode)
  20688. (beginning-of-visual-line n)
  20689. (move-beginning-of-line n)
  20690. ;; `move-beginning-of-line' may leave point after invisible
  20691. ;; characters if line starts with such of these (e.g., with
  20692. ;; a link at column 0). Really move to the beginning of the
  20693. ;; current visible line.
  20694. (beginning-of-line))
  20695. (cond
  20696. ;; No special behavior. Point is already at the beginning of
  20697. ;; a line, logical or visual.
  20698. ((not special))
  20699. ;; `beginning-of-visual-line' left point before logical beginning
  20700. ;; of line: point is at the beginning of a visual line. Bail
  20701. ;; out.
  20702. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  20703. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  20704. ;; At a headline, special position is before the title, but
  20705. ;; after any TODO keyword or priority cookie.
  20706. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  20707. (line-end-position)))
  20708. (bol (point)))
  20709. (if (eq special 'reversed)
  20710. (when (and (= origin bol) (eq last-command this-command))
  20711. (goto-char refpos))
  20712. (when (or (> origin refpos) (= origin bol))
  20713. (goto-char refpos)))))
  20714. ((and (looking-at org-list-full-item-re)
  20715. (memq (org-element-type (save-match-data (org-element-at-point)))
  20716. '(item plain-list)))
  20717. ;; Set special position at first white space character after
  20718. ;; bullet, and check-box, if any.
  20719. (let ((after-bullet
  20720. (let ((box (match-end 3)))
  20721. (cond ((not box) (match-end 1))
  20722. ((eq (char-after box) ?\s) (1+ box))
  20723. (t box)))))
  20724. (if (eq special 'reversed)
  20725. (when (and (= (point) origin) (eq last-command this-command))
  20726. (goto-char after-bullet))
  20727. (when (or (> origin after-bullet) (= (point) origin))
  20728. (goto-char after-bullet)))))
  20729. ;; No special context. Point is already at beginning of line.
  20730. (t nil))))
  20731. (defun org-end-of-line (&optional n)
  20732. "Go to the end of the line, but before ellipsis, if any.
  20733. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  20734. symbol `reversed', ignore tags on the first attempt, and only
  20735. move to after the tags when the cursor is already beyond the end
  20736. of the headline.
  20737. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  20738. on the second attempt.
  20739. With argument N not nil or 1, move forward N - 1 lines first."
  20740. (interactive "^p")
  20741. (let ((origin (point))
  20742. (special (pcase org-special-ctrl-a/e
  20743. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  20744. deactivate-mark)
  20745. ;; First move to a visible line.
  20746. (if (bound-and-true-p visual-line-mode)
  20747. (beginning-of-visual-line n)
  20748. (move-beginning-of-line n))
  20749. (cond
  20750. ;; At a headline, with tags.
  20751. ((and special
  20752. (save-excursion
  20753. (beginning-of-line)
  20754. (let ((case-fold-search nil))
  20755. (looking-at org-complex-heading-regexp)))
  20756. (match-end 5))
  20757. (let ((tags (save-excursion
  20758. (goto-char (match-beginning 5))
  20759. (skip-chars-backward " \t")
  20760. (point)))
  20761. (visual-end (and (bound-and-true-p visual-line-mode)
  20762. (save-excursion
  20763. (end-of-visual-line)
  20764. (point)))))
  20765. ;; If `end-of-visual-line' brings us before end of line or
  20766. ;; even tags, i.e., the headline spans over multiple visual
  20767. ;; lines, move there.
  20768. (cond ((and visual-end
  20769. (< visual-end tags)
  20770. (<= origin visual-end))
  20771. (goto-char visual-end))
  20772. ((eq special 'reversed)
  20773. (if (and (= origin (line-end-position))
  20774. (eq this-command last-command))
  20775. (goto-char tags)
  20776. (end-of-line)))
  20777. (t
  20778. (if (or (< origin tags) (= origin (line-end-position)))
  20779. (goto-char tags)
  20780. (end-of-line))))))
  20781. ((bound-and-true-p visual-line-mode)
  20782. (let ((bol (line-beginning-position)))
  20783. (end-of-visual-line)
  20784. ;; If `end-of-visual-line' gets us past the ellipsis at the
  20785. ;; end of a line, backtrack and use `end-of-line' instead.
  20786. (when (/= bol (line-beginning-position))
  20787. (goto-char bol)
  20788. (end-of-line))))
  20789. (t (end-of-line)))))
  20790. (defun org-backward-sentence (&optional _arg)
  20791. "Go to beginning of sentence, or beginning of table field.
  20792. This will call `backward-sentence' or `org-table-beginning-of-field',
  20793. depending on context."
  20794. (interactive)
  20795. (let* ((element (org-element-at-point))
  20796. (contents-begin (org-element-property :contents-begin element))
  20797. (table (org-element-lineage element '(table) t)))
  20798. (if (and table
  20799. (> (point) contents-begin)
  20800. (<= (point) (org-element-property :contents-end table)))
  20801. (call-interactively #'org-table-beginning-of-field)
  20802. (save-restriction
  20803. (when (and contents-begin
  20804. (< (point-min) contents-begin)
  20805. (> (point) contents-begin))
  20806. (narrow-to-region contents-begin
  20807. (org-element-property :contents-end element)))
  20808. (call-interactively #'backward-sentence)))))
  20809. (defun org-forward-sentence (&optional _arg)
  20810. "Go to end of sentence, or end of table field.
  20811. This will call `forward-sentence' or `org-table-end-of-field',
  20812. depending on context."
  20813. (interactive)
  20814. (if (and (org-at-heading-p)
  20815. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  20816. (save-restriction
  20817. (narrow-to-region (line-beginning-position) (line-end-position))
  20818. (call-interactively #'forward-sentence))
  20819. (let* ((element (org-element-at-point))
  20820. (contents-end (org-element-property :contents-end element))
  20821. (table (org-element-lineage element '(table) t)))
  20822. (if (and table
  20823. (>= (point) (org-element-property :contents-begin table))
  20824. (< (point) contents-end))
  20825. (call-interactively #'org-table-end-of-field)
  20826. (save-restriction
  20827. (when (and contents-end
  20828. (> (point-max) contents-end)
  20829. ;; Skip blank lines between elements.
  20830. (< (org-element-property :end element)
  20831. (save-excursion (goto-char contents-end)
  20832. (skip-chars-forward " \r\t\n"))))
  20833. (narrow-to-region (org-element-property :contents-begin element)
  20834. contents-end))
  20835. ;; End of heading is considered as the end of a sentence.
  20836. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  20837. (call-interactively #'forward-sentence)))))))
  20838. (defun org-kill-line (&optional _arg)
  20839. "Kill line, to tags or end of line."
  20840. (interactive)
  20841. (cond
  20842. ((or (not org-special-ctrl-k)
  20843. (bolp)
  20844. (not (org-at-heading-p)))
  20845. (when (and (get-char-property (line-end-position) 'invisible)
  20846. org-ctrl-k-protect-subtree
  20847. (or (eq org-ctrl-k-protect-subtree 'error)
  20848. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  20849. (user-error
  20850. (substitute-command-keys
  20851. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  20852. (call-interactively
  20853. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  20854. ((looking-at org-tag-line-re)
  20855. (let ((end (save-excursion
  20856. (goto-char (match-beginning 1))
  20857. (skip-chars-backward " \t"))))
  20858. (if (<= end (point)) ;on tags part
  20859. (kill-region (point) (line-end-position))
  20860. (kill-region (point) end)))
  20861. (org-align-tags))
  20862. (t (kill-region (point) (line-end-position)))))
  20863. (defun org-yank (&optional arg)
  20864. "Yank. If the kill is a subtree, treat it specially.
  20865. This command will look at the current kill and check if is a single
  20866. subtree, or a series of subtrees[1]. If it passes the test, and if the
  20867. cursor is at the beginning of a line or after the stars of a currently
  20868. empty headline, then the yank is handled specially. How exactly depends
  20869. on the value of the following variables.
  20870. `org-yank-folded-subtrees'
  20871. By default, this variable is non-nil, which results in
  20872. subtree(s) being folded after insertion, except if doing so
  20873. would swallow text after the yanked text.
  20874. `org-yank-adjusted-subtrees'
  20875. When non-nil (the default value is nil), the subtree will be
  20876. promoted or demoted in order to fit into the local outline tree
  20877. structure, which means that the level will be adjusted so that it
  20878. becomes the smaller one of the two *visible* surrounding headings.
  20879. Any prefix to this command will cause `yank' to be called directly with
  20880. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  20881. will just
  20882. plainly yank the text as it is.
  20883. \[1] The test checks if the first non-white line is a heading
  20884. and if there are no other headings with fewer stars."
  20885. (interactive "P")
  20886. (org-yank-generic 'yank arg))
  20887. (defun org-yank-generic (command arg)
  20888. "Perform some yank-like command.
  20889. This function implements the behavior described in the `org-yank'
  20890. documentation. However, it has been generalized to work for any
  20891. interactive command with similar behavior."
  20892. ;; pretend to be command COMMAND
  20893. (setq this-command command)
  20894. (if arg
  20895. (call-interactively command)
  20896. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  20897. (and (org-kill-is-subtree-p)
  20898. (or (bolp)
  20899. (and (looking-at "[ \t]*$")
  20900. (string-match
  20901. "\\`\\*+\\'"
  20902. (buffer-substring (point-at-bol) (point)))))))
  20903. swallowp)
  20904. (cond
  20905. ((and subtreep org-yank-folded-subtrees)
  20906. (let ((beg (point))
  20907. end)
  20908. (if (and subtreep org-yank-adjusted-subtrees)
  20909. (org-paste-subtree nil nil 'for-yank)
  20910. (call-interactively command))
  20911. (setq end (point))
  20912. (goto-char beg)
  20913. (when (and (bolp) subtreep
  20914. (not (setq swallowp
  20915. (org-yank-folding-would-swallow-text beg end))))
  20916. (org-with-limited-levels
  20917. (or (looking-at org-outline-regexp)
  20918. (re-search-forward org-outline-regexp-bol end t))
  20919. (while (and (< (point) end) (looking-at org-outline-regexp))
  20920. (outline-hide-subtree)
  20921. (org-cycle-show-empty-lines 'folded)
  20922. (condition-case nil
  20923. (outline-forward-same-level 1)
  20924. (error (goto-char end))))))
  20925. (when swallowp
  20926. (message
  20927. "Inserted text not folded because that would swallow text"))
  20928. (goto-char end)
  20929. (skip-chars-forward " \t\n\r")
  20930. (beginning-of-line 1)
  20931. (push-mark beg 'nomsg)))
  20932. ((and subtreep org-yank-adjusted-subtrees)
  20933. (let ((beg (point-at-bol)))
  20934. (org-paste-subtree nil nil 'for-yank)
  20935. (push-mark beg 'nomsg)))
  20936. (t
  20937. (call-interactively command))))))
  20938. (defun org-yank-folding-would-swallow-text (beg end)
  20939. "Would hide-subtree at BEG swallow any text after END?"
  20940. (let (level)
  20941. (org-with-limited-levels
  20942. (save-excursion
  20943. (goto-char beg)
  20944. (when (or (looking-at org-outline-regexp)
  20945. (re-search-forward org-outline-regexp-bol end t))
  20946. (setq level (org-outline-level)))
  20947. (goto-char end)
  20948. (skip-chars-forward " \t\r\n\v\f")
  20949. (not (or (eobp)
  20950. (and (bolp) (looking-at-p org-outline-regexp)
  20951. (<= (org-outline-level) level))))))))
  20952. (defun org-back-to-heading (&optional invisible-ok)
  20953. "Call `outline-back-to-heading', but provide a better error message."
  20954. (condition-case nil
  20955. (outline-back-to-heading invisible-ok)
  20956. (error (error "Before first headline at position %d in buffer %s"
  20957. (point) (current-buffer)))))
  20958. (defun org-before-first-heading-p ()
  20959. "Before first heading?"
  20960. (save-excursion
  20961. (end-of-line)
  20962. (null (re-search-backward org-outline-regexp-bol nil t))))
  20963. (defun org-at-heading-p (&optional ignored)
  20964. (outline-on-heading-p t))
  20965. (defun org-in-commented-heading-p (&optional no-inheritance)
  20966. "Non-nil if point is under a commented heading.
  20967. This function also checks ancestors of the current headline,
  20968. unless optional argument NO-INHERITANCE is non-nil."
  20969. (cond
  20970. ((org-before-first-heading-p) nil)
  20971. ((let ((headline (nth 4 (org-heading-components))))
  20972. (and headline
  20973. (let ((case-fold-search nil))
  20974. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  20975. headline)))))
  20976. (no-inheritance nil)
  20977. (t
  20978. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  20979. (defun org-at-comment-p nil
  20980. "Is cursor in a commented line?"
  20981. (save-excursion
  20982. (save-match-data
  20983. (beginning-of-line)
  20984. (looking-at "^[ \t]*# "))))
  20985. (defun org-at-drawer-p nil
  20986. "Is cursor at a drawer keyword?"
  20987. (save-excursion
  20988. (move-beginning-of-line 1)
  20989. (looking-at org-drawer-regexp)))
  20990. (defun org-at-block-p nil
  20991. "Is cursor at a block keyword?"
  20992. (save-excursion
  20993. (move-beginning-of-line 1)
  20994. (looking-at org-block-regexp)))
  20995. (defun org-point-at-end-of-empty-headline ()
  20996. "If point is at the end of an empty headline, return t, else nil.
  20997. If the heading only contains a TODO keyword, it is still still considered
  20998. empty."
  20999. (let ((case-fold-search nil))
  21000. (and (looking-at "[ \t]*$")
  21001. org-todo-line-regexp
  21002. (save-excursion
  21003. (beginning-of-line)
  21004. (looking-at org-todo-line-regexp)
  21005. (string= (match-string 3) "")))))
  21006. (defun org-at-heading-or-item-p ()
  21007. (or (org-at-heading-p) (org-at-item-p)))
  21008. (defun org-at-target-p ()
  21009. (or (org-in-regexp org-radio-target-regexp)
  21010. (org-in-regexp org-target-regexp)))
  21011. ;; Compatibility alias with Org versions < 7.8.03
  21012. (defalias 'org-on-target-p 'org-at-target-p)
  21013. (defun org-up-heading-all (arg)
  21014. "Move to the heading line of which the present line is a subheading.
  21015. This function considers both visible and invisible heading lines.
  21016. With argument, move up ARG levels."
  21017. (outline-up-heading arg t))
  21018. (defun org-up-heading-safe ()
  21019. "Move to the heading line of which the present line is a subheading.
  21020. This version will not throw an error. It will return the level of the
  21021. headline found, or nil if no higher level is found.
  21022. Also, this function will be a lot faster than `outline-up-heading',
  21023. because it relies on stars being the outline starters. This can really
  21024. make a significant difference in outlines with very many siblings."
  21025. (when (ignore-errors (org-back-to-heading t))
  21026. (let ((level-up (1- (funcall outline-level))))
  21027. (and (> level-up 0)
  21028. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  21029. (funcall outline-level)))))
  21030. (defun org-first-sibling-p ()
  21031. "Is this heading the first child of its parents?"
  21032. (interactive)
  21033. (let ((re org-outline-regexp-bol)
  21034. level l)
  21035. (unless (org-at-heading-p t)
  21036. (user-error "Not at a heading"))
  21037. (setq level (funcall outline-level))
  21038. (save-excursion
  21039. (if (not (re-search-backward re nil t))
  21040. t
  21041. (setq l (funcall outline-level))
  21042. (< l level)))))
  21043. (defun org-goto-sibling (&optional previous)
  21044. "Goto the next sibling, even if it is invisible.
  21045. When PREVIOUS is set, go to the previous sibling instead. Returns t
  21046. when a sibling was found. When none is found, return nil and don't
  21047. move point."
  21048. (let ((fun (if previous 're-search-backward 're-search-forward))
  21049. (pos (point))
  21050. (re org-outline-regexp-bol)
  21051. level l)
  21052. (when (ignore-errors (org-back-to-heading t))
  21053. (setq level (funcall outline-level))
  21054. (catch 'exit
  21055. (or previous (forward-char 1))
  21056. (while (funcall fun re nil t)
  21057. (setq l (funcall outline-level))
  21058. (when (< l level) (goto-char pos) (throw 'exit nil))
  21059. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  21060. (goto-char pos)
  21061. nil))))
  21062. (defun org-show-siblings ()
  21063. "Show all siblings of the current headline."
  21064. (save-excursion
  21065. (while (org-goto-sibling) (org-flag-heading nil)))
  21066. (save-excursion
  21067. (while (org-goto-sibling 'previous)
  21068. (org-flag-heading nil))))
  21069. (defun org-goto-first-child ()
  21070. "Goto the first child, even if it is invisible.
  21071. Return t when a child was found. Otherwise don't move point and
  21072. return nil."
  21073. (let (level (pos (point)) (re org-outline-regexp-bol))
  21074. (when (ignore-errors (org-back-to-heading t))
  21075. (setq level (outline-level))
  21076. (forward-char 1)
  21077. (if (and (re-search-forward re nil t) (> (outline-level) level))
  21078. (progn (goto-char (match-beginning 0)) t)
  21079. (goto-char pos) nil))))
  21080. (defun org-show-hidden-entry ()
  21081. "Show an entry where even the heading is hidden."
  21082. (save-excursion
  21083. (org-show-entry)))
  21084. (defun org-flag-heading (flag &optional entry)
  21085. "Flag the current heading. FLAG non-nil means make invisible.
  21086. When ENTRY is non-nil, show the entire entry."
  21087. (save-excursion
  21088. (org-back-to-heading t)
  21089. ;; Check if we should show the entire entry
  21090. (if (not entry)
  21091. (org-flag-region
  21092. (line-end-position 0) (line-end-position) flag 'outline)
  21093. (org-show-entry)
  21094. (save-excursion
  21095. (and (outline-next-heading)
  21096. (org-flag-heading nil))))))
  21097. (defun org-get-next-sibling ()
  21098. "Move to next heading of the same level, and return point.
  21099. If there is no such heading, return nil.
  21100. This is like outline-next-sibling, but invisible headings are ok."
  21101. (let ((level (funcall outline-level)))
  21102. (outline-next-heading)
  21103. (while (and (not (eobp)) (> (funcall outline-level) level))
  21104. (outline-next-heading))
  21105. (unless (or (eobp) (< (funcall outline-level) level))
  21106. (point))))
  21107. (defun org-get-last-sibling ()
  21108. "Move to previous heading of the same level, and return point.
  21109. If there is no such heading, return nil."
  21110. (let ((opoint (point))
  21111. (level (funcall outline-level)))
  21112. (outline-previous-heading)
  21113. (when (and (/= (point) opoint) (outline-on-heading-p t))
  21114. (while (and (> (funcall outline-level) level)
  21115. (not (bobp)))
  21116. (outline-previous-heading))
  21117. (unless (< (funcall outline-level) level)
  21118. (point)))))
  21119. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  21120. "Goto to the end of a subtree."
  21121. ;; This contains an exact copy of the original function, but it uses
  21122. ;; `org-back-to-heading', to make it work also in invisible
  21123. ;; trees. And is uses an invisible-ok argument.
  21124. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  21125. ;; Furthermore, when used inside Org, finding the end of a large subtree
  21126. ;; with many children and grandchildren etc, this can be much faster
  21127. ;; than the outline version.
  21128. (org-back-to-heading invisible-ok)
  21129. (let ((first t)
  21130. (level (funcall outline-level)))
  21131. (if (and (derived-mode-p 'org-mode) (< level 1000))
  21132. ;; A true heading (not a plain list item), in Org
  21133. ;; This means we can easily find the end by looking
  21134. ;; only for the right number of stars. Using a regexp to do
  21135. ;; this is so much faster than using a Lisp loop.
  21136. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  21137. (forward-char 1)
  21138. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  21139. ;; something else, do it the slow way
  21140. (while (and (not (eobp))
  21141. (or first (> (funcall outline-level) level)))
  21142. (setq first nil)
  21143. (outline-next-heading)))
  21144. (unless to-heading
  21145. (when (memq (preceding-char) '(?\n ?\^M))
  21146. ;; Go to end of line before heading
  21147. (forward-char -1)
  21148. (when (memq (preceding-char) '(?\n ?\^M))
  21149. ;; leave blank line before heading
  21150. (forward-char -1)))))
  21151. (point))
  21152. (defun org-end-of-meta-data (&optional full)
  21153. "Skip planning line and properties drawer in current entry.
  21154. When optional argument FULL is non-nil, also skip empty lines,
  21155. clocking lines and regular drawers at the beginning of the
  21156. entry."
  21157. (org-back-to-heading t)
  21158. (forward-line)
  21159. (when (looking-at-p org-planning-line-re) (forward-line))
  21160. (when (looking-at org-property-drawer-re)
  21161. (goto-char (match-end 0))
  21162. (forward-line))
  21163. (when (and full (not (org-at-heading-p)))
  21164. (catch 'exit
  21165. (let ((end (save-excursion (outline-next-heading) (point)))
  21166. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  21167. (while (not (eobp))
  21168. (cond ((looking-at-p org-drawer-regexp)
  21169. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  21170. (forward-line)
  21171. (throw 'exit t)))
  21172. ((looking-at-p re) (forward-line))
  21173. (t (throw 'exit t))))))))
  21174. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  21175. "Move forward to the ARG'th subheading at same level as this one.
  21176. Stop at the first and last subheadings of a superior heading.
  21177. Normally this only looks at visible headings, but when INVISIBLE-OK is
  21178. non-nil it will also look at invisible ones."
  21179. (interactive "p")
  21180. (let ((backward? (and arg (< arg 0))))
  21181. (if (org-before-first-heading-p)
  21182. (if backward? (goto-char (point-min)) (outline-next-heading))
  21183. (org-back-to-heading invisible-ok)
  21184. (unless backward? (end-of-line)) ;do not match current headline
  21185. (let ((level (- (match-end 0) (match-beginning 0) 1))
  21186. (f (if backward? #'re-search-backward #'re-search-forward))
  21187. (count (if arg (abs arg) 1))
  21188. (result (point)))
  21189. (while (and (> count 0)
  21190. (funcall f org-outline-regexp-bol nil 'move))
  21191. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  21192. (cond ((< l level) (setq count 0))
  21193. ((and (= l level)
  21194. (or invisible-ok
  21195. (not (org-invisible-p
  21196. (line-beginning-position)))))
  21197. (cl-decf count)
  21198. (when (= l level) (setq result (point)))))))
  21199. (goto-char result))
  21200. (beginning-of-line))))
  21201. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  21202. "Move backward to the ARG'th subheading at same level as this one.
  21203. Stop at the first and last subheadings of a superior heading."
  21204. (interactive "p")
  21205. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  21206. (defun org-next-visible-heading (arg)
  21207. "Move to the next visible heading.
  21208. This function wraps `outline-next-visible-heading' with
  21209. `org-with-limited-levels' in order to skip over inline tasks and
  21210. respect customization of `org-odd-levels-only'."
  21211. (interactive "p")
  21212. (org-with-limited-levels
  21213. (outline-next-visible-heading arg)))
  21214. (defun org-previous-visible-heading (arg)
  21215. "Move to the previous visible heading.
  21216. This function wraps `outline-previous-visible-heading' with
  21217. `org-with-limited-levels' in order to skip over inline tasks and
  21218. respect customization of `org-odd-levels-only'."
  21219. (interactive "p")
  21220. (org-with-limited-levels
  21221. (outline-previous-visible-heading arg)))
  21222. (defun org-forward-paragraph ()
  21223. "Move forward to beginning of next paragraph or equivalent.
  21224. The function moves point to the beginning of the next visible
  21225. structural element, which can be a paragraph, a table, a list
  21226. item, etc. It also provides some special moves for convenience:
  21227. - On an affiliated keyword, jump to the beginning of the
  21228. relative element.
  21229. - On an item or a footnote definition, move to the second
  21230. element inside, if any.
  21231. - On a table or a property drawer, jump after it.
  21232. - On a verse or source block, stop after blank lines."
  21233. (interactive)
  21234. (unless (eobp)
  21235. (let* ((deactivate-mark nil)
  21236. (element (org-element-at-point))
  21237. (type (org-element-type element))
  21238. (post-affiliated (org-element-property :post-affiliated element))
  21239. (contents-begin (org-element-property :contents-begin element))
  21240. (contents-end (org-element-property :contents-end element))
  21241. (end (let ((end (org-element-property :end element)) (parent element))
  21242. (while (and (setq parent (org-element-property :parent parent))
  21243. (= (org-element-property :contents-end parent) end))
  21244. (setq end (org-element-property :end parent)))
  21245. end)))
  21246. (cond ((not element)
  21247. (skip-chars-forward " \r\t\n")
  21248. (or (eobp) (beginning-of-line)))
  21249. ;; On affiliated keywords, move to element's beginning.
  21250. ((< (point) post-affiliated)
  21251. (goto-char post-affiliated))
  21252. ;; At a table row, move to the end of the table. Similarly,
  21253. ;; at a node property, move to the end of the property
  21254. ;; drawer.
  21255. ((memq type '(node-property table-row))
  21256. (goto-char (org-element-property
  21257. :end (org-element-property :parent element))))
  21258. ((memq type '(property-drawer table)) (goto-char end))
  21259. ;; Consider blank lines as separators in verse and source
  21260. ;; blocks to ease editing.
  21261. ((memq type '(src-block verse-block))
  21262. (when (eq type 'src-block)
  21263. (setq contents-end
  21264. (save-excursion (goto-char end)
  21265. (skip-chars-backward " \r\t\n")
  21266. (line-beginning-position))))
  21267. (beginning-of-line)
  21268. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  21269. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  21270. (goto-char end)
  21271. (skip-chars-forward " \r\t\n")
  21272. (if (= (point) contents-end) (goto-char end)
  21273. (beginning-of-line))))
  21274. ;; With no contents, just skip element.
  21275. ((not contents-begin) (goto-char end))
  21276. ;; If contents are invisible, skip the element altogether.
  21277. ((org-invisible-p (line-end-position))
  21278. (cl-case type
  21279. (headline
  21280. (org-with-limited-levels (outline-next-visible-heading 1)))
  21281. ;; At a plain list, make sure we move to the next item
  21282. ;; instead of skipping the whole list.
  21283. (plain-list (forward-char)
  21284. (org-forward-paragraph))
  21285. (otherwise (goto-char end))))
  21286. ((>= (point) contents-end) (goto-char end))
  21287. ((>= (point) contents-begin)
  21288. ;; This can only happen on paragraphs and plain lists.
  21289. (cl-case type
  21290. (paragraph (goto-char end))
  21291. ;; At a plain list, try to move to second element in
  21292. ;; first item, if possible.
  21293. (plain-list (end-of-line)
  21294. (org-forward-paragraph))))
  21295. ;; When contents start on the middle of a line (e.g. in
  21296. ;; items and footnote definitions), try to reach first
  21297. ;; element starting after current line.
  21298. ((> (line-end-position) contents-begin)
  21299. (end-of-line)
  21300. (org-forward-paragraph))
  21301. (t (goto-char contents-begin))))))
  21302. (defun org-backward-paragraph ()
  21303. "Move backward to start of previous paragraph or equivalent.
  21304. The function moves point to the beginning of the current
  21305. structural element, which can be a paragraph, a table, a list
  21306. item, etc., or to the beginning of the previous visible one if
  21307. point is already there. It also provides some special moves for
  21308. convenience:
  21309. - On an affiliated keyword, jump to the first one.
  21310. - On a table or a property drawer, move to its beginning.
  21311. - On comment, example, export, src and verse blocks, stop
  21312. before blank lines."
  21313. (interactive)
  21314. (unless (bobp)
  21315. (let* ((deactivate-mark nil)
  21316. (element (org-element-at-point))
  21317. (type (org-element-type element))
  21318. (contents-end (org-element-property :contents-end element))
  21319. (post-affiliated (org-element-property :post-affiliated element))
  21320. (begin (org-element-property :begin element))
  21321. (special? ;blocks handled specially
  21322. (memq type '(comment-block example-block export-block src-block
  21323. verse-block)))
  21324. (contents-begin
  21325. (if special?
  21326. ;; These types have no proper contents. Fake line
  21327. ;; below the block opening line as contents beginning.
  21328. (save-excursion (goto-char begin) (line-beginning-position 2))
  21329. (org-element-property :contents-begin element))))
  21330. (cond
  21331. ((not element) (goto-char (point-min)))
  21332. ((= (point) begin)
  21333. (backward-char)
  21334. (org-backward-paragraph))
  21335. ((<= (point) post-affiliated) (goto-char begin))
  21336. ;; Special behavior: on a table or a property drawer, move to
  21337. ;; its beginning.
  21338. ((memq type '(node-property table-row))
  21339. (goto-char (org-element-property
  21340. :post-affiliated (org-element-property :parent element))))
  21341. (special?
  21342. (if (<= (point) contents-begin) (goto-char post-affiliated)
  21343. ;; Inside a verse block, see blank lines as paragraph
  21344. ;; separators.
  21345. (let ((origin (point)))
  21346. (skip-chars-backward " \r\t\n" contents-begin)
  21347. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  21348. (skip-chars-forward " \r\t\n" origin)
  21349. (if (= (point) origin) (goto-char contents-begin)
  21350. (beginning-of-line))))))
  21351. ((eq type 'paragraph) (goto-char contents-begin)
  21352. ;; When at first paragraph in an item or a footnote definition,
  21353. ;; move directly to beginning of line.
  21354. (let ((parent-contents
  21355. (org-element-property
  21356. :contents-begin (org-element-property :parent element))))
  21357. (when (and parent-contents (= parent-contents contents-begin))
  21358. (beginning-of-line))))
  21359. ;; At the end of a greater element, move to the beginning of
  21360. ;; the last element within.
  21361. ((and contents-end (>= (point) contents-end))
  21362. (goto-char (1- contents-end))
  21363. (org-backward-paragraph))
  21364. (t (goto-char (or post-affiliated begin))))
  21365. ;; Ensure we never leave point invisible.
  21366. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  21367. (defun org-forward-element ()
  21368. "Move forward by one element.
  21369. Move to the next element at the same level, when possible."
  21370. (interactive)
  21371. (cond ((eobp) (user-error "Cannot move further down"))
  21372. ((org-with-limited-levels (org-at-heading-p))
  21373. (let ((origin (point)))
  21374. (goto-char (org-end-of-subtree nil t))
  21375. (unless (org-with-limited-levels (org-at-heading-p))
  21376. (goto-char origin)
  21377. (user-error "Cannot move further down"))))
  21378. (t
  21379. (let* ((elem (org-element-at-point))
  21380. (end (org-element-property :end elem))
  21381. (parent (org-element-property :parent elem)))
  21382. (cond ((and parent (= (org-element-property :contents-end parent) end))
  21383. (goto-char (org-element-property :end parent)))
  21384. ((integer-or-marker-p end) (goto-char end))
  21385. (t (message "No element at point")))))))
  21386. (defun org-backward-element ()
  21387. "Move backward by one element.
  21388. Move to the previous element at the same level, when possible."
  21389. (interactive)
  21390. (cond ((bobp) (user-error "Cannot move further up"))
  21391. ((org-with-limited-levels (org-at-heading-p))
  21392. ;; At a headline, move to the previous one, if any, or stay
  21393. ;; here.
  21394. (let ((origin (point)))
  21395. (org-with-limited-levels (org-backward-heading-same-level 1))
  21396. ;; When current headline has no sibling above, move to its
  21397. ;; parent.
  21398. (when (= (point) origin)
  21399. (or (org-with-limited-levels (org-up-heading-safe))
  21400. (progn (goto-char origin)
  21401. (user-error "Cannot move further up"))))))
  21402. (t
  21403. (let* ((elem (org-element-at-point))
  21404. (beg (org-element-property :begin elem)))
  21405. (cond
  21406. ;; Move to beginning of current element if point isn't
  21407. ;; there already.
  21408. ((null beg) (message "No element at point"))
  21409. ((/= (point) beg) (goto-char beg))
  21410. (t (goto-char beg)
  21411. (skip-chars-backward " \r\t\n")
  21412. (unless (bobp)
  21413. (let ((prev (org-element-at-point)))
  21414. (goto-char (org-element-property :begin prev))
  21415. (while (and (setq prev (org-element-property :parent prev))
  21416. (<= (org-element-property :end prev) beg))
  21417. (goto-char (org-element-property :begin prev)))))))))))
  21418. (defun org-up-element ()
  21419. "Move to upper element."
  21420. (interactive)
  21421. (if (org-with-limited-levels (org-at-heading-p))
  21422. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  21423. (let* ((elem (org-element-at-point))
  21424. (parent (org-element-property :parent elem)))
  21425. (if parent (goto-char (org-element-property :begin parent))
  21426. (if (org-with-limited-levels (org-before-first-heading-p))
  21427. (user-error "No surrounding element")
  21428. (org-with-limited-levels (org-back-to-heading)))))))
  21429. (defun org-down-element ()
  21430. "Move to inner element."
  21431. (interactive)
  21432. (let ((element (org-element-at-point)))
  21433. (cond
  21434. ((memq (org-element-type element) '(plain-list table))
  21435. (goto-char (org-element-property :contents-begin element))
  21436. (forward-char))
  21437. ((memq (org-element-type element) org-element-greater-elements)
  21438. ;; If contents are hidden, first disclose them.
  21439. (when (org-invisible-p (line-end-position)) (org-cycle))
  21440. (goto-char (or (org-element-property :contents-begin element)
  21441. (user-error "No content for this element"))))
  21442. (t (user-error "No inner element")))))
  21443. (defun org-drag-element-backward ()
  21444. "Move backward element at point."
  21445. (interactive)
  21446. (let ((elem (or (org-element-at-point)
  21447. (user-error "No element at point"))))
  21448. (if (eq (org-element-type elem) 'headline)
  21449. ;; Preserve point when moving a whole tree, even if point was
  21450. ;; on blank lines below the headline.
  21451. (let ((offset (skip-chars-backward " \t\n")))
  21452. (unwind-protect (org-move-subtree-up)
  21453. (forward-char (- offset))))
  21454. (let ((prev-elem
  21455. (save-excursion
  21456. (goto-char (org-element-property :begin elem))
  21457. (skip-chars-backward " \r\t\n")
  21458. (unless (bobp)
  21459. (let* ((beg (org-element-property :begin elem))
  21460. (prev (org-element-at-point))
  21461. (up prev))
  21462. (while (and (setq up (org-element-property :parent up))
  21463. (<= (org-element-property :end up) beg))
  21464. (setq prev up))
  21465. prev)))))
  21466. ;; Error out if no previous element or previous element is
  21467. ;; a parent of the current one.
  21468. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  21469. (user-error "Cannot drag element backward")
  21470. (let ((pos (point)))
  21471. (org-element-swap-A-B prev-elem elem)
  21472. (goto-char (+ (org-element-property :begin prev-elem)
  21473. (- pos (org-element-property :begin elem))))))))))
  21474. (defun org-drag-element-forward ()
  21475. "Move forward element at point."
  21476. (interactive)
  21477. (let* ((pos (point))
  21478. (elem (or (org-element-at-point)
  21479. (user-error "No element at point"))))
  21480. (when (= (point-max) (org-element-property :end elem))
  21481. (user-error "Cannot drag element forward"))
  21482. (goto-char (org-element-property :end elem))
  21483. (let ((next-elem (org-element-at-point)))
  21484. (when (or (org-element-nested-p elem next-elem)
  21485. (and (eq (org-element-type next-elem) 'headline)
  21486. (not (eq (org-element-type elem) 'headline))))
  21487. (goto-char pos)
  21488. (user-error "Cannot drag element forward"))
  21489. ;; Compute new position of point: it's shifted by NEXT-ELEM
  21490. ;; body's length (without final blanks) and by the length of
  21491. ;; blanks between ELEM and NEXT-ELEM.
  21492. (let ((size-next (- (save-excursion
  21493. (goto-char (org-element-property :end next-elem))
  21494. (skip-chars-backward " \r\t\n")
  21495. (forward-line)
  21496. ;; Small correction if buffer doesn't end
  21497. ;; with a newline character.
  21498. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  21499. (org-element-property :begin next-elem)))
  21500. (size-blank (- (org-element-property :end elem)
  21501. (save-excursion
  21502. (goto-char (org-element-property :end elem))
  21503. (skip-chars-backward " \r\t\n")
  21504. (forward-line)
  21505. (point)))))
  21506. (org-element-swap-A-B elem next-elem)
  21507. (goto-char (+ pos size-next size-blank))))))
  21508. (defun org-drag-line-forward (arg)
  21509. "Drag the line at point ARG lines forward."
  21510. (interactive "p")
  21511. (dotimes (_ (abs arg))
  21512. (let ((c (current-column)))
  21513. (if (< 0 arg)
  21514. (progn
  21515. (beginning-of-line 2)
  21516. (transpose-lines 1)
  21517. (beginning-of-line 0))
  21518. (transpose-lines 1)
  21519. (beginning-of-line -1))
  21520. (org-move-to-column c))))
  21521. (defun org-drag-line-backward (arg)
  21522. "Drag the line at point ARG lines backward."
  21523. (interactive "p")
  21524. (org-drag-line-forward (- arg)))
  21525. (defun org-mark-element ()
  21526. "Put point at beginning of this element, mark at end.
  21527. Interactively, if this command is repeated or (in Transient Mark
  21528. mode) if the mark is active, it marks the next element after the
  21529. ones already marked."
  21530. (interactive)
  21531. (let (deactivate-mark)
  21532. (if (and (called-interactively-p 'any)
  21533. (or (and (eq last-command this-command) (mark t))
  21534. (and transient-mark-mode mark-active)))
  21535. (set-mark
  21536. (save-excursion
  21537. (goto-char (mark))
  21538. (goto-char (org-element-property :end (org-element-at-point)))))
  21539. (let ((element (org-element-at-point)))
  21540. (end-of-line)
  21541. (push-mark (org-element-property :end element) t t)
  21542. (goto-char (org-element-property :begin element))))))
  21543. (defun org-narrow-to-element ()
  21544. "Narrow buffer to current element."
  21545. (interactive)
  21546. (let ((elem (org-element-at-point)))
  21547. (cond
  21548. ((eq (car elem) 'headline)
  21549. (narrow-to-region
  21550. (org-element-property :begin elem)
  21551. (org-element-property :end elem)))
  21552. ((memq (car elem) org-element-greater-elements)
  21553. (narrow-to-region
  21554. (org-element-property :contents-begin elem)
  21555. (org-element-property :contents-end elem)))
  21556. (t
  21557. (narrow-to-region
  21558. (org-element-property :begin elem)
  21559. (org-element-property :end elem))))))
  21560. (defun org-transpose-element ()
  21561. "Transpose current and previous elements, keeping blank lines between.
  21562. Point is moved after both elements."
  21563. (interactive)
  21564. (org-skip-whitespace)
  21565. (let ((end (org-element-property :end (org-element-at-point))))
  21566. (org-drag-element-backward)
  21567. (goto-char end)))
  21568. (defun org-unindent-buffer ()
  21569. "Un-indent the visible part of the buffer.
  21570. Relative indentation (between items, inside blocks, etc.) isn't
  21571. modified."
  21572. (interactive)
  21573. (unless (eq major-mode 'org-mode)
  21574. (user-error "Cannot un-indent a buffer not in Org mode"))
  21575. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  21576. (unindent-tree
  21577. (lambda (contents)
  21578. (dolist (element (reverse contents))
  21579. (if (memq (org-element-type element) '(headline section))
  21580. (funcall unindent-tree (org-element-contents element))
  21581. (save-excursion
  21582. (save-restriction
  21583. (narrow-to-region
  21584. (org-element-property :begin element)
  21585. (org-element-property :end element))
  21586. (org-do-remove-indentation))))))))
  21587. (funcall unindent-tree (org-element-contents parse-tree))))
  21588. (defun org-make-options-regexp (kwds &optional extra)
  21589. "Make a regular expression for keyword lines.
  21590. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  21591. when non-nil, is a regexp matching keywords names."
  21592. (concat "^[ \t]*#\\+\\("
  21593. (regexp-opt kwds)
  21594. (and extra (concat (and kwds "\\|") extra))
  21595. "\\):[ \t]*\\(.*\\)"))
  21596. ;;; Finish up
  21597. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  21598. (lambda () (add-hook 'change-major-mode-hook
  21599. 'org-show-all 'append 'local)))
  21600. (provide 'org)
  21601. (run-hooks 'org-load-hook)
  21602. ;;; org.el ends here