org.el 911 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071
  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-2017 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: http://orgmode.org
  9. ;;
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  26. ;; project planning with a fast and effective plain-text system.
  27. ;;
  28. ;; Org mode develops organizational tasks around NOTES files that
  29. ;; contain information about projects as plain text. Org mode is
  30. ;; implemented on top of outline-mode, which makes it possible to keep
  31. ;; the content of large files well structured. Visibility cycling and
  32. ;; structure editing help to work with the tree. Tables are easily
  33. ;; created with a built-in table editor. Org mode supports ToDo
  34. ;; items, deadlines, time stamps, and scheduling. It dynamically
  35. ;; compiles entries into an agenda that utilizes and smoothly
  36. ;; integrates much of the Emacs calendar and diary. Plain text
  37. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  38. ;; entries, and any files related to the projects. For printing and
  39. ;; sharing of notes, an Org file can be exported as a structured ASCII
  40. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  41. ;; file. It can also serve as a publishing tool for a set of linked
  42. ;; webpages.
  43. ;;
  44. ;; Installation and Activation
  45. ;; ---------------------------
  46. ;; See the corresponding sections in the manual at
  47. ;;
  48. ;; http://orgmode.org/org.html#Installation
  49. ;;
  50. ;; Documentation
  51. ;; -------------
  52. ;; The documentation of Org mode can be found in the TeXInfo file. The
  53. ;; distribution also contains a PDF version of it. At the homepage of
  54. ;; Org mode, you can read the same text online as HTML. There is also an
  55. ;; excellent reference card made by Philip Rooke. This card can be found
  56. ;; in the doc/ directory.
  57. ;;
  58. ;; A list of recent changes can be found at
  59. ;; http://orgmode.org/Changes.html
  60. ;;
  61. ;;; Code:
  62. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  63. (defvar-local org-table-formula-constants-local nil
  64. "Local version of `org-table-formula-constants'.")
  65. ;;;; Require other packages
  66. (require 'cl-lib)
  67. (eval-when-compile (require 'gnus-sum))
  68. (require 'calendar)
  69. (require 'find-func)
  70. (require 'format-spec)
  71. (or (eq this-command 'eval-buffer)
  72. (condition-case nil
  73. (load (concat (file-name-directory load-file-name)
  74. "org-loaddefs.el")
  75. nil t t t)
  76. (error
  77. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  78. (sit-for 3)
  79. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  80. (sit-for 3))))
  81. (require 'org-macs)
  82. (require 'org-compat)
  83. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  84. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  85. ;;
  86. ;; In Org buffers, the value of `outline-regexp' is that of
  87. ;; `org-outline-regexp'. The only function still directly relying on
  88. ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
  89. ;; job when `orgstruct-mode' is active.
  90. (defvar org-outline-regexp "\\*+ "
  91. "Regexp to match Org headlines.")
  92. (defvar org-outline-regexp-bol "^\\*+ "
  93. "Regexp to match Org headlines.
  94. This is similar to `org-outline-regexp' but additionally makes
  95. sure that we are at the beginning of the line.")
  96. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  97. "Matches a headline, putting stars and text into groups.
  98. Stars are put in group 1 and the trimmed body in group 2.")
  99. (declare-function calendar-check-holidays "holidays" (date))
  100. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  101. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  102. (declare-function org-add-archive-files "org-archive" (files))
  103. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  104. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  105. (declare-function org-agenda-redo "org-agenda" (&optional all))
  106. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  107. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  108. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  109. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  110. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  111. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  112. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  113. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  114. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  115. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  116. (declare-function org-clock-update-time-maybe "org-clock" ())
  117. (declare-function org-clocking-buffer "org-clock" ())
  118. (declare-function org-clocktable-shift "org-clock" (dir n))
  119. (declare-function
  120. org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  121. (declare-function org-element-at-point "org-element" ())
  122. (declare-function org-element-cache-refresh "org-element" (pos))
  123. (declare-function org-element-cache-reset "org-element" (&optional all))
  124. (declare-function org-element-contents "org-element" (element))
  125. (declare-function org-element-context "org-element" (&optional element))
  126. (declare-function org-element-copy "org-element" (datum))
  127. (declare-function org-element-interpret-data "org-element" (data))
  128. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  129. (declare-function org-element-link-parser "org-element" ())
  130. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  131. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  132. (declare-function org-element-property "org-element" (property element))
  133. (declare-function org-element-put-property "org-element" (element property value))
  134. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  135. (declare-function org-element-type "org-element" (element))
  136. (declare-function org-element-update-syntax "org-element" ())
  137. (declare-function org-id-find-id-file "org-id" (id))
  138. (declare-function org-id-get-create "org-id" (&optional force))
  139. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  140. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  141. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  142. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  143. (declare-function org-table-align "org-table" ())
  144. (declare-function org-table-begin "org-table" (&optional table-type))
  145. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  146. (declare-function org-table-blank-field "org-table" ())
  147. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  148. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  149. (declare-function org-table-cut-region "org-table" (beg end))
  150. (declare-function org-table-edit-field "org-table" (arg))
  151. (declare-function org-table-end "org-table" (&optional table-type))
  152. (declare-function org-table-end-of-field "org-table" (&optional n))
  153. (declare-function org-table-insert-row "org-table" (&optional arg))
  154. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  155. (declare-function org-table-maybe-eval-formula "org-table" ())
  156. (declare-function org-table-maybe-recalculate-line "org-table" ())
  157. (declare-function org-table-next-row "org-table" ())
  158. (declare-function org-table-paste-rectangle "org-table" ())
  159. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  160. (declare-function
  161. org-table-sort-lines "org-table"
  162. (&optional with-case sorting-type getkey-func compare-func interactive?))
  163. (declare-function org-table-shrink "org-table" (&optional begin end))
  164. (declare-function org-table-toggle-column-width "org-table" (&optional arg))
  165. (declare-function org-table-wrap-region "org-table" (arg))
  166. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  167. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  168. (declare-function orgtbl-mode "org-table" (&optional arg))
  169. (declare-function org-export-get-backend "ox" (name))
  170. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  171. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  172. (defvar ffap-url-regexp) ;Silence byte-compiler
  173. ;; load languages based on value of `org-babel-load-languages'
  174. (defvar org-babel-load-languages)
  175. ;;;###autoload
  176. (defun org-babel-do-load-languages (sym value)
  177. "Load the languages defined in `org-babel-load-languages'."
  178. (set-default sym value)
  179. (dolist (pair org-babel-load-languages)
  180. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  181. (if active
  182. (require (intern (concat "ob-" lang)))
  183. (funcall 'fmakunbound
  184. (intern (concat "org-babel-execute:" lang)))
  185. (funcall 'fmakunbound
  186. (intern (concat "org-babel-expand-body:" lang)))))))
  187. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  188. ;;;###autoload
  189. (defun org-babel-load-file (file &optional compile)
  190. "Load Emacs Lisp source code blocks in the Org FILE.
  191. This function exports the source code using `org-babel-tangle'
  192. and then loads the resulting file using `load-file'. With prefix
  193. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  194. file to byte-code before it is loaded."
  195. (interactive "fFile to load: \nP")
  196. (let* ((age (lambda (file)
  197. (float-time
  198. (time-subtract (current-time)
  199. (nth 5 (or (file-attributes (file-truename file))
  200. (file-attributes file)))))))
  201. (base-name (file-name-sans-extension file))
  202. (exported-file (concat base-name ".el")))
  203. ;; tangle if the Org file is newer than the elisp file
  204. (unless (and (file-exists-p exported-file)
  205. (> (funcall age file) (funcall age exported-file)))
  206. ;; Tangle-file traversal returns reversed list of tangled files
  207. ;; and we want to evaluate the first target.
  208. (setq exported-file
  209. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  210. (message "%s %s"
  211. (if compile
  212. (progn (byte-compile-file exported-file 'load)
  213. "Compiled and loaded")
  214. (progn (load-file exported-file) "Loaded"))
  215. exported-file)))
  216. (defcustom org-babel-load-languages '((emacs-lisp . t))
  217. "Languages which can be evaluated in Org buffers.
  218. This list can be used to load support for any of the languages
  219. below, note that each language will depend on a different set of
  220. system executables and/or Emacs modes. When a language is
  221. \"loaded\", then code blocks in that language can be evaluated
  222. with `org-babel-execute-src-block' bound by default to C-c
  223. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  224. be set to remove code block evaluation from the C-c C-c
  225. keybinding. By default only Emacs Lisp (which has no
  226. requirements) is loaded."
  227. :group 'org-babel
  228. :set 'org-babel-do-load-languages
  229. :version "24.1"
  230. :type '(alist :tag "Babel Languages"
  231. :key-type
  232. (choice
  233. (const :tag "Awk" awk)
  234. (const :tag "C" C)
  235. (const :tag "R" R)
  236. (const :tag "Asymptote" asymptote)
  237. (const :tag "Calc" calc)
  238. (const :tag "Clojure" clojure)
  239. (const :tag "CSS" css)
  240. (const :tag "Ditaa" ditaa)
  241. (const :tag "Dot" dot)
  242. (const :tag "Ebnf2ps" ebnf2ps)
  243. (const :tag "Emacs Lisp" emacs-lisp)
  244. (const :tag "Forth" forth)
  245. (const :tag "Fortran" fortran)
  246. (const :tag "Gnuplot" gnuplot)
  247. (const :tag "Haskell" haskell)
  248. (const :tag "hledger" hledger)
  249. (const :tag "IO" io)
  250. (const :tag "J" J)
  251. (const :tag "Java" java)
  252. (const :tag "Javascript" js)
  253. (const :tag "LaTeX" latex)
  254. (const :tag "Ledger" ledger)
  255. (const :tag "Lilypond" lilypond)
  256. (const :tag "Lisp" lisp)
  257. (const :tag "Makefile" makefile)
  258. (const :tag "Maxima" maxima)
  259. (const :tag "Matlab" matlab)
  260. (const :tag "Mscgen" mscgen)
  261. (const :tag "Ocaml" ocaml)
  262. (const :tag "Octave" octave)
  263. (const :tag "Org" org)
  264. (const :tag "Perl" perl)
  265. (const :tag "Pico Lisp" picolisp)
  266. (const :tag "PlantUML" plantuml)
  267. (const :tag "Python" python)
  268. (const :tag "Ruby" ruby)
  269. (const :tag "Sass" sass)
  270. (const :tag "Scala" scala)
  271. (const :tag "Scheme" scheme)
  272. (const :tag "Screen" screen)
  273. (const :tag "Shell Script" shell)
  274. (const :tag "Shen" shen)
  275. (const :tag "Sql" sql)
  276. (const :tag "Sqlite" sqlite)
  277. (const :tag "Stan" stan)
  278. (const :tag "Vala" vala))
  279. :value-type (boolean :tag "Activate" :value t)))
  280. ;;;; Customization variables
  281. (defcustom org-clone-delete-id nil
  282. "Remove ID property of clones of a subtree.
  283. When non-nil, clones of a subtree don't inherit the ID property.
  284. Otherwise they inherit the ID property with a new unique
  285. identifier."
  286. :type 'boolean
  287. :version "24.1"
  288. :group 'org-id)
  289. ;;; Version
  290. (org-check-version)
  291. ;;;###autoload
  292. (defun org-version (&optional here full message)
  293. "Show the Org version.
  294. Interactively, or when MESSAGE is non-nil, show it in echo area.
  295. With prefix argument, or when HERE is non-nil, insert it at point.
  296. In non-interactive uses, a reduced version string is output unless
  297. FULL is given."
  298. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  299. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  300. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  301. (load-suffixes (list ".el"))
  302. (org-install-dir
  303. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  304. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  305. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  306. (let* ((load-suffixes save-load-suffixes)
  307. (release (org-release))
  308. (git-version (org-git-version))
  309. (version (format "Org mode version %s (%s @ %s)"
  310. release
  311. git-version
  312. (if org-install-dir
  313. (if (string= org-dir org-install-dir)
  314. org-install-dir
  315. (concat "mixed installation! "
  316. org-install-dir
  317. " and "
  318. org-dir))
  319. "org-loaddefs.el can not be found!")))
  320. (version1 (if full version release)))
  321. (when here (insert version1))
  322. (when message (message "%s" version1))
  323. version1)))
  324. (defconst org-version (org-version))
  325. ;;; Syntax Constants
  326. ;;;; Block
  327. (defconst org-block-regexp
  328. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  329. "Regular expression for hiding blocks.")
  330. (defconst org-dblock-start-re
  331. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  332. "Matches the start line of a dynamic block, with parameters.")
  333. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  334. "Matches the end of a dynamic block.")
  335. ;;;; Clock and Planning
  336. (defconst org-clock-string "CLOCK:"
  337. "String used as prefix for timestamps clocking work hours on an item.")
  338. (defvar org-closed-string "CLOSED:"
  339. "String used as the prefix for timestamps logging closing a TODO entry.")
  340. (defvar org-deadline-string "DEADLINE:"
  341. "String to mark deadline entries.
  342. \\<org-mode-map>
  343. A deadline is this string, followed by a time stamp. It must be
  344. a word, terminated by a colon. You can insert a schedule keyword
  345. and a timestamp with `\\[org-deadline]'.")
  346. (defvar org-scheduled-string "SCHEDULED:"
  347. "String to mark scheduled TODO entries.
  348. \\<org-mode-map>
  349. A schedule is this string, followed by a time stamp. It must be
  350. a word, terminated by a colon. You can insert a schedule keyword
  351. and a timestamp with `\\[org-schedule]'.")
  352. (defconst org-ds-keyword-length
  353. (+ 2
  354. (apply #'max
  355. (mapcar #'length
  356. (list org-deadline-string org-scheduled-string
  357. org-clock-string org-closed-string))))
  358. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  359. (defconst org-planning-line-re
  360. (concat "^[ \t]*"
  361. (regexp-opt
  362. (list org-closed-string org-deadline-string org-scheduled-string)
  363. t))
  364. "Matches a line with planning info.
  365. Matched keyword is in group 1.")
  366. (defconst org-clock-line-re
  367. (concat "^[ \t]*" org-clock-string)
  368. "Matches a line with clock info.")
  369. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  370. "Matches the DEADLINE keyword.")
  371. (defconst org-deadline-time-regexp
  372. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  373. "Matches the DEADLINE keyword together with a time stamp.")
  374. (defconst org-deadline-time-hour-regexp
  375. (concat "\\<" org-deadline-string
  376. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  377. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  378. (defconst org-deadline-line-regexp
  379. (concat "\\<\\(" org-deadline-string "\\).*")
  380. "Matches the DEADLINE keyword and the rest of the line.")
  381. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  382. "Matches the SCHEDULED keyword.")
  383. (defconst org-scheduled-time-regexp
  384. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  385. "Matches the SCHEDULED keyword together with a time stamp.")
  386. (defconst org-scheduled-time-hour-regexp
  387. (concat "\\<" org-scheduled-string
  388. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  389. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  390. (defconst org-closed-time-regexp
  391. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  392. "Matches the CLOSED keyword together with a time stamp.")
  393. (defconst org-keyword-time-regexp
  394. (concat "\\<"
  395. (regexp-opt
  396. (list org-scheduled-string org-deadline-string org-closed-string
  397. org-clock-string)
  398. t)
  399. " *[[<]\\([^]>]+\\)[]>]")
  400. "Matches any of the 4 keywords, together with the time stamp.")
  401. (defconst org-keyword-time-not-clock-regexp
  402. (concat
  403. "\\<"
  404. (regexp-opt
  405. (list org-scheduled-string org-deadline-string org-closed-string) t)
  406. " *[[<]\\([^]>]+\\)[]>]")
  407. "Matches any of the 3 keywords, together with the time stamp.")
  408. (defconst org-maybe-keyword-time-regexp
  409. (concat "\\(\\<"
  410. (regexp-opt
  411. (list org-scheduled-string org-deadline-string org-closed-string
  412. org-clock-string)
  413. t)
  414. "\\)?"
  415. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  416. "\\|"
  417. "<%%([^\r\n>]*>\\)")
  418. "Matches a timestamp, possibly preceded by a keyword.")
  419. (defconst org-all-time-keywords
  420. (mapcar (lambda (w) (substring w 0 -1))
  421. (list org-scheduled-string org-deadline-string
  422. org-clock-string org-closed-string))
  423. "List of time keywords.")
  424. ;;;; Drawer
  425. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  426. "Matches first or last line of a hidden block.
  427. Group 1 contains drawer's name or \"END\".")
  428. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  429. "Regular expression matching the first line of a property drawer.")
  430. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  431. "Regular expression matching the last line of a property drawer.")
  432. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  433. "Regular expression matching the first line of a clock drawer.")
  434. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  435. "Regular expression matching the last line of a clock drawer.")
  436. (defconst org-property-drawer-re
  437. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  438. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  439. "[ \t]*:END:[ \t]*$")
  440. "Matches an entire property drawer.")
  441. (defconst org-clock-drawer-re
  442. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  443. org-clock-drawer-end-re "\\)\n?")
  444. "Matches an entire clock drawer.")
  445. ;;;; Headline
  446. (defconst org-heading-keyword-regexp-format
  447. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  448. "Printf format for a regexp matching a headline with some keyword.
  449. This regexp will match the headline of any node which has the
  450. exact keyword that is put into the format. The keyword isn't in
  451. any group by default, but the stars and the body are.")
  452. (defconst org-heading-keyword-maybe-regexp-format
  453. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  454. "Printf format for a regexp matching a headline, possibly with some keyword.
  455. This regexp can match any headline with the specified keyword, or
  456. without a keyword. The keyword isn't in any group by default,
  457. but the stars and the body are.")
  458. (defconst org-archive-tag "ARCHIVE"
  459. "The tag that marks a subtree as archived.
  460. An archived subtree does not open during visibility cycling, and does
  461. not contribute to the agenda listings.")
  462. (eval-and-compile
  463. (defconst org-comment-string "COMMENT"
  464. "Entries starting with this keyword will never be exported.
  465. \\<org-mode-map>
  466. An entry can be toggled between COMMENT and normal with
  467. `\\[org-toggle-comment]'."))
  468. ;;;; LaTeX Environments and Fragments
  469. (defconst org-latex-regexps
  470. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  471. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  472. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  473. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  474. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  475. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  476. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  477. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  478. "Regular expressions for matching embedded LaTeX.")
  479. ;;;; Node Property
  480. (defconst org-effort-property "Effort"
  481. "The property that is being used to keep track of effort estimates.
  482. Effort estimates given in this property need to have the format H:MM.")
  483. ;;;; Table
  484. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  485. "Detect an org-type or table-type table.")
  486. (defconst org-table-line-regexp "^[ \t]*|"
  487. "Detect an org-type table line.")
  488. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  489. "Detect an org-type table line.")
  490. (defconst org-table-hline-regexp "^[ \t]*|-"
  491. "Detect an org-type table hline.")
  492. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  493. "Detect a table-type table hline.")
  494. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  495. "Detect the first line outside a table when searching from within it.
  496. This works for both table types.")
  497. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  498. "Detect a #+TBLFM line.")
  499. ;;;; Timestamp
  500. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  501. "Regular expression for fast time stamp matching.")
  502. (defconst org-ts-regexp-inactive
  503. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  504. "Regular expression for fast inactive time stamp matching.")
  505. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  506. "Regular expression for fast time stamp matching.")
  507. (defconst org-ts-regexp0
  508. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  509. "Regular expression matching time strings for analysis.
  510. This one does not require the space after the date, so it can be used
  511. on a string that terminates immediately after the date.")
  512. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  513. "Regular expression matching time strings for analysis.")
  514. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  515. "Regular expression matching time stamps, with groups.")
  516. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  517. "Regular expression matching time stamps (also [..]), with groups.")
  518. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  519. "Regular expression matching a time stamp range.")
  520. (defconst org-tr-regexp-both
  521. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  522. "Regular expression matching a time stamp range.")
  523. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  524. org-ts-regexp "\\)?")
  525. "Regular expression matching a time stamp or time stamp range.")
  526. (defconst org-tsr-regexp-both
  527. (concat org-ts-regexp-both "\\(--?-?"
  528. org-ts-regexp-both "\\)?")
  529. "Regular expression matching a time stamp or time stamp range.
  530. The time stamps may be either active or inactive.")
  531. (defconst org-repeat-re
  532. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  533. "Regular expression for specifying repeated events.
  534. After a match, group 1 contains the repeat expression.")
  535. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  536. "Formats for `format-time-string' which are used for time stamps.")
  537. ;;; The custom variables
  538. (defgroup org nil
  539. "Outline-based notes management and organizer."
  540. :tag "Org"
  541. :group 'outlines
  542. :group 'calendar)
  543. (defcustom org-mode-hook nil
  544. "Mode hook for Org mode, run after the mode was turned on."
  545. :group 'org
  546. :type 'hook)
  547. (defcustom org-load-hook nil
  548. "Hook that is run after org.el has been loaded."
  549. :group 'org
  550. :type 'hook)
  551. (defcustom org-log-buffer-setup-hook nil
  552. "Hook that is run after an Org log buffer is created."
  553. :group 'org
  554. :version "24.1"
  555. :type 'hook)
  556. (defvar org-modules) ; defined below
  557. (defvar org-modules-loaded nil
  558. "Have the modules been loaded already?")
  559. (defun org-load-modules-maybe (&optional force)
  560. "Load all extensions listed in `org-modules'."
  561. (when (or force (not org-modules-loaded))
  562. (dolist (ext org-modules)
  563. (condition-case nil (require ext)
  564. (error (message "Problems while trying to load feature `%s'" ext))))
  565. (setq org-modules-loaded t)))
  566. (defun org-set-modules (var value)
  567. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  568. (set var value)
  569. (when (featurep 'org)
  570. (org-load-modules-maybe 'force)
  571. (org-element-cache-reset 'all)))
  572. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  573. "Modules that should always be loaded together with org.el.
  574. If a description starts with <C>, the file is not part of Emacs
  575. and loading it will require that you have downloaded and properly
  576. installed the Org mode distribution.
  577. You can also use this system to load external packages (i.e. neither Org
  578. core modules, nor modules from the CONTRIB directory). Just add symbols
  579. to the end of the list. If the package is called org-xyz.el, then you need
  580. to add the symbol `xyz', and the package must have a call to:
  581. (provide \\='org-xyz)
  582. For export specific modules, see also `org-export-backends'."
  583. :group 'org
  584. :set 'org-set-modules
  585. :version "24.4"
  586. :package-version '(Org . "8.0")
  587. :type
  588. '(set :greedy t
  589. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  590. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  591. (const :tag " crypt: Encryption of subtrees" org-crypt)
  592. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  593. (const :tag " docview: Links to doc-view buffers" org-docview)
  594. (const :tag " eww: Store link to url of eww" org-eww)
  595. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  596. (const :tag " habit: Track your consistency with habits" org-habit)
  597. (const :tag " id: Global IDs for identifying entries" org-id)
  598. (const :tag " info: Links to Info nodes" org-info)
  599. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  600. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  601. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  602. (const :tag " mouse: Additional mouse support" org-mouse)
  603. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  604. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  605. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  606. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  607. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  608. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  609. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  610. (const :tag "C collector: Collect properties into tables" org-collector)
  611. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  612. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  613. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  614. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  615. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  616. (const :tag "C eval: Include command output as text" org-eval)
  617. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  618. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  619. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  620. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  621. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  622. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  623. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  624. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  625. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  626. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  627. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  628. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  629. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  630. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  631. (const :tag "C registry: A registry for Org links" org-registry)
  632. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  633. (const :tag "C secretary: Team management with org-mode" org-secretary)
  634. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  635. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  636. (const :tag "C track: Keep up with Org mode development" org-track)
  637. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  638. (const :tag "C vm: Links to VM folders/messages" org-vm)
  639. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  640. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  641. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  642. (defvar org-export-registered-backends) ; From ox.el.
  643. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  644. (declare-function org-export-backend-name "ox" (backend) t)
  645. (defcustom org-export-backends '(ascii html icalendar latex odt)
  646. "List of export back-ends that should be always available.
  647. If a description starts with <C>, the file is not part of Emacs
  648. and loading it will require that you have downloaded and properly
  649. installed the Org mode distribution.
  650. Unlike to `org-modules', libraries in this list will not be
  651. loaded along with Org, but only once the export framework is
  652. needed.
  653. This variable needs to be set before org.el is loaded. If you
  654. need to make a change while Emacs is running, use the customize
  655. interface or run the following code, where VAL stands for the new
  656. value of the variable, after updating it:
  657. (progn
  658. (setq org-export-registered-backends
  659. (cl-remove-if-not
  660. (lambda (backend)
  661. (let ((name (org-export-backend-name backend)))
  662. (or (memq name val)
  663. (catch \\='parentp
  664. (dolist (b val)
  665. (and (org-export-derived-backend-p b name)
  666. (throw \\='parentp t)))))))
  667. org-export-registered-backends))
  668. (let ((new-list (mapcar #\\='org-export-backend-name
  669. org-export-registered-backends)))
  670. (dolist (backend val)
  671. (cond
  672. ((not (load (format \"ox-%s\" backend) t t))
  673. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  674. backend))
  675. ((not (memq backend new-list)) (push backend new-list))))
  676. (set-default \\='org-export-backends new-list)))
  677. Adding a back-end to this list will also pull the back-end it
  678. depends on, if any."
  679. :group 'org
  680. :group 'org-export
  681. :version "26.1"
  682. :package-version '(Org . "9.0")
  683. :initialize 'custom-initialize-set
  684. :set (lambda (var val)
  685. (if (not (featurep 'ox)) (set-default var val)
  686. ;; Any back-end not required anymore (not present in VAL and not
  687. ;; a parent of any back-end in the new value) is removed from the
  688. ;; list of registered back-ends.
  689. (setq org-export-registered-backends
  690. (cl-remove-if-not
  691. (lambda (backend)
  692. (let ((name (org-export-backend-name backend)))
  693. (or (memq name val)
  694. (catch 'parentp
  695. (dolist (b val)
  696. (and (org-export-derived-backend-p b name)
  697. (throw 'parentp t)))))))
  698. org-export-registered-backends))
  699. ;; Now build NEW-LIST of both new back-ends and required
  700. ;; parents.
  701. (let ((new-list (mapcar #'org-export-backend-name
  702. org-export-registered-backends)))
  703. (dolist (backend val)
  704. (cond
  705. ((not (load (format "ox-%s" backend) t t))
  706. (message "Problems while trying to load export back-end `%s'"
  707. backend))
  708. ((not (memq backend new-list)) (push backend new-list))))
  709. ;; Set VAR to that list with fixed dependencies.
  710. (set-default var new-list))))
  711. :type '(set :greedy t
  712. (const :tag " ascii Export buffer to ASCII format" ascii)
  713. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  714. (const :tag " html Export buffer to HTML format" html)
  715. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  716. (const :tag " latex Export buffer to LaTeX format" latex)
  717. (const :tag " man Export buffer to MAN format" man)
  718. (const :tag " md Export buffer to Markdown format" md)
  719. (const :tag " odt Export buffer to ODT format" odt)
  720. (const :tag " org Export buffer to Org format" org)
  721. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  722. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  723. (const :tag "C deck Export buffer to deck.js presentations" deck)
  724. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  725. (const :tag "C groff Export buffer to Groff format" groff)
  726. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  727. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  728. (const :tag "C s5 Export buffer to s5 presentations" s5)
  729. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  730. (eval-after-load 'ox
  731. '(dolist (backend org-export-backends)
  732. (condition-case nil (require (intern (format "ox-%s" backend)))
  733. (error (message "Problems while trying to load export back-end `%s'"
  734. backend)))))
  735. (defcustom org-support-shift-select nil
  736. "Non-nil means make shift-cursor commands select text when possible.
  737. \\<org-mode-map>\
  738. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  739. start selecting a region, or enlarge regions started in this way.
  740. In Org mode, in special contexts, these same keys are used for
  741. other purposes, important enough to compete with shift selection.
  742. Org tries to balance these needs by supporting `shift-select-mode'
  743. outside these special contexts, under control of this variable.
  744. The default of this variable is nil, to avoid confusing behavior. Shifted
  745. cursor keys will then execute Org commands in the following contexts:
  746. - on a headline, changing TODO state (left/right) and priority (up/down)
  747. - on a time stamp, changing the time
  748. - in a plain list item, changing the bullet type
  749. - in a property definition line, switching between allowed values
  750. - in the BEGIN line of a clock table (changing the time block).
  751. Outside these contexts, the commands will throw an error.
  752. When this variable is t and the cursor is not in a special
  753. context, Org mode will support shift-selection for making and
  754. enlarging regions. To make this more effective, the bullet
  755. cycling will no longer happen anywhere in an item line, but only
  756. if the cursor is exactly on the bullet.
  757. If you set this variable to the symbol `always', then the keys
  758. will not be special in headlines, property lines, and item lines,
  759. to make shift selection work there as well. If this is what you
  760. want, you can use the following alternative commands:
  761. `\\[org-todo]' and `\\[org-priority]' \
  762. to change TODO state and priority,
  763. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  764. can be used to switch TODO sets,
  765. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  766. and properties can be edited by hand or in column view.
  767. However, when the cursor is on a timestamp, shift-cursor commands
  768. will still edit the time stamp - this is just too good to give up."
  769. :group 'org
  770. :type '(choice
  771. (const :tag "Never" nil)
  772. (const :tag "When outside special context" t)
  773. (const :tag "Everywhere except timestamps" always)))
  774. (defcustom org-loop-over-headlines-in-active-region nil
  775. "Shall some commands act upon headlines in the active region?
  776. When set to t, some commands will be performed in all headlines
  777. within the active region.
  778. When set to `start-level', some commands will be performed in all
  779. headlines within the active region, provided that these headlines
  780. are of the same level than the first one.
  781. When set to a string, those commands will be performed on the
  782. matching headlines within the active region. Such string must be
  783. a tags/property/todo match as it is used in the agenda tags view.
  784. The list of commands is: `org-schedule', `org-deadline',
  785. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  786. `org-archive-to-archive-sibling'. The archiving commands skip
  787. already archived entries."
  788. :type '(choice (const :tag "Don't loop" nil)
  789. (const :tag "All headlines in active region" t)
  790. (const :tag "In active region, headlines at the same level than the first one" start-level)
  791. (string :tag "Tags/Property/Todo matcher"))
  792. :version "24.1"
  793. :group 'org-todo
  794. :group 'org-archive)
  795. (defcustom org-startup-folded t
  796. "Non-nil means entering Org mode will switch to OVERVIEW.
  797. This can also be configured on a per-file basis by adding one of
  798. the following lines anywhere in the buffer:
  799. #+STARTUP: fold (or `overview', this is equivalent)
  800. #+STARTUP: nofold (or `showall', this is equivalent)
  801. #+STARTUP: content
  802. #+STARTUP: showeverything
  803. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  804. to ignore this option when Org opens agenda files for the first
  805. time."
  806. :group 'org-startup
  807. :type '(choice
  808. (const :tag "nofold: show all" nil)
  809. (const :tag "fold: overview" t)
  810. (const :tag "content: all headlines" content)
  811. (const :tag "show everything, even drawers" showeverything)))
  812. (defcustom org-startup-truncated t
  813. "Non-nil means entering Org mode will set `truncate-lines'.
  814. This is useful since some lines containing links can be very long and
  815. uninteresting. Also tables look terrible when wrapped.
  816. The variable `org-startup-truncated' allows to configure
  817. truncation for Org mode different to the other modes that use the
  818. variable `truncate-lines' and as a shortcut instead of putting
  819. the variable `truncate-lines' into the `org-mode-hook'. If one
  820. wants to configure truncation for Org mode not statically but
  821. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  822. the variable `truncate-lines' has to be used because in such a
  823. case it is too late to set the variable `org-startup-truncated'."
  824. :group 'org-startup
  825. :type 'boolean)
  826. (defcustom org-startup-indented nil
  827. "Non-nil means turn on `org-indent-mode' on startup.
  828. This can also be configured on a per-file basis by adding one of
  829. the following lines anywhere in the buffer:
  830. #+STARTUP: indent
  831. #+STARTUP: noindent"
  832. :group 'org-structure
  833. :type '(choice
  834. (const :tag "Not" nil)
  835. (const :tag "Globally (slow on startup in large files)" t)))
  836. (defcustom org-use-sub-superscripts t
  837. "Non-nil means interpret \"_\" and \"^\" for display.
  838. If you want to control how Org exports those characters, see
  839. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  840. used to be an alias for `org-export-with-sub-superscripts' in
  841. Org <8.0, it is not anymore.
  842. When this option is turned on, you can use TeX-like syntax for
  843. sub- and superscripts within the buffer. Several characters after
  844. \"_\" or \"^\" will be considered as a single item - so grouping
  845. with {} is normally not needed. For example, the following things
  846. will be parsed as single sub- or superscripts:
  847. 10^24 or 10^tau several digits will be considered 1 item.
  848. 10^-12 or 10^-tau a leading sign with digits or a word
  849. x^2-y^3 will be read as x^2 - y^3, because items are
  850. terminated by almost any nonword/nondigit char.
  851. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  852. Still, ambiguity is possible. So when in doubt, use {} to enclose
  853. the sub/superscript. If you set this variable to the symbol `{}',
  854. the braces are *required* in order to trigger interpretations as
  855. sub/superscript. This can be helpful in documents that need \"_\"
  856. frequently in plain text."
  857. :group 'org-startup
  858. :version "24.4"
  859. :package-version '(Org . "8.0")
  860. :type '(choice
  861. (const :tag "Always interpret" t)
  862. (const :tag "Only with braces" {})
  863. (const :tag "Never interpret" nil)))
  864. (defcustom org-startup-with-beamer-mode nil
  865. "Non-nil means turn on `org-beamer-mode' on startup.
  866. This can also be configured on a per-file basis by adding one of
  867. the following lines anywhere in the buffer:
  868. #+STARTUP: beamer"
  869. :group 'org-startup
  870. :version "24.1"
  871. :type 'boolean)
  872. (defcustom org-startup-align-all-tables nil
  873. "Non-nil means align all tables when visiting a file.
  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: align
  877. #+STARTUP: noalign"
  878. :group 'org-startup
  879. :type 'boolean)
  880. (defcustom org-startup-shrink-all-tables nil
  881. "Non-nil means shrink all table columns with a width cookie.
  882. This can also be configured on a per-file basis by adding one of
  883. the following lines anywhere in the buffer:
  884. #+STARTUP: shrink"
  885. :group 'org-startup
  886. :type 'boolean
  887. :version "27.1"
  888. :package-version '(Org . "9.2")
  889. :safe #'booleanp)
  890. (defcustom org-startup-with-inline-images nil
  891. "Non-nil means show inline images when loading a new Org file.
  892. This can also be configured on a per-file basis by adding one of
  893. the following lines anywhere in the buffer:
  894. #+STARTUP: inlineimages
  895. #+STARTUP: noinlineimages"
  896. :group 'org-startup
  897. :version "24.1"
  898. :type 'boolean)
  899. (defcustom org-startup-with-latex-preview nil
  900. "Non-nil means preview LaTeX fragments when loading a new Org file.
  901. This can also be configured on a per-file basis by adding one of
  902. the following lines anywhere in the buffer:
  903. #+STARTUP: latexpreview
  904. #+STARTUP: nolatexpreview"
  905. :group 'org-startup
  906. :version "24.4"
  907. :package-version '(Org . "8.0")
  908. :type 'boolean)
  909. (defcustom org-insert-mode-line-in-empty-file nil
  910. "Non-nil means insert the first line setting Org mode in empty files.
  911. When the function `org-mode' is called interactively in an empty file, this
  912. normally means that the file name does not automatically trigger Org mode.
  913. To ensure that the file will always be in Org mode in the future, a
  914. line enforcing Org mode will be inserted into the buffer, if this option
  915. has been set."
  916. :group 'org-startup
  917. :type 'boolean)
  918. (defcustom org-replace-disputed-keys nil
  919. "Non-nil means use alternative key bindings for some keys.
  920. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  921. These keys are also used by other packages like shift-selection-mode'
  922. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  923. If you want to use Org mode together with one of these other modes,
  924. or more generally if you would like to move some Org mode commands to
  925. other keys, set this variable and configure the keys with the variable
  926. `org-disputed-keys'.
  927. This option is only relevant at load-time of Org mode, and must be set
  928. *before* org.el is loaded. Changing it requires a restart of Emacs to
  929. become effective."
  930. :group 'org-startup
  931. :type 'boolean)
  932. (defcustom org-use-extra-keys nil
  933. "Non-nil means use extra key sequence definitions for certain commands.
  934. This happens automatically if `window-system' is nil. This
  935. variable lets you do the same manually. You must set it before
  936. loading Org."
  937. :group 'org-startup
  938. :type 'boolean)
  939. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  940. (defcustom org-disputed-keys
  941. '(([(shift up)] . [(meta p)])
  942. ([(shift down)] . [(meta n)])
  943. ([(shift left)] . [(meta -)])
  944. ([(shift right)] . [(meta +)])
  945. ([(control shift right)] . [(meta shift +)])
  946. ([(control shift left)] . [(meta shift -)]))
  947. "Keys for which Org mode and other modes compete.
  948. This is an alist, cars are the default keys, second element specifies
  949. the alternative to use when `org-replace-disputed-keys' is t.
  950. Keys can be specified in any syntax supported by `define-key'.
  951. The value of this option takes effect only at Org mode startup,
  952. therefore you'll have to restart Emacs to apply it after changing."
  953. :group 'org-startup
  954. :type 'alist)
  955. (defun org-key (key)
  956. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  957. Or return the original if not disputed."
  958. (when org-replace-disputed-keys
  959. (let* ((nkey (key-description key))
  960. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  961. org-disputed-keys)))
  962. (setq key (if x (cdr x) key))))
  963. key)
  964. (defun org-defkey (keymap key def)
  965. "Define a key, possibly translated, as returned by `org-key'."
  966. (define-key keymap (org-key key) def))
  967. (defcustom org-ellipsis nil
  968. "The ellipsis to use in the Org mode outline.
  969. When nil, just use the standard three dots. When a non-empty string,
  970. use that string instead.
  971. The change affects only Org mode (which will then use its own display table).
  972. Changing this requires executing `\\[org-mode]' in a buffer to become
  973. effective."
  974. :group 'org-startup
  975. :type '(choice (const :tag "Default" nil)
  976. (string :tag "String" :value "...#"))
  977. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  978. (defvar org-display-table nil
  979. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  980. (defgroup org-keywords nil
  981. "Keywords in Org mode."
  982. :tag "Org Keywords"
  983. :group 'org)
  984. (defcustom org-closed-keep-when-no-todo nil
  985. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  986. :group 'org-todo
  987. :group 'org-keywords
  988. :version "24.4"
  989. :package-version '(Org . "8.0")
  990. :type 'boolean)
  991. (defgroup org-structure nil
  992. "Options concerning the general structure of Org files."
  993. :tag "Org Structure"
  994. :group 'org)
  995. (defgroup org-reveal-location nil
  996. "Options about how to make context of a location visible."
  997. :tag "Org Reveal Location"
  998. :group 'org-structure)
  999. (defcustom org-show-context-detail '((agenda . local)
  1000. (bookmark-jump . lineage)
  1001. (isearch . lineage)
  1002. (default . ancestors))
  1003. "Alist between context and visibility span when revealing a location.
  1004. \\<org-mode-map>Some actions may move point into invisible
  1005. locations. As a consequence, Org always expose a neighborhood
  1006. around point. How much is shown depends on the initial action,
  1007. or context. Valid contexts are
  1008. agenda when exposing an entry from the agenda
  1009. org-goto when using the command `org-goto' (`\\[org-goto]')
  1010. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1011. tags-tree when constructing a sparse tree based on tags matches
  1012. link-search when exposing search matches associated with a link
  1013. mark-goto when exposing the jump goal of a mark
  1014. bookmark-jump when exposing a bookmark location
  1015. isearch when exiting from an incremental search
  1016. default default for all contexts not set explicitly
  1017. Allowed visibility spans are
  1018. minimal show current headline; if point is not on headline,
  1019. also show entry
  1020. local show current headline, entry and next headline
  1021. ancestors show current headline and its direct ancestors; if
  1022. point is not on headline, also show entry
  1023. lineage show current headline, its direct ancestors and all
  1024. their children; if point is not on headline, also show
  1025. entry and first child
  1026. tree show current headline, its direct ancestors and all
  1027. their children; if point is not on headline, also show
  1028. entry and all children
  1029. canonical show current headline, its direct ancestors along with
  1030. their entries and children; if point is not located on
  1031. the headline, also show current entry and all children
  1032. As special cases, a nil or t value means show all contexts in
  1033. `minimal' or `canonical' view, respectively.
  1034. Some views can make displayed information very compact, but also
  1035. make it harder to edit the location of the match. In such
  1036. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1037. more context."
  1038. :group 'org-reveal-location
  1039. :version "26.1"
  1040. :package-version '(Org . "9.0")
  1041. :type '(choice
  1042. (const :tag "Canonical" t)
  1043. (const :tag "Minimal" nil)
  1044. (repeat :greedy t :tag "Individual contexts"
  1045. (cons
  1046. (choice :tag "Context"
  1047. (const agenda)
  1048. (const org-goto)
  1049. (const occur-tree)
  1050. (const tags-tree)
  1051. (const link-search)
  1052. (const mark-goto)
  1053. (const bookmark-jump)
  1054. (const isearch)
  1055. (const default))
  1056. (choice :tag "Detail level"
  1057. (const minimal)
  1058. (const local)
  1059. (const ancestors)
  1060. (const lineage)
  1061. (const tree)
  1062. (const canonical))))))
  1063. (defcustom org-indirect-buffer-display 'other-window
  1064. "How should indirect tree buffers be displayed?
  1065. This applies to indirect buffers created with the commands
  1066. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1067. Valid values are:
  1068. current-window Display in the current window
  1069. other-window Just display in another window.
  1070. dedicated-frame Create one new frame, and re-use it each time.
  1071. new-frame Make a new frame each time. Note that in this case
  1072. previously-made indirect buffers are kept, and you need to
  1073. kill these buffers yourself."
  1074. :group 'org-structure
  1075. :group 'org-agenda-windows
  1076. :type '(choice
  1077. (const :tag "In current window" current-window)
  1078. (const :tag "In current frame, other window" other-window)
  1079. (const :tag "Each time a new frame" new-frame)
  1080. (const :tag "One dedicated frame" dedicated-frame)))
  1081. (defcustom org-use-speed-commands nil
  1082. "Non-nil means activate single letter commands at beginning of a headline.
  1083. This may also be a function to test for appropriate locations where speed
  1084. commands should be active.
  1085. For example, to activate speed commands when the point is on any
  1086. star at the beginning of the headline, you can do this:
  1087. (setq org-use-speed-commands
  1088. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1089. :group 'org-structure
  1090. :type '(choice
  1091. (const :tag "Never" nil)
  1092. (const :tag "At beginning of headline stars" t)
  1093. (function)))
  1094. (defcustom org-speed-commands-user nil
  1095. "Alist of additional speed commands.
  1096. This list will be checked before `org-speed-commands-default'
  1097. when the variable `org-use-speed-commands' is non-nil
  1098. and when the cursor is at the beginning of a headline.
  1099. The car if each entry is a string with a single letter, which must
  1100. be assigned to `self-insert-command' in the global map.
  1101. The cdr is either a command to be called interactively, a function
  1102. to be called, or a form to be evaluated.
  1103. An entry that is just a list with a single string will be interpreted
  1104. as a descriptive headline that will be added when listing the speed
  1105. commands in the Help buffer using the `?' speed command."
  1106. :group 'org-structure
  1107. :type '(repeat :value ("k" . ignore)
  1108. (choice :value ("k" . ignore)
  1109. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1110. (cons :tag "Letter and Command"
  1111. (string :tag "Command letter")
  1112. (choice
  1113. (function)
  1114. (sexp))))))
  1115. (defcustom org-bookmark-names-plist
  1116. '(:last-capture "org-capture-last-stored"
  1117. :last-refile "org-refile-last-stored"
  1118. :last-capture-marker "org-capture-last-stored-marker")
  1119. "Names for bookmarks automatically set by some Org commands.
  1120. This can provide strings as names for a number of bookmarks Org sets
  1121. automatically. The following keys are currently implemented:
  1122. :last-capture
  1123. :last-capture-marker
  1124. :last-refile
  1125. When a key does not show up in the property list, the corresponding bookmark
  1126. is not set."
  1127. :group 'org-structure
  1128. :type 'plist)
  1129. (defgroup org-cycle nil
  1130. "Options concerning visibility cycling in Org mode."
  1131. :tag "Org Cycle"
  1132. :group 'org-structure)
  1133. (defcustom org-cycle-skip-children-state-if-no-children t
  1134. "Non-nil means skip CHILDREN state in entries that don't have any."
  1135. :group 'org-cycle
  1136. :type 'boolean)
  1137. (defcustom org-cycle-max-level nil
  1138. "Maximum level which should still be subject to visibility cycling.
  1139. Levels higher than this will, for cycling, be treated as text, not a headline.
  1140. When `org-odd-levels-only' is set, a value of N in this variable actually
  1141. means 2N-1 stars as the limiting headline.
  1142. When nil, cycle all levels.
  1143. Note that the limiting level of cycling is also influenced by
  1144. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1145. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1146. than its value."
  1147. :group 'org-cycle
  1148. :type '(choice
  1149. (const :tag "No limit" nil)
  1150. (integer :tag "Maximum level")))
  1151. (defcustom org-hide-block-startup nil
  1152. "Non-nil means entering Org mode will fold all blocks.
  1153. This can also be set in on a per-file basis with
  1154. #+STARTUP: hideblocks
  1155. #+STARTUP: showblocks"
  1156. :group 'org-startup
  1157. :group 'org-cycle
  1158. :type 'boolean)
  1159. (defcustom org-cycle-global-at-bob nil
  1160. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1161. This makes it possible to do global cycling without having to use `S-TAB'
  1162. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1163. line of the buffer
  1164. must not be a headline -- it may be empty or some other text.
  1165. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1166. sure the cursor stays at the beginning of the buffer.
  1167. When this option is nil, don't do anything special at the beginning of
  1168. the buffer."
  1169. :group 'org-cycle
  1170. :type 'boolean)
  1171. (defcustom org-cycle-level-after-item/entry-creation t
  1172. "Non-nil means cycle entry level or item indentation in new empty entries.
  1173. When the cursor is at the end of an empty headline, i.e., with only stars
  1174. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1175. and then all possible ancestor states, before returning to the original state.
  1176. This makes data entry extremely fast: M-RET to create a new headline,
  1177. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1178. When the cursor is at the end of an empty plain list item, one TAB will
  1179. make it a subitem, two or more tabs will back up to make this an item
  1180. higher up in the item hierarchy."
  1181. :group 'org-cycle
  1182. :type 'boolean)
  1183. (defcustom org-cycle-emulate-tab t
  1184. "Where should `org-cycle' emulate TAB.
  1185. nil Never
  1186. white Only in completely white lines
  1187. whitestart Only at the beginning of lines, before the first non-white char
  1188. t Everywhere except in headlines
  1189. exc-hl-bol Everywhere except at the start of a headline
  1190. If TAB is used in a place where it does not emulate TAB, the current subtree
  1191. visibility is cycled."
  1192. :group 'org-cycle
  1193. :type '(choice (const :tag "Never" nil)
  1194. (const :tag "Only in completely white lines" white)
  1195. (const :tag "Before first char in a line" whitestart)
  1196. (const :tag "Everywhere except in headlines" t)
  1197. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1198. (defcustom org-cycle-separator-lines 2
  1199. "Number of empty lines needed to keep an empty line between collapsed trees.
  1200. If you leave an empty line between the end of a subtree and the following
  1201. headline, this empty line is hidden when the subtree is folded.
  1202. Org mode will leave (exactly) one empty line visible if the number of
  1203. empty lines is equal or larger to the number given in this variable.
  1204. So the default 2 means at least 2 empty lines after the end of a subtree
  1205. are needed to produce free space between a collapsed subtree and the
  1206. following headline.
  1207. If the number is negative, and the number of empty lines is at least -N,
  1208. all empty lines are shown.
  1209. Special case: when 0, never leave empty lines in collapsed view."
  1210. :group 'org-cycle
  1211. :type 'integer)
  1212. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1213. (defcustom org-pre-cycle-hook nil
  1214. "Hook that is run before visibility cycling is happening.
  1215. The function(s) in this hook must accept a single argument which indicates
  1216. the new state that will be set right after running this hook. The
  1217. argument is a symbol. Before a global state change, it can have the values
  1218. `overview', `content', or `all'. Before a local state change, it can have
  1219. the values `folded', `children', or `subtree'."
  1220. :group 'org-cycle
  1221. :type 'hook)
  1222. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1223. org-cycle-hide-drawers
  1224. org-cycle-show-empty-lines
  1225. org-optimize-window-after-visibility-change)
  1226. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1227. The function(s) in this hook must accept a single argument which indicates
  1228. the new state that was set by the most recent `org-cycle' command. The
  1229. argument is a symbol. After a global state change, it can have the values
  1230. `overview', `contents', or `all'. After a local state change, it can have
  1231. the values `folded', `children', or `subtree'."
  1232. :group 'org-cycle
  1233. :type 'hook
  1234. :version "26.1"
  1235. :package-version '(Org . "8.3"))
  1236. (defgroup org-edit-structure nil
  1237. "Options concerning structure editing in Org mode."
  1238. :tag "Org Edit Structure"
  1239. :group 'org-structure)
  1240. (defcustom org-odd-levels-only nil
  1241. "Non-nil means skip even levels and only use odd levels for the outline.
  1242. This has the effect that two stars are being added/taken away in
  1243. promotion/demotion commands. It also influences how levels are
  1244. handled by the exporters.
  1245. Changing it requires restart of `font-lock-mode' to become effective
  1246. for fontification also in regions already fontified.
  1247. You may also set this on a per-file basis by adding one of the following
  1248. lines to the buffer:
  1249. #+STARTUP: odd
  1250. #+STARTUP: oddeven"
  1251. :group 'org-edit-structure
  1252. :group 'org-appearance
  1253. :type 'boolean)
  1254. (defcustom org-adapt-indentation t
  1255. "Non-nil means adapt indentation to outline node level.
  1256. When this variable is set, Org assumes that you write outlines by
  1257. indenting text in each node to align with the headline (after the
  1258. stars). The following issues are influenced by this variable:
  1259. - The indentation is increased by one space in a demotion
  1260. command, and decreased by one in a promotion command. However,
  1261. in the latter case, if shifting some line in the entry body
  1262. would alter document structure (e.g., insert a new headline),
  1263. indentation is not changed at all.
  1264. - Property drawers and planning information is inserted indented
  1265. when this variable is set. When nil, they will not be indented.
  1266. - TAB indents a line relative to current level. The lines below
  1267. a headline will be indented when this variable is set.
  1268. Note that this is all about true indentation, by adding and
  1269. removing space characters. See also `org-indent.el' which does
  1270. level-dependent indentation in a virtual way, i.e. at display
  1271. time in Emacs."
  1272. :group 'org-edit-structure
  1273. :type 'boolean)
  1274. (defcustom org-special-ctrl-a/e nil
  1275. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1276. When t, `C-a' will bring back the cursor to the beginning of the
  1277. headline text, i.e. after the stars and after a possible TODO
  1278. keyword. In an item, this will be the position after bullet and
  1279. check-box, if any. When the cursor is already at that position,
  1280. another `C-a' will bring it to the beginning of the line.
  1281. `C-e' will jump to the end of the headline, ignoring the presence
  1282. of tags in the headline. A second `C-e' will then jump to the
  1283. true end of the line, after any tags. This also means that, when
  1284. this variable is non-nil, `C-e' also will never jump beyond the
  1285. end of the heading of a folded section, i.e. not after the
  1286. ellipses.
  1287. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1288. normally, going to the true line boundary first. Only a directly
  1289. following, identical keypress will bring the cursor to the
  1290. special positions.
  1291. This may also be a cons cell where the behavior for `C-a' and
  1292. `C-e' is set separately."
  1293. :group 'org-edit-structure
  1294. :type '(choice
  1295. (const :tag "off" nil)
  1296. (const :tag "on: after stars/bullet and before tags first" t)
  1297. (const :tag "reversed: true line boundary first" reversed)
  1298. (cons :tag "Set C-a and C-e separately"
  1299. (choice :tag "Special C-a"
  1300. (const :tag "off" nil)
  1301. (const :tag "on: after stars/bullet first" t)
  1302. (const :tag "reversed: before stars/bullet first" reversed))
  1303. (choice :tag "Special C-e"
  1304. (const :tag "off" nil)
  1305. (const :tag "on: before tags first" t)
  1306. (const :tag "reversed: after tags first" reversed)))))
  1307. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1308. (defcustom org-special-ctrl-k nil
  1309. "Non-nil means `C-k' will behave specially in headlines.
  1310. When nil, `C-k' will call the default `kill-line' command.
  1311. When t, the following will happen while the cursor is in the headline:
  1312. - When the cursor is at the beginning of a headline, kill the entire
  1313. line and possible the folded subtree below the line.
  1314. - When in the middle of the headline text, kill the headline up to the tags.
  1315. - When after the headline text, kill the tags."
  1316. :group 'org-edit-structure
  1317. :type 'boolean)
  1318. (defcustom org-ctrl-k-protect-subtree nil
  1319. "Non-nil means, do not delete a hidden subtree with C-k.
  1320. When set to the symbol `error', simply throw an error when C-k is
  1321. used to kill (part-of) a headline that has hidden text behind it.
  1322. Any other non-nil value will result in a query to the user, if it is
  1323. OK to kill that hidden subtree. When nil, kill without remorse."
  1324. :group 'org-edit-structure
  1325. :version "24.1"
  1326. :type '(choice
  1327. (const :tag "Do not protect hidden subtrees" nil)
  1328. (const :tag "Protect hidden subtrees with a security query" t)
  1329. (const :tag "Never kill a hidden subtree with C-k" error)))
  1330. (defcustom org-special-ctrl-o t
  1331. "Non-nil means, make `C-o' insert a row in tables."
  1332. :group 'org-edit-structure
  1333. :type 'boolean)
  1334. (defcustom org-catch-invisible-edits nil
  1335. "Check if in invisible region before inserting or deleting a character.
  1336. Valid values are:
  1337. nil Do not check, so just do invisible edits.
  1338. error Throw an error and do nothing.
  1339. show Make point visible, and do the requested edit.
  1340. show-and-error Make point visible, then throw an error and abort the edit.
  1341. smart Make point visible, and do insertion/deletion if it is
  1342. adjacent to visible text and the change feels predictable.
  1343. Never delete a previously invisible character or add in the
  1344. middle or right after an invisible region. Basically, this
  1345. allows insertion and backward-delete right before ellipses.
  1346. FIXME: maybe in this case we should not even show?"
  1347. :group 'org-edit-structure
  1348. :version "24.1"
  1349. :type '(choice
  1350. (const :tag "Do not check" nil)
  1351. (const :tag "Throw error when trying to edit" error)
  1352. (const :tag "Unhide, but do not do the edit" show-and-error)
  1353. (const :tag "Show invisible part and do the edit" show)
  1354. (const :tag "Be smart and do the right thing" smart)))
  1355. (defcustom org-yank-folded-subtrees t
  1356. "Non-nil means when yanking subtrees, fold them.
  1357. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1358. it starts with a heading and all other headings in it are either children
  1359. or siblings, then fold all the subtrees. However, do this only if no
  1360. text after the yank would be swallowed into a folded tree by this action."
  1361. :group 'org-edit-structure
  1362. :type 'boolean)
  1363. (defcustom org-yank-adjusted-subtrees nil
  1364. "Non-nil means when yanking subtrees, adjust the level.
  1365. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1366. this function for details."
  1367. :group 'org-edit-structure
  1368. :type 'boolean)
  1369. (defcustom org-M-RET-may-split-line '((default . t))
  1370. "Non-nil means M-RET will split the line at the cursor position.
  1371. When nil, it will go to the end of the line before making a
  1372. new line.
  1373. You may also set this option in a different way for different
  1374. contexts. Valid contexts are:
  1375. headline when creating a new headline
  1376. item when creating a new item
  1377. table in a table field
  1378. default the value to be used for all contexts not explicitly
  1379. customized"
  1380. :group 'org-structure
  1381. :group 'org-table
  1382. :type '(choice
  1383. (const :tag "Always" t)
  1384. (const :tag "Never" nil)
  1385. (repeat :greedy t :tag "Individual contexts"
  1386. (cons
  1387. (choice :tag "Context"
  1388. (const headline)
  1389. (const item)
  1390. (const table)
  1391. (const default))
  1392. (boolean)))))
  1393. (defcustom org-insert-heading-respect-content nil
  1394. "Non-nil means insert new headings after the current subtree.
  1395. \\<org-mode-map>
  1396. When nil, the new heading is created directly after the current line.
  1397. The commands `\\[org-insert-heading-respect-content]' and \
  1398. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1399. for the duration of the command."
  1400. :group 'org-structure
  1401. :type 'boolean)
  1402. (defcustom org-blank-before-new-entry '((heading . auto)
  1403. (plain-list-item . auto))
  1404. "Should `org-insert-heading' leave a blank line before new heading/item?
  1405. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1406. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1407. which case Org will look at the surrounding headings/items and try to
  1408. make an intelligent decision whether to insert a blank line or not."
  1409. :group 'org-edit-structure
  1410. :type '(list
  1411. (cons (const heading)
  1412. (choice (const :tag "Never" nil)
  1413. (const :tag "Always" t)
  1414. (const :tag "Auto" auto)))
  1415. (cons (const plain-list-item)
  1416. (choice (const :tag "Never" nil)
  1417. (const :tag "Always" t)
  1418. (const :tag "Auto" auto)))))
  1419. (defcustom org-insert-heading-hook nil
  1420. "Hook being run after inserting a new heading."
  1421. :group 'org-edit-structure
  1422. :type 'hook)
  1423. (defcustom org-enable-fixed-width-editor t
  1424. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1425. This currently only means they are never auto-wrapped.
  1426. When nil, such lines will be treated like ordinary lines."
  1427. :group 'org-edit-structure
  1428. :type 'boolean)
  1429. (defgroup org-sparse-trees nil
  1430. "Options concerning sparse trees in Org mode."
  1431. :tag "Org Sparse Trees"
  1432. :group 'org-structure)
  1433. (defcustom org-highlight-sparse-tree-matches t
  1434. "Non-nil means highlight all matches that define a sparse tree.
  1435. The highlights will automatically disappear the next time the buffer is
  1436. changed by an edit command."
  1437. :group 'org-sparse-trees
  1438. :type 'boolean)
  1439. (defcustom org-remove-highlights-with-change t
  1440. "Non-nil means any change to the buffer will remove temporary highlights.
  1441. \\<org-mode-map>\
  1442. Such highlights are created by `org-occur' and `org-clock-display'.
  1443. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1444. to get rid of the highlights.
  1445. The highlights created by `org-toggle-latex-fragment' always need
  1446. `\\[org-toggle-latex-fragment]' to be removed."
  1447. :group 'org-sparse-trees
  1448. :group 'org-time
  1449. :type 'boolean)
  1450. (defcustom org-occur-case-fold-search t
  1451. "Non-nil means `org-occur' should be case-insensitive.
  1452. If set to `smart' the search will be case-insensitive only if it
  1453. doesn't specify any upper case character."
  1454. :group 'org-sparse-trees
  1455. :version "26.1"
  1456. :type '(choice
  1457. (const :tag "Case-sensitive" nil)
  1458. (const :tag "Case-insensitive" t)
  1459. (const :tag "Case-insensitive for lower case searches only" 'smart)))
  1460. (defcustom org-occur-hook '(org-first-headline-recenter)
  1461. "Hook that is run after `org-occur' has constructed a sparse tree.
  1462. This can be used to recenter the window to show as much of the structure
  1463. as possible."
  1464. :group 'org-sparse-trees
  1465. :type 'hook)
  1466. (defgroup org-table nil
  1467. "Options concerning tables in Org mode."
  1468. :tag "Org Table"
  1469. :group 'org)
  1470. (defcustom org-self-insert-cluster-for-undo nil
  1471. "Non-nil means cluster self-insert commands for undo when possible.
  1472. If this is set, then, like in the Emacs command loop, 20 consecutive
  1473. characters will be undone together.
  1474. This is configurable, because there is some impact on typing performance."
  1475. :group 'org-table
  1476. :type 'boolean)
  1477. (defcustom org-table-tab-recognizes-table.el t
  1478. "Non-nil means TAB will automatically notice a table.el table.
  1479. When it sees such a table, it moves point into it and - if necessary -
  1480. calls `table-recognize-table'."
  1481. :group 'org-table-editing
  1482. :type 'boolean)
  1483. (defgroup org-link nil
  1484. "Options concerning links in Org mode."
  1485. :tag "Org Link"
  1486. :group 'org)
  1487. (defvar-local org-link-abbrev-alist-local nil
  1488. "Buffer-local version of `org-link-abbrev-alist', which see.
  1489. The value of this is taken from the #+LINK lines.")
  1490. (defcustom org-link-parameters
  1491. '(("doi" :follow org--open-doi-link)
  1492. ("elisp" :follow org--open-elisp-link)
  1493. ("file" :complete org-file-complete-link)
  1494. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1495. ("help" :follow org--open-help-link)
  1496. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1497. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1498. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1499. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1500. ("shell" :follow org--open-shell-link))
  1501. "An alist of properties that defines all the links in Org mode.
  1502. The key in each association is a string of the link type.
  1503. Subsequent optional elements make up a p-list of link properties.
  1504. :follow - A function that takes the link path as an argument.
  1505. :export - A function that takes the link path, description and
  1506. export-backend as arguments.
  1507. :store - A function responsible for storing the link. See the
  1508. function `org-store-link-functions'.
  1509. :complete - A function that inserts a link with completion. The
  1510. function takes one optional prefix arg.
  1511. :face - A face for the link, or a function that returns a face.
  1512. The function takes one argument which is the link path. The
  1513. default face is `org-link'.
  1514. :mouse-face - The mouse-face. The default is `highlight'.
  1515. :display - `full' will not fold the link in descriptive
  1516. display. Default is `org-link'.
  1517. :help-echo - A string or function that takes (window object position)
  1518. as arguments and returns a string.
  1519. :keymap - A keymap that is active on the link. The default is
  1520. `org-mouse-map'.
  1521. :htmlize-link - A function for the htmlize-link. Defaults
  1522. to (list :uri \"type:path\")
  1523. :activate-func - A function to run at the end of font-lock
  1524. activation. The function must accept (link-start link-end path bracketp)
  1525. as arguments."
  1526. :group 'org-link
  1527. :type '(alist :tag "Link display parameters"
  1528. :value-type plist)
  1529. :version "26.1"
  1530. :package-version '(Org . "9.1"))
  1531. (defun org-link-get-parameter (type key)
  1532. "Get TYPE link property for KEY.
  1533. TYPE is a string and KEY is a plist keyword."
  1534. (plist-get
  1535. (cdr (assoc type org-link-parameters))
  1536. key))
  1537. (defun org-link-set-parameters (type &rest parameters)
  1538. "Set link TYPE properties to PARAMETERS.
  1539. PARAMETERS should be :key val pairs."
  1540. (let ((data (assoc type org-link-parameters)))
  1541. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1542. (push (cons type parameters) org-link-parameters)
  1543. (org-make-link-regexps)
  1544. (org-element-update-syntax))))
  1545. (defun org-link-types ()
  1546. "Return a list of known link types."
  1547. (mapcar #'car org-link-parameters))
  1548. (defcustom org-link-abbrev-alist nil
  1549. "Alist of link abbreviations.
  1550. The car of each element is a string, to be replaced at the start of a link.
  1551. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1552. links in Org buffers can have an optional tag after a double colon, e.g.,
  1553. [[linkkey:tag][description]]
  1554. The `linkkey' must be a single word, starting with a letter, followed
  1555. by letters, numbers, `-' or `_'.
  1556. If REPLACE is a string, the tag will simply be appended to create the link.
  1557. If the string contains \"%s\", the tag will be inserted there. If the string
  1558. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1559. at that point (see the function `url-hexify-string'). If the string contains
  1560. the specifier \"%(my-function)\", then the custom function `my-function' will
  1561. be invoked: this function takes the tag as its only argument and must return
  1562. a string.
  1563. REPLACE may also be a function that will be called with the tag as the
  1564. only argument to create the link, which should be returned as a string.
  1565. See the manual for examples."
  1566. :group 'org-link
  1567. :type '(repeat
  1568. (cons
  1569. (string :tag "Protocol")
  1570. (choice
  1571. (string :tag "Format")
  1572. (function)))))
  1573. (defcustom org-descriptive-links t
  1574. "Non-nil means Org will display descriptive links.
  1575. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1576. \"Org Website\", hiding the link itself and just displaying its
  1577. description. When set to nil, Org will display the full links
  1578. literally.
  1579. You can interactively set the value of this variable by calling
  1580. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1581. :group 'org-link
  1582. :type 'boolean)
  1583. (defcustom org-link-file-path-type 'adaptive
  1584. "How the path name in file links should be stored.
  1585. Valid values are:
  1586. relative Relative to the current directory, i.e. the directory of the file
  1587. into which the link is being inserted.
  1588. absolute Absolute path, if possible with ~ for home directory.
  1589. noabbrev Absolute path, no abbreviation of home directory.
  1590. adaptive Use relative path for files in the current directory and sub-
  1591. directories of it. For other files, use an absolute path."
  1592. :group 'org-link
  1593. :type '(choice
  1594. (const relative)
  1595. (const absolute)
  1596. (const noabbrev)
  1597. (const adaptive)))
  1598. (defvaralias 'org-activate-links 'org-highlight-links)
  1599. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1600. "Types of links that should be highlighted in Org files.
  1601. This is a list of symbols, each one of them leading to the
  1602. highlighting of a certain link type.
  1603. You can still open links that are not highlighted.
  1604. In principle, it does not hurt to turn on highlighting for all
  1605. link types. There may be a small gain when turning off unused
  1606. link types. The types are:
  1607. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1608. angle Links in angular brackets that may contain whitespace like
  1609. <bbdb:Carsten Dominik>.
  1610. plain Plain links in normal text, no whitespace, like http://google.com.
  1611. radio Text that is matched by a radio target, see manual for details.
  1612. tag Tag settings in a headline (link to tag search).
  1613. date Time stamps (link to calendar).
  1614. footnote Footnote labels.
  1615. If you set this variable during an Emacs session, use `org-mode-restart'
  1616. in the Org buffer so that the change takes effect."
  1617. :group 'org-link
  1618. :group 'org-appearance
  1619. :type '(set :greedy t
  1620. (const :tag "Double bracket links" bracket)
  1621. (const :tag "Angular bracket links" angle)
  1622. (const :tag "Plain text links" plain)
  1623. (const :tag "Radio target matches" radio)
  1624. (const :tag "Tags" tag)
  1625. (const :tag "Timestamps" date)
  1626. (const :tag "Footnotes" footnote)))
  1627. (defcustom org-make-link-description-function nil
  1628. "Function to use for generating link descriptions from links.
  1629. This function must take two parameters: the first one is the
  1630. link, the second one is the description generated by
  1631. `org-insert-link'. The function should return the description to
  1632. use."
  1633. :group 'org-link
  1634. :type '(choice (const nil) (function)))
  1635. (defgroup org-link-store nil
  1636. "Options concerning storing links in Org mode."
  1637. :tag "Org Store Link"
  1638. :group 'org-link)
  1639. (defcustom org-url-hexify-p t
  1640. "When non-nil, hexify URL when creating a link."
  1641. :type 'boolean
  1642. :version "24.3"
  1643. :group 'org-link-store)
  1644. (defcustom org-email-link-description-format "Email %c: %.30s"
  1645. "Format of the description part of a link to an email or usenet message.
  1646. The following %-escapes will be replaced by corresponding information:
  1647. %F full \"From\" field
  1648. %f name, taken from \"From\" field, address if no name
  1649. %T full \"To\" field
  1650. %t first name in \"To\" field, address if no name
  1651. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1652. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1653. %s subject
  1654. %d date
  1655. %m message-id.
  1656. You may use normal field width specification between the % and the letter.
  1657. This is for example useful to limit the length of the subject.
  1658. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1659. :group 'org-link-store
  1660. :type 'string)
  1661. (defcustom org-from-is-user-regexp
  1662. (let (r1 r2)
  1663. (when (and user-mail-address (not (string= user-mail-address "")))
  1664. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1665. (when (and user-full-name (not (string= user-full-name "")))
  1666. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1667. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1668. "Regexp matched against the \"From:\" header of an email or usenet message.
  1669. It should match if the message is from the user him/herself."
  1670. :group 'org-link-store
  1671. :type 'regexp)
  1672. (defcustom org-context-in-file-links t
  1673. "Non-nil means file links from `org-store-link' contain context.
  1674. \\<org-mode-map>
  1675. A search string will be added to the file name with :: as separator
  1676. and used to find the context when the link is activated by the command
  1677. `org-open-at-point'. When this option is t, the entire active region
  1678. will be placed in the search string of the file link. If set to a
  1679. positive integer, only the first n lines of context will be stored.
  1680. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1681. \\[org-store-link]')
  1682. negates this setting for the duration of the command."
  1683. :group 'org-link-store
  1684. :type '(choice boolean integer))
  1685. (defcustom org-keep-stored-link-after-insertion nil
  1686. "Non-nil means keep link in list for entire session.
  1687. \\<org-mode-map>
  1688. The command `org-store-link' adds a link pointing to the current
  1689. location to an internal list. These links accumulate during a session.
  1690. The command `org-insert-link' can be used to insert links into any
  1691. Org file (offering completion for all stored links).
  1692. When this option is nil, every link which has been inserted once using
  1693. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1694. unused
  1695. links more efficient."
  1696. :group 'org-link-store
  1697. :type 'boolean)
  1698. (defgroup org-link-follow nil
  1699. "Options concerning following links in Org mode."
  1700. :tag "Org Follow Link"
  1701. :group 'org-link)
  1702. (defcustom org-link-translation-function nil
  1703. "Function to translate links with different syntax to Org syntax.
  1704. This can be used to translate links created for example by the Planner
  1705. or emacs-wiki packages to Org syntax.
  1706. The function must accept two parameters, a TYPE containing the link
  1707. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1708. which is everything after the link protocol. It should return a cons
  1709. with possibly modified values of type and path.
  1710. Org contains a function for this, so if you set this variable to
  1711. `org-translate-link-from-planner', you should be able follow many
  1712. links created by planner."
  1713. :group 'org-link-follow
  1714. :type '(choice (const nil) (function)))
  1715. (defcustom org-follow-link-hook nil
  1716. "Hook that is run after a link has been followed."
  1717. :group 'org-link-follow
  1718. :type 'hook)
  1719. (defcustom org-tab-follows-link nil
  1720. "Non-nil means on links TAB will follow the link.
  1721. Needs to be set before org.el is loaded.
  1722. This really should not be used, it does not make sense, and the
  1723. implementation is bad."
  1724. :group 'org-link-follow
  1725. :type 'boolean)
  1726. (defcustom org-return-follows-link nil
  1727. "Non-nil means on links RET will follow the link.
  1728. In tables, the special behavior of RET has precedence."
  1729. :group 'org-link-follow
  1730. :type 'boolean)
  1731. (defcustom org-mouse-1-follows-link
  1732. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1733. "Non-nil means mouse-1 on a link will follow the link.
  1734. A longer mouse click will still set point. Needs to be set
  1735. before org.el is loaded."
  1736. :group 'org-link-follow
  1737. :version "26.1"
  1738. :package-version '(Org . "8.3")
  1739. :type '(choice
  1740. (const :tag "A double click follows the link" double)
  1741. (const :tag "Unconditionally follow the link with mouse-1" t)
  1742. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1743. (defcustom org-mark-ring-length 4
  1744. "Number of different positions to be recorded in the ring.
  1745. Changing this requires a restart of Emacs to work correctly."
  1746. :group 'org-link-follow
  1747. :type 'integer)
  1748. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1749. "Non-nil means internal fuzzy links can only match headlines.
  1750. When nil, the a fuzzy link may point to a target or a named
  1751. construct in the document. When set to the special value
  1752. `query-to-create', offer to create a new headline when none
  1753. matched.
  1754. Spaces and statistics cookies are ignored during heading searches."
  1755. :group 'org-link-follow
  1756. :version "24.1"
  1757. :type '(choice
  1758. (const :tag "Use fuzzy text search" nil)
  1759. (const :tag "Match only exact headline" t)
  1760. (const :tag "Match exact headline or query to create it"
  1761. query-to-create))
  1762. :safe #'symbolp)
  1763. (defcustom org-link-frame-setup
  1764. '((vm . vm-visit-folder-other-frame)
  1765. (vm-imap . vm-visit-imap-folder-other-frame)
  1766. (gnus . org-gnus-no-new-news)
  1767. (file . find-file-other-window)
  1768. (wl . wl-other-frame))
  1769. "Setup the frame configuration for following links.
  1770. When following a link with Emacs, it may often be useful to display
  1771. this link in another window or frame. This variable can be used to
  1772. set this up for the different types of links.
  1773. For VM, use any of
  1774. `vm-visit-folder'
  1775. `vm-visit-folder-other-window'
  1776. `vm-visit-folder-other-frame'
  1777. For Gnus, use any of
  1778. `gnus'
  1779. `gnus-other-frame'
  1780. `org-gnus-no-new-news'
  1781. For FILE, use any of
  1782. `find-file'
  1783. `find-file-other-window'
  1784. `find-file-other-frame'
  1785. For Wanderlust use any of
  1786. `wl'
  1787. `wl-other-frame'
  1788. For the calendar, use the variable `calendar-setup'.
  1789. For BBDB, it is currently only possible to display the matches in
  1790. another window."
  1791. :group 'org-link-follow
  1792. :type '(list
  1793. (cons (const vm)
  1794. (choice
  1795. (const vm-visit-folder)
  1796. (const vm-visit-folder-other-window)
  1797. (const vm-visit-folder-other-frame)))
  1798. (cons (const vm-imap)
  1799. (choice
  1800. (const vm-visit-imap-folder)
  1801. (const vm-visit-imap-folder-other-window)
  1802. (const vm-visit-imap-folder-other-frame)))
  1803. (cons (const gnus)
  1804. (choice
  1805. (const gnus)
  1806. (const gnus-other-frame)
  1807. (const org-gnus-no-new-news)))
  1808. (cons (const file)
  1809. (choice
  1810. (const find-file)
  1811. (const find-file-other-window)
  1812. (const find-file-other-frame)))
  1813. (cons (const wl)
  1814. (choice
  1815. (const wl)
  1816. (const wl-other-frame)))))
  1817. (defcustom org-display-internal-link-with-indirect-buffer nil
  1818. "Non-nil means use indirect buffer to display infile links.
  1819. Activating internal links (from one location in a file to another location
  1820. in the same file) normally just jumps to the location. When the link is
  1821. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1822. is displayed in
  1823. another window. When this option is set, the other window actually displays
  1824. an indirect buffer clone of the current buffer, to avoid any visibility
  1825. changes to the current buffer."
  1826. :group 'org-link-follow
  1827. :type 'boolean)
  1828. (defcustom org-open-non-existing-files nil
  1829. "Non-nil means `org-open-file' will open non-existing files.
  1830. When nil, an error will be generated.
  1831. This variable applies only to external applications because they
  1832. might choke on non-existing files. If the link is to a file that
  1833. will be opened in Emacs, the variable is ignored."
  1834. :group 'org-link-follow
  1835. :type 'boolean)
  1836. (defcustom org-open-directory-means-index-dot-org nil
  1837. "Non-nil means a link to a directory really means to index.org.
  1838. When nil, following a directory link will run dired or open a finder/explorer
  1839. window on that directory."
  1840. :group 'org-link-follow
  1841. :type 'boolean)
  1842. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1843. "Non-nil means ask for confirmation before executing shell links.
  1844. Shell links can be dangerous: just think about a link
  1845. [[shell:rm -rf ~/*][Google Search]]
  1846. This link would show up in your Org document as \"Google Search\",
  1847. but really it would remove your entire home directory.
  1848. Therefore we advise against setting this variable to nil.
  1849. Just change it to `y-or-n-p' if you want to confirm with a
  1850. single keystroke rather than having to type \"yes\"."
  1851. :group 'org-link-follow
  1852. :type '(choice
  1853. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1854. (const :tag "with y-or-n (faster)" y-or-n-p)
  1855. (const :tag "no confirmation (dangerous)" nil)))
  1856. (put 'org-confirm-shell-link-function
  1857. 'safe-local-variable
  1858. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1859. (defcustom org-confirm-shell-link-not-regexp ""
  1860. "A regexp to skip confirmation for shell links."
  1861. :group 'org-link-follow
  1862. :version "24.1"
  1863. :type 'regexp)
  1864. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1865. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1866. Elisp links can be dangerous: just think about a link
  1867. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1868. This link would show up in your Org document as \"Google Search\",
  1869. but really it would remove your entire home directory.
  1870. Therefore we advise against setting this variable to nil.
  1871. Just change it to `y-or-n-p' if you want to confirm with a
  1872. single keystroke rather than having to type \"yes\"."
  1873. :group 'org-link-follow
  1874. :type '(choice
  1875. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1876. (const :tag "with y-or-n (faster)" y-or-n-p)
  1877. (const :tag "no confirmation (dangerous)" nil)))
  1878. (put 'org-confirm-shell-link-function
  1879. 'safe-local-variable
  1880. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1881. (defcustom org-confirm-elisp-link-not-regexp ""
  1882. "A regexp to skip confirmation for Elisp links."
  1883. :group 'org-link-follow
  1884. :version "24.1"
  1885. :type 'regexp)
  1886. (defconst org-file-apps-defaults-gnu
  1887. '((remote . emacs)
  1888. (system . mailcap)
  1889. (t . mailcap))
  1890. "Default file applications on a UNIX or GNU/Linux system.
  1891. See `org-file-apps'.")
  1892. (defconst org-file-apps-defaults-macosx
  1893. '((remote . emacs)
  1894. (system . "open %s")
  1895. ("ps.gz" . "gv %s")
  1896. ("eps.gz" . "gv %s")
  1897. ("dvi" . "xdvi %s")
  1898. ("fig" . "xfig %s")
  1899. (t . "open %s"))
  1900. "Default file applications on a macOS system.
  1901. The system \"open\" is known as a default, but we use X11 applications
  1902. for some files for which the OS does not have a good default.
  1903. See `org-file-apps'.")
  1904. (defconst org-file-apps-defaults-windowsnt
  1905. (list '(remote . emacs)
  1906. (cons 'system (lambda (file _path)
  1907. (with-no-warnings (w32-shell-execute "open" file))))
  1908. (cons t (lambda (file _path)
  1909. (with-no-warnings (w32-shell-execute "open" file)))))
  1910. "Default file applications on a Windows NT system.
  1911. The system \"open\" is used for most files.
  1912. See `org-file-apps'.")
  1913. (defcustom org-file-apps
  1914. '((auto-mode . emacs)
  1915. ("\\.mm\\'" . default)
  1916. ("\\.x?html?\\'" . default)
  1917. ("\\.pdf\\'" . default))
  1918. "External applications for opening `file:path' items in a document.
  1919. \\<org-mode-map>\
  1920. Org mode uses system defaults for different file types, but
  1921. you can use this variable to set the application for a given file
  1922. extension. The entries in this list are cons cells where the car identifies
  1923. files and the cdr the corresponding command.
  1924. Possible values for the file identifier are:
  1925. \"string\" A string as a file identifier can be interpreted in different
  1926. ways, depending on its contents:
  1927. - Alphanumeric characters only:
  1928. Match links with this file extension.
  1929. Example: (\"pdf\" . \"evince %s\")
  1930. to open PDFs with evince.
  1931. - Regular expression: Match links where the
  1932. filename matches the regexp. If you want to
  1933. use groups here, use shy groups.
  1934. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1935. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1936. to open *.html and *.xhtml with firefox.
  1937. - Regular expression which contains (non-shy) groups:
  1938. Match links where the whole link, including \"::\", and
  1939. anything after that, matches the regexp.
  1940. In a custom command string, %1, %2, etc. are replaced with
  1941. the parts of the link that were matched by the groups.
  1942. For backwards compatibility, if a command string is given
  1943. that does not use any of the group matches, this case is
  1944. handled identically to the second one (i.e. match against
  1945. file name only).
  1946. In a custom function, you can access the group matches with
  1947. (match-string n link).
  1948. Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
  1949. \"evince -p %1 %s\")
  1950. to open [[file:document.pdf::5]] with evince at page 5.
  1951. `directory' Matches a directory
  1952. `remote' Matches a remote file, accessible through tramp or efs.
  1953. Remote files most likely should be visited through Emacs
  1954. because external applications cannot handle such paths.
  1955. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1956. so all files Emacs knows how to handle. Using this with
  1957. command `emacs' will open most files in Emacs. Beware that this
  1958. will also open html files inside Emacs, unless you add
  1959. (\"html\" . default) to the list as well.
  1960. `system' The system command to open files, like `open' on Windows
  1961. and macOS, and mailcap under GNU/Linux. This is the command
  1962. that will be selected if you call `org-open-at-point' with a
  1963. double prefix argument (`\\[universal-argument] \
  1964. \\[universal-argument] \\[org-open-at-point]').
  1965. t Default for files not matched by any of the other options.
  1966. Possible values for the command are:
  1967. `emacs' The file will be visited by the current Emacs process.
  1968. `default' Use the default application for this file type, which is the
  1969. association for t in the list, most likely in the system-specific
  1970. part. This can be used to overrule an unwanted setting in the
  1971. system-specific variable.
  1972. `system' Use the system command for opening files, like \"open\".
  1973. This command is specified by the entry whose car is `system'.
  1974. Most likely, the system-specific version of this variable
  1975. does define this command, but you can overrule/replace it
  1976. here.
  1977. `mailcap' Use command specified in the mailcaps.
  1978. string A command to be executed by a shell; %s will be replaced
  1979. by the path to the file.
  1980. function A Lisp function, which will be called with two arguments:
  1981. the file path and the original link string, without the
  1982. \"file:\" prefix.
  1983. For more examples, see the system specific constants
  1984. `org-file-apps-defaults-macosx'
  1985. `org-file-apps-defaults-windowsnt'
  1986. `org-file-apps-defaults-gnu'."
  1987. :group 'org-link-follow
  1988. :type '(repeat
  1989. (cons (choice :value ""
  1990. (string :tag "Extension")
  1991. (const :tag "System command to open files" system)
  1992. (const :tag "Default for unrecognized files" t)
  1993. (const :tag "Remote file" remote)
  1994. (const :tag "Links to a directory" directory)
  1995. (const :tag "Any files that have Emacs modes"
  1996. auto-mode))
  1997. (choice :value ""
  1998. (const :tag "Visit with Emacs" emacs)
  1999. (const :tag "Use default" default)
  2000. (const :tag "Use the system command" system)
  2001. (string :tag "Command")
  2002. (function :tag "Function")))))
  2003. (defcustom org-doi-server-url "http://dx.doi.org/"
  2004. "The URL of the DOI server."
  2005. :type 'string
  2006. :version "24.3"
  2007. :group 'org-link-follow)
  2008. (defgroup org-refile nil
  2009. "Options concerning refiling entries in Org mode."
  2010. :tag "Org Refile"
  2011. :group 'org)
  2012. (defcustom org-directory "~/org"
  2013. "Directory with Org files.
  2014. This is just a default location to look for Org files. There is no need
  2015. at all to put your files into this directory. It is used in the
  2016. following situations:
  2017. 1. When a capture template specifies a target file that is not an
  2018. absolute path. The path will then be interpreted relative to
  2019. `org-directory'
  2020. 2. When the value of variable `org-agenda-files' is a single file, any
  2021. relative paths in this file will be taken as relative to
  2022. `org-directory'."
  2023. :group 'org-refile
  2024. :group 'org-capture
  2025. :type 'directory)
  2026. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2027. "Default target for storing notes.
  2028. Used as a fall back file for org-capture.el, for templates that
  2029. do not specify a target file."
  2030. :group 'org-refile
  2031. :group 'org-capture
  2032. :type 'file)
  2033. (defcustom org-reverse-note-order nil
  2034. "Non-nil means store new notes at the beginning of a file or entry.
  2035. When nil, new notes will be filed to the end of a file or entry.
  2036. This can also be a list with cons cells of regular expressions that
  2037. are matched against file names, and values."
  2038. :group 'org-capture
  2039. :group 'org-refile
  2040. :type '(choice
  2041. (const :tag "Reverse always" t)
  2042. (const :tag "Reverse never" nil)
  2043. (repeat :tag "By file name regexp"
  2044. (cons regexp boolean))))
  2045. (defcustom org-log-refile nil
  2046. "Information to record when a task is refiled.
  2047. Possible values are:
  2048. nil Don't add anything
  2049. time Add a time stamp to the task
  2050. note Prompt for a note and add it with template `org-log-note-headings'
  2051. This option can also be set with on a per-file-basis with
  2052. #+STARTUP: nologrefile
  2053. #+STARTUP: logrefile
  2054. #+STARTUP: lognoterefile
  2055. You can have local logging settings for a subtree by setting the LOGGING
  2056. property to one or more of these keywords.
  2057. When bulk-refiling from the agenda, the value `note' is forbidden and
  2058. will temporarily be changed to `time'."
  2059. :group 'org-refile
  2060. :group 'org-progress
  2061. :version "24.1"
  2062. :type '(choice
  2063. (const :tag "No logging" nil)
  2064. (const :tag "Record timestamp" time)
  2065. (const :tag "Record timestamp with note." note)))
  2066. (defcustom org-refile-targets nil
  2067. "Targets for refiling entries with `\\[org-refile]'.
  2068. This is a list of cons cells. Each cell contains:
  2069. - a specification of the files to be considered, either a list of files,
  2070. or a symbol whose function or variable value will be used to retrieve
  2071. a file name or a list of file names. If you use `org-agenda-files' for
  2072. that, all agenda files will be scanned for targets. Nil means consider
  2073. headings in the current buffer.
  2074. - A specification of how to find candidate refile targets. This may be
  2075. any of:
  2076. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2077. This tag has to be present in all target headlines, inheritance will
  2078. not be considered.
  2079. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2080. todo keyword.
  2081. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2082. headlines that are refiling targets.
  2083. - a cons cell (:level . N). Any headline of level N is considered a target.
  2084. Note that, when `org-odd-levels-only' is set, level corresponds to
  2085. order in hierarchy, not to the number of stars.
  2086. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2087. Note that, when `org-odd-levels-only' is set, level corresponds to
  2088. order in hierarchy, not to the number of stars.
  2089. Each element of this list generates a set of possible targets.
  2090. The union of these sets is presented (with completion) to
  2091. the user by `org-refile'.
  2092. You can set the variable `org-refile-target-verify-function' to a function
  2093. to verify each headline found by the simple criteria above.
  2094. When this variable is nil, all top-level headlines in the current buffer
  2095. are used, equivalent to the value `((nil . (:level . 1))'."
  2096. :group 'org-refile
  2097. :type '(repeat
  2098. (cons
  2099. (choice :value org-agenda-files
  2100. (const :tag "All agenda files" org-agenda-files)
  2101. (const :tag "Current buffer" nil)
  2102. (function) (variable) (file))
  2103. (choice :tag "Identify target headline by"
  2104. (cons :tag "Specific tag" (const :value :tag) (string))
  2105. (cons :tag "TODO keyword" (const :value :todo) (string))
  2106. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2107. (cons :tag "Level number" (const :value :level) (integer))
  2108. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2109. (defcustom org-refile-target-verify-function nil
  2110. "Function to verify if the headline at point should be a refile target.
  2111. The function will be called without arguments, with point at the
  2112. beginning of the headline. It should return t and leave point
  2113. where it is if the headline is a valid target for refiling.
  2114. If the target should not be selected, the function must return nil.
  2115. In addition to this, it may move point to a place from where the search
  2116. should be continued. For example, the function may decide that the entire
  2117. subtree of the current entry should be excluded and move point to the end
  2118. of the subtree."
  2119. :group 'org-refile
  2120. :type '(choice
  2121. (const nil)
  2122. (function)))
  2123. (defcustom org-refile-use-cache nil
  2124. "Non-nil means cache refile targets to speed up the process.
  2125. \\<org-mode-map>\
  2126. The cache for a particular file will be updated automatically when
  2127. the buffer has been killed, or when any of the marker used for flagging
  2128. refile targets no longer points at a live buffer.
  2129. If you have added new entries to a buffer that might themselves be targets,
  2130. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2131. if you find that easier, \
  2132. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2133. \\[org-refile]'."
  2134. :group 'org-refile
  2135. :version "24.1"
  2136. :type 'boolean)
  2137. (defcustom org-refile-use-outline-path nil
  2138. "Non-nil means provide refile targets as paths.
  2139. So a level 3 headline will be available as level1/level2/level3.
  2140. When the value is `file', also include the file name (without directory)
  2141. into the path. In this case, you can also stop the completion after
  2142. the file name, to get entries inserted as top level in the file.
  2143. When `full-file-path', include the full file path.
  2144. When `buffer-name', use the buffer name."
  2145. :group 'org-refile
  2146. :type '(choice
  2147. (const :tag "Not" nil)
  2148. (const :tag "Yes" t)
  2149. (const :tag "Start with file name" file)
  2150. (const :tag "Start with full file path" full-file-path)
  2151. (const :tag "Start with buffer name" buffer-name)))
  2152. (defcustom org-outline-path-complete-in-steps t
  2153. "Non-nil means complete the outline path in hierarchical steps.
  2154. When Org uses the refile interface to select an outline path (see
  2155. `org-refile-use-outline-path'), the completion of the path can be
  2156. done in a single go, or it can be done in steps down the headline
  2157. hierarchy. Going in steps is probably the best if you do not use
  2158. a special completion package like `ido' or `icicles'. However,
  2159. when using these packages, going in one step can be very fast,
  2160. while still showing the whole path to the entry."
  2161. :group 'org-refile
  2162. :type 'boolean)
  2163. (defcustom org-refile-allow-creating-parent-nodes nil
  2164. "Non-nil means allow the creation of new nodes as refile targets.
  2165. New nodes are then created by adding \"/new node name\" to the completion
  2166. of an existing node. When the value of this variable is `confirm',
  2167. new node creation must be confirmed by the user (recommended).
  2168. When nil, the completion must match an existing entry.
  2169. Note that, if the new heading is not seen by the criteria
  2170. listed in `org-refile-targets', multiple instances of the same
  2171. heading would be created by trying again to file under the new
  2172. heading."
  2173. :group 'org-refile
  2174. :type '(choice
  2175. (const :tag "Never" nil)
  2176. (const :tag "Always" t)
  2177. (const :tag "Prompt for confirmation" confirm)))
  2178. (defcustom org-refile-active-region-within-subtree nil
  2179. "Non-nil means also refile active region within a subtree.
  2180. By default `org-refile' doesn't allow refiling regions if they
  2181. don't contain a set of subtrees, but it might be convenient to
  2182. do so sometimes: in that case, the first line of the region is
  2183. converted to a headline before refiling."
  2184. :group 'org-refile
  2185. :version "24.1"
  2186. :type 'boolean)
  2187. (defgroup org-todo nil
  2188. "Options concerning TODO items in Org mode."
  2189. :tag "Org TODO"
  2190. :group 'org)
  2191. (defgroup org-progress nil
  2192. "Options concerning Progress logging in Org mode."
  2193. :tag "Org Progress"
  2194. :group 'org-time)
  2195. (defvar org-todo-interpretation-widgets
  2196. '((:tag "Sequence (cycling hits every state)" sequence)
  2197. (:tag "Type (cycling directly to DONE)" type))
  2198. "The available interpretation symbols for customizing `org-todo-keywords'.
  2199. Interested libraries should add to this list.")
  2200. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2201. "List of TODO entry keyword sequences and their interpretation.
  2202. \\<org-mode-map>This is a list of sequences.
  2203. Each sequence starts with a symbol, either `sequence' or `type',
  2204. indicating if the keywords should be interpreted as a sequence of
  2205. action steps, or as different types of TODO items. The first
  2206. keywords are states requiring action - these states will select a headline
  2207. for inclusion into the global TODO list Org produces. If one of the
  2208. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2209. signify that no further action is necessary. If \"|\" is not found,
  2210. the last keyword is treated as the only DONE state of the sequence.
  2211. The command `\\[org-todo]' cycles an entry through these states, and one
  2212. additional state where no keyword is present. For details about this
  2213. cycling, see the manual.
  2214. TODO keywords and interpretation can also be set on a per-file basis with
  2215. the special #+SEQ_TODO and #+TYP_TODO lines.
  2216. Each keyword can optionally specify a character for fast state selection
  2217. \(in combination with the variable `org-use-fast-todo-selection')
  2218. and specifiers for state change logging, using the same syntax that
  2219. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2220. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2221. indicates to record a time stamp each time this state is selected.
  2222. Each keyword may also specify if a timestamp or a note should be
  2223. recorded when entering or leaving the state, by adding additional
  2224. characters in the parenthesis after the keyword. This looks like this:
  2225. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2226. record only the time of the state change. With X and Y being either
  2227. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2228. Y when leaving the state if and only if the *target* state does not
  2229. define X. You may omit any of the fast-selection key or X or /Y,
  2230. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2231. For backward compatibility, this variable may also be just a list
  2232. of keywords. In this case the interpretation (sequence or type) will be
  2233. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2234. :group 'org-todo
  2235. :group 'org-keywords
  2236. :type '(choice
  2237. (repeat :tag "Old syntax, just keywords"
  2238. (string :tag "Keyword"))
  2239. (repeat :tag "New syntax"
  2240. (cons
  2241. (choice
  2242. :tag "Interpretation"
  2243. ;;Quick and dirty way to see
  2244. ;;`org-todo-interpretations'. This takes the
  2245. ;;place of item arguments
  2246. :convert-widget
  2247. (lambda (widget)
  2248. (widget-put widget
  2249. :args (mapcar
  2250. (lambda (x)
  2251. (widget-convert
  2252. (cons 'const x)))
  2253. org-todo-interpretation-widgets))
  2254. widget))
  2255. (repeat
  2256. (string :tag "Keyword"))))))
  2257. (defvar-local org-todo-keywords-1 nil
  2258. "All TODO and DONE keywords active in a buffer.")
  2259. (defvar org-todo-keywords-for-agenda nil)
  2260. (defvar org-done-keywords-for-agenda nil)
  2261. (defvar org-todo-keyword-alist-for-agenda nil)
  2262. (defvar org-tag-alist-for-agenda nil
  2263. "Alist of all tags from all agenda files.")
  2264. (defvar org-tag-groups-alist-for-agenda nil
  2265. "Alist of all groups tags from all current agenda files.")
  2266. (defvar-local org-tag-groups-alist nil)
  2267. (defvar org-agenda-contributing-files nil)
  2268. (defvar-local org-current-tag-alist nil
  2269. "Alist of all tag groups in current buffer.
  2270. This variable takes into consideration `org-tag-alist',
  2271. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2272. (defvar-local org-not-done-keywords nil)
  2273. (defvar-local org-done-keywords nil)
  2274. (defvar-local org-todo-heads nil)
  2275. (defvar-local org-todo-sets nil)
  2276. (defvar-local org-todo-log-states nil)
  2277. (defvar-local org-todo-kwd-alist nil)
  2278. (defvar-local org-todo-key-alist nil)
  2279. (defvar-local org-todo-key-trigger nil)
  2280. (defcustom org-todo-interpretation 'sequence
  2281. "Controls how TODO keywords are interpreted.
  2282. This variable is in principle obsolete and is only used for
  2283. backward compatibility, if the interpretation of todo keywords is
  2284. not given already in `org-todo-keywords'. See that variable for
  2285. more information."
  2286. :group 'org-todo
  2287. :group 'org-keywords
  2288. :type '(choice (const sequence)
  2289. (const type)))
  2290. (defcustom org-use-fast-todo-selection t
  2291. "\\<org-mode-map>\
  2292. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2293. This variable describes if and under what circumstances the cycling
  2294. mechanism for TODO keywords will be replaced by a single-key, direct
  2295. selection scheme.
  2296. When nil, fast selection is never used.
  2297. When the symbol `prefix', it will be used when `org-todo' is called
  2298. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2299. in an Org buffer, and
  2300. `\\[universal-argument] t' in an agenda buffer.
  2301. When t, fast selection is used by default. In this case, the prefix
  2302. argument forces cycling instead.
  2303. In all cases, the special interface is only used if access keys have
  2304. actually been assigned by the user, i.e. if keywords in the configuration
  2305. are followed by a letter in parenthesis, like TODO(t)."
  2306. :group 'org-todo
  2307. :type '(choice
  2308. (const :tag "Never" nil)
  2309. (const :tag "By default" t)
  2310. (const :tag "Only with C-u C-c C-t" prefix)))
  2311. (defcustom org-provide-todo-statistics t
  2312. "Non-nil means update todo statistics after insert and toggle.
  2313. ALL-HEADLINES means update todo statistics by including headlines
  2314. with no TODO keyword as well, counting them as not done.
  2315. A list of TODO keywords means the same, but skip keywords that are
  2316. not in this list.
  2317. When set to a list of two lists, the first list contains keywords
  2318. to consider as TODO keywords, the second list contains keywords
  2319. to consider as DONE keywords.
  2320. When this is set, todo statistics is updated in the parent of the
  2321. current entry each time a todo state is changed."
  2322. :group 'org-todo
  2323. :type '(choice
  2324. (const :tag "Yes, only for TODO entries" t)
  2325. (const :tag "Yes, including all entries" all-headlines)
  2326. (repeat :tag "Yes, for TODOs in this list"
  2327. (string :tag "TODO keyword"))
  2328. (list :tag "Yes, for TODOs and DONEs in these lists"
  2329. (repeat (string :tag "TODO keyword"))
  2330. (repeat (string :tag "DONE keyword")))
  2331. (other :tag "No TODO statistics" nil)))
  2332. (defcustom org-hierarchical-todo-statistics t
  2333. "Non-nil means TODO statistics covers just direct children.
  2334. When nil, all entries in the subtree are considered.
  2335. This has only an effect if `org-provide-todo-statistics' is set.
  2336. To set this to nil for only a single subtree, use a COOKIE_DATA
  2337. property and include the word \"recursive\" into the value."
  2338. :group 'org-todo
  2339. :type 'boolean)
  2340. (defcustom org-after-todo-state-change-hook nil
  2341. "Hook which is run after the state of a TODO item was changed.
  2342. The new state (a string with a TODO keyword, or nil) is available in the
  2343. Lisp variable `org-state'."
  2344. :group 'org-todo
  2345. :type 'hook)
  2346. (defvar org-blocker-hook nil
  2347. "Hook for functions that are allowed to block a state change.
  2348. Functions in this hook should not modify the buffer.
  2349. Each function gets as its single argument a property list,
  2350. see `org-trigger-hook' for more information about this list.
  2351. If any of the functions in this hook returns nil, the state change
  2352. is blocked.")
  2353. (defvar org-trigger-hook nil
  2354. "Hook for functions that are triggered by a state change.
  2355. Each function gets as its single argument a property list with at
  2356. least the following elements:
  2357. (:type type-of-change :position pos-at-entry-start
  2358. :from old-state :to new-state)
  2359. Depending on the type, more properties may be present.
  2360. This mechanism is currently implemented for:
  2361. TODO state changes
  2362. ------------------
  2363. :type todo-state-change
  2364. :from previous state (keyword as a string), or nil, or a symbol
  2365. `todo' or `done', to indicate the general type of state.
  2366. :to new state, like in :from")
  2367. (defcustom org-enforce-todo-dependencies nil
  2368. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2369. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2370. be blocked if any prior sibling is not yet done.
  2371. Finally, if the parent is blocked because of ordered siblings of its own,
  2372. the child will also be blocked."
  2373. :set (lambda (var val)
  2374. (set var val)
  2375. (if val
  2376. (add-hook 'org-blocker-hook
  2377. 'org-block-todo-from-children-or-siblings-or-parent)
  2378. (remove-hook 'org-blocker-hook
  2379. 'org-block-todo-from-children-or-siblings-or-parent)))
  2380. :group 'org-todo
  2381. :type 'boolean)
  2382. (defcustom org-enforce-todo-checkbox-dependencies nil
  2383. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2384. When this is nil, checkboxes have no influence on switching TODO states.
  2385. When non-nil, you first need to check off all check boxes before the TODO
  2386. entry can be switched to DONE.
  2387. This variable needs to be set before org.el is loaded, and you need to
  2388. restart Emacs after a change to make the change effective. The only way
  2389. to change is while Emacs is running is through the customize interface."
  2390. :set (lambda (var val)
  2391. (set var val)
  2392. (if val
  2393. (add-hook 'org-blocker-hook
  2394. 'org-block-todo-from-checkboxes)
  2395. (remove-hook 'org-blocker-hook
  2396. 'org-block-todo-from-checkboxes)))
  2397. :group 'org-todo
  2398. :type 'boolean)
  2399. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2400. "Non-nil means inserting a TODO heading is treated as state change.
  2401. So when the command `\\[org-insert-todo-heading]' is used, state change
  2402. logging will apply if appropriate. When nil, the new TODO item will
  2403. be inserted directly, and no logging will take place."
  2404. :group 'org-todo
  2405. :type 'boolean)
  2406. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2407. "Non-nil means switching TODO states with S-cursor counts as state change.
  2408. This is the default behavior. However, setting this to nil allows a
  2409. convenient way to select a TODO state and bypass any logging associated
  2410. with that."
  2411. :group 'org-todo
  2412. :type 'boolean)
  2413. (defcustom org-todo-state-tags-triggers nil
  2414. "Tag changes that should be triggered by TODO state changes.
  2415. This is a list. Each entry is
  2416. (state-change (tag . flag) .......)
  2417. State-change can be a string with a state, and empty string to indicate the
  2418. state that has no TODO keyword, or it can be one of the symbols `todo'
  2419. or `done', meaning any not-done or done state, respectively."
  2420. :group 'org-todo
  2421. :group 'org-tags
  2422. :type '(repeat
  2423. (cons (choice :tag "When changing to"
  2424. (const :tag "Not-done state" todo)
  2425. (const :tag "Done state" done)
  2426. (string :tag "State"))
  2427. (repeat
  2428. (cons :tag "Tag action"
  2429. (string :tag "Tag")
  2430. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2431. (defcustom org-log-done nil
  2432. "Information to record when a task moves to the DONE state.
  2433. Possible values are:
  2434. nil Don't add anything, just change the keyword
  2435. time Add a time stamp to the task
  2436. note Prompt for a note and add it with template `org-log-note-headings'
  2437. This option can also be set with on a per-file-basis with
  2438. #+STARTUP: nologdone
  2439. #+STARTUP: logdone
  2440. #+STARTUP: lognotedone
  2441. You can have local logging settings for a subtree by setting the LOGGING
  2442. property to one or more of these keywords."
  2443. :group 'org-todo
  2444. :group 'org-progress
  2445. :type '(choice
  2446. (const :tag "No logging" nil)
  2447. (const :tag "Record CLOSED timestamp" time)
  2448. (const :tag "Record CLOSED timestamp with note." note)))
  2449. ;; Normalize old uses of org-log-done.
  2450. (cond
  2451. ((eq org-log-done t) (setq org-log-done 'time))
  2452. ((and (listp org-log-done) (memq 'done org-log-done))
  2453. (setq org-log-done 'note)))
  2454. (defcustom org-log-reschedule nil
  2455. "Information to record when the scheduling date of a tasks is modified.
  2456. Possible values are:
  2457. nil Don't add anything, just change the date
  2458. time Add a time stamp to the task
  2459. note Prompt for a note and add it with template `org-log-note-headings'
  2460. This option can also be set with on a per-file-basis with
  2461. #+STARTUP: nologreschedule
  2462. #+STARTUP: logreschedule
  2463. #+STARTUP: lognotereschedule"
  2464. :group 'org-todo
  2465. :group 'org-progress
  2466. :type '(choice
  2467. (const :tag "No logging" nil)
  2468. (const :tag "Record timestamp" time)
  2469. (const :tag "Record timestamp with note." note)))
  2470. (defcustom org-log-redeadline nil
  2471. "Information to record when the deadline date of a tasks is modified.
  2472. Possible values are:
  2473. nil Don't add anything, just change the date
  2474. time Add a time stamp to the task
  2475. note Prompt for a note and add it with template `org-log-note-headings'
  2476. This option can also be set with on a per-file-basis with
  2477. #+STARTUP: nologredeadline
  2478. #+STARTUP: logredeadline
  2479. #+STARTUP: lognoteredeadline
  2480. You can have local logging settings for a subtree by setting the LOGGING
  2481. property to one or more of these keywords."
  2482. :group 'org-todo
  2483. :group 'org-progress
  2484. :type '(choice
  2485. (const :tag "No logging" nil)
  2486. (const :tag "Record timestamp" time)
  2487. (const :tag "Record timestamp with note." note)))
  2488. (defcustom org-log-note-clock-out nil
  2489. "Non-nil means record a note when clocking out of an item.
  2490. This can also be configured on a per-file basis by adding one of
  2491. the following lines anywhere in the buffer:
  2492. #+STARTUP: lognoteclock-out
  2493. #+STARTUP: nolognoteclock-out"
  2494. :group 'org-todo
  2495. :group 'org-progress
  2496. :type 'boolean)
  2497. (defcustom org-log-done-with-time t
  2498. "Non-nil means the CLOSED time stamp will contain date and time.
  2499. When nil, only the date will be recorded."
  2500. :group 'org-progress
  2501. :type 'boolean)
  2502. (defcustom org-log-note-headings
  2503. '((done . "CLOSING NOTE %t")
  2504. (state . "State %-12s from %-12S %t")
  2505. (note . "Note taken on %t")
  2506. (reschedule . "Rescheduled from %S on %t")
  2507. (delschedule . "Not scheduled, was %S on %t")
  2508. (redeadline . "New deadline from %S on %t")
  2509. (deldeadline . "Removed deadline, was %S on %t")
  2510. (refile . "Refiled on %t")
  2511. (clock-out . ""))
  2512. "Headings for notes added to entries.
  2513. The value is an alist, with the car being a symbol indicating the
  2514. note context, and the cdr is the heading to be used. The heading
  2515. may also be the empty string. The following placeholders can be
  2516. used:
  2517. %t a time stamp.
  2518. %T an active time stamp instead the default inactive one
  2519. %d a short-format time stamp.
  2520. %D an active short-format time stamp.
  2521. %s the new TODO state or time stamp (inactive), in double quotes.
  2522. %S the old TODO state or time stamp (inactive), in double quotes.
  2523. %u the user name.
  2524. %U full user name.
  2525. In fact, it is not a good idea to change the `state' entry,
  2526. because Agenda Log mode depends on the format of these entries."
  2527. :group 'org-todo
  2528. :group 'org-progress
  2529. :type '(list :greedy t
  2530. (cons (const :tag "Heading when closing an item" done) string)
  2531. (cons (const :tag
  2532. "Heading when changing todo state (todo sequence only)"
  2533. state) string)
  2534. (cons (const :tag "Heading when just taking a note" note) string)
  2535. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2536. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2537. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2538. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2539. (cons (const :tag "Heading when refiling" refile) string)
  2540. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2541. (unless (assq 'note org-log-note-headings)
  2542. (push '(note . "%t") org-log-note-headings))
  2543. (defcustom org-log-into-drawer nil
  2544. "Non-nil means insert state change notes and time stamps into a drawer.
  2545. When nil, state changes notes will be inserted after the headline and
  2546. any scheduling and clock lines, but not inside a drawer.
  2547. The value of this variable should be the name of the drawer to use.
  2548. LOGBOOK is proposed as the default drawer for this purpose, you can
  2549. also set this to a string to define the drawer of your choice.
  2550. A value of t is also allowed, representing \"LOGBOOK\".
  2551. A value of t or nil can also be set with on a per-file-basis with
  2552. #+STARTUP: logdrawer
  2553. #+STARTUP: nologdrawer
  2554. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2555. will be ignored.
  2556. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2557. a subtree.
  2558. Do not check directly this variable in a Lisp program. Call
  2559. function `org-log-into-drawer' instead."
  2560. :group 'org-todo
  2561. :group 'org-progress
  2562. :type '(choice
  2563. (const :tag "Not into a drawer" nil)
  2564. (const :tag "LOGBOOK" t)
  2565. (string :tag "Other")))
  2566. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2567. (defun org-log-into-drawer ()
  2568. "Name of the log drawer, as a string, or nil.
  2569. This is the value of `org-log-into-drawer'. However, if the
  2570. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2571. be used instead of the default value."
  2572. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2573. (cond ((equal p "nil") nil)
  2574. ((equal p "t") "LOGBOOK")
  2575. ((stringp p) p)
  2576. (p "LOGBOOK")
  2577. ((stringp org-log-into-drawer) org-log-into-drawer)
  2578. (org-log-into-drawer "LOGBOOK"))))
  2579. (defcustom org-log-state-notes-insert-after-drawers nil
  2580. "Non-nil means insert state change notes after any drawers in entry.
  2581. Only the drawers that *immediately* follow the headline and the
  2582. deadline/scheduled line are skipped.
  2583. When nil, insert notes right after the heading and perhaps the line
  2584. with deadline/scheduling if present.
  2585. This variable will have no effect if `org-log-into-drawer' is
  2586. set."
  2587. :group 'org-todo
  2588. :group 'org-progress
  2589. :type 'boolean)
  2590. (defcustom org-log-states-order-reversed t
  2591. "Non-nil means the latest state note will be directly after heading.
  2592. When nil, the state change notes will be ordered according to time.
  2593. This option can also be set with on a per-file-basis with
  2594. #+STARTUP: logstatesreversed
  2595. #+STARTUP: nologstatesreversed"
  2596. :group 'org-todo
  2597. :group 'org-progress
  2598. :type 'boolean)
  2599. (defcustom org-todo-repeat-to-state nil
  2600. "The TODO state to which a repeater should return the repeating task.
  2601. By default this is the first task in a TODO sequence, or the previous state
  2602. in a TODO_TYP set. But you can specify another task here.
  2603. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2604. :group 'org-todo
  2605. :version "24.1"
  2606. :type '(choice (const :tag "Head of sequence" nil)
  2607. (string :tag "Specific state")))
  2608. (defcustom org-log-repeat 'time
  2609. "Non-nil means record moving through the DONE state when triggering repeat.
  2610. An auto-repeating task is immediately switched back to TODO when
  2611. marked DONE. If you are not logging state changes (by adding \"@\"
  2612. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2613. record a closing note, there will be no record of the task moving
  2614. through DONE. This variable forces taking a note anyway.
  2615. nil Don't force a record
  2616. time Record a time stamp
  2617. note Prompt for a note and add it with template `org-log-note-headings'
  2618. This option can also be set with on a per-file-basis with
  2619. #+STARTUP: nologrepeat
  2620. #+STARTUP: logrepeat
  2621. #+STARTUP: lognoterepeat
  2622. You can have local logging settings for a subtree by setting the LOGGING
  2623. property to one or more of these keywords."
  2624. :group 'org-todo
  2625. :group 'org-progress
  2626. :type '(choice
  2627. (const :tag "Don't force a record" nil)
  2628. (const :tag "Force recording the DONE state" time)
  2629. (const :tag "Force recording a note with the DONE state" note)))
  2630. (defgroup org-priorities nil
  2631. "Priorities in Org mode."
  2632. :tag "Org Priorities"
  2633. :group 'org-todo)
  2634. (defcustom org-enable-priority-commands t
  2635. "Non-nil means priority commands are active.
  2636. When nil, these commands will be disabled, so that you never accidentally
  2637. set a priority."
  2638. :group 'org-priorities
  2639. :type 'boolean)
  2640. (defcustom org-highest-priority ?A
  2641. "The highest priority of TODO items. A character like ?A, ?B etc.
  2642. Must have a smaller ASCII number than `org-lowest-priority'."
  2643. :group 'org-priorities
  2644. :type 'character)
  2645. (defcustom org-lowest-priority ?C
  2646. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2647. Must have a larger ASCII number than `org-highest-priority'."
  2648. :group 'org-priorities
  2649. :type 'character)
  2650. (defcustom org-default-priority ?B
  2651. "The default priority of TODO items.
  2652. This is the priority an item gets if no explicit priority is given.
  2653. When starting to cycle on an empty priority the first step in the cycle
  2654. depends on `org-priority-start-cycle-with-default'. The resulting first
  2655. step priority must not exceed the range from `org-highest-priority' to
  2656. `org-lowest-priority' which means that `org-default-priority' has to be
  2657. in this range exclusive or inclusive the range boundaries. Else the
  2658. first step refuses to set the default and the second will fall back
  2659. to (depending on the command used) the highest or lowest priority."
  2660. :group 'org-priorities
  2661. :type 'character)
  2662. (defcustom org-priority-start-cycle-with-default t
  2663. "Non-nil means start with default priority when starting to cycle.
  2664. When this is nil, the first step in the cycle will be (depending on the
  2665. command used) one higher or lower than the default priority.
  2666. See also `org-default-priority'."
  2667. :group 'org-priorities
  2668. :type 'boolean)
  2669. (defcustom org-get-priority-function nil
  2670. "Function to extract the priority from a string.
  2671. The string is normally the headline. If this is nil Org computes the
  2672. priority from the priority cookie like [#A] in the headline. It returns
  2673. an integer, increasing by 1000 for each priority level.
  2674. The user can set a different function here, which should take a string
  2675. as an argument and return the numeric priority."
  2676. :group 'org-priorities
  2677. :version "24.1"
  2678. :type '(choice
  2679. (const nil)
  2680. (function)))
  2681. (defgroup org-time nil
  2682. "Options concerning time stamps and deadlines in Org mode."
  2683. :tag "Org Time"
  2684. :group 'org)
  2685. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2686. "Number of minutes to round time stamps to.
  2687. \\<org-mode-map>\
  2688. These are two values, the first applies when first creating a time stamp.
  2689. The second applies when changing it with the commands `S-up' and `S-down'.
  2690. When changing the time stamp, this means that it will change in steps
  2691. of N minutes, as given by the second value.
  2692. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2693. numbers should be factors of 60, so for example 5, 10, 15.
  2694. When this is larger than 1, you can still force an exact time stamp by using
  2695. a double prefix argument to a time stamp command like \
  2696. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2697. and by using a prefix arg to `S-up/down' to specify the exact number
  2698. of minutes to shift."
  2699. :group 'org-time
  2700. :get (lambda (var) ; Make sure both elements are there
  2701. (if (integerp (default-value var))
  2702. (list (default-value var) 5)
  2703. (default-value var)))
  2704. :type '(list
  2705. (integer :tag "when inserting times")
  2706. (integer :tag "when modifying times")))
  2707. ;; Normalize old customizations of this variable.
  2708. (when (integerp org-time-stamp-rounding-minutes)
  2709. (setq org-time-stamp-rounding-minutes
  2710. (list org-time-stamp-rounding-minutes
  2711. org-time-stamp-rounding-minutes)))
  2712. (defcustom org-display-custom-times nil
  2713. "Non-nil means overlay custom formats over all time stamps.
  2714. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2715. To turn this on on a per-file basis, insert anywhere in the file:
  2716. #+STARTUP: customtime"
  2717. :group 'org-time
  2718. :set 'set-default
  2719. :type 'sexp)
  2720. (make-variable-buffer-local 'org-display-custom-times)
  2721. (defcustom org-time-stamp-custom-formats
  2722. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2723. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2724. These are overlaid over the default ISO format if the variable
  2725. `org-display-custom-times' is set. Time like %H:%M should be at the
  2726. end of the second format. The custom formats are also honored by export
  2727. commands, if custom time display is turned on at the time of export."
  2728. :group 'org-time
  2729. :type 'sexp)
  2730. (defun org-time-stamp-format (&optional long inactive)
  2731. "Get the right format for a time string."
  2732. (let ((f (if long (cdr org-time-stamp-formats)
  2733. (car org-time-stamp-formats))))
  2734. (if inactive
  2735. (concat "[" (substring f 1 -1) "]")
  2736. f)))
  2737. (defcustom org-deadline-warning-days 14
  2738. "Number of days before expiration during which a deadline becomes active.
  2739. This variable governs the display in sparse trees and in the agenda.
  2740. When 0 or negative, it means use this number (the absolute value of it)
  2741. even if a deadline has a different individual lead time specified.
  2742. Custom commands can set this variable in the options section."
  2743. :group 'org-time
  2744. :group 'org-agenda-daily/weekly
  2745. :type 'integer)
  2746. (defcustom org-scheduled-delay-days 0
  2747. "Number of days before a scheduled item becomes active.
  2748. This variable governs the display in sparse trees and in the agenda.
  2749. The default value (i.e. 0) means: don't delay scheduled item.
  2750. When negative, it means use this number (the absolute value of it)
  2751. even if a scheduled item has a different individual delay time
  2752. specified.
  2753. Custom commands can set this variable in the options section."
  2754. :group 'org-time
  2755. :group 'org-agenda-daily/weekly
  2756. :version "24.4"
  2757. :package-version '(Org . "8.0")
  2758. :type 'integer)
  2759. (defcustom org-read-date-prefer-future t
  2760. "Non-nil means assume future for incomplete date input from user.
  2761. This affects the following situations:
  2762. 1. The user gives a month but not a year.
  2763. For example, if it is April and you enter \"feb 2\", this will be read
  2764. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2765. 2. The user gives a day, but no month.
  2766. For example, if today is the 15th, and you enter \"3\", Org will read
  2767. this as the third of *next* month. However, if you enter \"17\",
  2768. it will be considered as *this* month.
  2769. If you set this variable to the symbol `time', then also the following
  2770. will work:
  2771. 3. If the user gives a time.
  2772. If the time is before now, it will be interpreted as tomorrow.
  2773. Currently none of this works for ISO week specifications.
  2774. When this option is nil, the current day, month and year will always be
  2775. used as defaults.
  2776. See also `org-agenda-jump-prefer-future'."
  2777. :group 'org-time
  2778. :type '(choice
  2779. (const :tag "Never" nil)
  2780. (const :tag "Check month and day" t)
  2781. (const :tag "Check month, day, and time" time)))
  2782. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2783. "Should the agenda jump command prefer the future for incomplete dates?
  2784. The default is to do the same as configured in `org-read-date-prefer-future'.
  2785. But you can also set a deviating value here.
  2786. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2787. :group 'org-agenda
  2788. :group 'org-time
  2789. :version "24.1"
  2790. :type '(choice
  2791. (const :tag "Use org-read-date-prefer-future"
  2792. org-read-date-prefer-future)
  2793. (const :tag "Never" nil)
  2794. (const :tag "Always" t)))
  2795. (defcustom org-read-date-force-compatible-dates t
  2796. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2797. Depending on the system Emacs is running on, certain dates cannot
  2798. be represented with the type used internally to represent time.
  2799. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2800. correctly. Some systems allow for earlier dates, some for later,
  2801. some for both. One way to find out it to insert any date into an
  2802. Org buffer, putting the cursor on the year and hitting S-up and
  2803. S-down to test the range.
  2804. When this variable is set to t, the date/time prompt will not let
  2805. you specify dates outside the 1970-2037 range, so it is certain that
  2806. these dates will work in whatever version of Emacs you are
  2807. running, and also that you can move a file from one Emacs implementation
  2808. to another. WHenever Org is forcing the year for you, it will display
  2809. a message and beep.
  2810. When this variable is nil, Org will check if the date is
  2811. representable in the specific Emacs implementation you are using.
  2812. If not, it will force a year, usually the current year, and beep
  2813. to remind you. Currently this setting is not recommended because
  2814. the likelihood that you will open your Org files in an Emacs that
  2815. has limited date range is not negligible.
  2816. A workaround for this problem is to use diary sexp dates for time
  2817. stamps outside of this range."
  2818. :group 'org-time
  2819. :version "24.1"
  2820. :type 'boolean)
  2821. (defcustom org-read-date-display-live t
  2822. "Non-nil means display current interpretation of date prompt live.
  2823. This display will be in an overlay, in the minibuffer."
  2824. :group 'org-time
  2825. :type 'boolean)
  2826. (defcustom org-read-date-popup-calendar t
  2827. "Non-nil means pop up a calendar when prompting for a date.
  2828. In the calendar, the date can be selected with mouse-1. However, the
  2829. minibuffer will also be active, and you can simply enter the date as well.
  2830. When nil, only the minibuffer will be available."
  2831. :group 'org-time
  2832. :type 'boolean)
  2833. (defvaralias 'org-popup-calendar-for-date-prompt
  2834. 'org-read-date-popup-calendar)
  2835. (defcustom org-extend-today-until 0
  2836. "The hour when your day really ends. Must be an integer.
  2837. This has influence for the following applications:
  2838. - When switching the agenda to \"today\". It it is still earlier than
  2839. the time given here, the day recognized as TODAY is actually yesterday.
  2840. - When a date is read from the user and it is still before the time given
  2841. here, the current date and time will be assumed to be yesterday, 23:59.
  2842. Also, timestamps inserted in capture templates follow this rule.
  2843. IMPORTANT: This is a feature whose implementation is and likely will
  2844. remain incomplete. Really, it is only here because past midnight seems to
  2845. be the favorite working time of John Wiegley :-)"
  2846. :group 'org-time
  2847. :type 'integer)
  2848. (defcustom org-use-effective-time nil
  2849. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2850. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2851. \"effective time\" of any timestamps between midnight and 8am will be
  2852. 23:59 of the previous day."
  2853. :group 'org-time
  2854. :version "24.1"
  2855. :type 'boolean)
  2856. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2857. "When non-nil, use the last clock out time for `org-todo'.
  2858. Note that this option has precedence over the combined use of
  2859. `org-use-effective-time' and `org-extend-today-until'."
  2860. :group 'org-time
  2861. :version "24.4"
  2862. :package-version '(Org . "8.0")
  2863. :type 'boolean)
  2864. (defcustom org-edit-timestamp-down-means-later nil
  2865. "Non-nil means S-down will increase the time in a time stamp.
  2866. When nil, S-up will increase."
  2867. :group 'org-time
  2868. :type 'boolean)
  2869. (defcustom org-calendar-follow-timestamp-change t
  2870. "Non-nil means make the calendar window follow timestamp changes.
  2871. When a timestamp is modified and the calendar window is visible, it will be
  2872. moved to the new date."
  2873. :group 'org-time
  2874. :type 'boolean)
  2875. (defgroup org-tags nil
  2876. "Options concerning tags in Org mode."
  2877. :tag "Org Tags"
  2878. :group 'org)
  2879. (defcustom org-tag-alist nil
  2880. "Default tags available in Org files.
  2881. The value of this variable is an alist. Associations either:
  2882. (TAG)
  2883. (TAG . SELECT)
  2884. (SPECIAL)
  2885. where TAG is a tag as a string, SELECT is character, used to
  2886. select that tag through the fast tag selection interface, and
  2887. SPECIAL is one of the following keywords: `:startgroup',
  2888. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2889. `:newline'. These keywords are used to define a hierarchy of
  2890. tags. See manual for details.
  2891. When this variable is nil, Org mode bases tag input on what is
  2892. already in the buffer. The value can be overridden locally by
  2893. using a TAGS keyword, e.g.,
  2894. #+TAGS: tag1 tag2
  2895. See also `org-tag-persistent-alist' to sidestep this behavior."
  2896. :group 'org-tags
  2897. :type '(repeat
  2898. (choice
  2899. (cons :tag "Tag with key"
  2900. (string :tag "Tag name")
  2901. (character :tag "Access char"))
  2902. (list :tag "Tag" (string :tag "Tag name"))
  2903. (const :tag "Start radio group" (:startgroup))
  2904. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2905. (const :tag "Group tags delimiter" (:grouptags))
  2906. (const :tag "End radio group" (:endgroup))
  2907. (const :tag "End tag group, non distinct" (:endgrouptag))
  2908. (const :tag "New line" (:newline)))))
  2909. (defcustom org-tag-persistent-alist nil
  2910. "Tags always available in Org files.
  2911. The value of this variable is an alist. Associations either:
  2912. (TAG)
  2913. (TAG . SELECT)
  2914. (SPECIAL)
  2915. where TAG is a tag as a string, SELECT is a character, used to
  2916. select that tag through the fast tag selection interface, and
  2917. SPECIAL is one of the following keywords: `:startgroup',
  2918. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2919. `:newline'. These keywords are used to define a hierarchy of
  2920. tags. See manual for details.
  2921. Unlike to `org-tag-alist', tags defined in this variable do not
  2922. depend on a local TAGS keyword. Instead, to disable these tags
  2923. on a per-file basis, insert anywhere in the file:
  2924. #+STARTUP: noptag"
  2925. :group 'org-tags
  2926. :type '(repeat
  2927. (choice
  2928. (cons :tag "Tag with key"
  2929. (string :tag "Tag name")
  2930. (character :tag "Access char"))
  2931. (list :tag "Tag" (string :tag "Tag name"))
  2932. (const :tag "Start radio group" (:startgroup))
  2933. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2934. (const :tag "Group tags delimiter" (:grouptags))
  2935. (const :tag "End radio group" (:endgroup))
  2936. (const :tag "End tag group, non distinct" (:endgrouptag))
  2937. (const :tag "New line" (:newline)))))
  2938. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2939. "If non-nil, always offer completion for all tags of all agenda files.
  2940. Instead of customizing this variable directly, you might want to
  2941. set it locally for capture buffers, because there no list of
  2942. tags in that file can be created dynamically (there are none).
  2943. (add-hook \\='org-capture-mode-hook
  2944. (lambda ()
  2945. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2946. :group 'org-tags
  2947. :version "24.1"
  2948. :type 'boolean)
  2949. (defvar org-file-tags nil
  2950. "List of tags that can be inherited by all entries in the file.
  2951. The tags will be inherited if the variable `org-use-tag-inheritance'
  2952. says they should be.
  2953. This variable is populated from #+FILETAGS lines.")
  2954. (defcustom org-use-fast-tag-selection 'auto
  2955. "Non-nil means use fast tag selection scheme.
  2956. This is a special interface to select and deselect tags with single keys.
  2957. When nil, fast selection is never used.
  2958. When the symbol `auto', fast selection is used if and only if selection
  2959. characters for tags have been configured, either through the variable
  2960. `org-tag-alist' or through a #+TAGS line in the buffer.
  2961. When t, fast selection is always used and selection keys are assigned
  2962. automatically if necessary."
  2963. :group 'org-tags
  2964. :type '(choice
  2965. (const :tag "Always" t)
  2966. (const :tag "Never" nil)
  2967. (const :tag "When selection characters are configured" auto)))
  2968. (defcustom org-fast-tag-selection-single-key nil
  2969. "Non-nil means fast tag selection exits after first change.
  2970. When nil, you have to press RET to exit it.
  2971. During fast tag selection, you can toggle this flag with `C-c'.
  2972. This variable can also have the value `expert'. In this case, the window
  2973. displaying the tags menu is not even shown, until you press C-c again."
  2974. :group 'org-tags
  2975. :type '(choice
  2976. (const :tag "No" nil)
  2977. (const :tag "Yes" t)
  2978. (const :tag "Expert" expert)))
  2979. (defvar org-fast-tag-selection-include-todo nil
  2980. "Non-nil means fast tags selection interface will also offer TODO states.
  2981. This is an undocumented feature, you should not rely on it.")
  2982. (defcustom org-tags-column -77
  2983. "The column to which tags should be indented in a headline.
  2984. If this number is positive, it specifies the column. If it is negative,
  2985. it means that the tags should be flushright to that column. For example,
  2986. -80 works well for a normal 80 character screen.
  2987. When 0, place tags directly after headline text, with only one space in
  2988. between."
  2989. :group 'org-tags
  2990. :type 'integer)
  2991. (defcustom org-auto-align-tags t
  2992. "Non-nil keeps tags aligned when modifying headlines.
  2993. Some operations (i.e. demoting) change the length of a headline and
  2994. therefore shift the tags around. With this option turned on, after
  2995. each such operation the tags are again aligned to `org-tags-column'."
  2996. :group 'org-tags
  2997. :type 'boolean)
  2998. (defcustom org-use-tag-inheritance t
  2999. "Non-nil means tags in levels apply also for sublevels.
  3000. When nil, only the tags directly given in a specific line apply there.
  3001. This may also be a list of tags that should be inherited, or a regexp that
  3002. matches tags that should be inherited. Additional control is possible
  3003. with the variable `org-tags-exclude-from-inheritance' which gives an
  3004. explicit list of tags to be excluded from inheritance, even if the value of
  3005. `org-use-tag-inheritance' would select it for inheritance.
  3006. If this option is t, a match early-on in a tree can lead to a large
  3007. number of matches in the subtree when constructing the agenda or creating
  3008. a sparse tree. If you only want to see the first match in a tree during
  3009. a search, check out the variable `org-tags-match-list-sublevels'."
  3010. :group 'org-tags
  3011. :type '(choice
  3012. (const :tag "Not" nil)
  3013. (const :tag "Always" t)
  3014. (repeat :tag "Specific tags" (string :tag "Tag"))
  3015. (regexp :tag "Tags matched by regexp")))
  3016. (defcustom org-tags-exclude-from-inheritance nil
  3017. "List of tags that should never be inherited.
  3018. This is a way to exclude a few tags from inheritance. For way to do
  3019. the opposite, to actively allow inheritance for selected tags,
  3020. see the variable `org-use-tag-inheritance'."
  3021. :group 'org-tags
  3022. :type '(repeat (string :tag "Tag")))
  3023. (defun org-tag-inherit-p (tag)
  3024. "Check if TAG is one that should be inherited."
  3025. (cond
  3026. ((member tag org-tags-exclude-from-inheritance) nil)
  3027. ((eq org-use-tag-inheritance t) t)
  3028. ((not org-use-tag-inheritance) nil)
  3029. ((stringp org-use-tag-inheritance)
  3030. (string-match org-use-tag-inheritance tag))
  3031. ((listp org-use-tag-inheritance)
  3032. (member tag org-use-tag-inheritance))
  3033. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3034. (defcustom org-tags-match-list-sublevels t
  3035. "Non-nil means list also sublevels of headlines matching a search.
  3036. This variable applies to tags/property searches, and also to stuck
  3037. projects because this search is based on a tags match as well.
  3038. When set to the symbol `indented', sublevels are indented with
  3039. leading dots.
  3040. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3041. the sublevels of a headline matching a tag search often also match
  3042. the same search. Listing all of them can create very long lists.
  3043. Setting this variable to nil causes subtrees of a match to be skipped.
  3044. This variable is semi-obsolete and probably should always be true. It
  3045. is better to limit inheritance to certain tags using the variables
  3046. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3047. :group 'org-tags
  3048. :type '(choice
  3049. (const :tag "No, don't list them" nil)
  3050. (const :tag "Yes, do list them" t)
  3051. (const :tag "List them, indented with leading dots" indented)))
  3052. (defcustom org-tags-sort-function nil
  3053. "When set, tags are sorted using this function as a comparator."
  3054. :group 'org-tags
  3055. :type '(choice
  3056. (const :tag "No sorting" nil)
  3057. (const :tag "Alphabetical" string<)
  3058. (const :tag "Reverse alphabetical" string>)
  3059. (function :tag "Custom function" nil)))
  3060. (defvar org-tags-history nil
  3061. "History of minibuffer reads for tags.")
  3062. (defvar org-last-tags-completion-table nil
  3063. "The last used completion table for tags.")
  3064. (defvar org-after-tags-change-hook nil
  3065. "Hook that is run after the tags in a line have changed.")
  3066. (defgroup org-properties nil
  3067. "Options concerning properties in Org mode."
  3068. :tag "Org Properties"
  3069. :group 'org)
  3070. (defcustom org-property-format "%-10s %s"
  3071. "How property key/value pairs should be formatted by `indent-line'.
  3072. When `indent-line' hits a property definition, it will format the line
  3073. according to this format, mainly to make sure that the values are
  3074. lined-up with respect to each other."
  3075. :group 'org-properties
  3076. :type 'string)
  3077. (defcustom org-properties-postprocess-alist nil
  3078. "Alist of properties and functions to adjust inserted values.
  3079. Elements of this alist must be of the form
  3080. ([string] [function])
  3081. where [string] must be a property name and [function] must be a
  3082. lambda expression: this lambda expression must take one argument,
  3083. the value to adjust, and return the new value as a string.
  3084. For example, this element will allow the property \"Remaining\"
  3085. to be updated wrt the relation between the \"Effort\" property
  3086. and the clock summary:
  3087. ((\"Remaining\" (lambda(value)
  3088. (let ((clocksum (org-clock-sum-current-item))
  3089. (effort (org-duration-to-minutes
  3090. (org-entry-get (point) \"Effort\"))))
  3091. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3092. :group 'org-properties
  3093. :version "24.1"
  3094. :type '(alist :key-type (string :tag "Property")
  3095. :value-type (function :tag "Function")))
  3096. (defcustom org-use-property-inheritance nil
  3097. "Non-nil means properties apply also for sublevels.
  3098. This setting is chiefly used during property searches. Turning it on can
  3099. cause significant overhead when doing a search, which is why it is not
  3100. on by default.
  3101. When nil, only the properties directly given in the current entry count.
  3102. When t, every property is inherited. The value may also be a list of
  3103. properties that should have inheritance, or a regular expression matching
  3104. properties that should be inherited.
  3105. However, note that some special properties use inheritance under special
  3106. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3107. and the properties ending in \"_ALL\" when they are used as descriptor
  3108. for valid values of a property.
  3109. Note for programmers:
  3110. When querying an entry with `org-entry-get', you can control if inheritance
  3111. should be used. By default, `org-entry-get' looks only at the local
  3112. properties. You can request inheritance by setting the inherit argument
  3113. to t (to force inheritance) or to `selective' (to respect the setting
  3114. in this variable)."
  3115. :group 'org-properties
  3116. :type '(choice
  3117. (const :tag "Not" nil)
  3118. (const :tag "Always" t)
  3119. (repeat :tag "Specific properties" (string :tag "Property"))
  3120. (regexp :tag "Properties matched by regexp")))
  3121. (defun org-property-inherit-p (property)
  3122. "Return a non-nil value if PROPERTY should be inherited."
  3123. (cond
  3124. ((eq org-use-property-inheritance t) t)
  3125. ((not org-use-property-inheritance) nil)
  3126. ((stringp org-use-property-inheritance)
  3127. (string-match org-use-property-inheritance property))
  3128. ((listp org-use-property-inheritance)
  3129. (member-ignore-case property org-use-property-inheritance))
  3130. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3131. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3132. "The default column format, if no other format has been defined.
  3133. This variable can be set on the per-file basis by inserting a line
  3134. #+COLUMNS: %25ITEM ....."
  3135. :group 'org-properties
  3136. :type 'string)
  3137. (defcustom org-columns-ellipses ".."
  3138. "The ellipses to be used when a field in column view is truncated.
  3139. When this is the empty string, as many characters as possible are shown,
  3140. but then there will be no visual indication that the field has been truncated.
  3141. When this is a string of length N, the last N characters of a truncated
  3142. field are replaced by this string. If the column is narrower than the
  3143. ellipses string, only part of the ellipses string will be shown."
  3144. :group 'org-properties
  3145. :type 'string)
  3146. (defconst org-global-properties-fixed
  3147. '(("VISIBILITY_ALL" . "folded children content all")
  3148. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3149. "List of property/value pairs that can be inherited by any entry.
  3150. These are fixed values, for the preset properties. The user variable
  3151. that can be used to add to this list is `org-global-properties'.
  3152. The entries in this list are cons cells where the car is a property
  3153. name and cdr is a string with the value. If the value represents
  3154. multiple items like an \"_ALL\" property, separate the items by
  3155. spaces.")
  3156. (defcustom org-global-properties nil
  3157. "List of property/value pairs that can be inherited by any entry.
  3158. This list will be combined with the constant `org-global-properties-fixed'.
  3159. The entries in this list are cons cells where the car is a property
  3160. name and cdr is a string with the value.
  3161. You can set buffer-local values for the same purpose in the variable
  3162. `org-file-properties' this by adding lines like
  3163. #+PROPERTY: NAME VALUE"
  3164. :group 'org-properties
  3165. :type '(repeat
  3166. (cons (string :tag "Property")
  3167. (string :tag "Value"))))
  3168. (defvar-local org-file-properties nil
  3169. "List of property/value pairs that can be inherited by any entry.
  3170. Valid for the current buffer.
  3171. This variable is populated from #+PROPERTY lines.")
  3172. (defgroup org-agenda nil
  3173. "Options concerning agenda views in Org mode."
  3174. :tag "Org Agenda"
  3175. :group 'org)
  3176. (defvar-local org-category nil
  3177. "Variable used by org files to set a category for agenda display.
  3178. Such files should use a file variable to set it, for example
  3179. # -*- mode: org; org-category: \"ELisp\"
  3180. or contain a special line
  3181. #+CATEGORY: ELisp
  3182. If the file does not specify a category, then file's base name
  3183. is used instead.")
  3184. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3185. (defcustom org-agenda-files nil
  3186. "The files to be used for agenda display.
  3187. If an entry is a directory, all files in that directory that are matched
  3188. by `org-agenda-file-regexp' will be part of the file list.
  3189. If the value of the variable is not a list but a single file name, then
  3190. the list of agenda files is actually stored and maintained in that file,
  3191. one agenda file per line. In this file paths can be given relative to
  3192. `org-directory'. Tilde expansion and environment variable substitution
  3193. are also made.
  3194. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3195. and removed with `\\[org-remove-file]'."
  3196. :group 'org-agenda
  3197. :type '(choice
  3198. (repeat :tag "List of files and directories" file)
  3199. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3200. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3201. "Regular expression to match files for `org-agenda-files'.
  3202. If any element in the list in that variable contains a directory instead
  3203. of a normal file, all files in that directory that are matched by this
  3204. regular expression will be included."
  3205. :group 'org-agenda
  3206. :type 'regexp)
  3207. (defcustom org-agenda-text-search-extra-files nil
  3208. "List of extra files to be searched by text search commands.
  3209. These files will be searched in addition to the agenda files by the
  3210. commands `org-search-view' (`\\[org-agenda] s') \
  3211. and `org-occur-in-agenda-files'.
  3212. Note that these files will only be searched for text search commands,
  3213. not for the other agenda views like todo lists, tag searches or the weekly
  3214. agenda. This variable is intended to list notes and possibly archive files
  3215. that should also be searched by these two commands.
  3216. In fact, if the first element in the list is the symbol `agenda-archives',
  3217. then all archive files of all agenda files will be added to the search
  3218. scope."
  3219. :group 'org-agenda
  3220. :type '(set :greedy t
  3221. (const :tag "Agenda Archives" agenda-archives)
  3222. (repeat :inline t (file))))
  3223. (defvaralias 'org-agenda-multi-occur-extra-files
  3224. 'org-agenda-text-search-extra-files)
  3225. (defcustom org-agenda-skip-unavailable-files nil
  3226. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3227. A nil value means to remove them, after a query, from the list."
  3228. :group 'org-agenda
  3229. :type 'boolean)
  3230. (defcustom org-calendar-to-agenda-key [?c]
  3231. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3232. The command `org-calendar-goto-agenda' will be bound to this key. The
  3233. default is the character `c' because then `c' can be used to switch back and
  3234. forth between agenda and calendar."
  3235. :group 'org-agenda
  3236. :type 'sexp)
  3237. (defcustom org-calendar-insert-diary-entry-key [?i]
  3238. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3239. This option is irrelevant until `org-agenda-diary-file' has been configured
  3240. to point to an Org file. When that is the case, the command
  3241. `org-agenda-diary-entry' will be bound to the key given here, by default
  3242. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3243. if you want to continue doing this, you need to change this to a different
  3244. key."
  3245. :group 'org-agenda
  3246. :type 'sexp)
  3247. (defcustom org-agenda-diary-file 'diary-file
  3248. "File to which to add new entries with the `i' key in agenda and calendar.
  3249. When this is the symbol `diary-file', the functionality in the Emacs
  3250. calendar will be used to add entries to the `diary-file'. But when this
  3251. points to a file, `org-agenda-diary-entry' will be used instead."
  3252. :group 'org-agenda
  3253. :type '(choice
  3254. (const :tag "The standard Emacs diary file" diary-file)
  3255. (file :tag "Special Org file diary entries")))
  3256. (eval-after-load "calendar"
  3257. '(progn
  3258. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3259. 'org-calendar-goto-agenda)
  3260. (add-hook 'calendar-mode-hook
  3261. (lambda ()
  3262. (unless (eq org-agenda-diary-file 'diary-file)
  3263. (define-key calendar-mode-map
  3264. org-calendar-insert-diary-entry-key
  3265. 'org-agenda-diary-entry))))))
  3266. (defgroup org-latex nil
  3267. "Options for embedding LaTeX code into Org mode."
  3268. :tag "Org LaTeX"
  3269. :group 'org)
  3270. (defcustom org-format-latex-options
  3271. '(:foreground default :background default :scale 1.0
  3272. :html-foreground "Black" :html-background "Transparent"
  3273. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3274. "Options for creating images from LaTeX fragments.
  3275. This is a property list with the following properties:
  3276. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3277. `default' means use the foreground of the default face.
  3278. `auto' means use the foreground from the text face.
  3279. :background the background color, or \"Transparent\".
  3280. `default' means use the background of the default face.
  3281. `auto' means use the background from the text face.
  3282. :scale a scaling factor for the size of the images, to get more pixels
  3283. :html-foreground, :html-background, :html-scale
  3284. the same numbers for HTML export.
  3285. :matchers a list indicating which matchers should be used to
  3286. find LaTeX fragments. Valid members of this list are:
  3287. \"begin\" find environments
  3288. \"$1\" find single characters surrounded by $.$
  3289. \"$\" find math expressions surrounded by $...$
  3290. \"$$\" find math expressions surrounded by $$....$$
  3291. \"\\(\" find math expressions surrounded by \\(...\\)
  3292. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3293. :group 'org-latex
  3294. :type 'plist)
  3295. (defcustom org-format-latex-signal-error t
  3296. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3297. When nil, just push out a message."
  3298. :group 'org-latex
  3299. :version "24.1"
  3300. :type 'boolean)
  3301. (defcustom org-latex-to-mathml-jar-file nil
  3302. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3303. Use this to specify additional executable file say a jar file.
  3304. When using MathToWeb as the converter, specify the full-path to
  3305. your mathtoweb.jar file."
  3306. :group 'org-latex
  3307. :version "24.1"
  3308. :type '(choice
  3309. (const :tag "None" nil)
  3310. (file :tag "JAR file" :must-match t)))
  3311. (defcustom org-latex-to-mathml-convert-command nil
  3312. "Command to convert LaTeX fragments to MathML.
  3313. Replace format-specifiers in the command as noted below and use
  3314. `shell-command' to convert LaTeX to MathML.
  3315. %j: Executable file in fully expanded form as specified by
  3316. `org-latex-to-mathml-jar-file'.
  3317. %I: Input LaTeX file in fully expanded form.
  3318. %i: The latex fragment to be converted.
  3319. %o: Output MathML file.
  3320. This command is used by `org-create-math-formula'.
  3321. When using MathToWeb as the converter, set this option to
  3322. \"java -jar %j -unicode -force -df %o %I\".
  3323. When using LaTeXML set this option to
  3324. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3325. :group 'org-latex
  3326. :version "24.1"
  3327. :type '(choice
  3328. (const :tag "None" nil)
  3329. (string :tag "\nShell command")))
  3330. (defcustom org-preview-latex-default-process 'dvipng
  3331. "The default process to convert LaTeX fragments to image files.
  3332. All available processes and theirs documents can be found in
  3333. `org-preview-latex-process-alist', which see."
  3334. :group 'org-latex
  3335. :version "26.1"
  3336. :package-version '(Org . "9.0")
  3337. :type 'symbol)
  3338. (defcustom org-preview-latex-process-alist
  3339. '((dvipng
  3340. :programs ("latex" "dvipng")
  3341. :description "dvi > png"
  3342. :message "you need to install the programs: latex and dvipng."
  3343. :image-input-type "dvi"
  3344. :image-output-type "png"
  3345. :image-size-adjust (1.0 . 1.0)
  3346. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3347. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3348. (dvisvgm
  3349. :programs ("latex" "dvisvgm")
  3350. :description "dvi > svg"
  3351. :message "you need to install the programs: latex and dvisvgm."
  3352. :use-xcolor t
  3353. :image-input-type "dvi"
  3354. :image-output-type "svg"
  3355. :image-size-adjust (1.7 . 1.5)
  3356. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3357. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3358. (imagemagick
  3359. :programs ("latex" "convert")
  3360. :description "pdf > png"
  3361. :message "you need to install the programs: latex and imagemagick."
  3362. :use-xcolor t
  3363. :image-input-type "pdf"
  3364. :image-output-type "png"
  3365. :image-size-adjust (1.0 . 1.0)
  3366. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3367. :image-converter
  3368. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3369. "Definitions of external processes for LaTeX previewing.
  3370. Org mode can use some external commands to generate TeX snippet's images for
  3371. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3372. `org-create-formula-image' how to call them.
  3373. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3374. PROPERTIES accepts the following attributes:
  3375. :programs list of strings, required programs.
  3376. :description string, describe the process.
  3377. :message string, message it when required programs cannot be found.
  3378. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3379. :image-output-type string, output file type of image converter (e.g., \"png\").
  3380. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3381. deal with background and foreground color of image.
  3382. Otherwise, dvipng style background and foreground color
  3383. format are generated. You may then refer to them in
  3384. command options with \"%F\" and \"%B\".
  3385. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3386. image size showed in buffer and the cdr element is for
  3387. HTML file. This option is only useful for process
  3388. developers, users should use variable
  3389. `org-format-latex-options' instead.
  3390. :post-clean list of strings, files matched are to be cleaned up once
  3391. the image is generated. When nil, the files with \".dvi\",
  3392. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3393. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3394. be cleaned up.
  3395. :latex-header list of strings, the LaTeX header of the snippet file.
  3396. When nil, the fallback value is used instead, which is
  3397. controlled by `org-format-latex-header',
  3398. `org-latex-default-packages-alist' and
  3399. `org-latex-packages-alist', which see.
  3400. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3401. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3402. replaced with values defined below.
  3403. :image-converter list of image converter commands strings. Each of them is
  3404. given to the shell and supports any of the following
  3405. place-holders defined below.
  3406. Place-holders used by `:image-converter' and `:latex-compiler':
  3407. %f input file name
  3408. %b base name of input file
  3409. %o base directory of input file
  3410. %O absolute output file name
  3411. Place-holders only used by `:image-converter':
  3412. %F foreground of image
  3413. %B background of image
  3414. %D dpi, which is used to adjust image size by some processing commands.
  3415. %S the image size scale ratio, which is used to adjust image size by some
  3416. processing commands."
  3417. :group 'org-latex
  3418. :version "26.1"
  3419. :package-version '(Org . "9.0")
  3420. :type '(alist :tag "LaTeX to image backends"
  3421. :value-type (plist)))
  3422. (defcustom org-preview-latex-image-directory "ltximg/"
  3423. "Path to store latex preview images.
  3424. A relative path here creates many directories relative to the
  3425. processed org files paths. An absolute path puts all preview
  3426. images at the same place."
  3427. :group 'org-latex
  3428. :version "26.1"
  3429. :package-version '(Org . "9.0")
  3430. :type 'string)
  3431. (defun org-format-latex-mathml-available-p ()
  3432. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3433. (save-match-data
  3434. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3435. org-latex-to-mathml-convert-command)
  3436. (let ((executable (car (split-string
  3437. org-latex-to-mathml-convert-command))))
  3438. (when (executable-find executable)
  3439. (if (string-match
  3440. "%j" org-latex-to-mathml-convert-command)
  3441. (file-readable-p org-latex-to-mathml-jar-file)
  3442. t))))))
  3443. (defcustom org-format-latex-header "\\documentclass{article}
  3444. \\usepackage[usenames]{color}
  3445. \[PACKAGES]
  3446. \[DEFAULT-PACKAGES]
  3447. \\pagestyle{empty} % do not remove
  3448. % The settings below are copied from fullpage.sty
  3449. \\setlength{\\textwidth}{\\paperwidth}
  3450. \\addtolength{\\textwidth}{-3cm}
  3451. \\setlength{\\oddsidemargin}{1.5cm}
  3452. \\addtolength{\\oddsidemargin}{-2.54cm}
  3453. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3454. \\setlength{\\textheight}{\\paperheight}
  3455. \\addtolength{\\textheight}{-\\headheight}
  3456. \\addtolength{\\textheight}{-\\headsep}
  3457. \\addtolength{\\textheight}{-\\footskip}
  3458. \\addtolength{\\textheight}{-3cm}
  3459. \\setlength{\\topmargin}{1.5cm}
  3460. \\addtolength{\\topmargin}{-2.54cm}"
  3461. "The document header used for processing LaTeX fragments.
  3462. It is imperative that this header make sure that no page number
  3463. appears on the page. The package defined in the variables
  3464. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3465. will either replace the placeholder \"[PACKAGES]\" in this
  3466. header, or they will be appended."
  3467. :group 'org-latex
  3468. :type 'string)
  3469. (defun org-set-packages-alist (var val)
  3470. "Set the packages alist and make sure it has 3 elements per entry."
  3471. (set var (mapcar (lambda (x)
  3472. (if (and (consp x) (= (length x) 2))
  3473. (list (car x) (nth 1 x) t)
  3474. x))
  3475. val)))
  3476. (defun org-get-packages-alist (var)
  3477. "Get the packages alist and make sure it has 3 elements per entry."
  3478. (mapcar (lambda (x)
  3479. (if (and (consp x) (= (length x) 2))
  3480. (list (car x) (nth 1 x) t)
  3481. x))
  3482. (default-value var)))
  3483. (defcustom org-latex-default-packages-alist
  3484. '(("AUTO" "inputenc" t ("pdflatex"))
  3485. ("T1" "fontenc" t ("pdflatex"))
  3486. ("" "graphicx" t)
  3487. ("" "grffile" t)
  3488. ("" "longtable" nil)
  3489. ("" "wrapfig" nil)
  3490. ("" "rotating" nil)
  3491. ("normalem" "ulem" t)
  3492. ("" "amsmath" t)
  3493. ("" "textcomp" t)
  3494. ("" "amssymb" t)
  3495. ("" "capt-of" nil)
  3496. ("" "hyperref" nil))
  3497. "Alist of default packages to be inserted in the header.
  3498. Change this only if one of the packages here causes an
  3499. incompatibility with another package you are using.
  3500. The packages in this list are needed by one part or another of
  3501. Org mode to function properly:
  3502. - inputenc, fontenc: for basic font and character selection
  3503. - graphicx: for including images
  3504. - grffile: allow periods and spaces in graphics file names
  3505. - longtable: For multipage tables
  3506. - wrapfig: for figure placement
  3507. - rotating: for sideways figures and tables
  3508. - ulem: for underline and strike-through
  3509. - amsmath: for subscript and superscript and math environments
  3510. - textcomp, amssymb: for various symbols used
  3511. for interpreting the entities in `org-entities'. You can skip
  3512. some of these packages if you don't use any of their symbols.
  3513. - capt-of: for captions outside of floats
  3514. - hyperref: for cross references
  3515. Therefore you should not modify this variable unless you know
  3516. what you are doing. The one reason to change it anyway is that
  3517. you might be loading some other package that conflicts with one
  3518. of the default packages. Each element is either a cell or
  3519. a string.
  3520. A cell is of the format
  3521. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3522. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3523. when compiling LaTeX snippets into images for inclusion into
  3524. non-LaTeX output. COMPILERS is a list of compilers that should
  3525. include the package, see `org-latex-compiler'. If the document
  3526. compiler is not in the list, and the list is non-nil, the package
  3527. will not be inserted in the final document.
  3528. A string will be inserted as-is in the header of the document."
  3529. :group 'org-latex
  3530. :group 'org-export-latex
  3531. :set 'org-set-packages-alist
  3532. :get 'org-get-packages-alist
  3533. :version "26.1"
  3534. :package-version '(Org . "8.3")
  3535. :type '(repeat
  3536. (choice
  3537. (list :tag "options/package pair"
  3538. (string :tag "options")
  3539. (string :tag "package")
  3540. (boolean :tag "Snippet"))
  3541. (string :tag "A line of LaTeX"))))
  3542. (defcustom org-latex-packages-alist nil
  3543. "Alist of packages to be inserted in every LaTeX header.
  3544. These will be inserted after `org-latex-default-packages-alist'.
  3545. Each element is either a cell or a string.
  3546. A cell is of the format:
  3547. (\"options\" \"package\" SNIPPET-FLAG)
  3548. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3549. needed when turning LaTeX snippets into images for inclusion into
  3550. non-LaTeX output.
  3551. A string will be inserted as-is in the header of the document.
  3552. Make sure that you only list packages here which:
  3553. - you want in every file;
  3554. - do not conflict with the setup in `org-format-latex-header';
  3555. - do not conflict with the default packages in
  3556. `org-latex-default-packages-alist'."
  3557. :group 'org-latex
  3558. :group 'org-export-latex
  3559. :set 'org-set-packages-alist
  3560. :get 'org-get-packages-alist
  3561. :type '(repeat
  3562. (choice
  3563. (list :tag "options/package pair"
  3564. (string :tag "options")
  3565. (string :tag "package")
  3566. (boolean :tag "Snippet"))
  3567. (string :tag "A line of LaTeX"))))
  3568. (defgroup org-appearance nil
  3569. "Settings for Org mode appearance."
  3570. :tag "Org Appearance"
  3571. :group 'org)
  3572. (defcustom org-level-color-stars-only nil
  3573. "Non-nil means fontify only the stars in each headline.
  3574. When nil, the entire headline is fontified.
  3575. Changing it requires restart of `font-lock-mode' to become effective
  3576. also in regions already fontified."
  3577. :group 'org-appearance
  3578. :type 'boolean)
  3579. (defcustom org-hide-leading-stars nil
  3580. "Non-nil means hide the first N-1 stars in a headline.
  3581. This works by using the face `org-hide' for these stars. This
  3582. face is white for a light background, and black for a dark
  3583. background. You may have to customize the face `org-hide' to
  3584. make this work.
  3585. Changing it requires restart of `font-lock-mode' to become effective
  3586. also in regions already fontified.
  3587. You may also set this on a per-file basis by adding one of the following
  3588. lines to the buffer:
  3589. #+STARTUP: hidestars
  3590. #+STARTUP: showstars"
  3591. :group 'org-appearance
  3592. :type 'boolean)
  3593. (defcustom org-hidden-keywords nil
  3594. "List of symbols corresponding to keywords to be hidden the org buffer.
  3595. For example, a value \\='(title) for this list will make the document's title
  3596. appear in the buffer without the initial #+TITLE: keyword."
  3597. :group 'org-appearance
  3598. :version "24.1"
  3599. :type '(set (const :tag "#+AUTHOR" author)
  3600. (const :tag "#+DATE" date)
  3601. (const :tag "#+EMAIL" email)
  3602. (const :tag "#+TITLE" title)))
  3603. (defcustom org-custom-properties nil
  3604. "List of properties (as strings) with a special meaning.
  3605. The default use of these custom properties is to let the user
  3606. hide them with `org-toggle-custom-properties-visibility'."
  3607. :group 'org-properties
  3608. :group 'org-appearance
  3609. :version "24.3"
  3610. :type '(repeat (string :tag "Property Name")))
  3611. (defcustom org-fontify-done-headline nil
  3612. "Non-nil means change the face of a headline if it is marked DONE.
  3613. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3614. When this is non-nil, the headline after the keyword is set to the
  3615. `org-headline-done' as an additional indication."
  3616. :group 'org-appearance
  3617. :type 'boolean)
  3618. (defcustom org-fontify-emphasized-text t
  3619. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3620. Changing this variable requires a restart of Emacs to take effect."
  3621. :group 'org-appearance
  3622. :type 'boolean)
  3623. (defcustom org-fontify-whole-heading-line nil
  3624. "Non-nil means fontify the whole line for headings.
  3625. This is useful when setting a background color for the
  3626. org-level-* faces."
  3627. :group 'org-appearance
  3628. :type 'boolean)
  3629. (defcustom org-highlight-latex-and-related nil
  3630. "Non-nil means highlight LaTeX related syntax in the buffer.
  3631. When non nil, the value should be a list containing any of the
  3632. following symbols:
  3633. `latex' Highlight LaTeX snippets and environments.
  3634. `script' Highlight subscript and superscript.
  3635. `entities' Highlight entities."
  3636. :group 'org-appearance
  3637. :version "24.4"
  3638. :package-version '(Org . "8.0")
  3639. :type '(choice
  3640. (const :tag "No highlighting" nil)
  3641. (set :greedy t :tag "Highlight"
  3642. (const :tag "LaTeX snippets and environments" latex)
  3643. (const :tag "Subscript and superscript" script)
  3644. (const :tag "Entities" entities))))
  3645. (defcustom org-hide-emphasis-markers nil
  3646. "Non-nil mean font-lock should hide the emphasis marker characters."
  3647. :group 'org-appearance
  3648. :type 'boolean)
  3649. (defcustom org-hide-macro-markers nil
  3650. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3651. :group 'org-appearance
  3652. :type 'boolean)
  3653. (defcustom org-pretty-entities nil
  3654. "Non-nil means show entities as UTF8 characters.
  3655. When nil, the \\name form remains in the buffer."
  3656. :group 'org-appearance
  3657. :version "24.1"
  3658. :type 'boolean)
  3659. (defcustom org-pretty-entities-include-sub-superscripts t
  3660. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3661. :group 'org-appearance
  3662. :version "24.1"
  3663. :type 'boolean)
  3664. (defvar org-emph-re nil
  3665. "Regular expression for matching emphasis.
  3666. After a match, the match groups contain these elements:
  3667. 0 The match of the full regular expression, including the characters
  3668. before and after the proper match
  3669. 1 The character before the proper match, or empty at beginning of line
  3670. 2 The proper match, including the leading and trailing markers
  3671. 3 The leading marker like * or /, indicating the type of highlighting
  3672. 4 The text between the emphasis markers, not including the markers
  3673. 5 The character after the match, empty at the end of a line")
  3674. (defvar org-verbatim-re nil
  3675. "Regular expression for matching verbatim text.")
  3676. (defvar org-emphasis-regexp-components) ; defined just below
  3677. (defvar org-emphasis-alist) ; defined just below
  3678. (defun org-set-emph-re (var val)
  3679. "Set variable and compute the emphasis regular expression."
  3680. (set var val)
  3681. (when (and (boundp 'org-emphasis-alist)
  3682. (boundp 'org-emphasis-regexp-components)
  3683. org-emphasis-alist org-emphasis-regexp-components)
  3684. (pcase-let*
  3685. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3686. (body (if (<= nl 0) body
  3687. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3688. (template
  3689. (format (concat "\\([%s]\\|^\\)" ;before markers
  3690. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3691. "\\([%s]\\|$\\)") ;after markers
  3692. pre border border body border post)))
  3693. (setq org-emph-re (format template "*/_+"))
  3694. (setq org-verbatim-re (format template "=~")))))
  3695. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3696. ;; set this option proved cumbersome. See this message/thread:
  3697. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3698. (defvar org-emphasis-regexp-components
  3699. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3700. "Components used to build the regular expression for emphasis.
  3701. This is a list with five entries. Terminology: In an emphasis string
  3702. like \" *strong word* \", we call the initial space PREMATCH, the final
  3703. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3704. and \"trong wor\" is the body. The different components in this variable
  3705. specify what is allowed/forbidden in each part:
  3706. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3707. post Chars allowed as postmatch. End of line will be allowed too.
  3708. border The chars *forbidden* as border characters.
  3709. body-regexp A regexp like \".\" to match a body character. Don't use
  3710. non-shy groups here, and don't allow newline here.
  3711. newline The maximum number of newlines allowed in an emphasis exp.
  3712. You need to reload Org or to restart Emacs after setting this.")
  3713. (defcustom org-emphasis-alist
  3714. '(("*" bold)
  3715. ("/" italic)
  3716. ("_" underline)
  3717. ("=" org-verbatim verbatim)
  3718. ("~" org-code verbatim)
  3719. ("+" (:strike-through t)))
  3720. "Alist of characters and faces to emphasize text.
  3721. Text starting and ending with a special character will be emphasized,
  3722. for example *bold*, _underlined_ and /italic/. This variable sets the
  3723. marker characters and the face to be used by font-lock for highlighting
  3724. in Org buffers.
  3725. You need to reload Org or to restart Emacs after customizing this."
  3726. :group 'org-appearance
  3727. :set 'org-set-emph-re
  3728. :version "24.4"
  3729. :package-version '(Org . "8.0")
  3730. :type '(repeat
  3731. (list
  3732. (string :tag "Marker character")
  3733. (choice
  3734. (face :tag "Font-lock-face")
  3735. (plist :tag "Face property list"))
  3736. (option (const verbatim)))))
  3737. (defvar org-protecting-blocks '("src" "example" "export")
  3738. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3739. This is needed for font-lock setup.")
  3740. ;;; Functions and variables from their packages
  3741. ;; Declared here to avoid compiler warnings
  3742. (defvar mark-active)
  3743. ;; Various packages
  3744. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3745. (declare-function calendar-forward-day "cal-move" (arg))
  3746. (declare-function calendar-goto-date "cal-move" (date))
  3747. (declare-function calendar-goto-today "cal-move" ())
  3748. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3749. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3750. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3751. (declare-function cdlatex-tab "ext:cdlatex" ())
  3752. (declare-function dired-get-filename
  3753. "dired"
  3754. (&optional localp no-error-if-not-filep))
  3755. (declare-function iswitchb-read-buffer
  3756. "iswitchb"
  3757. (prompt &optional
  3758. default require-match _predicate start matches-set))
  3759. (declare-function org-agenda-change-all-lines
  3760. "org-agenda"
  3761. (newhead hdmarker &optional fixface just-this))
  3762. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3763. "org-agenda"
  3764. (&optional end))
  3765. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3766. (declare-function org-agenda-format-item
  3767. "org-agenda"
  3768. (extra txt &optional level category tags dotime
  3769. remove-re habitp))
  3770. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3771. (declare-function org-agenda-save-markers-for-cut-and-paste
  3772. "org-agenda"
  3773. (beg end))
  3774. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3775. (declare-function org-agenda-skip "org-agenda" ())
  3776. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3777. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3778. (declare-function org-indent-mode "org-indent" (&optional arg))
  3779. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3780. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3781. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3782. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3783. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3784. (declare-function parse-time-string "parse-time" (string))
  3785. (defvar align-mode-rules-list)
  3786. (defvar calc-embedded-close-formula)
  3787. (defvar calc-embedded-open-formula)
  3788. (defvar calc-embedded-open-mode)
  3789. (defvar font-lock-unfontify-region-function)
  3790. (defvar iswitchb-temp-buflist)
  3791. (defvar org-agenda-tags-todo-honor-ignore-options)
  3792. (defvar remember-data-file)
  3793. (defvar texmathp-why)
  3794. ;;;###autoload
  3795. (defun turn-on-orgtbl ()
  3796. "Unconditionally turn on `orgtbl-mode'."
  3797. (require 'org-table)
  3798. (orgtbl-mode 1))
  3799. (defun org-at-table-p (&optional table-type)
  3800. "Non-nil if the cursor is inside an Org table.
  3801. If TABLE-TYPE is non-nil, also check for table.el-type tables."
  3802. (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
  3803. (or (not (derived-mode-p 'org-mode))
  3804. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3805. (and e (or table-type
  3806. (eq 'org (org-element-property :type e))))))))
  3807. (defun org-at-table.el-p ()
  3808. "Non-nil when point is at a table.el table."
  3809. (and (org-match-line "[ \t]*[|+]")
  3810. (let ((element (org-element-at-point)))
  3811. (and (eq (org-element-type element) 'table)
  3812. (eq (org-element-property :type element) 'table.el)))))
  3813. (defun org-at-table-hline-p ()
  3814. "Non-nil when point is inside a hline in a table.
  3815. Assume point is already in a table."
  3816. (org-match-line org-table-hline-regexp))
  3817. (defun org-table-map-tables (function &optional quietly)
  3818. "Apply FUNCTION to the start of all tables in the buffer."
  3819. (org-with-wide-buffer
  3820. (goto-char (point-min))
  3821. (while (re-search-forward org-table-any-line-regexp nil t)
  3822. (unless quietly
  3823. (message "Mapping tables: %d%%"
  3824. (floor (* 100.0 (point)) (buffer-size))))
  3825. (beginning-of-line 1)
  3826. (when (and (looking-at org-table-line-regexp)
  3827. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3828. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3829. (save-excursion (funcall function))
  3830. (or (looking-at org-table-line-regexp)
  3831. (forward-char 1)))
  3832. (re-search-forward org-table-any-border-regexp nil 1)))
  3833. (unless quietly (message "Mapping tables: done")))
  3834. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3835. (declare-function org-clock-update-mode-line "org-clock" ())
  3836. (declare-function org-resolve-clocks "org-clock"
  3837. (&optional also-non-dangling-p prompt last-valid))
  3838. (defun org-at-TBLFM-p (&optional pos)
  3839. "Non-nil when point (or POS) is in #+TBLFM line."
  3840. (save-excursion
  3841. (goto-char (or pos (point)))
  3842. (beginning-of-line)
  3843. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3844. (eq (org-element-type (org-element-at-point)) 'table))))
  3845. (defvar org-clock-start-time)
  3846. (defvar org-clock-marker (make-marker)
  3847. "Marker recording the last clock-in.")
  3848. (defvar org-clock-hd-marker (make-marker)
  3849. "Marker recording the last clock-in, but the headline position.")
  3850. (defvar org-clock-heading ""
  3851. "The heading of the current clock entry.")
  3852. (defun org-clock-is-active ()
  3853. "Return the buffer where the clock is currently running.
  3854. Return nil if no clock is running."
  3855. (marker-buffer org-clock-marker))
  3856. (defun org-check-running-clock ()
  3857. "Check if the current buffer contains the running clock.
  3858. If yes, offer to stop it and to save the buffer with the changes."
  3859. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3860. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3861. (buffer-name))))
  3862. (org-clock-out)
  3863. (when (y-or-n-p "Save changed buffer?")
  3864. (save-buffer))))
  3865. (defun org-clocktable-try-shift (dir n)
  3866. "Check if this line starts a clock table, if yes, shift the time block."
  3867. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3868. (org-clocktable-shift dir n)))
  3869. ;;;###autoload
  3870. (defun org-clock-persistence-insinuate ()
  3871. "Set up hooks for clock persistence."
  3872. (require 'org-clock)
  3873. (add-hook 'org-mode-hook 'org-clock-load)
  3874. (add-hook 'kill-emacs-hook 'org-clock-save))
  3875. (defgroup org-archive nil
  3876. "Options concerning archiving in Org mode."
  3877. :tag "Org Archive"
  3878. :group 'org-structure)
  3879. (defcustom org-archive-location "%s_archive::"
  3880. "The location where subtrees should be archived.
  3881. The value of this variable is a string, consisting of two parts,
  3882. separated by a double-colon. The first part is a filename and
  3883. the second part is a headline.
  3884. When the filename is omitted, archiving happens in the same file.
  3885. %s in the filename will be replaced by the current file
  3886. name (without the directory part). Archiving to a different file
  3887. is useful to keep archived entries from contributing to the
  3888. Org Agenda.
  3889. The archived entries will be filed as subtrees of the specified
  3890. headline. When the headline is omitted, the subtrees are simply
  3891. filed away at the end of the file, as top-level entries. Also in
  3892. the heading you can use %s to represent the file name, this can be
  3893. useful when using the same archive for a number of different files.
  3894. Here are a few examples:
  3895. \"%s_archive::\"
  3896. If the current file is Projects.org, archive in file
  3897. Projects.org_archive, as top-level trees. This is the default.
  3898. \"::* Archived Tasks\"
  3899. Archive in the current file, under the top-level headline
  3900. \"* Archived Tasks\".
  3901. \"~/org/archive.org::\"
  3902. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3903. \"~/org/archive.org::* From %s\"
  3904. Archive in file ~/org/archive.org (absolute path), under headlines
  3905. \"From FILENAME\" where file name is the current file name.
  3906. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3907. The \"datetree/\" string is special, signifying to archive
  3908. items to the datetree. Items are placed in either the CLOSED
  3909. date of the item, or the current date if there is no CLOSED date.
  3910. The heading will be a subentry to the current date. There doesn't
  3911. need to be a heading, but there always needs to be a slash after
  3912. datetree. For example, to store archived items directly in the
  3913. datetree, use \"~/org/datetree.org::datetree/\".
  3914. \"basement::** Finished Tasks\"
  3915. Archive in file ./basement (relative path), as level 3 trees
  3916. below the level 2 heading \"** Finished Tasks\".
  3917. You may set this option on a per-file basis by adding to the buffer a
  3918. line like
  3919. #+ARCHIVE: basement::** Finished Tasks
  3920. You may also define it locally for a subtree by setting an ARCHIVE property
  3921. in the entry. If such a property is found in an entry, or anywhere up
  3922. the hierarchy, it will be used."
  3923. :group 'org-archive
  3924. :type 'string)
  3925. (defcustom org-agenda-skip-archived-trees t
  3926. "Non-nil means the agenda will skip any items located in archived trees.
  3927. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3928. variable is no longer recommended, you should leave it at the value t.
  3929. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3930. :group 'org-archive
  3931. :group 'org-agenda-skip
  3932. :type 'boolean)
  3933. (defcustom org-columns-skip-archived-trees t
  3934. "Non-nil means ignore archived trees when creating column view."
  3935. :group 'org-archive
  3936. :group 'org-properties
  3937. :type 'boolean)
  3938. (defcustom org-cycle-open-archived-trees nil
  3939. "Non-nil means `org-cycle' will open archived trees.
  3940. An archived tree is a tree marked with the tag ARCHIVE.
  3941. When nil, archived trees will stay folded. You can still open them with
  3942. normal outline commands like `show-all', but not with the cycling commands."
  3943. :group 'org-archive
  3944. :group 'org-cycle
  3945. :type 'boolean)
  3946. (defcustom org-sparse-tree-open-archived-trees nil
  3947. "Non-nil means sparse tree construction shows matches in archived trees.
  3948. When nil, matches in these trees are highlighted, but the trees are kept in
  3949. collapsed state."
  3950. :group 'org-archive
  3951. :group 'org-sparse-trees
  3952. :type 'boolean)
  3953. (defcustom org-sparse-tree-default-date-type nil
  3954. "The default date type when building a sparse tree.
  3955. When this is nil, a date is a scheduled or a deadline timestamp.
  3956. Otherwise, these types are allowed:
  3957. all: all timestamps
  3958. active: only active timestamps (<...>)
  3959. inactive: only inactive timestamps ([...])
  3960. scheduled: only scheduled timestamps
  3961. deadline: only deadline timestamps"
  3962. :type '(choice (const :tag "Scheduled or deadline" nil)
  3963. (const :tag "All timestamps" all)
  3964. (const :tag "Only active timestamps" active)
  3965. (const :tag "Only inactive timestamps" inactive)
  3966. (const :tag "Only scheduled timestamps" scheduled)
  3967. (const :tag "Only deadline timestamps" deadline)
  3968. (const :tag "Only closed timestamps" closed))
  3969. :version "26.1"
  3970. :package-version '(Org . "8.3")
  3971. :group 'org-sparse-trees)
  3972. (defun org-cycle-hide-archived-subtrees (state)
  3973. "Re-hide all archived subtrees after a visibility state change.
  3974. STATE should be one of the symbols listed in the docstring of
  3975. `org-cycle-hook'."
  3976. (when (and (not org-cycle-open-archived-trees)
  3977. (not (memq state '(overview folded))))
  3978. (save-excursion
  3979. (let* ((globalp (memq state '(contents all)))
  3980. (beg (if globalp (point-min) (point)))
  3981. (end (if globalp (point-max) (org-end-of-subtree t))))
  3982. (org-hide-archived-subtrees beg end)
  3983. (goto-char beg)
  3984. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3985. (message "%s" (substitute-command-keys
  3986. "Subtree is archived and stays closed. Use \
  3987. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3988. (defun org-force-cycle-archived ()
  3989. "Cycle subtree even if it is archived."
  3990. (interactive)
  3991. (setq this-command 'org-cycle)
  3992. (let ((org-cycle-open-archived-trees t))
  3993. (call-interactively 'org-cycle)))
  3994. (defun org-hide-archived-subtrees (beg end)
  3995. "Re-hide all archived subtrees after a visibility state change."
  3996. (org-with-wide-buffer
  3997. (let ((case-fold-search nil)
  3998. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3999. (goto-char beg)
  4000. ;; Include headline point is currently on.
  4001. (beginning-of-line)
  4002. (while (and (< (point) end) (re-search-forward re end t))
  4003. (when (member org-archive-tag (org-get-tags))
  4004. (org-flag-subtree t)
  4005. (org-end-of-subtree t))))))
  4006. (declare-function outline-end-of-heading "outline" ())
  4007. (declare-function outline-flag-region "outline" (from to flag))
  4008. (defun org-flag-subtree (flag)
  4009. (save-excursion
  4010. (org-back-to-heading t)
  4011. (outline-end-of-heading)
  4012. (outline-flag-region (point)
  4013. (progn (org-end-of-subtree t) (point))
  4014. flag)))
  4015. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4016. ;; Declare Column View Code
  4017. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4018. (declare-function org-columns-compute "org-colview" (property))
  4019. ;; Declare ID code
  4020. (declare-function org-id-store-link "org-id")
  4021. (declare-function org-id-locations-load "org-id")
  4022. (declare-function org-id-locations-save "org-id")
  4023. (defvar org-id-track-globally)
  4024. ;;; Variables for pre-computed regular expressions, all buffer local
  4025. (defvar-local org-todo-regexp nil
  4026. "Matches any of the TODO state keywords.
  4027. Since TODO keywords are case-sensitive, `case-fold-search' is
  4028. expected to be bound to nil when matching against this regexp.")
  4029. (defvar-local org-not-done-regexp nil
  4030. "Matches any of the TODO state keywords except the last one.
  4031. Since TODO keywords are case-sensitive, `case-fold-search' is
  4032. expected to be bound to nil when matching against this regexp.")
  4033. (defvar-local org-not-done-heading-regexp nil
  4034. "Matches a TODO headline that is not done.
  4035. Since TODO keywords are case-sensitive, `case-fold-search' is
  4036. expected to be bound to nil when matching against this regexp.")
  4037. (defvar-local org-todo-line-regexp nil
  4038. "Matches a headline and puts TODO state into group 2 if present.
  4039. Since TODO keywords are case-sensitive, `case-fold-search' is
  4040. expected to be bound to nil when matching against this regexp.")
  4041. (defvar-local org-complex-heading-regexp nil
  4042. "Matches a headline and puts everything into groups:
  4043. group 1: Stars
  4044. group 2: The TODO keyword, maybe
  4045. group 3: Priority cookie
  4046. group 4: True headline
  4047. group 5: Tags
  4048. Since TODO keywords are case-sensitive, `case-fold-search' is
  4049. expected to be bound to nil when matching against this regexp.")
  4050. (defvar-local org-complex-heading-regexp-format nil
  4051. "Printf format to make regexp to match an exact headline.
  4052. This regexp will match the headline of any node which has the
  4053. exact headline text that is put into the format, but may have any
  4054. TODO state, priority and tags.")
  4055. (defvar-local org-todo-line-tags-regexp nil
  4056. "Matches a headline and puts TODO state into group 2 if present.
  4057. Also put tags into group 4 if tags are present.")
  4058. (defconst org-plain-time-of-day-regexp
  4059. (concat
  4060. "\\(\\<[012]?[0-9]"
  4061. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4062. "\\(--?"
  4063. "\\(\\<[012]?[0-9]"
  4064. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4065. "\\)?")
  4066. "Regular expression to match a plain time or time range.
  4067. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4068. groups carry important information:
  4069. 0 the full match
  4070. 1 the first time, range or not
  4071. 8 the second time, if it is a range.")
  4072. (defconst org-plain-time-extension-regexp
  4073. (concat
  4074. "\\(\\<[012]?[0-9]"
  4075. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4076. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4077. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4078. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4079. groups carry important information:
  4080. 0 the full match
  4081. 7 hours of duration
  4082. 9 minutes of duration")
  4083. (defconst org-stamp-time-of-day-regexp
  4084. (concat
  4085. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4086. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4087. "\\(--?"
  4088. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4089. "Regular expression to match a timestamp time or time range.
  4090. After a match, the following groups carry important information:
  4091. 0 the full match
  4092. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4093. 2 the first time, range or not
  4094. 4 the second time, if it is a range.")
  4095. (defconst org-startup-options
  4096. '(("fold" org-startup-folded t)
  4097. ("overview" org-startup-folded t)
  4098. ("nofold" org-startup-folded nil)
  4099. ("showall" org-startup-folded nil)
  4100. ("showeverything" org-startup-folded showeverything)
  4101. ("content" org-startup-folded content)
  4102. ("indent" org-startup-indented t)
  4103. ("noindent" org-startup-indented nil)
  4104. ("hidestars" org-hide-leading-stars t)
  4105. ("showstars" org-hide-leading-stars nil)
  4106. ("odd" org-odd-levels-only t)
  4107. ("oddeven" org-odd-levels-only nil)
  4108. ("align" org-startup-align-all-tables t)
  4109. ("noalign" org-startup-align-all-tables nil)
  4110. ("shrink" org-startup-shrink-all-tables t)
  4111. ("inlineimages" org-startup-with-inline-images t)
  4112. ("noinlineimages" org-startup-with-inline-images nil)
  4113. ("latexpreview" org-startup-with-latex-preview t)
  4114. ("nolatexpreview" org-startup-with-latex-preview nil)
  4115. ("customtime" org-display-custom-times t)
  4116. ("logdone" org-log-done time)
  4117. ("lognotedone" org-log-done note)
  4118. ("nologdone" org-log-done nil)
  4119. ("lognoteclock-out" org-log-note-clock-out t)
  4120. ("nolognoteclock-out" org-log-note-clock-out nil)
  4121. ("logrepeat" org-log-repeat state)
  4122. ("lognoterepeat" org-log-repeat note)
  4123. ("logdrawer" org-log-into-drawer t)
  4124. ("nologdrawer" org-log-into-drawer nil)
  4125. ("logstatesreversed" org-log-states-order-reversed t)
  4126. ("nologstatesreversed" org-log-states-order-reversed nil)
  4127. ("nologrepeat" org-log-repeat nil)
  4128. ("logreschedule" org-log-reschedule time)
  4129. ("lognotereschedule" org-log-reschedule note)
  4130. ("nologreschedule" org-log-reschedule nil)
  4131. ("logredeadline" org-log-redeadline time)
  4132. ("lognoteredeadline" org-log-redeadline note)
  4133. ("nologredeadline" org-log-redeadline nil)
  4134. ("logrefile" org-log-refile time)
  4135. ("lognoterefile" org-log-refile note)
  4136. ("nologrefile" org-log-refile nil)
  4137. ("fninline" org-footnote-define-inline t)
  4138. ("nofninline" org-footnote-define-inline nil)
  4139. ("fnlocal" org-footnote-section nil)
  4140. ("fnauto" org-footnote-auto-label t)
  4141. ("fnprompt" org-footnote-auto-label nil)
  4142. ("fnconfirm" org-footnote-auto-label confirm)
  4143. ("fnplain" org-footnote-auto-label plain)
  4144. ("fnadjust" org-footnote-auto-adjust t)
  4145. ("nofnadjust" org-footnote-auto-adjust nil)
  4146. ("constcgs" constants-unit-system cgs)
  4147. ("constSI" constants-unit-system SI)
  4148. ("noptag" org-tag-persistent-alist nil)
  4149. ("hideblocks" org-hide-block-startup t)
  4150. ("nohideblocks" org-hide-block-startup nil)
  4151. ("beamer" org-startup-with-beamer-mode t)
  4152. ("entitiespretty" org-pretty-entities t)
  4153. ("entitiesplain" org-pretty-entities nil))
  4154. "Variable associated with STARTUP options for org-mode.
  4155. Each element is a list of three items: the startup options (as written
  4156. in the #+STARTUP line), the corresponding variable, and the value to set
  4157. this variable to if the option is found. An optional forth element PUSH
  4158. means to push this value onto the list in the variable.")
  4159. (defcustom org-group-tags t
  4160. "When non-nil (the default), use group tags.
  4161. This can be turned on/off through `org-toggle-tags-groups'."
  4162. :group 'org-tags
  4163. :group 'org-startup
  4164. :type 'boolean)
  4165. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4166. (defun org-toggle-tags-groups ()
  4167. "Toggle support for group tags.
  4168. Support for group tags is controlled by the option
  4169. `org-group-tags', which is non-nil by default."
  4170. (interactive)
  4171. (setq org-group-tags (not org-group-tags))
  4172. (cond ((and (derived-mode-p 'org-agenda-mode)
  4173. org-group-tags)
  4174. (org-agenda-redo))
  4175. ((derived-mode-p 'org-mode)
  4176. (let ((org-inhibit-startup t)) (org-mode))))
  4177. (message "Groups tags support has been turned %s"
  4178. (if org-group-tags "on" "off")))
  4179. (defun org-set-regexps-and-options (&optional tags-only)
  4180. "Precompute regular expressions used in the current buffer.
  4181. When optional argument TAGS-ONLY is non-nil, only compute tags
  4182. related expressions."
  4183. (when (derived-mode-p 'org-mode)
  4184. (let ((alist (org--setup-collect-keywords
  4185. (org-make-options-regexp
  4186. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4187. (and (not tags-only)
  4188. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4189. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4190. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4191. ;; Startup options. Get this early since it does change
  4192. ;; behavior for other options (e.g., tags).
  4193. (let ((startup (cdr (assq 'startup alist))))
  4194. (dolist (option startup)
  4195. (let ((entry (assoc-string option org-startup-options t)))
  4196. (when entry
  4197. (let ((var (nth 1 entry))
  4198. (val (nth 2 entry)))
  4199. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4200. (unless (listp (symbol-value var))
  4201. (set (make-local-variable var) nil))
  4202. (add-to-list var val)))))))
  4203. (setq-local org-file-tags
  4204. (mapcar #'org-add-prop-inherited
  4205. (cdr (assq 'filetags alist))))
  4206. (setq org-current-tag-alist
  4207. (append org-tag-persistent-alist
  4208. (let ((tags (cdr (assq 'tags alist))))
  4209. (if tags (org-tag-string-to-alist tags)
  4210. org-tag-alist))))
  4211. (setq org-tag-groups-alist
  4212. (org-tag-alist-to-groups org-current-tag-alist))
  4213. (unless tags-only
  4214. ;; File properties.
  4215. (setq-local org-file-properties (cdr (assq 'property alist)))
  4216. ;; Archive location.
  4217. (let ((archive (cdr (assq 'archive alist))))
  4218. (when archive (setq-local org-archive-location archive)))
  4219. ;; Category.
  4220. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4221. (when cat
  4222. (setq-local org-category (intern cat))
  4223. (setq-local org-file-properties
  4224. (org--update-property-plist
  4225. "CATEGORY" cat org-file-properties))))
  4226. ;; Columns.
  4227. (let ((column (cdr (assq 'columns alist))))
  4228. (when column (setq-local org-columns-default-format column)))
  4229. ;; Constants.
  4230. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4231. ;; Link abbreviations.
  4232. (let ((links (cdr (assq 'link alist))))
  4233. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4234. ;; Priorities.
  4235. (let ((priorities (cdr (assq 'priorities alist))))
  4236. (when priorities
  4237. (setq-local org-highest-priority (nth 0 priorities))
  4238. (setq-local org-lowest-priority (nth 1 priorities))
  4239. (setq-local org-default-priority (nth 2 priorities))))
  4240. ;; Scripts.
  4241. (let ((scripts (assq 'scripts alist)))
  4242. (when scripts
  4243. (setq-local org-use-sub-superscripts (cdr scripts))))
  4244. ;; TODO keywords.
  4245. (setq-local org-todo-kwd-alist nil)
  4246. (setq-local org-todo-key-alist nil)
  4247. (setq-local org-todo-key-trigger nil)
  4248. (setq-local org-todo-keywords-1 nil)
  4249. (setq-local org-done-keywords nil)
  4250. (setq-local org-todo-heads nil)
  4251. (setq-local org-todo-sets nil)
  4252. (setq-local org-todo-log-states nil)
  4253. (let ((todo-sequences
  4254. (or (nreverse (cdr (assq 'todo alist)))
  4255. (let ((d (default-value 'org-todo-keywords)))
  4256. (if (not (stringp (car d))) d
  4257. ;; XXX: Backward compatibility code.
  4258. (list (cons org-todo-interpretation d)))))))
  4259. (dolist (sequence todo-sequences)
  4260. (let* ((sequence (or (run-hook-with-args-until-success
  4261. 'org-todo-setup-filter-hook sequence)
  4262. sequence))
  4263. (sequence-type (car sequence))
  4264. (keywords (cdr sequence))
  4265. (sep (member "|" keywords))
  4266. names alist)
  4267. (dolist (k (remove "|" keywords))
  4268. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4269. k)
  4270. (error "Invalid TODO keyword %s" k))
  4271. (let ((name (match-string 1 k))
  4272. (key (match-string 2 k))
  4273. (log (org-extract-log-state-settings k)))
  4274. (push name names)
  4275. (push (cons name (and key (string-to-char key))) alist)
  4276. (when log (push log org-todo-log-states))))
  4277. (let* ((names (nreverse names))
  4278. (done (if sep (org-remove-keyword-keys (cdr sep))
  4279. (last names)))
  4280. (head (car names))
  4281. (tail (list sequence-type head (car done) (org-last done))))
  4282. (add-to-list 'org-todo-heads head 'append)
  4283. (push names org-todo-sets)
  4284. (setq org-done-keywords (append org-done-keywords done nil))
  4285. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4286. (setq org-todo-key-alist
  4287. (append org-todo-key-alist
  4288. (and alist
  4289. (append '((:startgroup))
  4290. (nreverse alist)
  4291. '((:endgroup))))))
  4292. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4293. (setq org-todo-sets (nreverse org-todo-sets)
  4294. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4295. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4296. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4297. ;; Compute the regular expressions and other local variables.
  4298. ;; Using `org-outline-regexp-bol' would complicate them much,
  4299. ;; because of the fixed white space at the end of that string.
  4300. (unless org-done-keywords
  4301. (setq org-done-keywords
  4302. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4303. (setq org-not-done-keywords
  4304. (org-delete-all org-done-keywords
  4305. (copy-sequence org-todo-keywords-1))
  4306. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4307. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4308. org-not-done-heading-regexp
  4309. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4310. org-todo-line-regexp
  4311. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4312. org-complex-heading-regexp
  4313. (concat "^\\(\\*+\\)"
  4314. "\\(?: +" org-todo-regexp "\\)?"
  4315. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4316. "\\(?: +\\(.*?\\)\\)??"
  4317. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4318. "[ \t]*$")
  4319. org-complex-heading-regexp-format
  4320. (concat "^\\(\\*+\\)"
  4321. "\\(?: +" org-todo-regexp "\\)?"
  4322. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4323. "\\(?: +"
  4324. ;; Stats cookies can be stuck to body.
  4325. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4326. "\\(%s\\)"
  4327. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4328. "\\)"
  4329. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4330. "[ \t]*$")
  4331. org-todo-line-tags-regexp
  4332. (concat "^\\(\\*+\\)"
  4333. "\\(?: +" org-todo-regexp "\\)?"
  4334. "\\(?: +\\(.*?\\)\\)??"
  4335. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4336. "[ \t]*$"))
  4337. (org-compute-latex-and-related-regexp)))))
  4338. (defun org--setup-collect-keywords (regexp &optional files alist)
  4339. "Return setup keywords values as an alist.
  4340. REGEXP matches a subset of setup keywords. FILES is a list of
  4341. file names already visited. It is used to avoid circular setup
  4342. files. ALIST, when non-nil, is the alist computed so far.
  4343. Return value contains the following keys: `archive', `category',
  4344. `columns', `constants', `filetags', `link', `priorities',
  4345. `property', `scripts', `startup', `tags' and `todo'."
  4346. (org-with-wide-buffer
  4347. (goto-char (point-min))
  4348. (let ((case-fold-search t))
  4349. (while (re-search-forward regexp nil t)
  4350. (let ((element (org-element-at-point)))
  4351. (when (eq (org-element-type element) 'keyword)
  4352. (let ((key (org-element-property :key element))
  4353. (value (org-element-property :value element)))
  4354. (cond
  4355. ((equal key "ARCHIVE")
  4356. (when (org-string-nw-p value)
  4357. (push (cons 'archive value) alist)))
  4358. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4359. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4360. ((equal key "CONSTANTS")
  4361. (let* ((constants (assq 'constants alist))
  4362. (store (cdr constants)))
  4363. (dolist (pair (split-string value))
  4364. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4365. pair)
  4366. (let* ((name (match-string 1 pair))
  4367. (value (match-string 2 pair))
  4368. (old (assoc name store)))
  4369. (if old (setcdr old value)
  4370. (push (cons name value) store)))))
  4371. (if constants (setcdr constants store)
  4372. (push (cons 'constants store) alist))))
  4373. ((equal key "FILETAGS")
  4374. (when (org-string-nw-p value)
  4375. (let ((old (assq 'filetags alist))
  4376. (new (apply #'nconc
  4377. (mapcar (lambda (x) (org-split-string x ":"))
  4378. (split-string value)))))
  4379. (if old (setcdr old (append new (cdr old)))
  4380. (push (cons 'filetags new) alist)))))
  4381. ((equal key "LINK")
  4382. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4383. (let ((links (assq 'link alist))
  4384. (pair (cons (match-string-no-properties 1 value)
  4385. (match-string-no-properties 2 value))))
  4386. (if links (push pair (cdr links))
  4387. (push (list 'link pair) alist)))))
  4388. ((equal key "OPTIONS")
  4389. (when (and (org-string-nw-p value)
  4390. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4391. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4392. ((equal key "PRIORITIES")
  4393. (push (cons 'priorities
  4394. (let ((prio (split-string value)))
  4395. (if (< (length prio) 3) '(?A ?C ?B)
  4396. (mapcar #'string-to-char prio))))
  4397. alist))
  4398. ((equal key "PROPERTY")
  4399. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4400. (let* ((property (assq 'property alist))
  4401. (value (org--update-property-plist
  4402. (match-string-no-properties 1 value)
  4403. (match-string-no-properties 2 value)
  4404. (cdr property))))
  4405. (if property (setcdr property value)
  4406. (push (cons 'property value) alist)))))
  4407. ((equal key "STARTUP")
  4408. (let ((startup (assq 'startup alist)))
  4409. (if startup
  4410. (setcdr startup
  4411. (append (cdr startup) (split-string value)))
  4412. (push (cons 'startup (split-string value)) alist))))
  4413. ((equal key "TAGS")
  4414. (let ((tag-cell (assq 'tags alist)))
  4415. (if tag-cell
  4416. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4417. (push (cons 'tags value) alist))))
  4418. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4419. (let ((todo (assq 'todo alist))
  4420. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4421. (split-string value))))
  4422. (if todo (push value (cdr todo))
  4423. (push (list 'todo value) alist))))
  4424. ((equal key "SETUPFILE")
  4425. (unless buffer-read-only ; Do not check in Gnus messages.
  4426. (let ((f (and (org-string-nw-p value)
  4427. (expand-file-name
  4428. (org-unbracket-string "\"" "\"" value)))))
  4429. (when (and f (file-readable-p f) (not (member f files)))
  4430. (with-temp-buffer
  4431. (setq default-directory (file-name-directory f))
  4432. (insert-file-contents f)
  4433. (setq alist
  4434. ;; Fake Org mode to benefit from cache
  4435. ;; without recurring needlessly.
  4436. (let ((major-mode 'org-mode))
  4437. (org--setup-collect-keywords
  4438. regexp (cons f files) alist)))))))))))))))
  4439. alist)
  4440. (defun org-tag-string-to-alist (s)
  4441. "Return tag alist associated to string S.
  4442. S is a value for TAGS keyword or produced with
  4443. `org-tag-alist-to-string'. Return value is an alist suitable for
  4444. `org-tag-alist' or `org-tag-persistent-alist'."
  4445. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4446. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4447. "\\|{.+?}\\)" ; regular expression
  4448. "\\(?:(\\(.\\))\\)?\\'"))
  4449. alist group-flag)
  4450. (dolist (tokens lines (cdr (nreverse alist)))
  4451. (push '(:newline) alist)
  4452. (while tokens
  4453. (let ((token (pop tokens)))
  4454. (pcase token
  4455. ("{"
  4456. (push '(:startgroup) alist)
  4457. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4458. ("}"
  4459. (push '(:endgroup) alist)
  4460. (setq group-flag nil))
  4461. ("["
  4462. (push '(:startgrouptag) alist)
  4463. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4464. ("]"
  4465. (push '(:endgrouptag) alist)
  4466. (setq group-flag nil))
  4467. (":"
  4468. (push '(:grouptags) alist))
  4469. ((guard (string-match tag-re token))
  4470. (let ((tag (match-string 1 token))
  4471. (key (and (match-beginning 2)
  4472. (string-to-char (match-string 2 token)))))
  4473. ;; Push all tags in groups, no matter if they already
  4474. ;; appear somewhere else in the list.
  4475. (when (or group-flag (not (assoc tag alist)))
  4476. (push (cons tag key) alist))))))))))
  4477. (defun org-tag-alist-to-string (alist &optional skip-key)
  4478. "Return tag string associated to ALIST.
  4479. ALIST is an alist, as defined in `org-tag-alist' or
  4480. `org-tag-persistent-alist', or produced with
  4481. `org-tag-string-to-alist'.
  4482. Return value is a string suitable as a value for \"TAGS\"
  4483. keyword.
  4484. When optional argument SKIP-KEY is non-nil, skip selection keys
  4485. next to tags."
  4486. (mapconcat (lambda (token)
  4487. (pcase token
  4488. (`(:startgroup) "{")
  4489. (`(:endgroup) "}")
  4490. (`(:startgrouptag) "[")
  4491. (`(:endgrouptag) "]")
  4492. (`(:grouptags) ":")
  4493. (`(:newline) "\\n")
  4494. ((and
  4495. (guard (not skip-key))
  4496. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4497. (format "%s(%c)" tag key))
  4498. (`(,(and tag (pred stringp)) . ,_) tag)
  4499. (_ (user-error "Invalid tag token: %S" token))))
  4500. alist
  4501. " "))
  4502. (defun org-tag-alist-to-groups (alist)
  4503. "Return group alist from tag ALIST.
  4504. ALIST is an alist, as defined in `org-tag-alist' or
  4505. `org-tag-persistent-alist', or produced with
  4506. `org-tag-string-to-alist'. Return value is an alist following
  4507. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4508. a string, summarizing TAGS, as a list of strings."
  4509. (let (groups group-status current-group)
  4510. (dolist (token alist (nreverse groups))
  4511. (pcase token
  4512. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4513. (`(,(or :endgroup :endgrouptag))
  4514. (when (eq group-status 'append)
  4515. (push (nreverse current-group) groups))
  4516. (setq group-status nil))
  4517. (`(:grouptags) (setq group-status 'append))
  4518. ((and `(,tag . ,_) (guard group-status))
  4519. (if (eq group-status 'append) (push tag current-group)
  4520. (setq current-group (list tag))))
  4521. (_ nil)))))
  4522. (defvar org--file-cache (make-hash-table :test #'equal)
  4523. "Hash table to store contents of files referenced via a URL.
  4524. This is the cache of file URLs read using `org-file-contents'.")
  4525. (defun org-reset-file-cache ()
  4526. "Reset the cache of files downloaded by `org-file-contents'."
  4527. (clrhash org--file-cache))
  4528. (defun org-file-url-p (file)
  4529. "Non-nil if FILE is a URL."
  4530. (require 'ffap)
  4531. (string-match-p ffap-url-regexp file))
  4532. (defun org-file-contents (file &optional noerror nocache)
  4533. "Return the contents of FILE, as a string.
  4534. FILE can be a file name or URL.
  4535. If FILE is a URL, download the contents. If the URL contents are
  4536. already cached in the `org--file-cache' hash table, the download step
  4537. is skipped.
  4538. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4539. from file or URL.
  4540. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4541. is available. This option applies only if FILE is a URL."
  4542. (let* ((is-url (org-file-url-p file))
  4543. (cache (and is-url
  4544. (not nocache)
  4545. (gethash file org--file-cache))))
  4546. (cond
  4547. (cache)
  4548. (is-url
  4549. (with-current-buffer (url-retrieve-synchronously file)
  4550. (goto-char (point-min))
  4551. ;; Move point to after the url-retrieve header.
  4552. (search-forward "\n\n" nil :move)
  4553. ;; Search for the success code only in the url-retrieve header.
  4554. (if (save-excursion
  4555. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4556. ;; Update the cache `org--file-cache' and return contents.
  4557. (puthash file
  4558. (buffer-substring-no-properties (point) (point-max))
  4559. org--file-cache)
  4560. (funcall (if noerror #'message #'user-error)
  4561. "Unable to fetch file from %S"
  4562. file))))
  4563. (t
  4564. (with-temp-buffer
  4565. (condition-case nil
  4566. (progn
  4567. (insert-file-contents file)
  4568. (buffer-string))
  4569. (file-error
  4570. (funcall (if noerror #'message #'user-error)
  4571. "Unable to read file %S"
  4572. file))))))))
  4573. (defun org-extract-log-state-settings (x)
  4574. "Extract the log state setting from a TODO keyword string.
  4575. This will extract info from a string like \"WAIT(w@/!)\"."
  4576. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4577. (let ((kw (match-string 1 x))
  4578. (log1 (and (match-end 3) (match-string 3 x)))
  4579. (log2 (and (match-end 4) (match-string 4 x))))
  4580. (and (or log1 log2)
  4581. (list kw
  4582. (and log1 (if (equal log1 "!") 'time 'note))
  4583. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4584. (defun org-remove-keyword-keys (list)
  4585. "Remove a pair of parenthesis at the end of each string in LIST."
  4586. (mapcar (lambda (x)
  4587. (if (string-match "(.*)$" x)
  4588. (substring x 0 (match-beginning 0))
  4589. x))
  4590. list))
  4591. (defun org-assign-fast-keys (alist)
  4592. "Assign fast keys to a keyword-key alist.
  4593. Respect keys that are already there."
  4594. (let (new e (alt ?0))
  4595. (while (setq e (pop alist))
  4596. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4597. (cdr e)) ;; Key already assigned.
  4598. (push e new)
  4599. (let ((clist (string-to-list (downcase (car e))))
  4600. (used (append new alist)))
  4601. (when (= (car clist) ?@)
  4602. (pop clist))
  4603. (while (and clist (rassoc (car clist) used))
  4604. (pop clist))
  4605. (unless clist
  4606. (while (rassoc alt used)
  4607. (cl-incf alt)))
  4608. (push (cons (car e) (or (car clist) alt)) new))))
  4609. (nreverse new)))
  4610. ;;; Some variables used in various places
  4611. (defvar org-window-configuration nil
  4612. "Used in various places to store a window configuration.")
  4613. (defvar org-selected-window nil
  4614. "Used in various places to store a window configuration.")
  4615. (defvar org-finish-function nil
  4616. "Function to be called when `C-c C-c' is used.
  4617. This is for getting out of special buffers like capture.")
  4618. (defvar org-last-state)
  4619. ;; Defined somewhere in this file, but used before definition.
  4620. (defvar org-entities) ;; defined in org-entities.el
  4621. (defvar org-struct-menu)
  4622. (defvar org-org-menu)
  4623. (defvar org-tbl-menu)
  4624. ;;;; Define the Org mode
  4625. ;; We use a before-change function to check if a table might need
  4626. ;; an update.
  4627. (defvar org-table-may-need-update t
  4628. "Indicates that a table might need an update.
  4629. This variable is set by `org-before-change-function'.
  4630. `org-table-align' sets it back to nil.")
  4631. (defun org-before-change-function (_beg _end)
  4632. "Every change indicates that a table might need an update."
  4633. (setq org-table-may-need-update t))
  4634. (defvar org-mode-map)
  4635. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4636. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4637. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4638. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4639. (defvar org-table-buffer-is-an nil)
  4640. (defvar bidi-paragraph-direction)
  4641. (defvar buffer-face-mode-face)
  4642. (require 'outline)
  4643. ;; Other stuff we need.
  4644. (require 'time-date)
  4645. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4646. (require 'easymenu)
  4647. (autoload 'easy-menu-add "easymenu")
  4648. (require 'overlay)
  4649. ;; (require 'org-macs) moved higher up in the file before it is first used
  4650. (require 'org-entities)
  4651. ;; (require 'org-compat) moved higher up in the file before it is first used
  4652. (require 'org-faces)
  4653. (require 'org-list)
  4654. (require 'org-pcomplete)
  4655. (require 'org-src)
  4656. (require 'org-footnote)
  4657. (require 'org-macro)
  4658. ;; babel
  4659. (require 'ob)
  4660. ;;;###autoload
  4661. (define-derived-mode org-mode outline-mode "Org"
  4662. "Outline-based notes management and organizer, alias
  4663. \"Carsten's outline-mode for keeping track of everything.\"
  4664. Org mode develops organizational tasks around a NOTES file which
  4665. contains information about projects as plain text. Org mode is
  4666. implemented on top of Outline mode, which is ideal to keep the content
  4667. of large files well structured. It supports ToDo items, deadlines and
  4668. time stamps, which magically appear in the diary listing of the Emacs
  4669. calendar. Tables are easily created with a built-in table editor.
  4670. Plain text URL-like links connect to websites, emails (VM), Usenet
  4671. messages (Gnus), BBDB entries, and any files related to the project.
  4672. For printing and sharing of notes, an Org file (or a part of it)
  4673. can be exported as a structured ASCII or HTML file.
  4674. The following commands are available:
  4675. \\{org-mode-map}"
  4676. ;; Get rid of Outline menus, they are not needed
  4677. ;; Need to do this here because define-derived-mode sets up
  4678. ;; the keymap so late. Still, it is a waste to call this each time
  4679. ;; we switch another buffer into Org mode.
  4680. (define-key org-mode-map [menu-bar headings] 'undefined)
  4681. (define-key org-mode-map [menu-bar hide] 'undefined)
  4682. (define-key org-mode-map [menu-bar show] 'undefined)
  4683. (org-load-modules-maybe)
  4684. (org-install-agenda-files-menu)
  4685. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4686. (add-to-invisibility-spec '(org-hide-block . t))
  4687. (setq-local outline-regexp org-outline-regexp)
  4688. (setq-local outline-level 'org-outline-level)
  4689. (setq bidi-paragraph-direction 'left-to-right)
  4690. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4691. (unless org-display-table
  4692. (setq org-display-table (make-display-table)))
  4693. (set-display-table-slot
  4694. org-display-table 4
  4695. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4696. org-ellipsis)))
  4697. (setq buffer-display-table org-display-table))
  4698. (org-set-regexps-and-options)
  4699. (org-set-font-lock-defaults)
  4700. (when (and org-tag-faces (not org-tags-special-faces-re))
  4701. ;; tag faces set outside customize.... force initialization.
  4702. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4703. ;; Calc embedded
  4704. (setq-local calc-embedded-open-mode "# ")
  4705. ;; Modify a few syntax entries
  4706. (modify-syntax-entry ?@ "w")
  4707. (modify-syntax-entry ?\" "\"")
  4708. (modify-syntax-entry ?\\ "_")
  4709. (modify-syntax-entry ?~ "_")
  4710. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4711. ;; Activate before-change-function
  4712. (setq-local org-table-may-need-update t)
  4713. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4714. ;; Check for running clock before killing a buffer
  4715. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4716. ;; Initialize macros templates.
  4717. (org-macro-initialize-templates)
  4718. ;; Initialize radio targets.
  4719. (org-update-radio-target-regexp)
  4720. ;; Indentation.
  4721. (setq-local indent-line-function 'org-indent-line)
  4722. (setq-local indent-region-function 'org-indent-region)
  4723. ;; Filling and auto-filling.
  4724. (org-setup-filling)
  4725. ;; Comments.
  4726. (org-setup-comments-handling)
  4727. ;; Initialize cache.
  4728. (org-element-cache-reset)
  4729. ;; Beginning/end of defun
  4730. (setq-local beginning-of-defun-function 'org-backward-element)
  4731. (setq-local end-of-defun-function
  4732. (lambda ()
  4733. (if (not (org-at-heading-p))
  4734. (org-forward-element)
  4735. (org-forward-element)
  4736. (forward-char -1))))
  4737. ;; Next error for sparse trees
  4738. (setq-local next-error-function 'org-occur-next-match)
  4739. ;; Make sure dependence stuff works reliably, even for users who set it
  4740. ;; too late :-(
  4741. (if org-enforce-todo-dependencies
  4742. (add-hook 'org-blocker-hook
  4743. 'org-block-todo-from-children-or-siblings-or-parent)
  4744. (remove-hook 'org-blocker-hook
  4745. 'org-block-todo-from-children-or-siblings-or-parent))
  4746. (if org-enforce-todo-checkbox-dependencies
  4747. (add-hook 'org-blocker-hook
  4748. 'org-block-todo-from-checkboxes)
  4749. (remove-hook 'org-blocker-hook
  4750. 'org-block-todo-from-checkboxes))
  4751. ;; Align options lines
  4752. (setq-local
  4753. align-mode-rules-list
  4754. '((org-in-buffer-settings
  4755. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4756. (modes . '(org-mode)))))
  4757. ;; Imenu
  4758. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4759. ;; Make isearch reveal context
  4760. (setq-local outline-isearch-open-invisible-function
  4761. (lambda (&rest _) (org-show-context 'isearch)))
  4762. ;; Setup the pcomplete hooks
  4763. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4764. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4765. (setq-local pcomplete-default-completion-function 'ignore)
  4766. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4767. (setq-local pcomplete-termination-string "")
  4768. (setq-local buffer-face-mode-face 'org-default)
  4769. ;; If empty file that did not turn on Org mode automatically, make
  4770. ;; it to.
  4771. (when (and org-insert-mode-line-in-empty-file
  4772. (called-interactively-p 'any)
  4773. (= (point-min) (point-max)))
  4774. (insert "# -*- mode: org -*-\n\n"))
  4775. (unless org-inhibit-startup
  4776. (org-unmodified
  4777. (when org-startup-with-beamer-mode (org-beamer-mode))
  4778. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4779. (org-table-map-tables
  4780. (cond ((and org-startup-align-all-tables
  4781. org-startup-shrink-all-tables)
  4782. (lambda () (org-table-align) (org-table-shrink)))
  4783. (org-startup-align-all-tables #'org-table-align)
  4784. (t #'org-table-shrink))
  4785. t))
  4786. (when org-startup-with-inline-images (org-display-inline-images))
  4787. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4788. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4789. (when org-startup-truncated (setq truncate-lines t))
  4790. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4791. (org-refresh-effort-properties)))
  4792. ;; Try to set `org-hide' face correctly.
  4793. (let ((foreground (org-find-invisible-foreground)))
  4794. (when foreground
  4795. (set-face-foreground 'org-hide foreground))))
  4796. ;; Update `customize-package-emacs-version-alist'
  4797. (add-to-list 'customize-package-emacs-version-alist
  4798. '(Org ("8.0" . "24.4")
  4799. ("8.1" . "24.4")
  4800. ("8.2" . "24.4")
  4801. ("8.2.7" . "24.4")
  4802. ("8.3" . "26.1")
  4803. ("9.0" . "26.1")
  4804. ("9.1" . "26.1")
  4805. ("9.2" . "27.1")))
  4806. (defvar org-mode-transpose-word-syntax-table
  4807. (let ((st (make-syntax-table text-mode-syntax-table)))
  4808. (dolist (c org-emphasis-alist st)
  4809. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4810. (when (fboundp 'abbrev-table-put)
  4811. (abbrev-table-put org-mode-abbrev-table
  4812. :parents (list text-mode-abbrev-table)))
  4813. (defun org-find-invisible-foreground ()
  4814. (let ((candidates (remove
  4815. "unspecified-bg"
  4816. (nconc
  4817. (list (face-background 'default)
  4818. (face-background 'org-default))
  4819. (mapcar
  4820. (lambda (alist)
  4821. (when (boundp alist)
  4822. (cdr (assq 'background-color (symbol-value alist)))))
  4823. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4824. (list (face-foreground 'org-hide))))))
  4825. (car (remove nil candidates))))
  4826. (defun org-current-time (&optional rounding-minutes past)
  4827. "Current time, possibly rounded to ROUNDING-MINUTES.
  4828. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4829. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4830. the rounding returns a past time."
  4831. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4832. (car org-time-stamp-rounding-minutes)))
  4833. (time (decode-time)) res)
  4834. (if (< r 1)
  4835. (current-time)
  4836. (setq res
  4837. (apply 'encode-time
  4838. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4839. (nthcdr 2 time))))
  4840. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4841. (seconds-to-time (- (float-time res) (* r 60)))
  4842. res))))
  4843. (defun org-today ()
  4844. "Return today date, considering `org-extend-today-until'."
  4845. (time-to-days
  4846. (time-subtract (current-time)
  4847. (list 0 (* 3600 org-extend-today-until) 0))))
  4848. ;;;; Font-Lock stuff, including the activators
  4849. (defvar org-mouse-map (make-sparse-keymap))
  4850. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4851. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4852. (when org-mouse-1-follows-link
  4853. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4854. (when org-tab-follows-link
  4855. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  4856. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  4857. (require 'font-lock)
  4858. (defconst org-non-link-chars "]\t\n\r<>")
  4859. (defvar org-link-types-re nil
  4860. "Matches a link that has a url-like prefix like \"http:\"")
  4861. (defvar org-link-re-with-space nil
  4862. "Matches a link with spaces, optional angular brackets around it.")
  4863. (defvar org-link-re-with-space2 nil
  4864. "Matches a link with spaces, optional angular brackets around it.")
  4865. (defvar org-link-re-with-space3 nil
  4866. "Matches a link with spaces, only for internal part in bracket links.")
  4867. (defvar org-angle-link-re nil
  4868. "Matches link with angular brackets, spaces are allowed.")
  4869. (defvar org-plain-link-re nil
  4870. "Matches plain link, without spaces.")
  4871. (defvar org-bracket-link-regexp nil
  4872. "Matches a link in double brackets.")
  4873. (defvar org-bracket-link-analytic-regexp nil
  4874. "Regular expression used to analyze links.
  4875. Here is what the match groups contain after a match:
  4876. 1: http:
  4877. 2: http
  4878. 3: path
  4879. 4: [desc]
  4880. 5: desc")
  4881. (defvar org-bracket-link-analytic-regexp++ nil
  4882. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4883. (defvar org-any-link-re nil
  4884. "Regular expression matching any link.")
  4885. (defconst org-match-sexp-depth 3
  4886. "Number of stacked braces for sub/superscript matching.")
  4887. (defun org-create-multibrace-regexp (left right n)
  4888. "Create a regular expression which will match a balanced sexp.
  4889. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4890. as single character strings.
  4891. The regexp returned will match the entire expression including the
  4892. delimiters. It will also define a single group which contains the
  4893. match except for the outermost delimiters. The maximum depth of
  4894. stacked delimiters is N. Escaping delimiters is not possible."
  4895. (let* ((nothing (concat "[^" left right "]*?"))
  4896. (or "\\|")
  4897. (re nothing)
  4898. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4899. (while (> n 1)
  4900. (setq n (1- n)
  4901. re (concat re or next)
  4902. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4903. (concat left "\\(" re "\\)" right)))
  4904. (defconst org-match-substring-regexp
  4905. (concat
  4906. "\\(\\S-\\)\\([_^]\\)\\("
  4907. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4908. "\\|"
  4909. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4910. "\\|"
  4911. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4912. "The regular expression matching a sub- or superscript.")
  4913. (defconst org-match-substring-with-braces-regexp
  4914. (concat
  4915. "\\(\\S-\\)\\([_^]\\)"
  4916. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4917. "The regular expression matching a sub- or superscript, forcing braces.")
  4918. (defun org-make-link-regexps ()
  4919. "Update the link regular expressions.
  4920. This should be called after the variable `org-link-parameters' has changed."
  4921. (let ((types-re (regexp-opt (org-link-types) t)))
  4922. (setq org-link-types-re
  4923. (concat "\\`" types-re ":")
  4924. org-link-re-with-space
  4925. (concat "<?" types-re ":"
  4926. "\\([^" org-non-link-chars " ]"
  4927. "[^" org-non-link-chars "]*"
  4928. "[^" org-non-link-chars " ]\\)>?")
  4929. org-link-re-with-space2
  4930. (concat "<?" types-re ":"
  4931. "\\([^" org-non-link-chars " ]"
  4932. "[^\t\n\r]*"
  4933. "[^" org-non-link-chars " ]\\)>?")
  4934. org-link-re-with-space3
  4935. (concat "<?" types-re ":"
  4936. "\\([^" org-non-link-chars " ]"
  4937. "[^\t\n\r]*\\)")
  4938. org-angle-link-re
  4939. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  4940. types-re)
  4941. org-plain-link-re
  4942. (concat
  4943. "\\<" types-re ":"
  4944. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  4945. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  4946. org-bracket-link-regexp
  4947. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  4948. org-bracket-link-analytic-regexp
  4949. (concat
  4950. "\\[\\["
  4951. "\\(" types-re ":\\)?"
  4952. "\\([^]]+\\)"
  4953. "\\]"
  4954. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4955. "\\]")
  4956. org-bracket-link-analytic-regexp++
  4957. (concat
  4958. "\\[\\["
  4959. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  4960. "\\([^]]+\\)"
  4961. "\\]"
  4962. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4963. "\\]")
  4964. org-any-link-re
  4965. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  4966. org-angle-link-re "\\)\\|\\("
  4967. org-plain-link-re "\\)"))))
  4968. (org-make-link-regexps)
  4969. (defvar org-emph-face nil)
  4970. (defun org-do-emphasis-faces (limit)
  4971. "Run through the buffer and emphasize strings."
  4972. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4973. (car org-emphasis-regexp-components))))
  4974. (catch :exit
  4975. (while (re-search-forward quick-re limit t)
  4976. (let* ((marker (match-string 2))
  4977. (verbatim? (member marker '("~" "="))))
  4978. (when (save-excursion
  4979. (goto-char (match-beginning 0))
  4980. (and
  4981. ;; Do not match headline stars. Do not consider
  4982. ;; stars of a headline as closing marker for bold
  4983. ;; markup either.
  4984. (not (and (equal marker "*")
  4985. (save-excursion
  4986. (forward-char)
  4987. (skip-chars-backward "*")
  4988. (looking-at-p org-outline-regexp-bol))))
  4989. ;; Do not match table hlines.
  4990. (not (and (equal marker "+")
  4991. (org-match-line
  4992. "^[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4993. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4994. ;; At a table row, do not cross cell boundaries.
  4995. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4996. (string-match-p "|" (match-string 4))))))
  4997. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  4998. (font-lock-prepend-text-property
  4999. (match-beginning 2) (match-end 2) 'face face)
  5000. (when verbatim?
  5001. (org-remove-flyspell-overlays-in
  5002. (match-beginning 0) (match-end 0)))
  5003. (add-text-properties (match-beginning 2) (match-end 2)
  5004. '(font-lock-multiline t org-emphasis t))
  5005. (when org-hide-emphasis-markers
  5006. (add-text-properties (match-end 4) (match-beginning 5)
  5007. '(invisible org-link))
  5008. (add-text-properties (match-beginning 3) (match-end 3)
  5009. '(invisible org-link)))
  5010. (throw :exit t))))))))
  5011. (defun org-emphasize (&optional char)
  5012. "Insert or change an emphasis, i.e. a font like bold or italic.
  5013. If there is an active region, change that region to a new emphasis.
  5014. If there is no region, just insert the marker characters and position
  5015. the cursor between them.
  5016. CHAR should be the marker character. If it is a space, it means to
  5017. remove the emphasis of the selected region.
  5018. If CHAR is not given (for example in an interactive call) it will be
  5019. prompted for."
  5020. (interactive)
  5021. (let ((erc org-emphasis-regexp-components)
  5022. (string "") beg end move s)
  5023. (if (org-region-active-p)
  5024. (setq beg (region-beginning)
  5025. end (region-end)
  5026. string (buffer-substring beg end))
  5027. (setq move t))
  5028. (unless char
  5029. (message "Emphasis marker or tag: [%s]"
  5030. (mapconcat #'car org-emphasis-alist ""))
  5031. (setq char (read-char-exclusive)))
  5032. (if (equal char ?\s)
  5033. (setq s ""
  5034. move nil)
  5035. (unless (assoc (char-to-string char) org-emphasis-alist)
  5036. (user-error "No such emphasis marker: \"%c\"" char))
  5037. (setq s (char-to-string char)))
  5038. (while (and (> (length string) 1)
  5039. (equal (substring string 0 1) (substring string -1))
  5040. (assoc (substring string 0 1) org-emphasis-alist))
  5041. (setq string (substring string 1 -1)))
  5042. (setq string (concat s string s))
  5043. (when beg (delete-region beg end))
  5044. (unless (or (bolp)
  5045. (string-match (concat "[" (nth 0 erc) "\n]")
  5046. (char-to-string (char-before (point)))))
  5047. (insert " "))
  5048. (unless (or (eobp)
  5049. (string-match (concat "[" (nth 1 erc) "\n]")
  5050. (char-to-string (char-after (point)))))
  5051. (insert " ") (backward-char 1))
  5052. (insert string)
  5053. (and move (backward-char 1))))
  5054. (defconst org-nonsticky-props
  5055. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5056. (defsubst org-rear-nonsticky-at (pos)
  5057. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5058. (defun org-activate-links (limit)
  5059. "Add link properties to links.
  5060. This includes angle, plain, and bracket links."
  5061. (catch :exit
  5062. (while (re-search-forward org-any-link-re limit t)
  5063. (let* ((start (match-beginning 0))
  5064. (end (match-end 0))
  5065. (style (cond ((eq ?< (char-after start)) 'angle)
  5066. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5067. (t 'plain))))
  5068. (when (and (memq style org-highlight-links)
  5069. ;; Do not confuse plain links with tags.
  5070. (not (and (eq style 'plain)
  5071. (let ((face (get-text-property
  5072. (max (1- start) (point-min)) 'face)))
  5073. (if (consp face) (memq 'org-tag face)
  5074. (eq 'org-tag face))))))
  5075. (let* ((link-object (save-excursion
  5076. (goto-char start)
  5077. (save-match-data (org-element-link-parser))))
  5078. (link (org-element-property :raw-link link-object))
  5079. (type (org-element-property :type link-object))
  5080. (path (org-element-property :path link-object))
  5081. (properties ;for link's visible part
  5082. (list
  5083. 'face (pcase (org-link-get-parameter type :face)
  5084. ((and (pred functionp) face) (funcall face path))
  5085. ((and (pred facep) face) face)
  5086. ((and (pred consp) face) face) ;anonymous
  5087. (_ 'org-link))
  5088. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5089. 'highlight)
  5090. 'keymap (or (org-link-get-parameter type :keymap)
  5091. org-mouse-map)
  5092. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5093. ((and (pred stringp) echo) echo)
  5094. ((and (pred functionp) echo) echo)
  5095. (_ (concat "LINK: " link)))
  5096. 'htmlize-link (pcase (org-link-get-parameter type
  5097. :htmlize-link)
  5098. ((and (pred functionp) f) (funcall f))
  5099. (_ `(:uri ,link)))
  5100. 'font-lock-multiline t)))
  5101. (org-remove-flyspell-overlays-in start end)
  5102. (org-rear-nonsticky-at end)
  5103. (if (not (eq 'bracket style))
  5104. (add-text-properties start end properties)
  5105. ;; Handle invisible parts in bracket links.
  5106. (remove-text-properties start end '(invisible nil))
  5107. (let ((hidden
  5108. (append `(invisible
  5109. ,(or (org-link-get-parameter type :display)
  5110. 'org-link))
  5111. properties))
  5112. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5113. (visible-end (or (match-end 4) (match-end 2))))
  5114. (add-text-properties start visible-start hidden)
  5115. (add-text-properties visible-start visible-end properties)
  5116. (add-text-properties visible-end end hidden)
  5117. (org-rear-nonsticky-at visible-start)
  5118. (org-rear-nonsticky-at visible-end)))
  5119. (let ((f (org-link-get-parameter type :activate-func)))
  5120. (when (functionp f)
  5121. (funcall f start end path (eq style 'bracket))))
  5122. (throw :exit t))))) ;signal success
  5123. nil))
  5124. (defun org-activate-code (limit)
  5125. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5126. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5127. (remove-text-properties (match-beginning 0) (match-end 0)
  5128. '(display t invisible t intangible t))
  5129. t))
  5130. (defcustom org-src-fontify-natively t
  5131. "When non-nil, fontify code in code blocks.
  5132. See also the `org-block' face."
  5133. :type 'boolean
  5134. :version "26.1"
  5135. :package-version '(Org . "8.3")
  5136. :group 'org-appearance
  5137. :group 'org-babel)
  5138. (defcustom org-allow-promoting-top-level-subtree nil
  5139. "When non-nil, allow promoting a top level subtree.
  5140. The leading star of the top level headline will be replaced
  5141. by a #."
  5142. :type 'boolean
  5143. :version "24.1"
  5144. :group 'org-appearance)
  5145. (defun org-fontify-meta-lines-and-blocks (limit)
  5146. (condition-case nil
  5147. (org-fontify-meta-lines-and-blocks-1 limit)
  5148. (error (message "org-mode fontification error in %S at %d"
  5149. (current-buffer)
  5150. (line-number-at-pos)))))
  5151. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5152. "Fontify #+ lines and blocks."
  5153. (let ((case-fold-search t))
  5154. (when (re-search-forward
  5155. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5156. limit t)
  5157. (let ((beg (match-beginning 0))
  5158. (block-start (match-end 0))
  5159. (block-end nil)
  5160. (lang (match-string 7))
  5161. (beg1 (line-beginning-position 2))
  5162. (dc1 (downcase (match-string 2)))
  5163. (dc3 (downcase (match-string 3)))
  5164. end end1 quoting block-type)
  5165. (cond
  5166. ((and (match-end 4) (equal dc3 "+begin"))
  5167. ;; Truly a block
  5168. (setq block-type (downcase (match-string 5))
  5169. quoting (member block-type org-protecting-blocks))
  5170. (when (re-search-forward
  5171. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5172. nil t) ;; on purpose, we look further than LIMIT
  5173. (setq end (min (point-max) (match-end 0))
  5174. end1 (min (point-max) (1- (match-beginning 0))))
  5175. (setq block-end (match-beginning 0))
  5176. (when quoting
  5177. (org-remove-flyspell-overlays-in beg1 end1)
  5178. (remove-text-properties beg end
  5179. '(display t invisible t intangible t)))
  5180. (add-text-properties
  5181. beg end '(font-lock-fontified t font-lock-multiline t))
  5182. (add-text-properties beg beg1 '(face org-meta-line))
  5183. (org-remove-flyspell-overlays-in beg beg1)
  5184. (add-text-properties ; For end_src
  5185. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5186. (org-remove-flyspell-overlays-in end1 end)
  5187. (cond
  5188. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5189. (org-src-font-lock-fontify-block lang block-start block-end)
  5190. (add-text-properties beg1 block-end '(src-block t)))
  5191. (quoting
  5192. (add-text-properties beg1 (min (point-max) (1+ end1))
  5193. (list 'face
  5194. (list :inherit
  5195. (let ((face-name
  5196. (intern (format "org-block-%s" lang))))
  5197. (append (and (facep face-name) (list face-name))
  5198. '(org-block))))))) ; end of source block
  5199. ((not org-fontify-quote-and-verse-blocks))
  5200. ((string= block-type "quote")
  5201. (add-face-text-property
  5202. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5203. ((string= block-type "verse")
  5204. (add-face-text-property
  5205. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5206. (add-text-properties beg beg1 '(face org-block-begin-line))
  5207. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5208. '(face org-block-end-line))
  5209. t))
  5210. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5211. (org-remove-flyspell-overlays-in
  5212. (match-beginning 0)
  5213. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5214. (add-text-properties
  5215. beg (match-end 3)
  5216. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5217. '(font-lock-fontified t invisible t)
  5218. '(font-lock-fontified t face org-document-info-keyword)))
  5219. (add-text-properties
  5220. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5221. (if (string-equal dc1 "+title:")
  5222. '(font-lock-fontified t face org-document-title)
  5223. '(font-lock-fontified t face org-document-info))))
  5224. ((string-prefix-p "+caption" dc1)
  5225. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5226. (remove-text-properties (match-beginning 0) (match-end 0)
  5227. '(display t invisible t intangible t))
  5228. ;; Handle short captions.
  5229. (save-excursion
  5230. (beginning-of-line)
  5231. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5232. (add-text-properties (line-beginning-position) (match-end 1)
  5233. '(font-lock-fontified t face org-meta-line))
  5234. (add-text-properties (match-end 0) (line-end-position)
  5235. '(font-lock-fontified t face org-block))
  5236. t)
  5237. ((member dc3 '(" " ""))
  5238. (org-remove-flyspell-overlays-in beg (match-end 0))
  5239. (add-text-properties
  5240. beg (match-end 0)
  5241. '(font-lock-fontified t face font-lock-comment-face)))
  5242. (t ;; just any other in-buffer setting, but not indented
  5243. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5244. (remove-text-properties (match-beginning 0) (match-end 0)
  5245. '(display t invisible t intangible t))
  5246. (add-text-properties beg (match-end 0)
  5247. '(font-lock-fontified t face org-meta-line))
  5248. t))))))
  5249. (defun org-fontify-drawers (limit)
  5250. "Fontify drawers."
  5251. (when (re-search-forward org-drawer-regexp limit t)
  5252. (add-text-properties
  5253. (match-beginning 0) (match-end 0)
  5254. '(font-lock-fontified t face org-special-keyword))
  5255. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5256. t))
  5257. (defun org-fontify-macros (limit)
  5258. "Fontify macros."
  5259. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5260. (add-text-properties
  5261. (match-beginning 0) (match-end 0)
  5262. '(font-lock-fontified t face org-macro))
  5263. (when org-hide-macro-markers
  5264. (add-text-properties (match-end 2) (match-beginning 2)
  5265. '(invisible t))
  5266. (add-text-properties (match-beginning 1) (match-end 1)
  5267. '(invisible t)))
  5268. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5269. t))
  5270. (defun org-activate-footnote-links (limit)
  5271. "Add text properties for footnotes."
  5272. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5273. (when fn
  5274. (let* ((beg (nth 1 fn))
  5275. (end (nth 2 fn))
  5276. (label (car fn))
  5277. (referencep (/= (line-beginning-position) beg)))
  5278. (when (and referencep (nth 3 fn))
  5279. (save-excursion
  5280. (goto-char beg)
  5281. (search-forward (or label "fn:"))
  5282. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5283. (add-text-properties beg end
  5284. (list 'mouse-face 'highlight
  5285. 'keymap org-mouse-map
  5286. 'help-echo
  5287. (if referencep "Footnote reference"
  5288. "Footnote definition")
  5289. 'font-lock-fontified t
  5290. 'font-lock-multiline t
  5291. 'face 'org-footnote))))))
  5292. (defun org-activate-dates (limit)
  5293. "Add text properties for dates."
  5294. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5295. (not (equal (char-before (match-beginning 0)) 91)))
  5296. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5297. (add-text-properties (match-beginning 0) (match-end 0)
  5298. (list 'mouse-face 'highlight
  5299. 'keymap org-mouse-map))
  5300. (org-rear-nonsticky-at (match-end 0))
  5301. (when org-display-custom-times
  5302. ;; If it's a date range, activate custom time for second date.
  5303. (when (match-end 3)
  5304. (org-display-custom-time (match-beginning 3) (match-end 3)))
  5305. (org-display-custom-time (match-beginning 1) (match-end 1)))
  5306. t))
  5307. (defvar-local org-target-link-regexp nil
  5308. "Regular expression matching radio targets in plain text.")
  5309. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5310. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5311. border border border))
  5312. "Regular expression matching a link target.")
  5313. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5314. "Regular expression matching a radio target.")
  5315. (defconst org-any-target-regexp
  5316. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5317. "Regular expression matching any target.")
  5318. (defun org-activate-target-links (limit)
  5319. "Add text properties for target matches."
  5320. (when org-target-link-regexp
  5321. (let ((case-fold-search t))
  5322. (when (re-search-forward org-target-link-regexp limit t)
  5323. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5324. (add-text-properties (match-beginning 1) (match-end 1)
  5325. (list 'mouse-face 'highlight
  5326. 'keymap org-mouse-map
  5327. 'help-echo "Radio target link"
  5328. 'org-linked-text t))
  5329. (org-rear-nonsticky-at (match-end 1))
  5330. t))))
  5331. (defun org-update-radio-target-regexp ()
  5332. "Find all radio targets in this file and update the regular expression.
  5333. Also refresh fontification if needed."
  5334. (interactive)
  5335. (let ((old-regexp org-target-link-regexp)
  5336. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5337. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5338. (targets
  5339. (org-with-wide-buffer
  5340. (goto-char (point-min))
  5341. (let (rtn)
  5342. (while (re-search-forward org-radio-target-regexp nil t)
  5343. ;; Make sure point is really within the object.
  5344. (backward-char)
  5345. (let ((obj (org-element-context)))
  5346. (when (eq (org-element-type obj) 'radio-target)
  5347. (cl-pushnew (org-element-property :value obj) rtn
  5348. :test #'equal))))
  5349. rtn))))
  5350. (setq org-target-link-regexp
  5351. (and targets
  5352. (concat before-re
  5353. (mapconcat
  5354. (lambda (x)
  5355. (replace-regexp-in-string
  5356. " +" "\\s-+" (regexp-quote x) t t))
  5357. targets
  5358. "\\|")
  5359. after-re)))
  5360. (unless (equal old-regexp org-target-link-regexp)
  5361. ;; Clean-up cache.
  5362. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5363. ((not org-target-link-regexp) old-regexp)
  5364. (t
  5365. (concat before-re
  5366. (mapconcat
  5367. (lambda (re)
  5368. (substring re (length before-re)
  5369. (- (length after-re))))
  5370. (list old-regexp org-target-link-regexp)
  5371. "\\|")
  5372. after-re)))))
  5373. (org-with-wide-buffer
  5374. (goto-char (point-min))
  5375. (while (re-search-forward regexp nil t)
  5376. (org-element-cache-refresh (match-beginning 1)))))
  5377. ;; Re fontify buffer.
  5378. (when (memq 'radio org-highlight-links)
  5379. (org-restart-font-lock)))))
  5380. (defvar org-latex-and-related-regexp nil
  5381. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5382. (defun org-compute-latex-and-related-regexp ()
  5383. "Compute regular expression for LaTeX, entities and sub/superscript.
  5384. Result depends on variable `org-highlight-latex-and-related'."
  5385. (setq-local
  5386. org-latex-and-related-regexp
  5387. (let* ((re-sub
  5388. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5389. ((eq org-use-sub-superscripts '{})
  5390. (list org-match-substring-with-braces-regexp))
  5391. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5392. (re-latex
  5393. (when (memq 'latex org-highlight-latex-and-related)
  5394. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5395. (delq nil
  5396. (mapcar (lambda (x)
  5397. (and (member (car x) matchers) (nth 1 x)))
  5398. org-latex-regexps)))))
  5399. (re-entities
  5400. (when (memq 'entities org-highlight-latex-and-related)
  5401. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5402. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5403. (defun org-do-latex-and-related (limit)
  5404. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5405. LIMIT bounds the search for syntax to highlight. Stop at first
  5406. highlighted object, if any. Return t if some highlighting was
  5407. done, nil otherwise."
  5408. (when (org-string-nw-p org-latex-and-related-regexp)
  5409. (catch 'found
  5410. (while (re-search-forward org-latex-and-related-regexp limit t)
  5411. (unless
  5412. (cl-some
  5413. (lambda (f)
  5414. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5415. (save-excursion
  5416. (goto-char (1+ (match-beginning 0)))
  5417. (face-at-point nil t)))
  5418. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5419. '(?_ ?^))
  5420. 1
  5421. 0)))
  5422. (font-lock-prepend-text-property
  5423. (+ offset (match-beginning 0)) (match-end 0)
  5424. 'face 'org-latex-and-related)
  5425. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5426. '(font-lock-multiline t)))
  5427. (throw 'found t)))
  5428. nil)))
  5429. (defun org-restart-font-lock ()
  5430. "Restart `font-lock-mode', to force refontification."
  5431. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5432. (font-lock-mode -1)
  5433. (font-lock-mode 1)))
  5434. (defun org-activate-tags (limit)
  5435. (when (re-search-forward
  5436. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5437. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5438. (add-text-properties (match-beginning 1) (match-end 1)
  5439. (list 'mouse-face 'highlight
  5440. 'keymap org-mouse-map))
  5441. (org-rear-nonsticky-at (match-end 1))
  5442. t))
  5443. (defun org-outline-level ()
  5444. "Compute the outline level of the heading at point.
  5445. If this is called at a normal headline, the level is the number
  5446. of stars. Use `org-reduced-level' to remove the effect of
  5447. `org-odd-levels'. Unlike to `org-current-level', this function
  5448. takes into consideration inlinetasks."
  5449. (org-with-wide-buffer
  5450. (end-of-line)
  5451. (if (re-search-backward org-outline-regexp-bol nil t)
  5452. (1- (- (match-end 0) (match-beginning 0)))
  5453. 0)))
  5454. (defvar org-font-lock-keywords nil)
  5455. (defsubst org-re-property (property &optional literal allow-null value)
  5456. "Return a regexp matching a PROPERTY line.
  5457. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5458. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5459. non-nil, match properties even without a value.
  5460. Match group 3 is set to the value when it exists. If there is no
  5461. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5462. With optional argument VALUE, match only property lines with
  5463. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5464. unless LITERAL is non-nil."
  5465. (concat
  5466. "^\\(?4:[ \t]*\\)"
  5467. (format "\\(?1::\\(?2:%s\\):\\)"
  5468. (if literal property (regexp-quote property)))
  5469. (cond (value
  5470. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5471. (if literal value (regexp-quote value))))
  5472. (allow-null
  5473. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5474. (t
  5475. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5476. (defconst org-property-re
  5477. (org-re-property "\\S-+" 'literal t)
  5478. "Regular expression matching a property line.
  5479. There are four matching groups:
  5480. 1: :PROPKEY: including the leading and trailing colon,
  5481. 2: PROPKEY without the leading and trailing colon,
  5482. 3: PROPVAL without leading or trailing spaces,
  5483. 4: the indentation of the current line,
  5484. 5: trailing whitespace.")
  5485. (defvar org-font-lock-hook nil
  5486. "Functions to be called for special font lock stuff.")
  5487. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5488. (defvar org-font-lock-set-keywords-hook nil
  5489. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5490. This is called after `org-font-lock-extra-keywords' is defined, but before
  5491. it is installed to be used by font lock. This can be useful if something
  5492. needs to be inserted at a specific position in the font-lock sequence.")
  5493. (defun org-font-lock-hook (limit)
  5494. "Run `org-font-lock-hook' within LIMIT."
  5495. (run-hook-with-args 'org-font-lock-hook limit))
  5496. (defun org-set-font-lock-defaults ()
  5497. "Set font lock defaults for the current buffer."
  5498. (let* ((em org-fontify-emphasized-text)
  5499. (lk org-highlight-links)
  5500. (org-font-lock-extra-keywords
  5501. (list
  5502. ;; Call the hook
  5503. '(org-font-lock-hook)
  5504. ;; Headlines
  5505. `(,(if org-fontify-whole-heading-line
  5506. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5507. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5508. (1 (org-get-level-face 1))
  5509. (2 (org-get-level-face 2))
  5510. (3 (org-get-level-face 3)))
  5511. ;; Table lines
  5512. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5513. (1 'org-table t))
  5514. ;; Table internals
  5515. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5516. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5517. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5518. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5519. ;; Drawers
  5520. '(org-fontify-drawers)
  5521. ;; Properties
  5522. (list org-property-re
  5523. '(1 'org-special-keyword t)
  5524. '(3 'org-property-value t))
  5525. ;; Link related fontification.
  5526. '(org-activate-links)
  5527. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5528. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5529. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5530. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5531. ;; Targets.
  5532. (list org-any-target-regexp '(0 'org-target t))
  5533. ;; Diary sexps.
  5534. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5535. ;; Macro
  5536. '(org-fontify-macros)
  5537. ;; TODO keyword
  5538. (list (format org-heading-keyword-regexp-format
  5539. org-todo-regexp)
  5540. '(2 (org-get-todo-face 2) t))
  5541. ;; DONE
  5542. (if org-fontify-done-headline
  5543. (list (format org-heading-keyword-regexp-format
  5544. (concat
  5545. "\\(?:"
  5546. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5547. "\\)"))
  5548. '(2 'org-headline-done t))
  5549. nil)
  5550. ;; Priorities
  5551. '(org-font-lock-add-priority-faces)
  5552. ;; Tags
  5553. '(org-font-lock-add-tag-faces)
  5554. ;; Tags groups
  5555. (when (and org-group-tags org-tag-groups-alist)
  5556. (list (concat org-outline-regexp-bol ".+\\(:"
  5557. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5558. ":\\).*$")
  5559. '(1 'org-tag-group prepend)))
  5560. ;; Special keywords
  5561. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5562. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5563. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5564. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5565. ;; Emphasis
  5566. (when em '(org-do-emphasis-faces))
  5567. ;; Checkboxes
  5568. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5569. 1 'org-checkbox prepend)
  5570. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5571. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5572. (0 (org-get-checkbox-statistics-face) t)))
  5573. ;; Description list items
  5574. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5575. 1 'org-list-dt prepend)
  5576. ;; ARCHIVEd headings
  5577. (list (concat
  5578. org-outline-regexp-bol
  5579. "\\(.*:" org-archive-tag ":.*\\)")
  5580. '(1 'org-archived prepend))
  5581. ;; Specials
  5582. '(org-do-latex-and-related)
  5583. '(org-fontify-entities)
  5584. '(org-raise-scripts)
  5585. ;; Code
  5586. '(org-activate-code (1 'org-code t))
  5587. ;; COMMENT
  5588. (list (format
  5589. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5590. org-todo-regexp
  5591. org-comment-string)
  5592. '(9 'org-special-keyword t))
  5593. ;; Blocks and meta lines
  5594. '(org-fontify-meta-lines-and-blocks))))
  5595. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5596. (run-hooks 'org-font-lock-set-keywords-hook)
  5597. ;; Now set the full font-lock-keywords
  5598. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5599. (setq-local font-lock-defaults
  5600. '(org-font-lock-keywords t nil nil backward-paragraph))
  5601. (kill-local-variable 'font-lock-keywords)
  5602. nil))
  5603. (defun org-toggle-pretty-entities ()
  5604. "Toggle the composition display of entities as UTF8 characters."
  5605. (interactive)
  5606. (setq-local org-pretty-entities (not org-pretty-entities))
  5607. (org-restart-font-lock)
  5608. (if org-pretty-entities
  5609. (message "Entities are now displayed as UTF8 characters")
  5610. (save-restriction
  5611. (widen)
  5612. (decompose-region (point-min) (point-max))
  5613. (message "Entities are now displayed as plain text"))))
  5614. (defvar-local org-custom-properties-overlays nil
  5615. "List of overlays used for custom properties.")
  5616. (defun org-toggle-custom-properties-visibility ()
  5617. "Display or hide properties in `org-custom-properties'."
  5618. (interactive)
  5619. (if org-custom-properties-overlays
  5620. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5621. (setq org-custom-properties-overlays nil))
  5622. (when org-custom-properties
  5623. (org-with-wide-buffer
  5624. (goto-char (point-min))
  5625. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5626. (while (re-search-forward regexp nil t)
  5627. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5628. (when (and end (< (point) end))
  5629. ;; Hide first custom property in current drawer.
  5630. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5631. (overlay-put o 'invisible t)
  5632. (overlay-put o 'org-custom-property t)
  5633. (push o org-custom-properties-overlays))
  5634. ;; Hide additional custom properties in the same drawer.
  5635. (while (re-search-forward regexp end t)
  5636. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5637. (overlay-put o 'invisible t)
  5638. (overlay-put o 'org-custom-property t)
  5639. (push o org-custom-properties-overlays)))))
  5640. ;; Each entry is limited to a single property drawer.
  5641. (outline-next-heading)))))))
  5642. (defun org-fontify-entities (limit)
  5643. "Find an entity to fontify."
  5644. (let (ee)
  5645. (when org-pretty-entities
  5646. (catch 'match
  5647. ;; "\_ "-family is left out on purpose. Only the first one,
  5648. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5649. ;; confusing when adding a second white space character.
  5650. (while (re-search-forward
  5651. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5652. limit t)
  5653. (when (and (not (org-at-comment-p))
  5654. (setq ee (org-entity-get (match-string 1)))
  5655. (= (length (nth 6 ee)) 1))
  5656. (let* ((end (if (equal (match-string 2) "{}")
  5657. (match-end 2)
  5658. (match-end 1))))
  5659. (add-text-properties
  5660. (match-beginning 0) end
  5661. (list 'font-lock-fontified t))
  5662. (compose-region (match-beginning 0) end
  5663. (nth 6 ee) nil)
  5664. (backward-char 1)
  5665. (throw 'match t))))
  5666. nil))))
  5667. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5668. "Fontify string S like in Org mode."
  5669. (with-temp-buffer
  5670. (insert s)
  5671. (let ((org-odd-levels-only odd-levels))
  5672. (org-mode)
  5673. (org-font-lock-ensure)
  5674. (buffer-string))))
  5675. (defvar org-m nil)
  5676. (defvar org-l nil)
  5677. (defvar org-f nil)
  5678. (defun org-get-level-face (n)
  5679. "Get the right face for match N in font-lock matching of headlines."
  5680. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5681. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5682. (if org-cycle-level-faces
  5683. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5684. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5685. (cond
  5686. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5687. ((eq n 2) org-f)
  5688. (t (unless org-level-color-stars-only org-f))))
  5689. (defun org-face-from-face-or-color (context inherit face-or-color)
  5690. "Create a face list that inherits INHERIT, but sets the foreground color.
  5691. When FACE-OR-COLOR is not a string, just return it."
  5692. (if (stringp face-or-color)
  5693. (list :inherit inherit
  5694. (cdr (assoc context org-faces-easy-properties))
  5695. face-or-color)
  5696. face-or-color))
  5697. (defun org-get-todo-face (kwd)
  5698. "Get the right face for a TODO keyword KWD.
  5699. If KWD is a number, get the corresponding match group."
  5700. (when (numberp kwd) (setq kwd (match-string kwd)))
  5701. (or (org-face-from-face-or-color
  5702. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5703. (and (member kwd org-done-keywords) 'org-done)
  5704. 'org-todo))
  5705. (defun org-get-priority-face (priority)
  5706. "Get the right face for PRIORITY.
  5707. PRIORITY is a character."
  5708. (or (org-face-from-face-or-color
  5709. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5710. 'org-priority))
  5711. (defun org-get-tag-face (tag)
  5712. "Get the right face for TAG.
  5713. If TAG is a number, get the corresponding match group."
  5714. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5715. (or (org-face-from-face-or-color
  5716. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5717. 'org-tag)))
  5718. (defun org-font-lock-add-priority-faces (limit)
  5719. "Add the special priority faces."
  5720. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5721. (add-text-properties
  5722. (match-beginning 1) (match-end 1)
  5723. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5724. 'font-lock-fontified t))))
  5725. (defun org-font-lock-add-tag-faces (limit)
  5726. "Add the special tag faces."
  5727. (when (and org-tag-faces org-tags-special-faces-re)
  5728. (while (re-search-forward org-tags-special-faces-re limit t)
  5729. (add-text-properties (match-beginning 1) (match-end 1)
  5730. (list 'face (org-get-tag-face 1)
  5731. 'font-lock-fontified t))
  5732. (backward-char 1))))
  5733. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5734. "Remove fontification and activation overlays from links."
  5735. (font-lock-default-unfontify-region beg end)
  5736. (let* ((buffer-undo-list t)
  5737. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5738. (inhibit-modification-hooks t)
  5739. deactivate-mark buffer-file-name buffer-file-truename)
  5740. (decompose-region beg end)
  5741. (remove-text-properties beg end
  5742. '(mouse-face t keymap t org-linked-text t
  5743. invisible t intangible t
  5744. org-emphasis t))
  5745. (org-remove-font-lock-display-properties beg end)))
  5746. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5747. ((raise 0.3) (height 0.7))
  5748. ((raise -0.5))
  5749. ((raise 0.5)))
  5750. "Display properties for showing superscripts and subscripts.")
  5751. (defun org-remove-font-lock-display-properties (beg end)
  5752. "Remove specific display properties that have been added by font lock.
  5753. The will remove the raise properties that are used to show superscripts
  5754. and subscripts."
  5755. (let (next prop)
  5756. (while (< beg end)
  5757. (setq next (next-single-property-change beg 'display nil end)
  5758. prop (get-text-property beg 'display))
  5759. (when (member prop org-script-display)
  5760. (put-text-property beg next 'display nil))
  5761. (setq beg next))))
  5762. (defun org-raise-scripts (limit)
  5763. "Add raise properties to sub/superscripts."
  5764. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5765. (re-search-forward
  5766. (if (eq org-use-sub-superscripts t)
  5767. org-match-substring-regexp
  5768. org-match-substring-with-braces-regexp)
  5769. limit t))
  5770. (let* ((pos (point)) table-p comment-p
  5771. (mpos (match-beginning 3))
  5772. (emph-p (get-text-property mpos 'org-emphasis))
  5773. (link-p (get-text-property mpos 'mouse-face))
  5774. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5775. (goto-char (point-at-bol))
  5776. (setq table-p (looking-at-p org-table-dataline-regexp)
  5777. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5778. (goto-char pos)
  5779. ;; Handle a_b^c
  5780. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5781. (unless (or comment-p emph-p link-p keyw-p)
  5782. (put-text-property (match-beginning 3) (match-end 0)
  5783. 'display
  5784. (if (equal (char-after (match-beginning 2)) ?^)
  5785. (nth (if table-p 3 1) org-script-display)
  5786. (nth (if table-p 2 0) org-script-display)))
  5787. (add-text-properties (match-beginning 2) (match-end 2)
  5788. (list 'invisible t))
  5789. (when (and (eq (char-after (match-beginning 3)) ?{)
  5790. (eq (char-before (match-end 3)) ?}))
  5791. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5792. (list 'invisible t))
  5793. (add-text-properties (1- (match-end 3)) (match-end 3)
  5794. (list 'invisible t))))
  5795. t)))
  5796. ;;;; Visibility cycling, including org-goto and indirect buffer
  5797. ;;; Cycling
  5798. (defvar-local org-cycle-global-status nil)
  5799. (put 'org-cycle-global-status 'org-state t)
  5800. (defvar-local org-cycle-subtree-status nil)
  5801. (put 'org-cycle-subtree-status 'org-state t)
  5802. (defvar org-inlinetask-min-level)
  5803. (defun org-unlogged-message (&rest args)
  5804. "Display a message, but avoid logging it in the *Messages* buffer."
  5805. (let ((message-log-max nil))
  5806. (apply 'message args)))
  5807. ;;;###autoload
  5808. (defun org-cycle (&optional arg)
  5809. "TAB-action and visibility cycling for Org mode.
  5810. This is the command invoked in Org mode by the `TAB' key. Its main
  5811. purpose is outline visibility cycling, but it also invokes other actions
  5812. in special contexts.
  5813. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5814. the entire
  5815. buffer through 3 states (global cycling)
  5816. 1. OVERVIEW: Show only top-level headlines.
  5817. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5818. 3. SHOW ALL: Show everything.
  5819. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5820. switch to the startup visibility,
  5821. determined by the variable `org-startup-folded', and by any VISIBILITY
  5822. properties in the buffer.
  5823. With a `\\[universal-argument] \\[universal-argument] \
  5824. \\[universal-argument]' prefix argument, show the entire buffer, including
  5825. any drawers.
  5826. When inside a table, re-align the table and move to the next field.
  5827. When point is at the beginning of a headline, rotate the subtree started
  5828. by this line through 3 different states (local cycling)
  5829. 1. FOLDED: Only the main headline is shown.
  5830. 2. CHILDREN: The main headline and the direct children are shown.
  5831. From this state, you can move to one of the children
  5832. and zoom in further.
  5833. 3. SUBTREE: Show the entire subtree, including body text.
  5834. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5835. When point is at the beginning of an empty headline and the variable
  5836. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5837. of the headline by demoting and promoting it to likely levels. This
  5838. speeds up creation document structure by pressing `TAB' once or several
  5839. times right after creating a new headline.
  5840. When there is a numeric prefix, go up to a heading with level ARG, do
  5841. a `show-subtree' and return to the previous cursor position. If ARG
  5842. is negative, go up that many levels.
  5843. When point is not at the beginning of a headline, execute the global
  5844. binding for `TAB', which is re-indenting the line. See the option
  5845. `org-cycle-emulate-tab' for details.
  5846. As a special case, if point is at the beginning of the buffer and there is
  5847. no headline in line 1, this function will act as if called with prefix arg
  5848. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  5849. prefix arg, but only
  5850. if the variable `org-cycle-global-at-bob' is t."
  5851. (interactive "P")
  5852. (org-load-modules-maybe)
  5853. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5854. (and org-cycle-level-after-item/entry-creation
  5855. (or (org-cycle-level)
  5856. (org-cycle-item-indentation))))
  5857. (let* ((limit-level
  5858. (or org-cycle-max-level
  5859. (and (boundp 'org-inlinetask-min-level)
  5860. org-inlinetask-min-level
  5861. (1- org-inlinetask-min-level))))
  5862. (nstars (and limit-level
  5863. (if org-odd-levels-only
  5864. (and limit-level (1- (* limit-level 2)))
  5865. limit-level)))
  5866. (org-outline-regexp
  5867. (if (not (derived-mode-p 'org-mode))
  5868. outline-regexp
  5869. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5870. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5871. (not (looking-at org-outline-regexp))))
  5872. (org-cycle-hook
  5873. (if bob-special
  5874. (delq 'org-optimize-window-after-visibility-change
  5875. (copy-sequence org-cycle-hook))
  5876. org-cycle-hook))
  5877. (pos (point)))
  5878. (cond
  5879. ((equal arg '(16))
  5880. (setq last-command 'dummy)
  5881. (org-set-startup-visibility)
  5882. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5883. ((equal arg '(64))
  5884. (outline-show-all)
  5885. (org-unlogged-message "Entire buffer visible, including drawers"))
  5886. ((equal arg '(4)) (org-cycle-internal-global))
  5887. ;; Try hiding block at point.
  5888. ((org-hide-block-toggle-maybe))
  5889. ;; Try cdlatex TAB completion
  5890. ((org-try-cdlatex-tab))
  5891. ;; Table: enter it or move to the next field.
  5892. ((org-at-table-p 'any)
  5893. (if (org-at-table.el-p)
  5894. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  5895. Use `\\[org-edit-special]' to edit table.el tables"))
  5896. (if arg (org-table-edit-field t)
  5897. (org-table-justify-field-maybe)
  5898. (call-interactively 'org-table-next-field))))
  5899. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  5900. ;; Global cycling: delegate to `org-cycle-internal-global'.
  5901. (bob-special (org-cycle-internal-global))
  5902. ;; Drawers: delegate to `org-flag-drawer'.
  5903. ((save-excursion
  5904. (beginning-of-line 1)
  5905. (looking-at org-drawer-regexp))
  5906. (org-flag-drawer ; toggle block visibility
  5907. (not (get-char-property (match-end 0) 'invisible))))
  5908. ;; Show-subtree, ARG levels up from here.
  5909. ((integerp arg)
  5910. (save-excursion
  5911. (org-back-to-heading)
  5912. (outline-up-heading (if (< arg 0) (- arg)
  5913. (- (funcall outline-level) arg)))
  5914. (org-show-subtree)))
  5915. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5916. ((and (featurep 'org-inlinetask)
  5917. (org-inlinetask-at-task-p)
  5918. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5919. (org-inlinetask-toggle-visibility))
  5920. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5921. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  5922. (save-excursion (move-beginning-of-line 1)
  5923. (looking-at org-outline-regexp)))
  5924. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5925. (org-cycle-internal-local))
  5926. ;; From there: TAB emulation and template completion.
  5927. (buffer-read-only (org-back-to-heading))
  5928. ((run-hook-with-args-until-success
  5929. 'org-tab-after-check-for-cycling-hook))
  5930. ((org-try-structure-completion))
  5931. ((run-hook-with-args-until-success
  5932. 'org-tab-before-tab-emulation-hook))
  5933. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5934. (or (not (bolp))
  5935. (not (looking-at org-outline-regexp))))
  5936. (call-interactively (global-key-binding "\t")))
  5937. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  5938. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5939. (or (and (eq org-cycle-emulate-tab 'white)
  5940. (= (match-end 0) (point-at-eol)))
  5941. (and (eq org-cycle-emulate-tab 'whitestart)
  5942. (>= (match-end 0) pos))))
  5943. t
  5944. (eq org-cycle-emulate-tab t))
  5945. (call-interactively (global-key-binding "\t")))
  5946. (t (save-excursion
  5947. (org-back-to-heading)
  5948. (org-cycle)))))))
  5949. (defun org-cycle-internal-global ()
  5950. "Do the global cycling action."
  5951. ;; Hack to avoid display of messages for .org attachments in Gnus
  5952. (let ((ga (string-match "\\*fontification" (buffer-name))))
  5953. (cond
  5954. ((and (eq last-command this-command)
  5955. (eq org-cycle-global-status 'overview))
  5956. ;; We just created the overview - now do table of contents
  5957. ;; This can be slow in very large buffers, so indicate action
  5958. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5959. (unless ga (org-unlogged-message "CONTENTS..."))
  5960. (org-content)
  5961. (unless ga (org-unlogged-message "CONTENTS...done"))
  5962. (setq org-cycle-global-status 'contents)
  5963. (run-hook-with-args 'org-cycle-hook 'contents))
  5964. ((and (eq last-command this-command)
  5965. (eq org-cycle-global-status 'contents))
  5966. ;; We just showed the table of contents - now show everything
  5967. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5968. (outline-show-all)
  5969. (unless ga (org-unlogged-message "SHOW ALL"))
  5970. (setq org-cycle-global-status 'all)
  5971. (run-hook-with-args 'org-cycle-hook 'all))
  5972. (t
  5973. ;; Default action: go to overview
  5974. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5975. (org-overview)
  5976. (unless ga (org-unlogged-message "OVERVIEW"))
  5977. (setq org-cycle-global-status 'overview)
  5978. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5979. (defvar org-called-with-limited-levels nil
  5980. "Non-nil when `org-with-limited-levels' is currently active.")
  5981. (defun org-cycle-internal-local ()
  5982. "Do the local cycling action."
  5983. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5984. ;; First, determine end of headline (EOH), end of subtree or item
  5985. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5986. (save-excursion
  5987. (if (org-at-item-p)
  5988. (progn
  5989. (beginning-of-line)
  5990. (setq struct (org-list-struct))
  5991. (setq eoh (point-at-eol))
  5992. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5993. (setq has-children (org-list-has-child-p (point) struct)))
  5994. (org-back-to-heading)
  5995. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5996. (setq eos (save-excursion (org-end-of-subtree t t)
  5997. (when (bolp) (backward-char)) (point)))
  5998. (setq has-children
  5999. (or (save-excursion
  6000. (let ((level (funcall outline-level)))
  6001. (outline-next-heading)
  6002. (and (org-at-heading-p t)
  6003. (> (funcall outline-level) level))))
  6004. (save-excursion
  6005. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6006. ;; Determine end invisible part of buffer (EOL)
  6007. (beginning-of-line 2)
  6008. (while (and (not (eobp)) ;This is like `next-line'.
  6009. (get-char-property (1- (point)) 'invisible))
  6010. (goto-char (next-single-char-property-change (point) 'invisible))
  6011. (and (eolp) (beginning-of-line 2)))
  6012. (setq eol (point)))
  6013. ;; Find out what to do next and set `this-command'
  6014. (cond
  6015. ((= eos eoh)
  6016. ;; Nothing is hidden behind this heading
  6017. (unless (org-before-first-heading-p)
  6018. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6019. (org-unlogged-message "EMPTY ENTRY")
  6020. (setq org-cycle-subtree-status nil)
  6021. (save-excursion
  6022. (goto-char eos)
  6023. (outline-next-heading)
  6024. (when (org-invisible-p) (org-flag-heading nil))))
  6025. ((and (or (>= eol eos)
  6026. (not (string-match "\\S-" (buffer-substring eol eos))))
  6027. (or has-children
  6028. (not (setq children-skipped
  6029. org-cycle-skip-children-state-if-no-children))))
  6030. ;; Entire subtree is hidden in one line: children view
  6031. (unless (org-before-first-heading-p)
  6032. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6033. (if (org-at-item-p)
  6034. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6035. (org-show-entry)
  6036. (org-with-limited-levels (org-show-children))
  6037. ;; FIXME: This slows down the func way too much.
  6038. ;; How keep drawers hidden in subtree anyway?
  6039. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6040. ;; (org-cycle-hide-drawers 'subtree))
  6041. ;; Fold every list in subtree to top-level items.
  6042. (when (eq org-cycle-include-plain-lists 'integrate)
  6043. (save-excursion
  6044. (org-back-to-heading)
  6045. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6046. (beginning-of-line 1)
  6047. (let* ((struct (org-list-struct))
  6048. (prevs (org-list-prevs-alist struct))
  6049. (end (org-list-get-bottom-point struct)))
  6050. (dolist (e (org-list-get-all-items (point) struct prevs))
  6051. (org-list-set-item-visibility e struct 'folded))
  6052. (goto-char (if (< end eos) end eos)))))))
  6053. (org-unlogged-message "CHILDREN")
  6054. (save-excursion
  6055. (goto-char eos)
  6056. (outline-next-heading)
  6057. (when (org-invisible-p) (org-flag-heading nil)))
  6058. (setq org-cycle-subtree-status 'children)
  6059. (unless (org-before-first-heading-p)
  6060. (run-hook-with-args 'org-cycle-hook 'children)))
  6061. ((or children-skipped
  6062. (and (eq last-command this-command)
  6063. (eq org-cycle-subtree-status 'children)))
  6064. ;; We just showed the children, or no children are there,
  6065. ;; now show everything.
  6066. (unless (org-before-first-heading-p)
  6067. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6068. (outline-flag-region eoh eos nil)
  6069. (org-unlogged-message
  6070. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6071. (setq org-cycle-subtree-status 'subtree)
  6072. (unless (org-before-first-heading-p)
  6073. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6074. (t
  6075. ;; Default action: hide the subtree.
  6076. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6077. (outline-flag-region eoh eos t)
  6078. (org-unlogged-message "FOLDED")
  6079. (setq org-cycle-subtree-status 'folded)
  6080. (unless (org-before-first-heading-p)
  6081. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6082. ;;;###autoload
  6083. (defun org-global-cycle (&optional arg)
  6084. "Cycle the global visibility. For details see `org-cycle'.
  6085. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6086. With a numeric prefix, show all headlines up to that level."
  6087. (interactive "P")
  6088. (let ((org-cycle-include-plain-lists
  6089. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6090. (cond
  6091. ((integerp arg)
  6092. (outline-show-all)
  6093. (outline-hide-sublevels arg)
  6094. (setq org-cycle-global-status 'contents))
  6095. ((equal arg '(4))
  6096. (org-set-startup-visibility)
  6097. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6098. (t
  6099. (org-cycle '(4))))))
  6100. (defun org-set-startup-visibility ()
  6101. "Set the visibility required by startup options and properties."
  6102. (cond
  6103. ((eq org-startup-folded t)
  6104. (org-overview))
  6105. ((eq org-startup-folded 'content)
  6106. (org-content))
  6107. ((or (eq org-startup-folded 'showeverything)
  6108. (eq org-startup-folded nil))
  6109. (outline-show-all)))
  6110. (unless (eq org-startup-folded 'showeverything)
  6111. (when org-hide-block-startup (org-hide-block-all))
  6112. (org-set-visibility-according-to-property 'no-cleanup)
  6113. (org-cycle-hide-archived-subtrees 'all)
  6114. (org-cycle-hide-drawers 'all)
  6115. (org-cycle-show-empty-lines t)))
  6116. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6117. "Switch subtree visibilities according to :VISIBILITY: property."
  6118. (interactive)
  6119. (org-with-wide-buffer
  6120. (goto-char (point-min))
  6121. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6122. (if (not (org-at-property-p)) (outline-next-heading)
  6123. (let ((state (match-string 3)))
  6124. (save-excursion
  6125. (org-back-to-heading t)
  6126. (outline-hide-subtree)
  6127. (org-reveal)
  6128. (cond
  6129. ((equal state "folded")
  6130. (outline-hide-subtree))
  6131. ((equal state "children")
  6132. (org-show-hidden-entry)
  6133. (org-show-children))
  6134. ((equal state "content")
  6135. (save-excursion
  6136. (save-restriction
  6137. (org-narrow-to-subtree)
  6138. (org-content))))
  6139. ((member state '("all" "showall"))
  6140. (outline-show-subtree)))))))
  6141. (unless no-cleanup
  6142. (org-cycle-hide-archived-subtrees 'all)
  6143. (org-cycle-hide-drawers 'all)
  6144. (org-cycle-show-empty-lines 'all))))
  6145. ;; This function uses outline-regexp instead of the more fundamental
  6146. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6147. ;; buffers, where outline-regexp is needed.
  6148. (defun org-overview ()
  6149. "Switch to overview mode, showing only top-level headlines.
  6150. This shows all headlines with a level equal or greater than the level
  6151. of the first headline in the buffer. This is important, because if the
  6152. first headline is not level one, then (hide-sublevels 1) gives confusing
  6153. results."
  6154. (interactive)
  6155. (save-excursion
  6156. (let ((level
  6157. (save-excursion
  6158. (goto-char (point-min))
  6159. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6160. (goto-char (match-beginning 0))
  6161. (funcall outline-level)))))
  6162. (and level (outline-hide-sublevels level)))))
  6163. (defun org-content (&optional arg)
  6164. "Show all headlines in the buffer, like a table of contents.
  6165. With numerical argument N, show content up to level N."
  6166. (interactive "P")
  6167. (org-overview)
  6168. (save-excursion
  6169. ;; Visit all headings and show their offspring
  6170. (and (integerp arg) (org-overview))
  6171. (goto-char (point-max))
  6172. (catch 'exit
  6173. (while (and (progn (condition-case nil
  6174. (outline-previous-visible-heading 1)
  6175. (error (goto-char (point-min))))
  6176. t)
  6177. (looking-at org-outline-regexp))
  6178. (if (integerp arg)
  6179. (org-show-children (1- arg))
  6180. (outline-show-branches))
  6181. (when (bobp) (throw 'exit nil))))))
  6182. (defun org-optimize-window-after-visibility-change (state)
  6183. "Adjust the window after a change in outline visibility.
  6184. This function is the default value of the hook `org-cycle-hook'."
  6185. (when (get-buffer-window (current-buffer))
  6186. (cond
  6187. ((eq state 'content) nil)
  6188. ((eq state 'all) nil)
  6189. ((eq state 'folded) nil)
  6190. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6191. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6192. (defun org-remove-empty-overlays-at (pos)
  6193. "Remove outline overlays that do not contain non-white stuff."
  6194. (dolist (o (overlays-at pos))
  6195. (and (eq 'outline (overlay-get o 'invisible))
  6196. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6197. (overlay-end o))))
  6198. (delete-overlay o))))
  6199. (defun org-clean-visibility-after-subtree-move ()
  6200. "Fix visibility issues after moving a subtree."
  6201. ;; First, find a reasonable region to look at:
  6202. ;; Start two siblings above, end three below
  6203. (let* ((beg (save-excursion
  6204. (and (org-get-last-sibling)
  6205. (org-get-last-sibling))
  6206. (point)))
  6207. (end (save-excursion
  6208. (and (org-get-next-sibling)
  6209. (org-get-next-sibling)
  6210. (org-get-next-sibling))
  6211. (if (org-at-heading-p)
  6212. (point-at-eol)
  6213. (point))))
  6214. (level (looking-at "\\*+"))
  6215. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6216. (save-excursion
  6217. (save-restriction
  6218. (narrow-to-region beg end)
  6219. (when re
  6220. ;; Properly fold already folded siblings
  6221. (goto-char (point-min))
  6222. (while (re-search-forward re nil t)
  6223. (when (and (not (org-invisible-p))
  6224. (save-excursion
  6225. (goto-char (point-at-eol)) (org-invisible-p)))
  6226. (outline-hide-entry))))
  6227. (org-cycle-show-empty-lines 'overview)
  6228. (org-cycle-hide-drawers 'overview)))))
  6229. (defun org-cycle-show-empty-lines (state)
  6230. "Show empty lines above all visible headlines.
  6231. The region to be covered depends on STATE when called through
  6232. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6233. entire buffer covered. Note that an empty line is only shown if there
  6234. are at least `org-cycle-separator-lines' empty lines before the headline."
  6235. (when (/= org-cycle-separator-lines 0)
  6236. (save-excursion
  6237. (let* ((n (abs org-cycle-separator-lines))
  6238. (re (cond
  6239. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6240. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6241. (t (let ((ns (number-to-string (- n 2))))
  6242. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6243. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6244. beg end)
  6245. (cond
  6246. ((memq state '(overview contents t))
  6247. (setq beg (point-min) end (point-max)))
  6248. ((memq state '(children folded))
  6249. (setq beg (point)
  6250. end (progn (org-end-of-subtree t t)
  6251. (line-beginning-position 2)))))
  6252. (when beg
  6253. (goto-char beg)
  6254. (while (re-search-forward re end t)
  6255. (unless (get-char-property (match-end 1) 'invisible)
  6256. (let ((e (match-end 1))
  6257. (b (if (>= org-cycle-separator-lines 0)
  6258. (match-beginning 1)
  6259. (save-excursion
  6260. (goto-char (match-beginning 0))
  6261. (skip-chars-backward " \t\n")
  6262. (line-end-position)))))
  6263. (outline-flag-region b e nil))))))))
  6264. ;; Never hide empty lines at the end of the file.
  6265. (save-excursion
  6266. (goto-char (point-max))
  6267. (outline-previous-heading)
  6268. (outline-end-of-heading)
  6269. (when (and (looking-at "[ \t\n]+")
  6270. (= (match-end 0) (point-max)))
  6271. (outline-flag-region (point) (match-end 0) nil))))
  6272. (defun org-show-empty-lines-in-parent ()
  6273. "Move to the parent and re-show empty lines before visible headlines."
  6274. (save-excursion
  6275. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6276. (org-cycle-show-empty-lines context))))
  6277. (defun org-files-list ()
  6278. "Return `org-agenda-files' list, plus all open Org files.
  6279. This is useful for operations that need to scan all of a user's
  6280. open and agenda-wise Org files."
  6281. (let ((files (mapcar 'expand-file-name (org-agenda-files))))
  6282. (dolist (buf (buffer-list))
  6283. (with-current-buffer buf
  6284. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6285. (cl-pushnew (expand-file-name (buffer-file-name)) files))))
  6286. files))
  6287. (defsubst org-entry-beginning-position ()
  6288. "Return the beginning position of the current entry."
  6289. (save-excursion (org-back-to-heading t) (point)))
  6290. (defsubst org-entry-end-position ()
  6291. "Return the end position of the current entry."
  6292. (save-excursion (outline-next-heading) (point)))
  6293. (defun org-cycle-hide-drawers (state &optional exceptions)
  6294. "Re-hide all drawers after a visibility state change.
  6295. STATE should be one of the symbols listed in the docstring of
  6296. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  6297. a list of strings specifying which drawers should not be hidden."
  6298. (when (and (derived-mode-p 'org-mode)
  6299. (not (memq state '(overview folded contents))))
  6300. (save-excursion
  6301. (let* ((globalp (eq state 'all))
  6302. (beg (if globalp (point-min) (point)))
  6303. (end (if globalp (point-max)
  6304. (if (eq state 'children)
  6305. (save-excursion (outline-next-heading) (point))
  6306. (org-end-of-subtree t)))))
  6307. (goto-char beg)
  6308. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6309. (unless (member-ignore-case (match-string 1) exceptions)
  6310. (let ((drawer (org-element-at-point)))
  6311. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6312. (org-flag-drawer t drawer)
  6313. ;; Make sure to skip drawer entirely or we might flag
  6314. ;; it another time when matching its ending line with
  6315. ;; `org-drawer-regexp'.
  6316. (goto-char (org-element-property :end drawer))))))))))
  6317. (defun org-flag-drawer (flag &optional element)
  6318. "When FLAG is non-nil, hide the drawer we are at.
  6319. Otherwise make it visible. When optional argument ELEMENT is
  6320. a parsed drawer, as returned by `org-element-at-point', hide or
  6321. show that drawer instead."
  6322. (let ((drawer (or element
  6323. (and (save-excursion
  6324. (beginning-of-line)
  6325. (looking-at-p org-drawer-regexp))
  6326. (org-element-at-point)))))
  6327. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6328. (let ((post (org-element-property :post-affiliated drawer)))
  6329. (save-excursion
  6330. (outline-flag-region
  6331. (progn (goto-char post) (line-end-position))
  6332. (progn (goto-char (org-element-property :end drawer))
  6333. (skip-chars-backward " \r\t\n")
  6334. (line-end-position))
  6335. flag))
  6336. ;; When the drawer is hidden away, make sure point lies in
  6337. ;; a visible part of the buffer.
  6338. (when (and flag (> (line-beginning-position) post))
  6339. (goto-char post))))))
  6340. (defun org-subtree-end-visible-p ()
  6341. "Is the end of the current subtree visible?"
  6342. (pos-visible-in-window-p
  6343. (save-excursion (org-end-of-subtree t) (point))))
  6344. (defun org-first-headline-recenter ()
  6345. "Move cursor to the first headline and recenter the headline."
  6346. (let ((window (get-buffer-window)))
  6347. (when window
  6348. (goto-char (point-min))
  6349. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6350. (set-window-start window (line-beginning-position))))))
  6351. ;;; Saving and restoring visibility
  6352. (defun org-outline-overlay-data (&optional use-markers)
  6353. "Return a list of the locations of all outline overlays.
  6354. These are overlays with the `invisible' property value `outline'.
  6355. The return value is a list of cons cells, with start and stop
  6356. positions for each overlay.
  6357. If USE-MARKERS is set, return the positions as markers."
  6358. (let (beg end)
  6359. (org-with-wide-buffer
  6360. (delq nil
  6361. (mapcar (lambda (o)
  6362. (when (eq (overlay-get o 'invisible) 'outline)
  6363. (setq beg (overlay-start o)
  6364. end (overlay-end o))
  6365. (and beg end (> end beg)
  6366. (if use-markers
  6367. (cons (copy-marker beg)
  6368. (copy-marker end t))
  6369. (cons beg end)))))
  6370. (overlays-in (point-min) (point-max)))))))
  6371. (defun org-set-outline-overlay-data (data)
  6372. "Create visibility overlays for all positions in DATA.
  6373. DATA should have been made by `org-outline-overlay-data'."
  6374. (org-with-wide-buffer
  6375. (outline-show-all)
  6376. (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
  6377. ;;; Folding of blocks
  6378. (defvar-local org-hide-block-overlays nil
  6379. "Overlays hiding blocks.")
  6380. (defun org-block-map (function &optional start end)
  6381. "Call FUNCTION at the head of all source blocks in the current buffer.
  6382. Optional arguments START and END can be used to limit the range."
  6383. (let ((start (or start (point-min)))
  6384. (end (or end (point-max))))
  6385. (save-excursion
  6386. (goto-char start)
  6387. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6388. (save-excursion
  6389. (save-match-data
  6390. (goto-char (match-beginning 0))
  6391. (funcall function)))))))
  6392. (defun org-hide-block-toggle-all ()
  6393. "Toggle the visibility of all blocks in the current buffer."
  6394. (org-block-map 'org-hide-block-toggle))
  6395. (defun org-hide-block-all ()
  6396. "Fold all blocks in the current buffer."
  6397. (interactive)
  6398. (org-show-block-all)
  6399. (org-block-map 'org-hide-block-toggle-maybe))
  6400. (defun org-show-block-all ()
  6401. "Unfold all blocks in the current buffer."
  6402. (interactive)
  6403. (mapc #'delete-overlay org-hide-block-overlays)
  6404. (setq org-hide-block-overlays nil))
  6405. (defun org-hide-block-toggle-maybe ()
  6406. "Toggle visibility of block at point.
  6407. Unlike to `org-hide-block-toggle', this function does not throw
  6408. an error. Return a non-nil value when toggling is successful."
  6409. (interactive)
  6410. (ignore-errors (org-hide-block-toggle)))
  6411. (defun org-hide-block-toggle (&optional force)
  6412. "Toggle the visibility of the current block.
  6413. When optional argument FORCE is `off', make block visible. If it
  6414. is non-nil, hide it unconditionally. Throw an error when not at
  6415. a block. Return a non-nil value when toggling is successful."
  6416. (interactive)
  6417. (let ((element (org-element-at-point)))
  6418. (unless (memq (org-element-type element)
  6419. '(center-block comment-block dynamic-block example-block
  6420. export-block quote-block special-block
  6421. src-block verse-block))
  6422. (user-error "Not at a block"))
  6423. (let* ((start (save-excursion
  6424. (goto-char (org-element-property :post-affiliated element))
  6425. (line-end-position)))
  6426. (end (save-excursion
  6427. (goto-char (org-element-property :end element))
  6428. (skip-chars-backward " \r\t\n")
  6429. (line-end-position)))
  6430. (overlays (overlays-at start)))
  6431. (cond
  6432. ;; Do nothing when not before or at the block opening line or
  6433. ;; at the block closing line.
  6434. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6435. ((and (not (eq force 'off))
  6436. (not (memq t (mapcar
  6437. (lambda (o)
  6438. (eq (overlay-get o 'invisible) 'org-hide-block))
  6439. overlays))))
  6440. (let ((ov (make-overlay start end)))
  6441. (overlay-put ov 'invisible 'org-hide-block)
  6442. ;; Make the block accessible to `isearch'.
  6443. (overlay-put
  6444. ov 'isearch-open-invisible
  6445. (lambda (ov)
  6446. (when (memq ov org-hide-block-overlays)
  6447. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6448. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6449. (delete-overlay ov))))
  6450. (push ov org-hide-block-overlays)
  6451. ;; When the block is hidden away, make sure point is left in
  6452. ;; a visible part of the buffer.
  6453. (when (> (line-beginning-position) start)
  6454. (goto-char start)
  6455. (beginning-of-line))
  6456. ;; Signal successful toggling.
  6457. t))
  6458. ((or (not force) (eq force 'off))
  6459. (dolist (ov overlays t)
  6460. (when (memq ov org-hide-block-overlays)
  6461. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6462. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6463. (delete-overlay ov))))))))
  6464. ;; Remove overlays when changing major mode
  6465. (add-hook 'org-mode-hook
  6466. (lambda () (add-hook 'change-major-mode-hook
  6467. 'org-show-block-all 'append 'local)))
  6468. ;;; Indirect buffer display of subtrees
  6469. (defvar org-indirect-dedicated-frame nil
  6470. "This is the frame being used for indirect tree display.")
  6471. (defvar org-last-indirect-buffer nil)
  6472. (defun org-tree-to-indirect-buffer (&optional arg)
  6473. "Create indirect buffer and narrow it to current subtree.
  6474. With a numerical prefix ARG, go up to this level and then take that tree.
  6475. If ARG is negative, go up that many levels.
  6476. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6477. indirect buffer previously made with this command, to avoid proliferation of
  6478. indirect buffers. However, when you call the command with a \
  6479. `\\[universal-argument]' prefix, or
  6480. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6481. so that you can work with several indirect buffers at the same time. If
  6482. `org-indirect-buffer-display' is `dedicated-frame', the \
  6483. `\\[universal-argument]' prefix also
  6484. requests that a new frame be made for the new buffer, so that the dedicated
  6485. frame is not changed."
  6486. (interactive "P")
  6487. (let ((cbuf (current-buffer))
  6488. (cwin (selected-window))
  6489. (pos (point))
  6490. beg end level heading ibuf)
  6491. (save-excursion
  6492. (org-back-to-heading t)
  6493. (when (numberp arg)
  6494. (setq level (org-outline-level))
  6495. (when (< arg 0) (setq arg (+ level arg)))
  6496. (while (> (setq level (org-outline-level)) arg)
  6497. (org-up-heading-safe)))
  6498. (setq beg (point)
  6499. heading (org-get-heading 'no-tags))
  6500. (org-end-of-subtree t t)
  6501. (when (org-at-heading-p) (backward-char 1))
  6502. (setq end (point)))
  6503. (when (and (buffer-live-p org-last-indirect-buffer)
  6504. (not (eq org-indirect-buffer-display 'new-frame))
  6505. (not arg))
  6506. (kill-buffer org-last-indirect-buffer))
  6507. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6508. org-last-indirect-buffer ibuf)
  6509. (cond
  6510. ((or (eq org-indirect-buffer-display 'new-frame)
  6511. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6512. (select-frame (make-frame))
  6513. (delete-other-windows)
  6514. (pop-to-buffer-same-window ibuf)
  6515. (org-set-frame-title heading))
  6516. ((eq org-indirect-buffer-display 'dedicated-frame)
  6517. (raise-frame
  6518. (select-frame (or (and org-indirect-dedicated-frame
  6519. (frame-live-p org-indirect-dedicated-frame)
  6520. org-indirect-dedicated-frame)
  6521. (setq org-indirect-dedicated-frame (make-frame)))))
  6522. (delete-other-windows)
  6523. (pop-to-buffer-same-window ibuf)
  6524. (org-set-frame-title (concat "Indirect: " heading)))
  6525. ((eq org-indirect-buffer-display 'current-window)
  6526. (pop-to-buffer-same-window ibuf))
  6527. ((eq org-indirect-buffer-display 'other-window)
  6528. (pop-to-buffer ibuf))
  6529. (t (error "Invalid value")))
  6530. (narrow-to-region beg end)
  6531. (outline-show-all)
  6532. (goto-char pos)
  6533. (run-hook-with-args 'org-cycle-hook 'all)
  6534. (and (window-live-p cwin) (select-window cwin))))
  6535. (defun org-get-indirect-buffer (&optional buffer heading)
  6536. (setq buffer (or buffer (current-buffer)))
  6537. (let ((n 1) (base (buffer-name buffer)) bname)
  6538. (while (buffer-live-p
  6539. (get-buffer
  6540. (setq bname
  6541. (concat base "-"
  6542. (if heading (concat heading "-" (number-to-string n))
  6543. (number-to-string n))))))
  6544. (setq n (1+ n)))
  6545. (condition-case nil
  6546. (make-indirect-buffer buffer bname 'clone)
  6547. (error (make-indirect-buffer buffer bname)))))
  6548. (defun org-set-frame-title (title)
  6549. "Set the title of the current frame to the string TITLE."
  6550. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6551. ;;;; Structure editing
  6552. ;;; Inserting headlines
  6553. (defun org--line-empty-p (n)
  6554. "Is the Nth next line empty?
  6555. Counts the current line as N = 1 and the previous line as N = 0;
  6556. see `beginning-of-line'."
  6557. (save-excursion
  6558. (and (not (bobp))
  6559. (or (beginning-of-line n) t)
  6560. (save-match-data
  6561. (looking-at "[ \t]*$")))))
  6562. (defun org-previous-line-empty-p ()
  6563. "Is the previous line a blank line?
  6564. When NEXT is non-nil, check the next line instead."
  6565. (org--line-empty-p 0))
  6566. (defun org-next-line-empty-p ()
  6567. "Is the previous line a blank line?
  6568. When NEXT is non-nil, check the next line instead."
  6569. (org--line-empty-p 2))
  6570. (defun org--blank-before-heading-p (&optional parent)
  6571. "Non-nil when an empty line should precede a new heading here.
  6572. When optional argument PARENT is non-nil, consider parent
  6573. headline instead of current one."
  6574. (pcase (assq 'heading org-blank-before-new-entry)
  6575. (`(heading . auto)
  6576. (save-excursion
  6577. (org-with-limited-levels
  6578. (unless (and (org-before-first-heading-p)
  6579. (not (outline-next-heading)))
  6580. (org-back-to-heading t)
  6581. (when parent (org-up-heading-safe))
  6582. (cond ((not (bobp))
  6583. (org-previous-line-empty-p))
  6584. ((outline-next-heading)
  6585. (org-previous-line-empty-p))
  6586. ;; Ignore trailing spaces on last buffer line.
  6587. ((progn (skip-chars-backward " \t") (bolp))
  6588. (org-previous-line-empty-p))
  6589. (t nil))))))
  6590. (`(heading . ,value) value)
  6591. (_ nil)))
  6592. (defun org-insert-heading (&optional arg invisible-ok top)
  6593. "Insert a new heading or an item with the same depth at point.
  6594. If point is at the beginning of a heading, insert a new heading
  6595. or a new headline above the current one. When at the beginning
  6596. of a regular line of text, turn it into a heading.
  6597. If point is in the middle of a line, split it and create a new
  6598. headline with the text in the current line after point (see
  6599. `org-M-RET-may-split-line' on how to modify this behavior). As
  6600. a special case, on a headline, splitting can only happen on the
  6601. title itself. E.g., this excludes breaking stars or tags.
  6602. With a `\\[universal-argument]' prefix, set \
  6603. `org-insert-heading-respect-content' to
  6604. a non-nil value for the duration of the command. This forces the
  6605. insertion of a heading after the current subtree, independently
  6606. on the location of point.
  6607. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6608. insert the heading at the end of the tree
  6609. above the current heading. For example, if point is within a
  6610. 2nd-level heading, then it will insert a 2nd-level heading at
  6611. the end of the 1st-level parent subtree.
  6612. When INVISIBLE-OK is set, stop at invisible headlines when going
  6613. back. This is important for non-interactive uses of the
  6614. command.
  6615. When optional argument TOP is non-nil, insert a level 1 heading,
  6616. unconditionally."
  6617. (interactive "P")
  6618. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6619. (level (org-current-level))
  6620. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6621. (cond
  6622. ((or org-insert-heading-respect-content
  6623. (member arg '((4) (16)))
  6624. (and (not invisible-ok)
  6625. (invisible-p (max (1- (point)) (point-min)))))
  6626. ;; Position point at the location of insertion.
  6627. (if (not level) ;before first headline
  6628. (org-with-limited-levels (outline-next-heading))
  6629. ;; Make sure we end up on a visible headline if INVISIBLE-OK
  6630. ;; is nil.
  6631. (org-with-limited-levels (org-back-to-heading invisible-ok))
  6632. (cond ((equal arg '(16))
  6633. (org-up-heading-safe)
  6634. (org-end-of-subtree t t))
  6635. (t
  6636. (org-end-of-subtree t t))))
  6637. (unless (bolp) (insert "\n")) ;ensure final newline
  6638. (unless (and blank? (org-previous-line-empty-p))
  6639. (org-N-empty-lines-before-current (if blank? 1 0)))
  6640. (insert stars " \n")
  6641. (forward-char -1))
  6642. ;; At a headline...
  6643. ((org-at-heading-p)
  6644. (cond ((bolp)
  6645. (when blank? (save-excursion (insert "\n")))
  6646. (save-excursion (insert stars " \n"))
  6647. (unless (and blank? (org-previous-line-empty-p))
  6648. (org-N-empty-lines-before-current (if blank? 1 0)))
  6649. (end-of-line))
  6650. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6651. (org-match-line org-complex-heading-regexp)
  6652. (org-pos-in-match-range (point) 4))
  6653. ;; Grab the text that should moved to the new headline.
  6654. ;; Preserve tags.
  6655. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6656. (if (looking-at "[ \t]*$") (replace-match "")
  6657. (org-set-tags nil t))
  6658. (end-of-line)
  6659. (when blank? (insert "\n"))
  6660. (insert "\n" stars " ")
  6661. (when (org-string-nw-p split) (insert split))
  6662. (when (eobp) (save-excursion (insert "\n")))))
  6663. (t
  6664. (end-of-line)
  6665. (when blank? (insert "\n"))
  6666. (insert "\n" stars " ")
  6667. (when (eobp) (save-excursion (insert "\n"))))))
  6668. ;; On regular text, turn line into a headline or split, if
  6669. ;; appropriate.
  6670. ((bolp)
  6671. (insert stars " ")
  6672. (unless (and blank? (org-previous-line-empty-p))
  6673. (org-N-empty-lines-before-current (if blank? 1 0))))
  6674. (t
  6675. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6676. (end-of-line))
  6677. (insert "\n" stars " ")
  6678. (unless (and blank? (org-previous-line-empty-p))
  6679. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6680. (run-hooks 'org-insert-heading-hook))
  6681. (defun org-N-empty-lines-before-current (n)
  6682. "Make the number of empty lines before current exactly N.
  6683. So this will delete or add empty lines."
  6684. (let ((column (current-column)))
  6685. (beginning-of-line)
  6686. (unless (bobp)
  6687. (let ((start (save-excursion
  6688. (skip-chars-backward " \r\t\n")
  6689. (line-end-position))))
  6690. (delete-region start (line-end-position 0))))
  6691. (insert (make-string n ?\n))
  6692. (move-to-column column)))
  6693. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6694. "Return the heading of the current entry, without the stars.
  6695. When NO-TAGS is non-nil, don't include tags.
  6696. When NO-TODO is non-nil, don't include TODO keywords.
  6697. When NO-PRIORITY is non-nil, don't include priority cookie.
  6698. When NO-COMMENT is non-nil, don't include COMMENT string."
  6699. (save-excursion
  6700. (org-back-to-heading t)
  6701. (let ((case-fold-search nil))
  6702. (looking-at org-complex-heading-regexp)
  6703. (let ((todo (and (not no-todo) (match-string 2)))
  6704. (priority (and (not no-priority) (match-string 3)))
  6705. (headline (pcase (match-string 4)
  6706. (`nil "")
  6707. ((and (guard no-comment) h)
  6708. (replace-regexp-in-string
  6709. (eval-when-compile
  6710. (format "\\`%s[ \t]+" org-comment-string))
  6711. "" h))
  6712. (h h)))
  6713. (tags (and (not no-tags) (match-string 5))))
  6714. (mapconcat #'identity
  6715. (delq nil (list todo priority headline tags))
  6716. " ")))))
  6717. (defvar orgstruct-mode) ; defined below
  6718. (defun org-heading-components ()
  6719. "Return the components of the current heading.
  6720. This is a list with the following elements:
  6721. - the level as an integer
  6722. - the reduced level, different if `org-odd-levels-only' is set.
  6723. - the TODO keyword, or nil
  6724. - the priority character, like ?A, or nil if no priority is given
  6725. - the headline text itself, or the tags string if no headline text
  6726. - the tags string, or nil."
  6727. (save-excursion
  6728. (org-back-to-heading t)
  6729. (when (let (case-fold-search)
  6730. (looking-at
  6731. (if orgstruct-mode
  6732. org-heading-regexp
  6733. org-complex-heading-regexp)))
  6734. (if orgstruct-mode
  6735. (list (length (match-string 1))
  6736. (org-reduced-level (length (match-string 1)))
  6737. nil
  6738. nil
  6739. (match-string 2)
  6740. nil)
  6741. (list (length (match-string 1))
  6742. (org-reduced-level (length (match-string 1)))
  6743. (match-string-no-properties 2)
  6744. (and (match-end 3) (aref (match-string 3) 2))
  6745. (match-string-no-properties 4)
  6746. (match-string-no-properties 5))))))
  6747. (defun org-get-entry ()
  6748. "Get the entry text, after heading, entire subtree."
  6749. (save-excursion
  6750. (org-back-to-heading t)
  6751. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6752. (defun org-edit-headline (&optional heading)
  6753. "Edit the current headline.
  6754. Set it to HEADING when provided."
  6755. (interactive)
  6756. (org-with-wide-buffer
  6757. (org-back-to-heading t)
  6758. (let ((case-fold-search nil))
  6759. (when (looking-at org-complex-heading-regexp)
  6760. (let* ((old (match-string-no-properties 4))
  6761. (new (save-match-data
  6762. (org-trim (or heading (read-string "Edit: " old))))))
  6763. (unless (equal old new)
  6764. (if old (replace-match new t t nil 4)
  6765. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6766. (insert " " new))
  6767. (org-set-tags nil t)
  6768. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6769. (defun org-insert-heading-after-current ()
  6770. "Insert a new heading with same level as current, after current subtree."
  6771. (interactive)
  6772. (org-back-to-heading)
  6773. (org-insert-heading)
  6774. (org-move-subtree-down)
  6775. (end-of-line 1))
  6776. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6777. "Insert heading with `org-insert-heading-respect-content' set to t."
  6778. (interactive)
  6779. (org-insert-heading '(4) invisible-ok))
  6780. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6781. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6782. (interactive)
  6783. (org-insert-todo-heading force-state '(4)))
  6784. (defun org-insert-todo-heading (arg &optional force-heading)
  6785. "Insert a new heading with the same level and TODO state as current heading.
  6786. If the heading has no TODO state, or if the state is DONE, use
  6787. the first state (TODO by default). Also with one prefix arg,
  6788. force first state. With two prefix args, force inserting at the
  6789. end of the parent subtree.
  6790. When called at a plain list item, insert a new item with an
  6791. unchecked check box."
  6792. (interactive "P")
  6793. (when (or force-heading (not (org-insert-item 'checkbox)))
  6794. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6795. force-heading))
  6796. (save-excursion
  6797. (org-forward-heading-same-level -1)
  6798. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6799. (let* ((new-mark-x
  6800. (if (or (equal arg '(4))
  6801. (not (match-beginning 2))
  6802. (member (match-string 2) org-done-keywords))
  6803. (car org-todo-keywords-1)
  6804. (match-string 2)))
  6805. (new-mark
  6806. (or
  6807. (run-hook-with-args-until-success
  6808. 'org-todo-get-default-hook new-mark-x nil)
  6809. new-mark-x)))
  6810. (beginning-of-line 1)
  6811. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6812. (if org-treat-insert-todo-heading-as-state-change
  6813. (org-todo new-mark)
  6814. (insert new-mark " "))))
  6815. (when org-provide-todo-statistics
  6816. (org-update-parent-todo-statistics))))
  6817. (defun org-insert-subheading (arg)
  6818. "Insert a new subheading and demote it.
  6819. Works for outline headings and for plain lists alike."
  6820. (interactive "P")
  6821. (org-insert-heading arg)
  6822. (cond
  6823. ((org-at-heading-p) (org-do-demote))
  6824. ((org-at-item-p) (org-indent-item))))
  6825. (defun org-insert-todo-subheading (arg)
  6826. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6827. Works for outline headings and for plain lists alike."
  6828. (interactive "P")
  6829. (org-insert-todo-heading arg)
  6830. (cond
  6831. ((org-at-heading-p) (org-do-demote))
  6832. ((org-at-item-p) (org-indent-item))))
  6833. ;;; Promotion and Demotion
  6834. (defvar org-after-demote-entry-hook nil
  6835. "Hook run after an entry has been demoted.
  6836. The cursor will be at the beginning of the entry.
  6837. When a subtree is being demoted, the hook will be called for each node.")
  6838. (defvar org-after-promote-entry-hook nil
  6839. "Hook run after an entry has been promoted.
  6840. The cursor will be at the beginning of the entry.
  6841. When a subtree is being promoted, the hook will be called for each node.")
  6842. (defun org-promote-subtree ()
  6843. "Promote the entire subtree.
  6844. See also `org-promote'."
  6845. (interactive)
  6846. (save-excursion
  6847. (org-with-limited-levels (org-map-tree 'org-promote)))
  6848. (org-fix-position-after-promote))
  6849. (defun org-demote-subtree ()
  6850. "Demote the entire subtree.
  6851. See `org-demote' and `org-promote'."
  6852. (interactive)
  6853. (save-excursion
  6854. (org-with-limited-levels (org-map-tree 'org-demote)))
  6855. (org-fix-position-after-promote))
  6856. (defun org-do-promote ()
  6857. "Promote the current heading higher up the tree.
  6858. If the region is active in `transient-mark-mode', promote all
  6859. headings in the region."
  6860. (interactive)
  6861. (save-excursion
  6862. (if (org-region-active-p)
  6863. (org-map-region 'org-promote (region-beginning) (region-end))
  6864. (org-promote)))
  6865. (org-fix-position-after-promote))
  6866. (defun org-do-demote ()
  6867. "Demote the current heading lower down the tree.
  6868. If the region is active in `transient-mark-mode', demote all
  6869. headings in the region."
  6870. (interactive)
  6871. (save-excursion
  6872. (if (org-region-active-p)
  6873. (org-map-region 'org-demote (region-beginning) (region-end))
  6874. (org-demote)))
  6875. (org-fix-position-after-promote))
  6876. (defun org-fix-position-after-promote ()
  6877. "Fix cursor position and indentation after demoting/promoting."
  6878. (let ((pos (point)))
  6879. (when (save-excursion
  6880. (beginning-of-line)
  6881. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6882. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6883. (cond ((eobp) (insert " "))
  6884. ((eolp) (insert " "))
  6885. ((equal (char-after) ?\s) (forward-char 1))))))
  6886. (defun org-current-level ()
  6887. "Return the level of the current entry, or nil if before the first headline.
  6888. The level is the number of stars at the beginning of the
  6889. headline. Use `org-reduced-level' to remove the effect of
  6890. `org-odd-levels'. Unlike to `org-outline-level', this function
  6891. ignores inlinetasks."
  6892. (let ((level (org-with-limited-levels (org-outline-level))))
  6893. (and (> level 0) level)))
  6894. (defun org-get-previous-line-level ()
  6895. "Return the outline depth of the last headline before the current line.
  6896. Returns 0 for the first headline in the buffer, and nil if before the
  6897. first headline."
  6898. (and (org-current-level)
  6899. (or (and (/= (line-beginning-position) (point-min))
  6900. (save-excursion (beginning-of-line 0) (org-current-level)))
  6901. 0)))
  6902. (defun org-reduced-level (l)
  6903. "Compute the effective level of a heading.
  6904. This takes into account the setting of `org-odd-levels-only'."
  6905. (cond
  6906. ((zerop l) 0)
  6907. (org-odd-levels-only (1+ (floor (/ l 2))))
  6908. (t l)))
  6909. (defun org-level-increment ()
  6910. "Return the number of stars that will be added or removed at a
  6911. time to headlines when structure editing, based on the value of
  6912. `org-odd-levels-only'."
  6913. (if org-odd-levels-only 2 1))
  6914. (defun org-get-valid-level (level &optional change)
  6915. "Rectify a level change under the influence of `org-odd-levels-only'.
  6916. LEVEL is a current level, CHANGE is by how much the level should
  6917. be modified. Even if CHANGE is nil, LEVEL may be returned
  6918. modified because even level numbers will become the next higher
  6919. odd number. Returns values greater than 0."
  6920. (if org-odd-levels-only
  6921. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6922. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6923. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6924. (max 1 (+ level (or change 0)))))
  6925. (defun org-promote ()
  6926. "Promote the current heading higher up the tree."
  6927. (org-with-wide-buffer
  6928. (org-back-to-heading t)
  6929. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6930. after-change-functions))
  6931. (level (save-match-data (funcall outline-level)))
  6932. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6933. (diff (abs (- level (length up-head) -1))))
  6934. (cond
  6935. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6936. (replace-match "# " nil t))
  6937. ((= level 1)
  6938. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6939. (t (replace-match up-head nil t)))
  6940. (unless (= level 1)
  6941. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  6942. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6943. (run-hooks 'org-after-promote-entry-hook))))
  6944. (defun org-demote ()
  6945. "Demote the current heading lower down the tree."
  6946. (org-with-wide-buffer
  6947. (org-back-to-heading t)
  6948. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6949. after-change-functions))
  6950. (level (save-match-data (funcall outline-level)))
  6951. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6952. (diff (abs (- level (length down-head) -1))))
  6953. (replace-match down-head nil t)
  6954. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  6955. (when org-adapt-indentation (org-fixup-indentation diff))
  6956. (run-hooks 'org-after-demote-entry-hook))))
  6957. (defun org-cycle-level ()
  6958. "Cycle the level of an empty headline through possible states.
  6959. This goes first to child, then to parent, level, then up the hierarchy.
  6960. After top level, it switches back to sibling level."
  6961. (interactive)
  6962. (let ((org-adapt-indentation nil))
  6963. (when (org-point-at-end-of-empty-headline)
  6964. (setq this-command 'org-cycle-level) ; Only needed for caching
  6965. (let ((cur-level (org-current-level))
  6966. (prev-level (org-get-previous-line-level)))
  6967. (cond
  6968. ;; If first headline in file, promote to top-level.
  6969. ((= prev-level 0)
  6970. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6971. do (org-do-promote)))
  6972. ;; If same level as prev, demote one.
  6973. ((= prev-level cur-level)
  6974. (org-do-demote))
  6975. ;; If parent is top-level, promote to top level if not already.
  6976. ((= prev-level 1)
  6977. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6978. do (org-do-promote)))
  6979. ;; If top-level, return to prev-level.
  6980. ((= cur-level 1)
  6981. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6982. do (org-do-demote)))
  6983. ;; If less than prev-level, promote one.
  6984. ((< cur-level prev-level)
  6985. (org-do-promote))
  6986. ;; If deeper than prev-level, promote until higher than
  6987. ;; prev-level.
  6988. ((> cur-level prev-level)
  6989. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6990. do (org-do-promote))))
  6991. t))))
  6992. (defun org-map-tree (fun)
  6993. "Call FUN for every heading underneath the current one."
  6994. (org-back-to-heading t)
  6995. (let ((level (funcall outline-level)))
  6996. (save-excursion
  6997. (funcall fun)
  6998. (while (and (progn
  6999. (outline-next-heading)
  7000. (> (funcall outline-level) level))
  7001. (not (eobp)))
  7002. (funcall fun)))))
  7003. (defun org-map-region (fun beg end)
  7004. "Call FUN for every heading between BEG and END."
  7005. (let ((org-ignore-region t))
  7006. (save-excursion
  7007. (setq end (copy-marker end))
  7008. (goto-char beg)
  7009. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7010. (< (point) end))
  7011. (funcall fun))
  7012. (while (and (progn
  7013. (outline-next-heading)
  7014. (< (point) end))
  7015. (not (eobp)))
  7016. (funcall fun)))))
  7017. (defun org-fixup-indentation (diff)
  7018. "Change the indentation in the current entry by DIFF.
  7019. DIFF is an integer. Indentation is done according to the
  7020. following rules:
  7021. - Planning information and property drawers are always indented
  7022. according to the new level of the headline;
  7023. - Footnote definitions and their contents are ignored;
  7024. - Inlinetasks' boundaries are not shifted;
  7025. - Empty lines are ignored;
  7026. - Other lines' indentation are shifted by DIFF columns, unless
  7027. it would introduce a structural change in the document, in
  7028. which case no shifting is done at all.
  7029. Assume point is at a heading or an inlinetask beginning."
  7030. (org-with-wide-buffer
  7031. (narrow-to-region (line-beginning-position)
  7032. (save-excursion
  7033. (if (org-with-limited-levels (org-at-heading-p))
  7034. (org-with-limited-levels (outline-next-heading))
  7035. (org-inlinetask-goto-end))
  7036. (point)))
  7037. (forward-line)
  7038. ;; Indent properly planning info and property drawer.
  7039. (when (looking-at-p org-planning-line-re)
  7040. (org-indent-line)
  7041. (forward-line))
  7042. (when (looking-at org-property-drawer-re)
  7043. (goto-char (match-end 0))
  7044. (forward-line)
  7045. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7046. (catch 'no-shift
  7047. (when (zerop diff) (throw 'no-shift nil))
  7048. ;; If DIFF is negative, first check if a shift is possible at all
  7049. ;; (e.g., it doesn't break structure). This can only happen if
  7050. ;; some contents are not properly indented.
  7051. (let ((case-fold-search t))
  7052. (when (< diff 0)
  7053. (let ((diff (- diff))
  7054. (forbidden-re (concat org-outline-regexp
  7055. "\\|"
  7056. (substring org-footnote-definition-re 1))))
  7057. (save-excursion
  7058. (while (not (eobp))
  7059. (cond
  7060. ((looking-at-p "[ \t]*$") (forward-line))
  7061. ((and (looking-at-p org-footnote-definition-re)
  7062. (let ((e (org-element-at-point)))
  7063. (and (eq (org-element-type e) 'footnote-definition)
  7064. (goto-char (org-element-property :end e))))))
  7065. ((looking-at-p org-outline-regexp) (forward-line))
  7066. ;; Give up if shifting would move before column 0 or
  7067. ;; if it would introduce a headline or a footnote
  7068. ;; definition.
  7069. (t
  7070. (skip-chars-forward " \t")
  7071. (let ((ind (current-column)))
  7072. (when (or (< ind diff)
  7073. (and (= ind diff) (looking-at-p forbidden-re)))
  7074. (throw 'no-shift nil)))
  7075. ;; Ignore contents of example blocks and source
  7076. ;; blocks if their indentation is meant to be
  7077. ;; preserved. Jump to block's closing line.
  7078. (beginning-of-line)
  7079. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7080. (let ((e (org-element-at-point)))
  7081. (and (memq (org-element-type e)
  7082. '(example-block src-block))
  7083. (or org-src-preserve-indentation
  7084. (org-element-property :preserve-indent e))
  7085. (goto-char (org-element-property :end e))
  7086. (progn (skip-chars-backward " \r\t\n")
  7087. (beginning-of-line)
  7088. t))))
  7089. (forward-line))))))))
  7090. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7091. ;; by DIFF. Also skip contents of source or example blocks
  7092. ;; when indentation is meant to be preserved.
  7093. (while (not (eobp))
  7094. (cond
  7095. ((and (looking-at-p org-footnote-definition-re)
  7096. (let ((e (org-element-at-point)))
  7097. (and (eq (org-element-type e) 'footnote-definition)
  7098. (goto-char (org-element-property :end e))))))
  7099. ((looking-at-p org-outline-regexp) (forward-line))
  7100. ((looking-at-p "[ \t]*$") (forward-line))
  7101. (t
  7102. (indent-line-to (+ (org-get-indentation) diff))
  7103. (beginning-of-line)
  7104. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7105. (let ((e (org-element-at-point)))
  7106. (and (memq (org-element-type e)
  7107. '(example-block src-block))
  7108. (or org-src-preserve-indentation
  7109. (org-element-property :preserve-indent e))
  7110. (goto-char (org-element-property :end e))
  7111. (progn (skip-chars-backward " \r\t\n")
  7112. (beginning-of-line)
  7113. t))))
  7114. (forward-line)))))))))
  7115. (defun org-convert-to-odd-levels ()
  7116. "Convert an Org file with all levels allowed to one with odd levels.
  7117. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7118. level 5 etc."
  7119. (interactive)
  7120. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7121. (let ((outline-level 'org-outline-level)
  7122. (org-odd-levels-only nil) n)
  7123. (save-excursion
  7124. (goto-char (point-min))
  7125. (while (re-search-forward "^\\*\\*+ " nil t)
  7126. (setq n (- (length (match-string 0)) 2))
  7127. (while (>= (setq n (1- n)) 0)
  7128. (org-demote))
  7129. (end-of-line 1))))))
  7130. (defun org-convert-to-oddeven-levels ()
  7131. "Convert an Org file with only odd levels to one with odd/even levels.
  7132. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7133. file contains a section with an even level, conversion would
  7134. destroy the structure of the file. An error is signaled in this
  7135. case."
  7136. (interactive)
  7137. (goto-char (point-min))
  7138. ;; First check if there are no even levels
  7139. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7140. (org-show-set-visibility 'canonical)
  7141. (error "Not all levels are odd in this file. Conversion not possible"))
  7142. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7143. (let ((outline-regexp org-outline-regexp)
  7144. (outline-level 'org-outline-level)
  7145. (org-odd-levels-only nil) n)
  7146. (save-excursion
  7147. (goto-char (point-min))
  7148. (while (re-search-forward "^\\*\\*+ " nil t)
  7149. (setq n (/ (1- (length (match-string 0))) 2))
  7150. (while (>= (setq n (1- n)) 0)
  7151. (org-promote))
  7152. (end-of-line 1))))))
  7153. (defun org-tr-level (n)
  7154. "Make N odd if required."
  7155. (if org-odd-levels-only (1+ (/ n 2)) n))
  7156. ;;; Vertical tree motion, cutting and pasting of subtrees
  7157. (defun org-move-subtree-up (&optional arg)
  7158. "Move the current subtree up past ARG headlines of the same level."
  7159. (interactive "p")
  7160. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7161. (defun org-move-subtree-down (&optional arg)
  7162. "Move the current subtree down past ARG headlines of the same level."
  7163. (interactive "p")
  7164. (setq arg (prefix-numeric-value arg))
  7165. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7166. 'org-get-last-sibling))
  7167. (ins-point (make-marker))
  7168. (cnt (abs arg))
  7169. (col (current-column))
  7170. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7171. ;; Select the tree
  7172. (org-back-to-heading)
  7173. (setq beg0 (point))
  7174. (save-excursion
  7175. (setq ne-beg (org-back-over-empty-lines))
  7176. (setq beg (point)))
  7177. (save-match-data
  7178. (save-excursion (outline-end-of-heading)
  7179. (setq folded (org-invisible-p)))
  7180. (progn (org-end-of-subtree nil t)
  7181. (unless (eobp) (backward-char))))
  7182. (outline-next-heading)
  7183. (setq ne-end (org-back-over-empty-lines))
  7184. (setq end (point))
  7185. (goto-char beg0)
  7186. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7187. ;; include less whitespace
  7188. (save-excursion
  7189. (goto-char beg)
  7190. (forward-line (- ne-beg ne-end))
  7191. (setq beg (point))))
  7192. ;; Find insertion point, with error handling
  7193. (while (> cnt 0)
  7194. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7195. (progn (goto-char beg0)
  7196. (user-error "Cannot move past superior level or buffer limit")))
  7197. (setq cnt (1- cnt)))
  7198. (when (> arg 0)
  7199. ;; Moving forward - still need to move over subtree
  7200. (org-end-of-subtree t t)
  7201. (save-excursion
  7202. (org-back-over-empty-lines)
  7203. (or (bolp) (newline))))
  7204. (setq ne-ins (org-back-over-empty-lines))
  7205. (move-marker ins-point (point))
  7206. (setq txt (buffer-substring beg end))
  7207. (org-save-markers-in-region beg end)
  7208. (delete-region beg end)
  7209. (org-remove-empty-overlays-at beg)
  7210. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7211. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7212. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7213. (let ((bbb (point)))
  7214. (insert-before-markers txt)
  7215. (org-reinstall-markers-in-region bbb)
  7216. (move-marker ins-point bbb))
  7217. (or (bolp) (insert "\n"))
  7218. (setq ins-end (point))
  7219. (goto-char ins-point)
  7220. (org-skip-whitespace)
  7221. (when (and (< arg 0)
  7222. (org-first-sibling-p)
  7223. (> ne-ins ne-beg))
  7224. ;; Move whitespace back to beginning
  7225. (save-excursion
  7226. (goto-char ins-end)
  7227. (let ((kill-whole-line t))
  7228. (kill-line (- ne-ins ne-beg)) (point)))
  7229. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7230. (move-marker ins-point nil)
  7231. (if folded
  7232. (outline-hide-subtree)
  7233. (org-show-entry)
  7234. (org-show-children)
  7235. (org-cycle-hide-drawers 'children))
  7236. (org-clean-visibility-after-subtree-move)
  7237. ;; move back to the initial column we were at
  7238. (move-to-column col)))
  7239. (defvar org-subtree-clip ""
  7240. "Clipboard for cut and paste of subtrees.
  7241. This is actually only a copy of the kill, because we use the normal kill
  7242. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7243. (defvar org-subtree-clip-folded nil
  7244. "Was the last copied subtree folded?
  7245. This is used to fold the tree back after pasting.")
  7246. (defun org-cut-subtree (&optional n)
  7247. "Cut the current subtree into the clipboard.
  7248. With prefix arg N, cut this many sequential subtrees.
  7249. This is a short-hand for marking the subtree and then cutting it."
  7250. (interactive "p")
  7251. (org-copy-subtree n 'cut))
  7252. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7253. "Copy the current subtree it in the clipboard.
  7254. With prefix arg N, copy this many sequential subtrees.
  7255. This is a short-hand for marking the subtree and then copying it.
  7256. If CUT is non-nil, actually cut the subtree.
  7257. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7258. of some markers in the region, even if CUT is non-nil. This is
  7259. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7260. (interactive "p")
  7261. (let (beg end folded (beg0 (point)))
  7262. (if (called-interactively-p 'any)
  7263. (org-back-to-heading nil) ; take what looks like a subtree
  7264. (org-back-to-heading t)) ; take what is really there
  7265. (setq beg (point))
  7266. (skip-chars-forward " \t\r\n")
  7267. (save-match-data
  7268. (if nosubtrees
  7269. (outline-next-heading)
  7270. (save-excursion (outline-end-of-heading)
  7271. (setq folded (org-invisible-p)))
  7272. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7273. (org-end-of-subtree t t)))
  7274. ;; Include the end of an inlinetask
  7275. (when (and (featurep 'org-inlinetask)
  7276. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7277. "END[ \t]*$")))
  7278. (end-of-line))
  7279. (setq end (point))
  7280. (goto-char beg0)
  7281. (when (> end beg)
  7282. (setq org-subtree-clip-folded folded)
  7283. (when (or cut force-store-markers)
  7284. (org-save-markers-in-region beg end))
  7285. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7286. (setq org-subtree-clip (current-kill 0))
  7287. (message "%s: Subtree(s) with %d characters"
  7288. (if cut "Cut" "Copied")
  7289. (length org-subtree-clip)))))
  7290. (defun org-paste-subtree (&optional level tree for-yank remove)
  7291. "Paste the clipboard as a subtree, with modification of headline level.
  7292. The entire subtree is promoted or demoted in order to match a new headline
  7293. level.
  7294. If the cursor is at the beginning of a headline, the same level as
  7295. that headline is used to paste the tree.
  7296. If not, the new level is derived from the *visible* headings
  7297. before and after the insertion point, and taken to be the inferior headline
  7298. level of the two. So if the previous visible heading is level 3 and the
  7299. next is level 4 (or vice versa), level 4 will be used for insertion.
  7300. This makes sure that the subtree remains an independent subtree and does
  7301. not swallow low level entries.
  7302. You can also force a different level, either by using a numeric prefix
  7303. argument, or by inserting the heading marker by hand. For example, if the
  7304. cursor is after \"*****\", then the tree will be shifted to level 5.
  7305. If optional TREE is given, use this text instead of the kill ring.
  7306. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7307. move back over whitespace before inserting, and move point to the end of
  7308. the inserted text when done.
  7309. When REMOVE is non-nil, remove the subtree from the clipboard."
  7310. (interactive "P")
  7311. (setq tree (or tree (and kill-ring (current-kill 0))))
  7312. (unless (org-kill-is-subtree-p tree)
  7313. (user-error "%s"
  7314. (substitute-command-keys
  7315. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7316. (org-with-limited-levels
  7317. (let* ((visp (not (org-invisible-p)))
  7318. (txt tree)
  7319. (^re_ "\\(\\*+\\)[ \t]*")
  7320. (old-level (if (string-match org-outline-regexp-bol txt)
  7321. (- (match-end 0) (match-beginning 0) 1)
  7322. -1))
  7323. (force-level (cond (level (prefix-numeric-value level))
  7324. ((and (looking-at "[ \t]*$")
  7325. (string-match
  7326. "^\\*+$" (buffer-substring
  7327. (point-at-bol) (point))))
  7328. (- (match-end 0) (match-beginning 0)))
  7329. ((and (bolp)
  7330. (looking-at org-outline-regexp))
  7331. (- (match-end 0) (point) 1))))
  7332. (previous-level (save-excursion
  7333. (condition-case nil
  7334. (progn
  7335. (outline-previous-visible-heading 1)
  7336. (if (looking-at ^re_)
  7337. (- (match-end 0) (match-beginning 0) 1)
  7338. 1))
  7339. (error 1))))
  7340. (next-level (save-excursion
  7341. (condition-case nil
  7342. (progn
  7343. (or (looking-at org-outline-regexp)
  7344. (outline-next-visible-heading 1))
  7345. (if (looking-at ^re_)
  7346. (- (match-end 0) (match-beginning 0) 1)
  7347. 1))
  7348. (error 1))))
  7349. (new-level (or force-level (max previous-level next-level)))
  7350. (shift (if (or (= old-level -1)
  7351. (= new-level -1)
  7352. (= old-level new-level))
  7353. 0
  7354. (- new-level old-level)))
  7355. (delta (if (> shift 0) -1 1))
  7356. (func (if (> shift 0) 'org-demote 'org-promote))
  7357. (org-odd-levels-only nil)
  7358. beg end newend)
  7359. ;; Remove the forced level indicator
  7360. (when force-level
  7361. (delete-region (point-at-bol) (point)))
  7362. ;; Paste
  7363. (beginning-of-line (if (bolp) 1 2))
  7364. (setq beg (point))
  7365. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7366. (insert-before-markers txt)
  7367. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7368. (setq newend (point))
  7369. (org-reinstall-markers-in-region beg)
  7370. (setq end (point))
  7371. (goto-char beg)
  7372. (skip-chars-forward " \t\n\r")
  7373. (setq beg (point))
  7374. (when (and (org-invisible-p) visp)
  7375. (save-excursion (outline-show-heading)))
  7376. ;; Shift if necessary
  7377. (unless (= shift 0)
  7378. (save-restriction
  7379. (narrow-to-region beg end)
  7380. (while (not (= shift 0))
  7381. (org-map-region func (point-min) (point-max))
  7382. (setq shift (+ delta shift)))
  7383. (goto-char (point-min))
  7384. (setq newend (point-max))))
  7385. (when (or (called-interactively-p 'interactive) for-yank)
  7386. (message "Clipboard pasted as level %d subtree" new-level))
  7387. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7388. kill-ring
  7389. (eq org-subtree-clip (current-kill 0))
  7390. org-subtree-clip-folded)
  7391. ;; The tree was folded before it was killed/copied
  7392. (outline-hide-subtree))
  7393. (and for-yank (goto-char newend))
  7394. (and remove (setq kill-ring (cdr kill-ring))))))
  7395. (defun org-kill-is-subtree-p (&optional txt)
  7396. "Check if the current kill is an outline subtree, or a set of trees.
  7397. Returns nil if kill does not start with a headline, or if the first
  7398. headline level is not the largest headline level in the tree.
  7399. So this will actually accept several entries of equal levels as well,
  7400. which is OK for `org-paste-subtree'.
  7401. If optional TXT is given, check this string instead of the current kill."
  7402. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7403. (re (org-get-limited-outline-regexp))
  7404. (^re (concat "^" re))
  7405. (start-level (and kill
  7406. (string-match
  7407. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7408. kill)
  7409. (- (match-end 2) (match-beginning 2) 1)))
  7410. (start (1+ (or (match-beginning 2) -1))))
  7411. (if (not start-level)
  7412. (progn
  7413. nil) ;; does not even start with a heading
  7414. (catch 'exit
  7415. (while (setq start (string-match ^re kill (1+ start)))
  7416. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7417. (throw 'exit nil)))
  7418. t))))
  7419. (defvar org-markers-to-move nil
  7420. "Markers that should be moved with a cut-and-paste operation.
  7421. Those markers are stored together with their positions relative to
  7422. the start of the region.")
  7423. (defun org-save-markers-in-region (beg end)
  7424. "Check markers in region.
  7425. If these markers are between BEG and END, record their position relative
  7426. to BEG, so that after moving the block of text, we can put the markers back
  7427. into place.
  7428. This function gets called just before an entry or tree gets cut from the
  7429. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7430. called immediately, to move the markers with the entries."
  7431. (setq org-markers-to-move nil)
  7432. (when (featurep 'org-clock)
  7433. (org-clock-save-markers-for-cut-and-paste beg end))
  7434. (when (featurep 'org-agenda)
  7435. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7436. (defun org-check-and-save-marker (marker beg end)
  7437. "Check if MARKER is between BEG and END.
  7438. If yes, remember the marker and the distance to BEG."
  7439. (when (and (marker-buffer marker)
  7440. (equal (marker-buffer marker) (current-buffer))
  7441. (>= marker beg) (< marker end))
  7442. (push (cons marker (- marker beg)) org-markers-to-move)))
  7443. (defun org-reinstall-markers-in-region (beg)
  7444. "Move all remembered markers to their position relative to BEG."
  7445. (dolist (x org-markers-to-move)
  7446. (move-marker (car x) (+ beg (cdr x))))
  7447. (setq org-markers-to-move nil))
  7448. (defun org-narrow-to-subtree ()
  7449. "Narrow buffer to the current subtree."
  7450. (interactive)
  7451. (save-excursion
  7452. (save-match-data
  7453. (org-with-limited-levels
  7454. (narrow-to-region
  7455. (progn (org-back-to-heading t) (point))
  7456. (progn (org-end-of-subtree t t)
  7457. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7458. (point)))))))
  7459. (defun org-narrow-to-block ()
  7460. "Narrow buffer to the current block."
  7461. (interactive)
  7462. (let* ((case-fold-search t)
  7463. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7464. "^[ \t]*#\\+end_.*")))
  7465. (if blockp
  7466. (narrow-to-region (car blockp) (cdr blockp))
  7467. (user-error "Not in a block"))))
  7468. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7469. "Clone the task (subtree) at point N times.
  7470. The clones will be inserted as siblings.
  7471. In interactive use, the user will be prompted for the number of
  7472. clones to be produced. If the entry has a timestamp, the user
  7473. will also be prompted for a time shift, which may be a repeater
  7474. as used in time stamps, for example `+3d'. To disable this,
  7475. you can call the function with a universal prefix argument.
  7476. When a valid repeater is given and the entry contains any time
  7477. stamps, the clones will become a sequence in time, with time
  7478. stamps in the subtree shifted for each clone produced. If SHIFT
  7479. is nil or the empty string, time stamps will be left alone. The
  7480. ID property of the original subtree is removed.
  7481. In each clone, all the CLOCK entries will be removed. This
  7482. prevents Org from considering that the clocked times overlap.
  7483. If the original subtree did contain time stamps with a repeater,
  7484. the following will happen:
  7485. - the repeater will be removed in each clone
  7486. - an additional clone will be produced, with the current, unshifted
  7487. date(s) in the entry.
  7488. - the original entry will be placed *after* all the clones, with
  7489. repeater intact.
  7490. - the start days in the repeater in the original entry will be shifted
  7491. to past the last clone.
  7492. In this way you can spell out a number of instances of a repeating task,
  7493. and still retain the repeater to cover future instances of the task.
  7494. As described above, N+1 clones are produced when the original
  7495. subtree has a repeater. Setting N to 0, then, can be used to
  7496. remove the repeater from a subtree and create a shifted clone
  7497. with the original repeater."
  7498. (interactive "nNumber of clones to produce: ")
  7499. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7500. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7501. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7502. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7503. (shift
  7504. (or shift
  7505. (if (and (not (equal current-prefix-arg '(4)))
  7506. (save-excursion
  7507. (goto-char beg)
  7508. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7509. (read-from-minibuffer
  7510. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7511. ""))) ;No time shift
  7512. (doshift
  7513. (and (org-string-nw-p shift)
  7514. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7515. shift)
  7516. (user-error "Invalid shift specification %s" shift)))))
  7517. (goto-char end-of-tree)
  7518. (unless (bolp) (insert "\n"))
  7519. (let* ((end (point))
  7520. (template (buffer-substring beg end))
  7521. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7522. (shift-what (pcase (and doshift (match-string 2 shift))
  7523. (`nil nil)
  7524. ("d" 'day)
  7525. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7526. ("m" 'month)
  7527. ("y" 'year)
  7528. (_ (error "Unsupported time unit"))))
  7529. (nmin 1)
  7530. (nmax n)
  7531. (n-no-remove -1)
  7532. (idprop (org-entry-get nil "ID")))
  7533. (when (and doshift
  7534. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7535. template))
  7536. (delete-region beg end)
  7537. (setq end beg)
  7538. (setq nmin 0)
  7539. (setq nmax (1+ nmax))
  7540. (setq n-no-remove nmax))
  7541. (goto-char end)
  7542. (cl-loop for n from nmin to nmax do
  7543. (insert
  7544. ;; Prepare clone.
  7545. (with-temp-buffer
  7546. (insert template)
  7547. (org-mode)
  7548. (goto-char (point-min))
  7549. (org-show-subtree)
  7550. (and idprop (if org-clone-delete-id
  7551. (org-entry-delete nil "ID")
  7552. (org-id-get-create t)))
  7553. (unless (= n 0)
  7554. (while (re-search-forward org-clock-line-re nil t)
  7555. (delete-region (line-beginning-position)
  7556. (line-beginning-position 2)))
  7557. (goto-char (point-min))
  7558. (while (re-search-forward org-drawer-regexp nil t)
  7559. (org-remove-empty-drawer-at (point))))
  7560. (goto-char (point-min))
  7561. (when doshift
  7562. (while (re-search-forward org-ts-regexp-both nil t)
  7563. (org-timestamp-change (* n shift-n) shift-what))
  7564. (unless (= n n-no-remove)
  7565. (goto-char (point-min))
  7566. (while (re-search-forward org-ts-regexp nil t)
  7567. (save-excursion
  7568. (goto-char (match-beginning 0))
  7569. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7570. (delete-region (match-beginning 1) (match-end 1)))))))
  7571. (buffer-string)))))
  7572. (goto-char beg)))
  7573. ;;; Outline Sorting
  7574. (defun org-sort (&optional with-case)
  7575. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7576. Optional argument WITH-CASE means sort case-sensitively."
  7577. (interactive "P")
  7578. (org-call-with-arg
  7579. (cond ((org-at-table-p) #'org-table-sort-lines)
  7580. ((org-at-item-p) #'org-sort-list)
  7581. (t #'org-sort-entries))
  7582. with-case))
  7583. (defun org-sort-remove-invisible (s)
  7584. "Remove invisible part of links and emphasis markers from string S."
  7585. (remove-text-properties 0 (length s) org-rm-props s)
  7586. (replace-regexp-in-string
  7587. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7588. (replace-regexp-in-string
  7589. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7590. (org-link-display-format s)
  7591. t t) t t))
  7592. (defvar org-priority-regexp) ; defined later in the file
  7593. (defvar org-after-sorting-entries-or-items-hook nil
  7594. "Hook that is run after a bunch of entries or items have been sorted.
  7595. When children are sorted, the cursor is in the parent line when this
  7596. hook gets called. When a region or a plain list is sorted, the cursor
  7597. will be in the first entry of the sorted region/list.")
  7598. (defun org-sort-entries
  7599. (&optional with-case sorting-type getkey-func compare-func property
  7600. interactive?)
  7601. "Sort entries on a certain level of an outline tree.
  7602. If there is an active region, the entries in the region are sorted.
  7603. Else, if the cursor is before the first entry, sort the top-level items.
  7604. Else, the children of the entry at point are sorted.
  7605. Sorting can be alphabetically, numerically, by date/time as given by
  7606. a time stamp, by a property, by priority order, or by a custom function.
  7607. The command prompts for the sorting type unless it has been given to the
  7608. function through the SORTING-TYPE argument, which needs to be a character,
  7609. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7610. the precise meaning of each character:
  7611. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7612. c By creation time, which is assumed to be the first inactive time stamp
  7613. at the beginning of a line.
  7614. d By deadline date/time.
  7615. k By clocking time.
  7616. n Numerically, by converting the beginning of the entry/item to a number.
  7617. o By order of TODO keywords.
  7618. p By priority according to the cookie.
  7619. r By the value of a property.
  7620. s By scheduled date/time.
  7621. t By date/time, either the first active time stamp in the entry, or, if
  7622. none exist, by the first inactive one.
  7623. Capital letters will reverse the sort order.
  7624. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7625. called with point at the beginning of the record. It must return a
  7626. value that is compatible with COMPARE-FUNC, the function used to
  7627. compare entries.
  7628. Comparing entries ignores case by default. However, with an optional argument
  7629. WITH-CASE, the sorting considers case as well.
  7630. Sorting is done against the visible part of the headlines, it ignores hidden
  7631. links.
  7632. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7633. A non-nil value for INTERACTIVE? is used to signal that this
  7634. function is being called interactively."
  7635. (interactive (list current-prefix-arg nil nil nil nil t))
  7636. (let ((case-func (if with-case 'identity 'downcase))
  7637. start beg end stars re re2
  7638. txt what tmp)
  7639. ;; Find beginning and end of region to sort
  7640. (cond
  7641. ((org-region-active-p)
  7642. ;; we will sort the region
  7643. (setq end (region-end)
  7644. what "region")
  7645. (goto-char (region-beginning))
  7646. (unless (org-at-heading-p) (outline-next-heading))
  7647. (setq start (point)))
  7648. ((or (org-at-heading-p)
  7649. (ignore-errors (progn (org-back-to-heading) t)))
  7650. ;; we will sort the children of the current headline
  7651. (org-back-to-heading)
  7652. (setq start (point)
  7653. end (progn (org-end-of-subtree t t)
  7654. (or (bolp) (insert "\n"))
  7655. (when (>= (org-back-over-empty-lines) 1)
  7656. (forward-line 1))
  7657. (point))
  7658. what "children")
  7659. (goto-char start)
  7660. (outline-show-subtree)
  7661. (outline-next-heading))
  7662. (t
  7663. ;; we will sort the top-level entries in this file
  7664. (goto-char (point-min))
  7665. (or (org-at-heading-p) (outline-next-heading))
  7666. (setq start (point))
  7667. (goto-char (point-max))
  7668. (beginning-of-line 1)
  7669. (when (looking-at ".*?\\S-")
  7670. ;; File ends in a non-white line
  7671. (end-of-line 1)
  7672. (insert "\n"))
  7673. (setq end (point-max))
  7674. (setq what "top-level")
  7675. (goto-char start)
  7676. (outline-show-all)))
  7677. (setq beg (point))
  7678. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7679. (looking-at "\\(\\*+\\)")
  7680. (setq stars (match-string 1)
  7681. re (concat "^" (regexp-quote stars) " +")
  7682. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7683. txt (buffer-substring beg end))
  7684. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7685. (when (and (not (equal stars "*")) (string-match re2 txt))
  7686. (user-error "Region to sort contains a level above the first entry"))
  7687. (unless sorting-type
  7688. (message
  7689. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7690. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7691. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7692. what)
  7693. (setq sorting-type (read-char-exclusive)))
  7694. (unless getkey-func
  7695. (and (= (downcase sorting-type) ?f)
  7696. (setq getkey-func
  7697. (or (and interactive?
  7698. (org-read-function
  7699. "Function for extracting keys: "))
  7700. (error "Missing key extractor")))))
  7701. (and (= (downcase sorting-type) ?r)
  7702. (not property)
  7703. (setq property
  7704. (completing-read "Property: "
  7705. (mapcar #'list (org-buffer-property-keys t))
  7706. nil t)))
  7707. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7708. (message "Sorting entries...")
  7709. (save-restriction
  7710. (narrow-to-region start end)
  7711. (let ((restore-clock?
  7712. ;; The clock marker is lost when using `sort-subr'; mark
  7713. ;; the clock with temporary `:org-clock-marker-backup'
  7714. ;; text property.
  7715. (when (and (eq (org-clock-is-active) (current-buffer))
  7716. (<= start (marker-position org-clock-marker))
  7717. (>= end (marker-position org-clock-marker)))
  7718. (org-with-silent-modifications
  7719. (put-text-property (1- org-clock-marker) org-clock-marker
  7720. :org-clock-marker-backup t))
  7721. t))
  7722. (dcst (downcase sorting-type))
  7723. (case-fold-search nil)
  7724. (now (current-time)))
  7725. (sort-subr
  7726. (/= dcst sorting-type)
  7727. ;; This function moves to the beginning character of the "record" to
  7728. ;; be sorted.
  7729. (lambda nil
  7730. (if (re-search-forward re nil t)
  7731. (goto-char (match-beginning 0))
  7732. (goto-char (point-max))))
  7733. ;; This function moves to the last character of the "record" being
  7734. ;; sorted.
  7735. (lambda nil
  7736. (save-match-data
  7737. (condition-case nil
  7738. (outline-forward-same-level 1)
  7739. (error
  7740. (goto-char (point-max))))))
  7741. ;; This function returns the value that gets sorted against.
  7742. (lambda nil
  7743. (cond
  7744. ((= dcst ?n)
  7745. (if (looking-at org-complex-heading-regexp)
  7746. (string-to-number (org-sort-remove-invisible (match-string 4)))
  7747. nil))
  7748. ((= dcst ?a)
  7749. (if (looking-at org-complex-heading-regexp)
  7750. (funcall case-func (org-sort-remove-invisible (match-string 4)))
  7751. nil))
  7752. ((= dcst ?k)
  7753. (or (get-text-property (point) :org-clock-minutes) 0))
  7754. ((= dcst ?t)
  7755. (let ((end (save-excursion (outline-next-heading) (point))))
  7756. (if (or (re-search-forward org-ts-regexp end t)
  7757. (re-search-forward org-ts-regexp-both end t))
  7758. (org-time-string-to-seconds (match-string 0))
  7759. (float-time now))))
  7760. ((= dcst ?c)
  7761. (let ((end (save-excursion (outline-next-heading) (point))))
  7762. (if (re-search-forward
  7763. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7764. end t)
  7765. (org-time-string-to-seconds (match-string 0))
  7766. (float-time now))))
  7767. ((= dcst ?s)
  7768. (let ((end (save-excursion (outline-next-heading) (point))))
  7769. (if (re-search-forward org-scheduled-time-regexp end t)
  7770. (org-time-string-to-seconds (match-string 1))
  7771. (float-time now))))
  7772. ((= dcst ?d)
  7773. (let ((end (save-excursion (outline-next-heading) (point))))
  7774. (if (re-search-forward org-deadline-time-regexp end t)
  7775. (org-time-string-to-seconds (match-string 1))
  7776. (float-time now))))
  7777. ((= dcst ?p)
  7778. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7779. (string-to-char (match-string 2))
  7780. org-default-priority))
  7781. ((= dcst ?r)
  7782. (or (org-entry-get nil property) ""))
  7783. ((= dcst ?o)
  7784. (when (looking-at org-complex-heading-regexp)
  7785. (let* ((m (match-string 2))
  7786. (s (if (member m org-done-keywords) '- '+)))
  7787. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7788. ((= dcst ?f)
  7789. (if getkey-func
  7790. (progn
  7791. (setq tmp (funcall getkey-func))
  7792. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7793. tmp)
  7794. (error "Invalid key function `%s'" getkey-func)))
  7795. (t (error "Invalid sorting type `%c'" sorting-type))))
  7796. nil
  7797. (cond
  7798. ((= dcst ?a) 'string<)
  7799. ((= dcst ?f)
  7800. (or compare-func
  7801. (and interactive?
  7802. (org-read-function
  7803. (concat "Function for comparing keys "
  7804. "(empty for default `sort-subr' predicate): ")
  7805. 'allow-empty))))
  7806. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
  7807. (when restore-clock?
  7808. (move-marker org-clock-marker
  7809. (1+ (next-single-property-change
  7810. start :org-clock-marker-backup)))
  7811. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7812. '(:org-clock-marker-backup t)))))
  7813. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7814. (message "Sorting entries...done")))
  7815. ;;; The orgstruct minor mode
  7816. ;; Define a minor mode which can be used in other modes in order to
  7817. ;; integrate the Org mode structure editing commands.
  7818. ;; This is really a hack, because the Org mode structure commands use
  7819. ;; keys which normally belong to the major mode. Here is how it
  7820. ;; works: The minor mode defines all the keys necessary to operate the
  7821. ;; structure commands, but wraps the commands into a function which
  7822. ;; tests if the cursor is currently at a headline or a plain list
  7823. ;; item. If that is the case, the structure command is used,
  7824. ;; temporarily setting many Org mode variables like regular
  7825. ;; expressions for filling etc. However, when any of those keys is
  7826. ;; used at a different location, function uses `key-binding' to look
  7827. ;; up if the key has an associated command in another currently active
  7828. ;; keymap (minor modes, major mode, global), and executes that
  7829. ;; command. There might be problems if any of the keys is otherwise
  7830. ;; used as a prefix key.
  7831. (defcustom orgstruct-heading-prefix-regexp ""
  7832. "Regexp that matches the custom prefix of Org headlines in
  7833. orgstruct(++)-mode."
  7834. :group 'org
  7835. :version "26.1"
  7836. :package-version '(Org . "8.3")
  7837. :type 'regexp)
  7838. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  7839. (defcustom orgstruct-setup-hook nil
  7840. "Hook run after orgstruct-mode-map is filled."
  7841. :group 'org
  7842. :version "24.4"
  7843. :package-version '(Org . "8.0")
  7844. :type 'hook)
  7845. (defvar orgstruct-initialized nil)
  7846. (defvar org-local-vars nil
  7847. "List of local variables, for use by `orgstruct-mode'.")
  7848. ;;;###autoload
  7849. (define-minor-mode orgstruct-mode
  7850. "Toggle the minor mode `orgstruct-mode'.
  7851. This mode is for using Org mode structure commands in other
  7852. modes. The following keys behave as if Org mode were active, if
  7853. the cursor is on a headline, or on a plain list item (both as
  7854. defined by Org mode)."
  7855. nil " OrgStruct" (make-sparse-keymap)
  7856. (funcall (if orgstruct-mode
  7857. 'add-to-invisibility-spec
  7858. 'remove-from-invisibility-spec)
  7859. '(outline . t))
  7860. (when orgstruct-mode
  7861. (org-load-modules-maybe)
  7862. (unless orgstruct-initialized
  7863. (orgstruct-setup)
  7864. (setq orgstruct-initialized t))))
  7865. ;;;###autoload
  7866. (defun turn-on-orgstruct ()
  7867. "Unconditionally turn on `orgstruct-mode'."
  7868. (orgstruct-mode 1))
  7869. (defvar-local orgstruct-is-++ nil
  7870. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  7871. (defvar-local org-fb-vars nil)
  7872. (defun orgstruct++-mode (&optional arg)
  7873. "Toggle `orgstruct-mode', the enhanced version of it.
  7874. In addition to setting orgstruct-mode, this also exports all
  7875. indentation and autofilling variables from Org mode into the
  7876. buffer. It will also recognize item context in multiline items."
  7877. (interactive "P")
  7878. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  7879. (if (< arg 1)
  7880. (progn (orgstruct-mode -1)
  7881. (dolist (v org-fb-vars)
  7882. (set (make-local-variable (car v))
  7883. (if (eq (car-safe (cadr v)) 'quote)
  7884. (cl-cadadr v)
  7885. (nth 1 v)))))
  7886. (orgstruct-mode 1)
  7887. (setq org-fb-vars nil)
  7888. (unless org-local-vars
  7889. (setq org-local-vars (org-get-local-variables)))
  7890. (let (var val)
  7891. (dolist (x org-local-vars)
  7892. (when (string-match
  7893. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
  7894. \\|fill-prefix\\|indent-\\)"
  7895. (symbol-name (car x)))
  7896. (setq var (car x) val (nth 1 x))
  7897. (push (list var `(quote ,(eval var))) org-fb-vars)
  7898. (set (make-local-variable var)
  7899. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  7900. (setq-local orgstruct-is-++ t))))
  7901. ;;;###autoload
  7902. (defun turn-on-orgstruct++ ()
  7903. "Unconditionally turn on `orgstruct++-mode'."
  7904. (orgstruct++-mode 1))
  7905. (defun orgstruct-error ()
  7906. "Error when there is no default binding for a structure key."
  7907. (interactive)
  7908. (funcall (if (fboundp 'user-error)
  7909. 'user-error
  7910. 'error)
  7911. "This key has no function outside structure elements"))
  7912. (defun orgstruct-setup ()
  7913. "Setup orgstruct keymap."
  7914. (dolist (cell '((org-demote . t)
  7915. (org-metaleft . t)
  7916. (org-metaright . t)
  7917. (org-promote . t)
  7918. (org-shiftmetaleft . t)
  7919. (org-shiftmetaright . t)
  7920. org-backward-element
  7921. org-backward-heading-same-level
  7922. org-ctrl-c-ret
  7923. org-ctrl-c-minus
  7924. org-ctrl-c-star
  7925. org-cycle
  7926. org-force-cycle-archived
  7927. org-forward-heading-same-level
  7928. org-insert-heading
  7929. org-insert-heading-respect-content
  7930. org-kill-note-or-show-branches
  7931. org-mark-subtree
  7932. org-meta-return
  7933. org-metadown
  7934. org-metaup
  7935. org-narrow-to-subtree
  7936. org-promote-subtree
  7937. org-reveal
  7938. org-shiftdown
  7939. org-shiftleft
  7940. org-shiftmetadown
  7941. org-shiftmetaup
  7942. org-shiftright
  7943. org-shifttab
  7944. org-shifttab
  7945. org-shiftup
  7946. org-show-children
  7947. org-show-subtree
  7948. org-sort
  7949. org-up-element
  7950. outline-demote
  7951. outline-next-visible-heading
  7952. outline-previous-visible-heading
  7953. outline-promote
  7954. outline-up-heading))
  7955. (let ((f (or (car-safe cell) cell))
  7956. (disable-when-heading-prefix (cdr-safe cell)))
  7957. (when (fboundp f)
  7958. (let ((new-bindings))
  7959. (dolist (binding (nconc (where-is-internal f org-mode-map)
  7960. (where-is-internal f outline-mode-map)))
  7961. (push binding new-bindings)
  7962. ;; TODO use local-function-key-map
  7963. (dolist (rep '(("<tab>" . "TAB")
  7964. ("<return>" . "RET")
  7965. ("<escape>" . "ESC")
  7966. ("<delete>" . "DEL")))
  7967. (setq binding (read-kbd-macro
  7968. (let ((case-fold-search))
  7969. (replace-regexp-in-string
  7970. (regexp-quote (cdr rep))
  7971. (car rep)
  7972. (key-description binding)))))
  7973. (cl-pushnew binding new-bindings :test 'equal)))
  7974. (dolist (binding new-bindings)
  7975. (let ((key (lookup-key orgstruct-mode-map binding)))
  7976. (when (or (not key) (numberp key))
  7977. (ignore-errors
  7978. (org-defkey orgstruct-mode-map
  7979. binding
  7980. (orgstruct-make-binding
  7981. f binding disable-when-heading-prefix))))))))))
  7982. (run-hooks 'orgstruct-setup-hook))
  7983. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  7984. "Create a function for binding in the structure minor mode.
  7985. FUN is the command to call inside a table. KEY is the key that
  7986. should be checked in for a command to execute outside of tables.
  7987. Non-nil `disable-when-heading-prefix' means to disable the command
  7988. if `orgstruct-heading-prefix-regexp' is not empty."
  7989. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  7990. (let ((nname name)
  7991. (i 0))
  7992. (while (fboundp (intern nname))
  7993. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  7994. (setq name (intern nname)))
  7995. (eval
  7996. (let ((bindings '((org-heading-regexp
  7997. (concat "^"
  7998. orgstruct-heading-prefix-regexp
  7999. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  8000. (org-outline-regexp
  8001. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  8002. (org-outline-regexp-bol
  8003. (concat "^" org-outline-regexp))
  8004. (outline-regexp org-outline-regexp)
  8005. (outline-heading-end-regexp "\n")
  8006. (outline-level 'org-outline-level)
  8007. (outline-heading-alist))))
  8008. `(defun ,name (arg)
  8009. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8010. "Outside of structure, run the binding of `"
  8011. (key-description key) "'."
  8012. (when disable-when-heading-prefix
  8013. (concat
  8014. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8015. "back to the default binding due to limitations of Org's implementation of\n"
  8016. "`" (symbol-name fun) "'.")))
  8017. (interactive "p")
  8018. (let* ((disable
  8019. ,(and disable-when-heading-prefix
  8020. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8021. (fallback
  8022. (or disable
  8023. (not
  8024. (let* ,bindings
  8025. (org-context-p 'headline 'item
  8026. ,(when (memq fun
  8027. '(org-insert-heading
  8028. org-insert-heading-respect-content
  8029. org-meta-return))
  8030. '(when orgstruct-is-++
  8031. 'item-body))))))))
  8032. (if fallback
  8033. (let* ((orgstruct-mode)
  8034. (binding
  8035. (let ((key ,key))
  8036. (catch 'exit
  8037. (dolist
  8038. (rep
  8039. '(nil
  8040. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8041. ("<\\([^>]*\\)return>" . "\\1RET")
  8042. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8043. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8044. nil)
  8045. (when rep
  8046. (setq key (read-kbd-macro
  8047. (let ((case-fold-search))
  8048. (replace-regexp-in-string
  8049. (car rep)
  8050. (cdr rep)
  8051. (key-description key))))))
  8052. (when (key-binding key)
  8053. (throw 'exit (key-binding key))))))))
  8054. (if (keymapp binding)
  8055. (org-set-transient-map binding)
  8056. (let ((func (or binding
  8057. (unless disable
  8058. 'orgstruct-error))))
  8059. (when func
  8060. (call-interactively func)))))
  8061. (org-run-like-in-org-mode
  8062. (lambda ()
  8063. (interactive)
  8064. (let* ,bindings
  8065. (call-interactively ',fun)))))))))
  8066. name))
  8067. (defun org-contextualize-keys (alist contexts)
  8068. "Return valid elements in ALIST depending on CONTEXTS.
  8069. `org-agenda-custom-commands' or `org-capture-templates' are the
  8070. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8071. or `org-capture-templates-contexts' are the associated contexts
  8072. definitions."
  8073. (let ((contexts
  8074. ;; normalize contexts
  8075. (mapcar
  8076. (lambda(c) (cond ((listp (cadr c))
  8077. (list (car c) (car c) (nth 1 c)))
  8078. ((string= "" (cadr c))
  8079. (list (car c) (car c) (nth 2 c)))
  8080. (t c)))
  8081. contexts))
  8082. (a alist) r s)
  8083. ;; loop over all commands or templates
  8084. (dolist (c a)
  8085. (let (vrules repl)
  8086. (cond
  8087. ((not (assoc (car c) contexts))
  8088. (push c r))
  8089. ((and (assoc (car c) contexts)
  8090. (setq vrules (org-contextualize-validate-key
  8091. (car c) contexts)))
  8092. (mapc (lambda (vr)
  8093. (unless (equal (car vr) (cadr vr))
  8094. (setq repl vr)))
  8095. vrules)
  8096. (if (not repl) (push c r)
  8097. (push (cadr repl) s)
  8098. (push
  8099. (cons (car c)
  8100. (cdr (or (assoc (cadr repl) alist)
  8101. (error "Undefined key `%s' as contextual replacement for `%s'"
  8102. (cadr repl) (car c)))))
  8103. r))))))
  8104. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8105. (delq
  8106. nil
  8107. (delete-dups
  8108. (mapcar (lambda (x)
  8109. (let ((tpl (car x)))
  8110. (unless (delq
  8111. nil
  8112. (mapcar (lambda (y)
  8113. (equal y tpl))
  8114. s))
  8115. x)))
  8116. (reverse r))))))
  8117. (defun org-contextualize-validate-key (key contexts)
  8118. "Check CONTEXTS for agenda or capture KEY."
  8119. (let (res)
  8120. (dolist (r contexts)
  8121. (dolist (rr (car (last r)))
  8122. (when
  8123. (and (equal key (car r))
  8124. (if (functionp rr) (funcall rr)
  8125. (or (and (eq (car rr) 'in-file)
  8126. (buffer-file-name)
  8127. (string-match (cdr rr) (buffer-file-name)))
  8128. (and (eq (car rr) 'in-mode)
  8129. (string-match (cdr rr) (symbol-name major-mode)))
  8130. (and (eq (car rr) 'in-buffer)
  8131. (string-match (cdr rr) (buffer-name)))
  8132. (when (and (eq (car rr) 'not-in-file)
  8133. (buffer-file-name))
  8134. (not (string-match (cdr rr) (buffer-file-name))))
  8135. (when (eq (car rr) 'not-in-mode)
  8136. (not (string-match (cdr rr) (symbol-name major-mode))))
  8137. (when (eq (car rr) 'not-in-buffer)
  8138. (not (string-match (cdr rr) (buffer-name)))))))
  8139. (push r res))))
  8140. (delete-dups (delq nil res))))
  8141. (defun org-context-p (&rest contexts)
  8142. "Check if local context is any of CONTEXTS.
  8143. Possible values in the list of contexts are `table', `headline', and `item'."
  8144. (let ((pos (point)))
  8145. (goto-char (point-at-bol))
  8146. (prog1 (or (and (memq 'table contexts)
  8147. (looking-at "[ \t]*|"))
  8148. (and (memq 'headline contexts)
  8149. (looking-at org-outline-regexp))
  8150. (and (memq 'item contexts)
  8151. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8152. (and (memq 'item-body contexts)
  8153. (org-in-item-p)))
  8154. (goto-char pos))))
  8155. ;;;###autoload
  8156. (defun org-run-like-in-org-mode (cmd)
  8157. "Run a command, pretending that the current buffer is in Org mode.
  8158. This will temporarily bind local variables that are typically bound in
  8159. Org mode to the values they have in Org mode, and then interactively
  8160. call CMD."
  8161. (org-load-modules-maybe)
  8162. (unless org-local-vars
  8163. (setq org-local-vars (org-get-local-variables)))
  8164. (let (binds)
  8165. (dolist (var org-local-vars)
  8166. (when (or (not (boundp (car var)))
  8167. (eq (symbol-value (car var))
  8168. (default-value (car var))))
  8169. (push (list (car var) `(quote ,(cadr var))) binds)))
  8170. (eval `(let ,binds
  8171. (call-interactively (quote ,cmd))))))
  8172. (defun org-get-category (&optional pos force-refresh)
  8173. "Get the category applying to position POS."
  8174. (save-match-data
  8175. (when force-refresh (org-refresh-category-properties))
  8176. (let ((pos (or pos (point))))
  8177. (or (get-text-property pos 'org-category)
  8178. (progn (org-refresh-category-properties)
  8179. (get-text-property pos 'org-category))))))
  8180. ;;; Refresh properties
  8181. (defun org-refresh-properties (dprop tprop)
  8182. "Refresh buffer text properties.
  8183. DPROP is the drawer property and TPROP is either the
  8184. corresponding text property to set, or an alist with each element
  8185. being a text property (as a symbol) and a function to apply to
  8186. the value of the drawer property."
  8187. (let* ((case-fold-search t)
  8188. (inhibit-read-only t)
  8189. (inherit? (org-property-inherit-p dprop))
  8190. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  8191. (global (and inherit? (org--property-global-value dprop nil))))
  8192. (org-with-silent-modifications
  8193. (org-with-point-at 1
  8194. ;; Set global values (e.g., values defined through
  8195. ;; "#+PROPERTY:" keywords) to the whole buffer.
  8196. (when global (put-text-property (point-min) (point-max) tprop global))
  8197. ;; Set local values.
  8198. (while (re-search-forward property-re nil t)
  8199. (when (org-at-property-p)
  8200. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  8201. (outline-next-heading))))))
  8202. (defun org-refresh-property (tprop p &optional inherit)
  8203. "Refresh the buffer text property TPROP from the drawer property P.
  8204. The refresh happens only for the current headline, or the whole
  8205. sub-tree if optional argument INHERIT is non-nil."
  8206. (unless (org-before-first-heading-p)
  8207. (save-excursion
  8208. (org-back-to-heading t)
  8209. (let ((start (point))
  8210. (end (save-excursion
  8211. (if inherit (org-end-of-subtree t t)
  8212. (or (outline-next-heading) (point-max))))))
  8213. (if (symbolp tprop)
  8214. ;; TPROP is a text property symbol.
  8215. (put-text-property start end tprop p)
  8216. ;; TPROP is an alist with (property . function) elements.
  8217. (pcase-dolist (`(,prop . ,f) tprop)
  8218. (put-text-property start end prop (funcall f p))))))))
  8219. (defun org-refresh-category-properties ()
  8220. "Refresh category text properties in the buffer."
  8221. (let ((case-fold-search t)
  8222. (inhibit-read-only t)
  8223. (default-category
  8224. (cond ((null org-category)
  8225. (if buffer-file-name
  8226. (file-name-sans-extension
  8227. (file-name-nondirectory buffer-file-name))
  8228. "???"))
  8229. ((symbolp org-category) (symbol-name org-category))
  8230. (t org-category))))
  8231. (org-with-silent-modifications
  8232. (org-with-wide-buffer
  8233. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8234. ;; This is the default category for the buffer. If none is
  8235. ;; found, fall-back to `org-category' or buffer file name.
  8236. (put-text-property
  8237. (point-min) (point-max)
  8238. 'org-category
  8239. (catch 'buffer-category
  8240. (goto-char (point-max))
  8241. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8242. (let ((element (org-element-at-point)))
  8243. (when (eq (org-element-type element) 'keyword)
  8244. (throw 'buffer-category
  8245. (org-element-property :value element)))))
  8246. default-category))
  8247. ;; Set sub-tree specific categories.
  8248. (goto-char (point-min))
  8249. (let ((regexp (org-re-property "CATEGORY")))
  8250. (while (re-search-forward regexp nil t)
  8251. (let ((value (match-string-no-properties 3)))
  8252. (when (org-at-property-p)
  8253. (put-text-property
  8254. (save-excursion (org-back-to-heading t) (point))
  8255. (save-excursion (org-end-of-subtree t t) (point))
  8256. 'org-category
  8257. value)))))))))
  8258. (defun org-refresh-stats-properties ()
  8259. "Refresh stats text properties in the buffer."
  8260. (org-with-silent-modifications
  8261. (org-with-point-at 1
  8262. (let ((regexp (concat org-outline-regexp-bol
  8263. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8264. (while (re-search-forward regexp nil t)
  8265. (let* ((numerator (string-to-number (match-string 1)))
  8266. (denominator (and (match-end 2)
  8267. (string-to-number (match-string 2))))
  8268. (stats (cond ((not denominator) numerator) ;percent
  8269. ((= denominator 0) 0)
  8270. (t (/ (* numerator 100) denominator)))))
  8271. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8272. 'org-stats stats)))))))
  8273. (defun org-refresh-effort-properties ()
  8274. "Refresh effort properties"
  8275. (org-refresh-properties
  8276. org-effort-property
  8277. '((effort . identity)
  8278. (effort-minutes . org-duration-to-minutes))))
  8279. ;;;; Link Stuff
  8280. ;;; Link abbreviations
  8281. (defun org-link-expand-abbrev (link)
  8282. "Apply replacements as defined in `org-link-abbrev-alist'."
  8283. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8284. (let* ((key (match-string 1 link))
  8285. (as (or (assoc key org-link-abbrev-alist-local)
  8286. (assoc key org-link-abbrev-alist)))
  8287. (tag (and (match-end 2) (match-string 3 link)))
  8288. rpl)
  8289. (if (not as)
  8290. link
  8291. (setq rpl (cdr as))
  8292. (cond
  8293. ((symbolp rpl) (funcall rpl tag))
  8294. ((string-match "%(\\([^)]+\\))" rpl)
  8295. (replace-match
  8296. (save-match-data
  8297. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8298. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8299. ((string-match "%h" rpl)
  8300. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8301. (t (concat rpl tag)))))
  8302. link))
  8303. ;;; Storing and inserting links
  8304. (defvar org-insert-link-history nil
  8305. "Minibuffer history for links inserted with `org-insert-link'.")
  8306. (defvar org-stored-links nil
  8307. "Contains the links stored with `org-store-link'.")
  8308. (defvar org-store-link-plist nil
  8309. "Plist with info about the most recently link created with `org-store-link'.")
  8310. (defun org-store-link-functions ()
  8311. "Return a list of functions that are called to create and store a link.
  8312. The functions defined in the :store property of
  8313. `org-link-parameters'.
  8314. Each function will be called in turn until one returns a non-nil
  8315. value. Each function should check if it is responsible for
  8316. creating this link (for example by looking at the major mode).
  8317. If not, it must exit and return nil. If yes, it should return
  8318. a non-nil value after calling `org-store-link-props' with a list
  8319. of properties and values. Special properties are:
  8320. :type The link prefix, like \"http\". This must be given.
  8321. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8322. This is obligatory as well.
  8323. :description Optional default description for the second pair
  8324. of brackets in an Org mode link. The user can still change
  8325. this when inserting this link into an Org mode buffer.
  8326. In addition to these, any additional properties can be specified
  8327. and then used in capture templates."
  8328. (cl-loop for link in org-link-parameters
  8329. with store-func
  8330. do (setq store-func (org-link-get-parameter (car link) :store))
  8331. if store-func
  8332. collect store-func))
  8333. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8334. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8335. ;;;###autoload
  8336. (defun org-store-link (arg)
  8337. "Store an org-link to the current location.
  8338. \\<org-mode-map>
  8339. This link is added to `org-stored-links' and can later be inserted
  8340. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8341. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8342. A single
  8343. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8344. `org-gnus-prefer-web-links' for links to Usenet articles.
  8345. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8346. skipping storing functions that are not
  8347. part of Org core.
  8348. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8349. prefix ARG forces storing a link for each line in the
  8350. active region."
  8351. (interactive "P")
  8352. (org-load-modules-maybe)
  8353. (if (and (equal arg '(64)) (org-region-active-p))
  8354. (save-excursion
  8355. (let ((end (region-end)))
  8356. (goto-char (region-beginning))
  8357. (set-mark (point))
  8358. (while (< (point-at-eol) end)
  8359. (move-end-of-line 1) (activate-mark)
  8360. (let (current-prefix-arg)
  8361. (call-interactively 'org-store-link))
  8362. (move-beginning-of-line 2)
  8363. (set-mark (point)))))
  8364. (setq org-store-link-plist nil)
  8365. (let (link cpltxt desc description search
  8366. txt custom-id agenda-link sfuns sfunsn)
  8367. (cond
  8368. ;; Store a link using an external link type
  8369. ((and (not (equal arg '(16)))
  8370. (setq sfuns
  8371. (delq
  8372. nil (mapcar (lambda (f)
  8373. (let (fs) (if (funcall f) (push f fs))))
  8374. (org-store-link-functions)))
  8375. sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
  8376. (or (and (cdr sfuns)
  8377. (funcall (intern
  8378. (completing-read
  8379. "Which function for creating the link? "
  8380. sfunsn nil t (car sfunsn)))))
  8381. (funcall (caar sfuns)))
  8382. (setq link (plist-get org-store-link-plist :link)
  8383. desc (or (plist-get org-store-link-plist
  8384. :description)
  8385. link))))
  8386. ;; Store a link from a source code buffer.
  8387. ((org-src-edit-buffer-p)
  8388. (let ((coderef-format (org-src-coderef-format)))
  8389. (cond ((save-excursion
  8390. (beginning-of-line)
  8391. (looking-at (org-src-coderef-regexp coderef-format)))
  8392. (setq link (format "(%s)" (match-string-no-properties 3))))
  8393. ((called-interactively-p 'any)
  8394. (let ((label (read-string "Code line label: ")))
  8395. (end-of-line)
  8396. (setq link (format coderef-format label))
  8397. (let ((gc (- 79 (length link))))
  8398. (if (< (current-column) gc)
  8399. (org-move-to-column gc t)
  8400. (insert " ")))
  8401. (insert link)
  8402. (setq link (concat "(" label ")"))
  8403. (setq desc nil)))
  8404. (t (setq link nil)))))
  8405. ;; We are in the agenda, link to referenced location
  8406. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8407. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8408. (get-text-property (point) 'org-marker))))
  8409. (when m
  8410. (org-with-point-at m
  8411. (setq agenda-link
  8412. (if (called-interactively-p 'any)
  8413. (call-interactively 'org-store-link)
  8414. (org-store-link nil)))))))
  8415. ((eq major-mode 'calendar-mode)
  8416. (let ((cd (calendar-cursor-to-date)))
  8417. (setq link
  8418. (format-time-string
  8419. (car org-time-stamp-formats)
  8420. (apply 'encode-time
  8421. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8422. nil nil nil))))
  8423. (org-store-link-props :type "calendar" :date cd)))
  8424. ((eq major-mode 'help-mode)
  8425. (setq link (concat "help:" (save-excursion
  8426. (goto-char (point-min))
  8427. (looking-at "^[^ ]+")
  8428. (match-string 0))))
  8429. (org-store-link-props :type "help"))
  8430. ((eq major-mode 'w3-mode)
  8431. (setq cpltxt (if (and (buffer-name)
  8432. (not (string-match "Untitled" (buffer-name))))
  8433. (buffer-name)
  8434. (url-view-url t))
  8435. link (url-view-url t))
  8436. (org-store-link-props :type "w3" :url (url-view-url t)))
  8437. ((eq major-mode 'image-mode)
  8438. (setq cpltxt (concat "file:"
  8439. (abbreviate-file-name buffer-file-name))
  8440. link cpltxt)
  8441. (org-store-link-props :type "image" :file buffer-file-name))
  8442. ;; In dired, store a link to the file of the current line
  8443. ((derived-mode-p 'dired-mode)
  8444. (let ((file (dired-get-filename nil t)))
  8445. (setq file (if file
  8446. (abbreviate-file-name
  8447. (expand-file-name (dired-get-filename nil t)))
  8448. ;; otherwise, no file so use current directory.
  8449. default-directory))
  8450. (setq cpltxt (concat "file:" file)
  8451. link cpltxt)))
  8452. ((setq search (run-hook-with-args-until-success
  8453. 'org-create-file-search-functions))
  8454. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8455. "::" search))
  8456. (setq cpltxt (or description link)))
  8457. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8458. (org-with-limited-levels
  8459. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8460. (cond
  8461. ;; Store a link using the target at point
  8462. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8463. (setq cpltxt
  8464. (concat "file:"
  8465. (abbreviate-file-name
  8466. (buffer-file-name (buffer-base-buffer)))
  8467. "::" (match-string 1))
  8468. link cpltxt))
  8469. ((and (featurep 'org-id)
  8470. (or (eq org-id-link-to-org-use-id t)
  8471. (and (called-interactively-p 'any)
  8472. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8473. (and (eq org-id-link-to-org-use-id
  8474. 'create-if-interactive-and-no-custom-id)
  8475. (not custom-id))))
  8476. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8477. ;; Store a link using the ID at point
  8478. (setq link (condition-case nil
  8479. (prog1 (org-id-store-link)
  8480. (setq desc (or (plist-get org-store-link-plist
  8481. :description)
  8482. "")))
  8483. (error
  8484. ;; Probably before first headline, link only to file
  8485. (concat "file:"
  8486. (abbreviate-file-name
  8487. (buffer-file-name (buffer-base-buffer))))))))
  8488. (t
  8489. ;; Just link to current headline
  8490. (setq cpltxt (concat "file:"
  8491. (abbreviate-file-name
  8492. (buffer-file-name (buffer-base-buffer)))))
  8493. ;; Add a context search string
  8494. (when (org-xor org-context-in-file-links
  8495. (equal arg '(4)))
  8496. (let* ((element (org-element-at-point))
  8497. (name (org-element-property :name element)))
  8498. (setq txt (cond
  8499. ((org-at-heading-p) nil)
  8500. (name)
  8501. ((org-region-active-p)
  8502. (buffer-substring (region-beginning) (region-end)))))
  8503. (when (or (null txt) (string-match "\\S-" txt))
  8504. (setq cpltxt
  8505. (concat cpltxt "::"
  8506. (condition-case nil
  8507. (org-make-org-heading-search-string txt)
  8508. (error "")))
  8509. desc (or name
  8510. (nth 4 (ignore-errors (org-heading-components)))
  8511. "NONE")))))
  8512. (when (string-match "::\\'" cpltxt)
  8513. (setq cpltxt (substring cpltxt 0 -2)))
  8514. (setq link cpltxt)))))
  8515. ((buffer-file-name (buffer-base-buffer))
  8516. ;; Just link to this file here.
  8517. (setq cpltxt (concat "file:"
  8518. (abbreviate-file-name
  8519. (buffer-file-name (buffer-base-buffer)))))
  8520. ;; Add a context string.
  8521. (when (org-xor org-context-in-file-links
  8522. (equal arg '(4)))
  8523. (setq txt (if (org-region-active-p)
  8524. (buffer-substring (region-beginning) (region-end))
  8525. (buffer-substring (point-at-bol) (point-at-eol))))
  8526. ;; Only use search option if there is some text.
  8527. (when (string-match "\\S-" txt)
  8528. (setq cpltxt
  8529. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8530. desc "NONE")))
  8531. (setq link cpltxt))
  8532. ((called-interactively-p 'interactive)
  8533. (user-error "No method for storing a link from this buffer"))
  8534. (t (setq link nil)))
  8535. ;; We're done setting link and desc, clean up
  8536. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8537. (setq link (or link cpltxt)
  8538. desc (or desc cpltxt))
  8539. (cond ((not desc))
  8540. ((equal desc "NONE") (setq desc nil))
  8541. (t (setq desc
  8542. (replace-regexp-in-string
  8543. org-bracket-link-analytic-regexp
  8544. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8545. desc))))
  8546. ;; Return the link
  8547. (if (not (and (or (called-interactively-p 'any)
  8548. executing-kbd-macro)
  8549. link))
  8550. (or agenda-link (and link (org-make-link-string link desc)))
  8551. (push (list link desc) org-stored-links)
  8552. (message "Stored: %s" (or desc link))
  8553. (when custom-id
  8554. (setq link (concat "file:" (abbreviate-file-name
  8555. (buffer-file-name)) "::#" custom-id))
  8556. (push (list link desc) org-stored-links))
  8557. (car org-stored-links)))))
  8558. (defun org-store-link-props (&rest plist)
  8559. "Store link properties.
  8560. The properties are pre-processed by extracting names, addresses
  8561. and dates."
  8562. (let ((x (plist-get plist :from)))
  8563. (when x
  8564. (let ((adr (mail-extract-address-components x)))
  8565. (setq plist (plist-put plist :fromname (car adr)))
  8566. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8567. (let ((x (plist-get plist :to)))
  8568. (when x
  8569. (let ((adr (mail-extract-address-components x)))
  8570. (setq plist (plist-put plist :toname (car adr)))
  8571. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8572. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8573. (when x
  8574. (setq plist (plist-put plist :date-timestamp
  8575. (format-time-string
  8576. (org-time-stamp-format t) x)))
  8577. (setq plist (plist-put plist :date-timestamp-inactive
  8578. (format-time-string
  8579. (org-time-stamp-format t t) x)))))
  8580. (let ((from (plist-get plist :from))
  8581. (to (plist-get plist :to)))
  8582. (when (and from to org-from-is-user-regexp)
  8583. (setq plist
  8584. (plist-put plist :fromto
  8585. (if (string-match org-from-is-user-regexp from)
  8586. (concat "to %t")
  8587. (concat "from %f"))))))
  8588. (setq org-store-link-plist plist))
  8589. (defun org-add-link-props (&rest plist)
  8590. "Add these properties to the link property list."
  8591. (let (key value)
  8592. (while plist
  8593. (setq key (pop plist) value (pop plist))
  8594. (setq org-store-link-plist
  8595. (plist-put org-store-link-plist key value)))))
  8596. (defun org-email-link-description (&optional fmt)
  8597. "Return the description part of an email link.
  8598. This takes information from `org-store-link-plist' and formats it
  8599. according to FMT (default from `org-email-link-description-format')."
  8600. (setq fmt (or fmt org-email-link-description-format))
  8601. (let* ((p org-store-link-plist)
  8602. (to (plist-get p :toaddress))
  8603. (from (plist-get p :fromaddress))
  8604. (table
  8605. (list
  8606. (cons "%c" (plist-get p :fromto))
  8607. (cons "%F" (plist-get p :from))
  8608. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8609. (cons "%T" (plist-get p :to))
  8610. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8611. (cons "%s" (plist-get p :subject))
  8612. (cons "%d" (plist-get p :date))
  8613. (cons "%m" (plist-get p :message-id)))))
  8614. (when (string-match "%c" fmt)
  8615. ;; Check if the user wrote this message
  8616. (if (and org-from-is-user-regexp from to
  8617. (save-match-data (string-match org-from-is-user-regexp from)))
  8618. (setq fmt (replace-match "to %t" t t fmt))
  8619. (setq fmt (replace-match "from %f" t t fmt))))
  8620. (org-replace-escapes fmt table)))
  8621. (defun org-make-org-heading-search-string (&optional string)
  8622. "Make search string for the current headline or STRING."
  8623. (let ((s (or string
  8624. (and (derived-mode-p 'org-mode)
  8625. (save-excursion
  8626. (org-back-to-heading t)
  8627. (org-element-property :raw-value (org-element-at-point))))))
  8628. (lines org-context-in-file-links))
  8629. (unless string (setq s (concat "*" s))) ;Add * for headlines
  8630. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8631. (when (and string (integerp lines) (> lines 0))
  8632. (let ((slines (org-split-string s "\n")))
  8633. (when (< lines (length slines))
  8634. (setq s (mapconcat
  8635. 'identity
  8636. (reverse (nthcdr (- (length slines) lines)
  8637. (reverse slines))) "\n")))))
  8638. (mapconcat #'identity (split-string s) " ")))
  8639. (defun org-make-link-string (link &optional description)
  8640. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8641. (unless (org-string-nw-p link) (error "Empty link"))
  8642. (let ((uri (cond ((string-match org-link-types-re link)
  8643. (concat (match-string 1 link)
  8644. (org-link-escape (substring link (match-end 1)))))
  8645. ;; For readability, url-encode internal links only
  8646. ;; when absolutely needed (i.e, when they contain
  8647. ;; square brackets). File links however, are
  8648. ;; encoded since, e.g., spaces are significant.
  8649. ((or (file-name-absolute-p link)
  8650. (string-match-p "\\`\\.\\.?/\\|[][]" link))
  8651. (org-link-escape link))
  8652. (t link)))
  8653. (description
  8654. (and (org-string-nw-p description)
  8655. ;; Remove brackets from description, as they are fatal.
  8656. (replace-regexp-in-string
  8657. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8658. (org-trim description)))))
  8659. (format "[[%s]%s]"
  8660. uri
  8661. (if description (format "[%s]" description) ""))))
  8662. (defconst org-link-escape-chars
  8663. ;;%20 %5B %5D %25
  8664. '(?\s ?\[ ?\] ?%)
  8665. "List of characters that should be escaped in a link when stored to Org.
  8666. This is the list that is used for internal purposes.")
  8667. (defun org-link-escape (text &optional table merge)
  8668. "Return percent escaped representation of TEXT.
  8669. TEXT is a string with the text to escape.
  8670. Optional argument TABLE is a list with characters that should be
  8671. escaped. When nil, `org-link-escape-chars' is used.
  8672. If optional argument MERGE is set, merge TABLE into
  8673. `org-link-escape-chars'."
  8674. (let ((characters-to-encode
  8675. (cond ((null table) org-link-escape-chars)
  8676. (merge (append org-link-escape-chars table))
  8677. (t table))))
  8678. (mapconcat
  8679. (lambda (c)
  8680. (if (or (memq c characters-to-encode)
  8681. (and org-url-hexify-p (or (< c 32) (> c 126))))
  8682. (mapconcat (lambda (e) (format "%%%.2X" e))
  8683. (or (encode-coding-char c 'utf-8)
  8684. (error "Unable to percent escape character: %c" c))
  8685. "")
  8686. (char-to-string c)))
  8687. text "")))
  8688. (defun org-link-unescape (str)
  8689. "Unhex hexified Unicode parts in string STR.
  8690. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  8691. reciprocal of `org-link-escape', which see."
  8692. (if (org-string-nw-p str)
  8693. (replace-regexp-in-string
  8694. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  8695. str))
  8696. (defun org-link-unescape-compound (hex)
  8697. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  8698. Note: this function also decodes single byte encodings like
  8699. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  8700. (save-match-data
  8701. (let* ((bytes (cdr (split-string hex "%")))
  8702. (ret "")
  8703. (eat 0)
  8704. (sum 0))
  8705. (while bytes
  8706. (let* ((val (string-to-number (pop bytes) 16))
  8707. (shift-xor
  8708. (if (= 0 eat)
  8709. (cond
  8710. ((>= val 252) (cons 6 252))
  8711. ((>= val 248) (cons 5 248))
  8712. ((>= val 240) (cons 4 240))
  8713. ((>= val 224) (cons 3 224))
  8714. ((>= val 192) (cons 2 192))
  8715. (t (cons 0 0)))
  8716. (cons 6 128))))
  8717. (when (>= val 192) (setq eat (car shift-xor)))
  8718. (setq val (logxor val (cdr shift-xor)))
  8719. (setq sum (+ (lsh sum (car shift-xor)) val))
  8720. (when (> eat 0) (setq eat (- eat 1)))
  8721. (cond
  8722. ((= 0 eat) ;multi byte
  8723. (setq ret (concat ret (char-to-string sum)))
  8724. (setq sum 0))
  8725. ((not bytes) ; single byte(s)
  8726. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  8727. ret)))
  8728. (defun org-link-unescape-single-byte-sequence (hex)
  8729. "Unhexify hex-encoded single byte character sequences."
  8730. (mapconcat (lambda (byte)
  8731. (char-to-string (string-to-number byte 16)))
  8732. (cdr (split-string hex "%")) ""))
  8733. (defun org-fixup-message-id-for-http (s)
  8734. "Replace special characters in a message id, so it can be used in an http query."
  8735. (when (string-match "%" s)
  8736. (setq s (mapconcat (lambda (c)
  8737. (if (eq c ?%)
  8738. "%25"
  8739. (char-to-string c)))
  8740. s "")))
  8741. (while (string-match "<" s)
  8742. (setq s (replace-match "%3C" t t s)))
  8743. (while (string-match ">" s)
  8744. (setq s (replace-match "%3E" t t s)))
  8745. (while (string-match "@" s)
  8746. (setq s (replace-match "%40" t t s)))
  8747. s)
  8748. (defun org-link-prettify (link)
  8749. "Return a human-readable representation of LINK.
  8750. The car of LINK must be a raw link.
  8751. The cdr of LINK must be either a link description or nil."
  8752. (let ((desc (or (cadr link) "<no description>")))
  8753. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  8754. "<" (car link) ">")))
  8755. ;;;###autoload
  8756. (defun org-insert-link-global ()
  8757. "Insert a link like Org mode does.
  8758. This command can be called in any mode to insert a link in Org syntax."
  8759. (interactive)
  8760. (org-load-modules-maybe)
  8761. (org-run-like-in-org-mode 'org-insert-link))
  8762. (defun org-insert-all-links (arg &optional pre post)
  8763. "Insert all links in `org-stored-links'.
  8764. When a universal prefix, do not delete the links from `org-stored-links'.
  8765. When `ARG' is a number, insert the last N link(s).
  8766. `PRE' and `POST' are optional arguments to define a string to
  8767. prepend or to append."
  8768. (interactive "P")
  8769. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  8770. (links (copy-sequence org-stored-links))
  8771. (pr (or pre "- "))
  8772. (po (or post "\n"))
  8773. (cnt 1) l)
  8774. (if (null org-stored-links)
  8775. (message "No link to insert")
  8776. (while (and (or (listp arg) (>= arg cnt))
  8777. (setq l (if (listp arg)
  8778. (pop links)
  8779. (pop org-stored-links))))
  8780. (setq cnt (1+ cnt))
  8781. (insert pr)
  8782. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  8783. (insert po)))))
  8784. (defun org-insert-last-stored-link (arg)
  8785. "Insert the last link stored in `org-stored-links'."
  8786. (interactive "p")
  8787. (org-insert-all-links arg "" "\n"))
  8788. (defun org-link-fontify-links-to-this-file ()
  8789. "Fontify links to the current file in `org-stored-links'."
  8790. (let ((f (buffer-file-name)) a b)
  8791. (setq a (mapcar (lambda(l)
  8792. (let ((ll (car l)))
  8793. (when (and (string-match "^file:\\(.+\\)::" ll)
  8794. (equal f (expand-file-name (match-string 1 ll))))
  8795. ll)))
  8796. org-stored-links))
  8797. (when (featurep 'org-id)
  8798. (setq b (mapcar (lambda(l)
  8799. (let ((ll (car l)))
  8800. (when (and (string-match "^id:\\(.+\\)$" ll)
  8801. (equal f (expand-file-name
  8802. (or (org-id-find-id-file
  8803. (match-string 1 ll)) ""))))
  8804. ll)))
  8805. org-stored-links)))
  8806. (mapcar (lambda(l)
  8807. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  8808. (delq nil (append a b)))))
  8809. (defvar org--links-history nil)
  8810. (defun org-insert-link (&optional complete-file link-location default-description)
  8811. "Insert a link. At the prompt, enter the link.
  8812. Completion can be used to insert any of the link protocol prefixes in use.
  8813. The history can be used to select a link previously stored with
  8814. `org-store-link'. When the empty string is entered (i.e. if you just
  8815. press `RET' at the prompt), the link defaults to the most recently
  8816. stored link. As `SPC' triggers completion in the minibuffer, you need to
  8817. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  8818. You will also be prompted for a description, and if one is given, it will
  8819. be displayed in the buffer instead of the link.
  8820. If there is already a link at point, this command will allow you to edit
  8821. link and description parts.
  8822. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  8823. file name can be
  8824. selected using completion. The path to the file will be relative to the
  8825. current directory if the file is in the current directory or a subdirectory.
  8826. Otherwise, the link will be the absolute path as completed in the minibuffer
  8827. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  8828. option `org-link-file-path-type'.
  8829. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  8830. absolute path even if the file is in
  8831. the current directory or below.
  8832. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8833. prefix negates `org-keep-stored-link-after-insertion'.
  8834. If the LINK-LOCATION parameter is non-nil, this value will be used as
  8835. the link location instead of reading one interactively.
  8836. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  8837. be used as the default description. Otherwise, if
  8838. `org-make-link-description-function' is non-nil, this function
  8839. will be called with the link target, and the result will be the
  8840. default link description."
  8841. (interactive "P")
  8842. (let* ((wcf (current-window-configuration))
  8843. (origbuf (current-buffer))
  8844. (region (when (org-region-active-p)
  8845. (buffer-substring (region-beginning) (region-end))))
  8846. (remove (and region (list (region-beginning) (region-end))))
  8847. (desc region)
  8848. (link link-location)
  8849. (abbrevs org-link-abbrev-alist-local)
  8850. entry all-prefixes auto-desc)
  8851. (cond
  8852. (link-location) ; specified by arg, just use it.
  8853. ((org-in-regexp org-bracket-link-regexp 1)
  8854. ;; We do have a link at point, and we are going to edit it.
  8855. (setq remove (list (match-beginning 0) (match-end 0)))
  8856. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  8857. (setq link (read-string "Link: "
  8858. (org-link-unescape
  8859. (match-string-no-properties 1)))))
  8860. ((or (org-in-regexp org-angle-link-re)
  8861. (org-in-regexp org-plain-link-re))
  8862. ;; Convert to bracket link
  8863. (setq remove (list (match-beginning 0) (match-end 0))
  8864. link (read-string "Link: "
  8865. (org-unbracket-string "<" ">" (match-string 0)))))
  8866. ((member complete-file '((4) (16)))
  8867. ;; Completing read for file names.
  8868. (setq link (org-file-complete-link complete-file)))
  8869. (t
  8870. ;; Read link, with completion for stored links.
  8871. (org-link-fontify-links-to-this-file)
  8872. (org-switch-to-buffer-other-window "*Org Links*")
  8873. (with-current-buffer "*Org Links*"
  8874. (erase-buffer)
  8875. (insert "Insert a link.
  8876. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  8877. (when org-stored-links
  8878. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  8879. (insert (mapconcat 'org-link-prettify
  8880. (reverse org-stored-links) "\n")))
  8881. (goto-char (point-min)))
  8882. (let ((cw (selected-window)))
  8883. (select-window (get-buffer-window "*Org Links*" 'visible))
  8884. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  8885. (unless (pos-visible-in-window-p (point-max))
  8886. (org-fit-window-to-buffer))
  8887. (and (window-live-p cw) (select-window cw)))
  8888. (setq all-prefixes (append (mapcar 'car abbrevs)
  8889. (mapcar 'car org-link-abbrev-alist)
  8890. (org-link-types)))
  8891. (unwind-protect
  8892. ;; Fake a link history, containing the stored links.
  8893. (let ((org--links-history
  8894. (append (mapcar #'car org-stored-links)
  8895. org-insert-link-history)))
  8896. (setq link
  8897. (org-completing-read
  8898. "Link: "
  8899. (append
  8900. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  8901. (mapcar #'car org-stored-links))
  8902. nil nil nil
  8903. 'org--links-history
  8904. (caar org-stored-links)))
  8905. (unless (org-string-nw-p link) (user-error "No link selected"))
  8906. (dolist (l org-stored-links)
  8907. (when (equal link (cadr l))
  8908. (setq link (car l))
  8909. (setq auto-desc t)))
  8910. (when (or (member link all-prefixes)
  8911. (and (equal ":" (substring link -1))
  8912. (member (substring link 0 -1) all-prefixes)
  8913. (setq link (substring link 0 -1))))
  8914. (setq link (with-current-buffer origbuf
  8915. (org-link-try-special-completion link)))))
  8916. (set-window-configuration wcf)
  8917. (kill-buffer "*Org Links*"))
  8918. (setq entry (assoc link org-stored-links))
  8919. (or entry (push link org-insert-link-history))
  8920. (setq desc (or desc (nth 1 entry)))))
  8921. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  8922. (not org-keep-stored-link-after-insertion))
  8923. (setq org-stored-links (delq (assoc link org-stored-links)
  8924. org-stored-links)))
  8925. (when (and (string-match org-plain-link-re link)
  8926. (not (string-match org-ts-regexp link)))
  8927. ;; URL-like link, normalize the use of angular brackets.
  8928. (setq link (org-unbracket-string "<" ">" link)))
  8929. ;; Check if we are linking to the current file with a search
  8930. ;; option If yes, simplify the link by using only the search
  8931. ;; option.
  8932. (when (and buffer-file-name
  8933. (let ((case-fold-search nil))
  8934. (string-match "\\`file:\\(.+?\\)::" link)))
  8935. (let ((path (match-string-no-properties 1 link))
  8936. (search (substring-no-properties link (match-end 0))))
  8937. (save-match-data
  8938. (when (equal (file-truename buffer-file-name) (file-truename path))
  8939. ;; We are linking to this same file, with a search option
  8940. (setq link search)))))
  8941. ;; Check if we can/should use a relative path. If yes, simplify the link
  8942. (let ((case-fold-search nil))
  8943. (when (string-match "\\`\\(file\\|docview\\):" link)
  8944. (let* ((type (match-string-no-properties 0 link))
  8945. (path (substring-no-properties link (match-end 0)))
  8946. (origpath path))
  8947. (cond
  8948. ((or (eq org-link-file-path-type 'absolute)
  8949. (equal complete-file '(16)))
  8950. (setq path (abbreviate-file-name (expand-file-name path))))
  8951. ((eq org-link-file-path-type 'noabbrev)
  8952. (setq path (expand-file-name path)))
  8953. ((eq org-link-file-path-type 'relative)
  8954. (setq path (file-relative-name path)))
  8955. (t
  8956. (save-match-data
  8957. (if (string-match (concat "^" (regexp-quote
  8958. (expand-file-name
  8959. (file-name-as-directory
  8960. default-directory))))
  8961. (expand-file-name path))
  8962. ;; We are linking a file with relative path name.
  8963. (setq path (substring (expand-file-name path)
  8964. (match-end 0)))
  8965. (setq path (abbreviate-file-name (expand-file-name path)))))))
  8966. (setq link (concat type path))
  8967. (when (equal desc origpath)
  8968. (setq desc path)))))
  8969. (unless auto-desc
  8970. (let ((initial-input
  8971. (cond
  8972. (default-description)
  8973. ((not org-make-link-description-function) desc)
  8974. (t (condition-case nil
  8975. (funcall org-make-link-description-function link desc)
  8976. (error
  8977. (message "Can't get link description from `%s'"
  8978. (symbol-name org-make-link-description-function))
  8979. (sit-for 2)
  8980. nil))))))
  8981. (setq desc (read-string "Description: " initial-input))))
  8982. (unless (string-match "\\S-" desc) (setq desc nil))
  8983. (when remove (apply 'delete-region remove))
  8984. (insert (org-make-link-string link desc))
  8985. ;; Redisplay so as the new link has proper invisible characters.
  8986. (sit-for 0)))
  8987. (defun org-link-try-special-completion (type)
  8988. "If there is completion support for link type TYPE, offer it."
  8989. (let ((fun (org-link-get-parameter type :complete)))
  8990. (if (functionp fun)
  8991. (funcall fun)
  8992. (read-string "Link (no completion support): " (concat type ":")))))
  8993. (defun org-file-complete-link (&optional arg)
  8994. "Create a file link using completion."
  8995. (let ((file (read-file-name "File: "))
  8996. (pwd (file-name-as-directory (expand-file-name ".")))
  8997. (pwd1 (file-name-as-directory (abbreviate-file-name
  8998. (expand-file-name ".")))))
  8999. (cond ((equal arg '(16))
  9000. (concat "file:"
  9001. (abbreviate-file-name (expand-file-name file))))
  9002. ((string-match
  9003. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9004. (concat "file:" (match-string 1 file)))
  9005. ((string-match
  9006. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9007. (expand-file-name file))
  9008. (concat "file:"
  9009. (match-string 1 (expand-file-name file))))
  9010. (t (concat "file:" file)))))
  9011. ;;; Opening/following a link
  9012. (defvar org-link-search-failed nil)
  9013. (defvar org-open-link-functions nil
  9014. "Hook for functions finding a plain text link.
  9015. These functions must take a single argument, the link content.
  9016. They will be called for links that look like [[link text][description]]
  9017. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9018. like a filename (e.g. \"./blue.png\").
  9019. These functions will be called *before* Org attempts to resolve the
  9020. link by doing text searches in the current buffer - so if you want a
  9021. link \"[[target]]\" to still find \"<<target>>\", your function should
  9022. handle this as a special case.
  9023. When the function does handle the link, it must return a non-nil value.
  9024. If it decides that it is not responsible for this link, it must return
  9025. nil to indicate that that Org can continue with other options like
  9026. exact and fuzzy text search.")
  9027. (defun org-next-link (&optional search-backward)
  9028. "Move forward to the next link.
  9029. If the link is in hidden text, expose it."
  9030. (interactive "P")
  9031. (when (and org-link-search-failed (eq this-command last-command))
  9032. (goto-char (point-min))
  9033. (message "Link search wrapped back to beginning of buffer"))
  9034. (setq org-link-search-failed nil)
  9035. (let* ((pos (point))
  9036. (ct (org-context))
  9037. (a (assq :link ct))
  9038. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9039. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9040. ((looking-at org-any-link-re)
  9041. ;; Don't stay stuck at link without an org-link face
  9042. (forward-char (if search-backward -1 1))))
  9043. (if (funcall srch-fun org-any-link-re nil t)
  9044. (progn
  9045. (goto-char (match-beginning 0))
  9046. (when (org-invisible-p) (org-show-context)))
  9047. (goto-char pos)
  9048. (setq org-link-search-failed t)
  9049. (message "No further link found"))))
  9050. (defun org-previous-link ()
  9051. "Move backward to the previous link.
  9052. If the link is in hidden text, expose it."
  9053. (interactive)
  9054. (funcall 'org-next-link t))
  9055. (defun org-translate-link (s)
  9056. "Translate a link string if a translation function has been defined."
  9057. (with-temp-buffer
  9058. (insert (org-trim s))
  9059. (org-trim (org-element-interpret-data (org-element-context)))))
  9060. (defun org-translate-link-from-planner (type path)
  9061. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9062. This is still an experimental function, your mileage may vary."
  9063. (cond
  9064. ((member type '("http" "https" "news" "ftp"))
  9065. ;; standard Internet links are the same.
  9066. nil)
  9067. ((and (equal type "irc") (string-match "^//" path))
  9068. ;; Planner has two / at the beginning of an irc link, we have 1.
  9069. ;; We should have zero, actually....
  9070. (setq path (substring path 1)))
  9071. ((and (equal type "lisp") (string-match "^/" path))
  9072. ;; Planner has a slash, we do not.
  9073. (setq type "elisp" path (substring path 1)))
  9074. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9075. ;; A typical message link. Planner has the id after the final slash,
  9076. ;; we separate it with a hash mark
  9077. (setq path (concat (match-string 1 path) "#"
  9078. (org-unbracket-string "<" ">" (match-string 2 path))))))
  9079. (cons type path))
  9080. (defun org-find-file-at-mouse (ev)
  9081. "Open file link or URL at mouse."
  9082. (interactive "e")
  9083. (mouse-set-point ev)
  9084. (org-open-at-point 'in-emacs))
  9085. (defun org-open-at-mouse (ev)
  9086. "Open file link or URL at mouse.
  9087. See the docstring of `org-open-file' for details."
  9088. (interactive "e")
  9089. (mouse-set-point ev)
  9090. (when (eq major-mode 'org-agenda-mode)
  9091. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9092. (org-open-at-point))
  9093. (defvar org-window-config-before-follow-link nil
  9094. "The window configuration before following a link.
  9095. This is saved in case the need arises to restore it.")
  9096. ;;;###autoload
  9097. (defun org-open-at-point-global ()
  9098. "Follow a link or time-stamp like Org mode does.
  9099. This command can be called in any mode to follow an external link
  9100. or a time-stamp that has Org mode syntax. Its behavior is
  9101. undefined when called on internal links (e.g., fuzzy links).
  9102. Raise an error when there is nothing to follow. "
  9103. (interactive)
  9104. (cond ((org-in-regexp org-any-link-re)
  9105. (org-open-link-from-string (match-string-no-properties 0)))
  9106. ((or (org-in-regexp org-ts-regexp-both nil t)
  9107. (org-in-regexp org-tsr-regexp-both nil t))
  9108. (org-follow-timestamp-link))
  9109. (t (user-error "No link found"))))
  9110. ;;;###autoload
  9111. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9112. "Open a link in the string S, as if it was in Org mode."
  9113. (interactive "sLink: \nP")
  9114. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9115. (with-temp-buffer
  9116. (let ((org-inhibit-startup (not reference-buffer)))
  9117. (org-mode)
  9118. (insert s)
  9119. (goto-char (point-min))
  9120. (when reference-buffer
  9121. (setq org-link-abbrev-alist-local
  9122. (with-current-buffer reference-buffer
  9123. org-link-abbrev-alist-local)))
  9124. (org-open-at-point arg reference-buffer)))))
  9125. (defvar org-open-at-point-functions nil
  9126. "Hook that is run when following a link at point.
  9127. Functions in this hook must return t if they identify and follow
  9128. a link at point. If they don't find anything interesting at point,
  9129. they must return nil.")
  9130. (defvar org-link-search-inhibit-query nil)
  9131. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9132. (defun org--open-doi-link (path)
  9133. "Open a \"doi\" type link.
  9134. PATH is a the path to search for, as a string."
  9135. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9136. (defun org--open-elisp-link (path)
  9137. "Open a \"elisp\" type link.
  9138. PATH is the sexp to evaluate, as a string."
  9139. (let ((cmd path))
  9140. (if (or (and (org-string-nw-p
  9141. org-confirm-elisp-link-not-regexp)
  9142. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  9143. (not org-confirm-elisp-link-function)
  9144. (funcall org-confirm-elisp-link-function
  9145. (format "Execute \"%s\" as elisp? "
  9146. (org-add-props cmd nil 'face 'org-warning))))
  9147. (message "%s => %s" cmd
  9148. (if (eq (string-to-char cmd) ?\()
  9149. (eval (read cmd))
  9150. (call-interactively (read cmd))))
  9151. (user-error "Abort"))))
  9152. (defun org--open-help-link (path)
  9153. "Open a \"help\" type link.
  9154. PATH is a symbol name, as a string."
  9155. (pcase (intern path)
  9156. ((and (pred fboundp) variable) (describe-function variable))
  9157. ((and (pred boundp) function) (describe-variable function))
  9158. (name (user-error "Unknown function or variable: %s" name))))
  9159. (defun org--open-shell-link (path)
  9160. "Open a \"shell\" type link.
  9161. PATH is the command to execute, as a string."
  9162. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9163. (cmd path))
  9164. (if (or (and (org-string-nw-p
  9165. org-confirm-shell-link-not-regexp)
  9166. (string-match
  9167. org-confirm-shell-link-not-regexp cmd))
  9168. (not org-confirm-shell-link-function)
  9169. (funcall org-confirm-shell-link-function
  9170. (format "Execute \"%s\" in shell? "
  9171. (org-add-props cmd nil
  9172. 'face 'org-warning))))
  9173. (progn
  9174. (message "Executing %s" cmd)
  9175. (shell-command cmd buf)
  9176. (when (featurep 'midnight)
  9177. (setq clean-buffer-list-kill-buffer-names
  9178. (cons (buffer-name buf)
  9179. clean-buffer-list-kill-buffer-names))))
  9180. (user-error "Abort"))))
  9181. (defun org-open-at-point (&optional arg reference-buffer)
  9182. "Open link, timestamp, footnote or tags at point.
  9183. When point is on a link, follow it. Normally, files will be
  9184. opened by an appropriate application. If the optional prefix
  9185. argument ARG is non-nil, Emacs will visit the file. With
  9186. a double prefix argument, try to open outside of Emacs, in the
  9187. application the system uses for this file type.
  9188. When point is on a timestamp, open the agenda at the day
  9189. specified.
  9190. When point is a footnote definition, move to the first reference
  9191. found. If it is on a reference, move to the associated
  9192. definition.
  9193. When point is on a headline, display a list of every link in the
  9194. entry, so it is possible to pick one, or all, of them. If point
  9195. is on a tag, call `org-tags-view' instead.
  9196. When optional argument REFERENCE-BUFFER is non-nil, it should
  9197. specify a buffer from where the link search should happen. This
  9198. is used internally by `org-open-link-from-string'.
  9199. On top of syntactically correct links, this function will also
  9200. try to open links and time-stamps in comments, example
  9201. blocks... i.e., whenever point is on something looking like
  9202. a timestamp or a link."
  9203. (interactive "P")
  9204. ;; On a code block, open block's results.
  9205. (unless (call-interactively 'org-babel-open-src-block-result)
  9206. (org-load-modules-maybe)
  9207. (setq org-window-config-before-follow-link (current-window-configuration))
  9208. (org-remove-occur-highlights nil nil t)
  9209. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9210. (let* ((context
  9211. ;; Only consider supported types, even if they are not
  9212. ;; the closest one.
  9213. (org-element-lineage
  9214. (org-element-context)
  9215. '(clock footnote-definition footnote-reference headline
  9216. inlinetask link timestamp)
  9217. t))
  9218. (type (org-element-type context))
  9219. (value (org-element-property :value context)))
  9220. (cond
  9221. ;; On a headline or an inlinetask, but not on a timestamp,
  9222. ;; a link, a footnote reference.
  9223. ((memq type '(headline inlinetask))
  9224. (org-match-line org-complex-heading-regexp)
  9225. (if (and (match-beginning 5)
  9226. (>= (point) (match-beginning 5))
  9227. (< (point) (match-end 5)))
  9228. ;; On tags.
  9229. (org-tags-view arg (substring (match-string 5) 0 -1))
  9230. ;; Not on tags.
  9231. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  9232. (`(nil . ,_)
  9233. (require 'org-attach)
  9234. (org-attach-reveal 'if-exists))
  9235. (`(,links . ,links-end)
  9236. (dolist (link (if (stringp links) (list links) links))
  9237. (search-forward link nil links-end)
  9238. (goto-char (match-beginning 0))
  9239. (org-open-at-point))))))
  9240. ;; On a footnote reference or at definition's label.
  9241. ((or (eq type 'footnote-reference)
  9242. (and (eq type 'footnote-definition)
  9243. (save-excursion
  9244. ;; Do not validate action when point is on the
  9245. ;; spaces right after the footnote label, in
  9246. ;; order to be on par with behaviour on links.
  9247. (skip-chars-forward " \t")
  9248. (let ((begin
  9249. (org-element-property :contents-begin context)))
  9250. (if begin (< (point) begin)
  9251. (= (org-element-property :post-affiliated context)
  9252. (line-beginning-position)))))))
  9253. (org-footnote-action))
  9254. ;; No valid context. Ignore catch-all types like `headline'.
  9255. ;; If point is on something looking like a link or
  9256. ;; a time-stamp, try opening it. It may be useful in
  9257. ;; comments, example blocks...
  9258. ((memq type '(footnote-definition headline inlinetask nil))
  9259. (call-interactively #'org-open-at-point-global))
  9260. ;; On a clock line, make sure point is on the timestamp
  9261. ;; before opening it.
  9262. ((and (eq type 'clock)
  9263. value
  9264. (>= (point) (org-element-property :begin value))
  9265. (<= (point) (org-element-property :end value)))
  9266. (org-follow-timestamp-link))
  9267. ;; Do nothing on white spaces after an object.
  9268. ((>= (point)
  9269. (save-excursion
  9270. (goto-char (org-element-property :end context))
  9271. (skip-chars-backward " \t")
  9272. (point)))
  9273. (user-error "No link found"))
  9274. ((eq type 'timestamp) (org-follow-timestamp-link))
  9275. ((eq type 'link)
  9276. (let ((type (org-element-property :type context))
  9277. (path (org-link-unescape (org-element-property :path context))))
  9278. ;; Switch back to REFERENCE-BUFFER needed when called in
  9279. ;; a temporary buffer through `org-open-link-from-string'.
  9280. (with-current-buffer (or reference-buffer (current-buffer))
  9281. (cond
  9282. ((equal type "file")
  9283. (if (string-match "[*?{]" (file-name-nondirectory path))
  9284. (dired path)
  9285. ;; Look into `org-link-parameters' in order to find
  9286. ;; a DEDICATED-FUNCTION to open file. The function
  9287. ;; will be applied on raw link instead of parsed
  9288. ;; link due to the limitation in `org-add-link-type'
  9289. ;; ("open" function called with a single argument).
  9290. ;; If no such function is found, fallback to
  9291. ;; `org-open-file'.
  9292. (let* ((option (org-element-property :search-option context))
  9293. (app (org-element-property :application context))
  9294. (dedicated-function
  9295. (org-link-get-parameter
  9296. (if app (concat type "+" app) type)
  9297. :follow)))
  9298. (if dedicated-function
  9299. (funcall dedicated-function
  9300. (concat path
  9301. (and option (concat "::" option))))
  9302. (apply #'org-open-file
  9303. path
  9304. (cond (arg)
  9305. ((equal app "emacs") 'emacs)
  9306. ((equal app "sys") 'system))
  9307. (cond ((not option) nil)
  9308. ((string-match-p "\\`[0-9]+\\'" option)
  9309. (list (string-to-number option)))
  9310. (t (list nil
  9311. (org-link-unescape option)))))))))
  9312. ((functionp (org-link-get-parameter type :follow))
  9313. (funcall (org-link-get-parameter type :follow) path))
  9314. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9315. (unless (run-hook-with-args-until-success
  9316. 'org-open-link-functions path)
  9317. (if (not arg) (org-mark-ring-push)
  9318. (switch-to-buffer-other-window
  9319. (org-get-buffer-for-internal-link (current-buffer))))
  9320. (let ((destination
  9321. (org-with-wide-buffer
  9322. (if (equal type "radio")
  9323. (org-search-radio-target
  9324. (org-element-property :path context))
  9325. (org-link-search
  9326. (if (member type '("custom-id" "coderef"))
  9327. (org-element-property :raw-link context)
  9328. path)
  9329. ;; Prevent fuzzy links from matching
  9330. ;; themselves.
  9331. (and (equal type "fuzzy")
  9332. (+ 2 (org-element-property :begin context)))))
  9333. (point))))
  9334. (unless (and (<= (point-min) destination)
  9335. (>= (point-max) destination))
  9336. (widen))
  9337. (goto-char destination))))
  9338. (t (browse-url-at-point))))))
  9339. (t (user-error "No link found")))))
  9340. (run-hook-with-args 'org-follow-link-hook)))
  9341. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9342. "Offer links in the current entry and return the selected link.
  9343. If there is only one link, return it.
  9344. If NTH is an integer, return the NTH link found.
  9345. If ZERO is a string, check also this string for a link, and if
  9346. there is one, return it."
  9347. (with-current-buffer buffer
  9348. (org-with-wide-buffer
  9349. (goto-char marker)
  9350. (let ((cnt ?0)
  9351. have-zero end links link c)
  9352. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9353. (push (match-string 0 zero) links)
  9354. (setq cnt (1- cnt) have-zero t))
  9355. (save-excursion
  9356. (org-back-to-heading t)
  9357. (setq end (save-excursion (outline-next-heading) (point)))
  9358. (while (re-search-forward org-any-link-re end t)
  9359. (push (match-string 0) links))
  9360. (setq links (org-uniquify (reverse links))))
  9361. (cond
  9362. ((null links)
  9363. (message "No links"))
  9364. ((equal (length links) 1)
  9365. (setq link (car links)))
  9366. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9367. (setq link (nth (if have-zero nth (1- nth)) links)))
  9368. (t ; we have to select a link
  9369. (save-excursion
  9370. (save-window-excursion
  9371. (delete-other-windows)
  9372. (with-output-to-temp-buffer "*Select Link*"
  9373. (dolist (l links)
  9374. (cond
  9375. ((not (string-match org-bracket-link-regexp l))
  9376. (princ (format "[%c] %s\n" (cl-incf cnt)
  9377. (org-unbracket-string "<" ">" l))))
  9378. ((match-end 3)
  9379. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9380. (match-string 3 l) (match-string 1 l))))
  9381. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9382. (match-string 1 l)))))))
  9383. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9384. (message "Select link to open, RET to open all:")
  9385. (setq c (read-char-exclusive))
  9386. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9387. (when (equal c ?q) (user-error "Abort"))
  9388. (if (equal c ?\C-m)
  9389. (setq link links)
  9390. (setq nth (- c ?0))
  9391. (when have-zero (setq nth (1+ nth)))
  9392. (unless (and (integerp nth) (>= (length links) nth))
  9393. (user-error "Invalid link selection"))
  9394. (setq link (nth (1- nth) links)))))
  9395. (cons link end)))))
  9396. ;; TODO: These functions are deprecated since `org-open-at-point'
  9397. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9398. (defun org-open-file-with-system (path)
  9399. "Open file at PATH using the system way of opening it."
  9400. (org-open-file path 'system))
  9401. (defun org-open-file-with-emacs (path)
  9402. "Open file at PATH in Emacs."
  9403. (org-open-file path 'emacs))
  9404. ;;; File search
  9405. (defvar org-create-file-search-functions nil
  9406. "List of functions to construct the right search string for a file link.
  9407. These functions are called in turn with point at the location to
  9408. which the link should point.
  9409. A function in the hook should first test if it would like to
  9410. handle this file type, for example by checking the `major-mode'
  9411. or the file extension. If it decides not to handle this file, it
  9412. should just return nil to give other functions a chance. If it
  9413. does handle the file, it must return the search string to be used
  9414. when following the link. The search string will be part of the
  9415. file link, given after a double colon, and `org-open-at-point'
  9416. will automatically search for it. If special measures must be
  9417. taken to make the search successful, another function should be
  9418. added to the companion hook `org-execute-file-search-functions',
  9419. which see.
  9420. A function in this hook may also use `setq' to set the variable
  9421. `description' to provide a suggestion for the descriptive text to
  9422. be used for this link when it gets inserted into an Org buffer
  9423. with \\[org-insert-link].")
  9424. (defvar org-execute-file-search-functions nil
  9425. "List of functions to execute a file search triggered by a link.
  9426. Functions added to this hook must accept a single argument, the
  9427. search string that was part of the file link, the part after the
  9428. double colon. The function must first check if it would like to
  9429. handle this search, for example by checking the `major-mode' or
  9430. the file extension. If it decides not to handle this search, it
  9431. should just return nil to give other functions a chance. If it
  9432. does handle the search, it must return a non-nil value to keep
  9433. other functions from trying.
  9434. Each function can access the current prefix argument through the
  9435. variable `current-prefix-arg'. Note that a single prefix is used
  9436. to force opening a link in Emacs, so it may be good to only use a
  9437. numeric or double prefix to guide the search function.
  9438. In case this is needed, a function in this hook can also restore
  9439. the window configuration before `org-open-at-point' was called using:
  9440. (set-window-configuration org-window-config-before-follow-link)")
  9441. (defun org-search-radio-target (target)
  9442. "Search a radio target matching TARGET in current buffer.
  9443. White spaces are not significant."
  9444. (let ((re (format "<<<%s>>>"
  9445. (mapconcat #'regexp-quote
  9446. (split-string target)
  9447. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9448. (origin (point)))
  9449. (goto-char (point-min))
  9450. (catch :radio-match
  9451. (while (re-search-forward re nil t)
  9452. (backward-char)
  9453. (let ((object (org-element-context)))
  9454. (when (eq (org-element-type object) 'radio-target)
  9455. (goto-char (org-element-property :begin object))
  9456. (org-show-context 'link-search)
  9457. (throw :radio-match nil))))
  9458. (goto-char origin)
  9459. (user-error "No match for radio target: %s" target))))
  9460. (defun org-link-search (s &optional avoid-pos stealth)
  9461. "Search for a search string S.
  9462. If S starts with \"#\", it triggers a custom ID search.
  9463. If S is enclosed within parenthesis, it initiates a coderef
  9464. search.
  9465. If S is surrounded by forward slashes, it is interpreted as
  9466. a regular expression. In Org mode files, this will create an
  9467. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9468. to list matches. If the current buffer is in `dired-mode', grep
  9469. will be used to search in all files.
  9470. When AVOID-POS is given, ignore matches near that position.
  9471. When optional argument STEALTH is non-nil, do not modify
  9472. visibility around point, thus ignoring `org-show-context-detail'
  9473. variable.
  9474. Search is case-insensitive and ignores white spaces. Return type
  9475. of matched result, which is either `dedicated' or `fuzzy'."
  9476. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9477. (let* ((case-fold-search t)
  9478. (origin (point))
  9479. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9480. (starred (eq (string-to-char normalized) ?*))
  9481. (words (split-string (if starred (substring s 1) s)))
  9482. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9483. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9484. type)
  9485. (cond
  9486. ;; Check if there are any special search functions.
  9487. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9488. ((eq (string-to-char s) ?#)
  9489. ;; Look for a custom ID S if S starts with "#".
  9490. (let* ((id (substring normalized 1))
  9491. (match (org-find-property "CUSTOM_ID" id)))
  9492. (if match (progn (goto-char match) (setf type 'dedicated))
  9493. (error "No match for custom ID: %s" id))))
  9494. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9495. ;; Look for coderef targets if S is enclosed within parenthesis.
  9496. (let ((coderef (match-string-no-properties 1 normalized))
  9497. (re (substring s-single-re 1 -1)))
  9498. (goto-char (point-min))
  9499. (catch :coderef-match
  9500. (while (re-search-forward re nil t)
  9501. (let ((element (org-element-at-point)))
  9502. (when (and (memq (org-element-type element)
  9503. '(example-block src-block))
  9504. ;; Build proper regexp according to current
  9505. ;; block's label format.
  9506. (let ((label-fmt
  9507. (regexp-quote
  9508. (or (org-element-property :label-fmt element)
  9509. org-coderef-label-format))))
  9510. (save-excursion
  9511. (beginning-of-line)
  9512. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9513. (format label-fmt coderef))))))
  9514. (setq type 'dedicated)
  9515. (goto-char (match-beginning 1))
  9516. (throw :coderef-match nil))))
  9517. (goto-char origin)
  9518. (error "No match for coderef: %s" coderef))))
  9519. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9520. ;; Look for a regular expression.
  9521. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9522. (match-string 1 s)))
  9523. ;; From here, we handle fuzzy links.
  9524. ;;
  9525. ;; Look for targets, only if not in a headline search.
  9526. ((and (not starred)
  9527. (let ((target (format "<<%s>>" s-multi-re)))
  9528. (catch :target-match
  9529. (goto-char (point-min))
  9530. (while (re-search-forward target nil t)
  9531. (backward-char)
  9532. (let ((context (org-element-context)))
  9533. (when (eq (org-element-type context) 'target)
  9534. (setq type 'dedicated)
  9535. (goto-char (org-element-property :begin context))
  9536. (throw :target-match t))))
  9537. nil))))
  9538. ;; Look for elements named after S, only if not in a headline
  9539. ;; search.
  9540. ((and (not starred)
  9541. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9542. (catch :name-match
  9543. (goto-char (point-min))
  9544. (while (re-search-forward name nil t)
  9545. (let ((element (org-element-at-point)))
  9546. (when (equal words
  9547. (split-string
  9548. (org-element-property :name element)))
  9549. (setq type 'dedicated)
  9550. (beginning-of-line)
  9551. (throw :name-match t))))
  9552. nil))))
  9553. ;; Regular text search. Prefer headlines in Org mode buffers.
  9554. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9555. ;; statistics cookies and tags.
  9556. ((and (derived-mode-p 'org-mode)
  9557. (let ((title-re
  9558. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9559. org-outline-regexp-bol
  9560. org-comment-string
  9561. (mapconcat #'regexp-quote words ".+")))
  9562. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9563. (comment-re (eval-when-compile
  9564. (format "\\`%s[ \t]+" org-comment-string))))
  9565. (goto-char (point-min))
  9566. (catch :found
  9567. (while (re-search-forward title-re nil t)
  9568. (when (equal words
  9569. (split-string
  9570. (replace-regexp-in-string
  9571. cookie-re ""
  9572. (replace-regexp-in-string
  9573. comment-re "" (org-get-heading t t t)))))
  9574. (throw :found t)))
  9575. nil)))
  9576. (beginning-of-line)
  9577. (setq type 'dedicated))
  9578. ;; Offer to create non-existent headline depending on
  9579. ;; `org-link-search-must-match-exact-headline'.
  9580. ((and (derived-mode-p 'org-mode)
  9581. (not org-link-search-inhibit-query)
  9582. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9583. (yes-or-no-p "No match - create this as a new heading? "))
  9584. (goto-char (point-max))
  9585. (unless (bolp) (newline))
  9586. (org-insert-heading nil t t)
  9587. (insert s "\n")
  9588. (beginning-of-line 0))
  9589. ;; Only headlines are looked after. No need to process
  9590. ;; further: throw an error.
  9591. ((and (derived-mode-p 'org-mode)
  9592. (or starred org-link-search-must-match-exact-headline))
  9593. (goto-char origin)
  9594. (error "No match for fuzzy expression: %s" normalized))
  9595. ;; Regular text search.
  9596. ((catch :fuzzy-match
  9597. (goto-char (point-min))
  9598. (while (re-search-forward s-multi-re nil t)
  9599. ;; Skip match if it contains AVOID-POS or it is included in
  9600. ;; a link with a description but outside the description.
  9601. (unless (or (and avoid-pos
  9602. (<= (match-beginning 0) avoid-pos)
  9603. (> (match-end 0) avoid-pos))
  9604. (and (save-match-data
  9605. (org-in-regexp org-bracket-link-regexp))
  9606. (match-beginning 3)
  9607. (or (> (match-beginning 3) (point))
  9608. (<= (match-end 3) (point)))
  9609. (org-element-lineage
  9610. (save-match-data (org-element-context))
  9611. '(link) t)))
  9612. (goto-char (match-beginning 0))
  9613. (setq type 'fuzzy)
  9614. (throw :fuzzy-match t)))
  9615. nil))
  9616. ;; All failed. Throw an error.
  9617. (t (goto-char origin)
  9618. (error "No match for fuzzy expression: %s" normalized)))
  9619. ;; Disclose surroundings of match, if appropriate.
  9620. (when (and (derived-mode-p 'org-mode) (not stealth))
  9621. (org-show-context 'link-search))
  9622. type))
  9623. (defun org-get-buffer-for-internal-link (buffer)
  9624. "Return a buffer to be used for displaying the link target of internal links."
  9625. (cond
  9626. ((not org-display-internal-link-with-indirect-buffer)
  9627. buffer)
  9628. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9629. (message "Buffer is already a clone, not making another one")
  9630. ;; we also do not modify visibility in this case
  9631. buffer)
  9632. (t ; make a new indirect buffer for displaying the link
  9633. (let* ((bn (buffer-name buffer))
  9634. (ibn (concat bn "(Clone)"))
  9635. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9636. (with-current-buffer ib (org-overview))
  9637. ib))))
  9638. (defun org-do-occur (regexp &optional cleanup)
  9639. "Call the Emacs command `occur'.
  9640. If CLEANUP is non-nil, remove the printout of the regular expression
  9641. in the *Occur* buffer. This is useful if the regex is long and not useful
  9642. to read."
  9643. (occur regexp)
  9644. (when cleanup
  9645. (let ((cwin (selected-window)) win beg end)
  9646. (when (setq win (get-buffer-window "*Occur*"))
  9647. (select-window win))
  9648. (goto-char (point-min))
  9649. (when (re-search-forward "match[a-z]+" nil t)
  9650. (setq beg (match-end 0))
  9651. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  9652. (setq end (1- (match-beginning 0)))))
  9653. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  9654. (goto-char (point-min))
  9655. (select-window cwin))))
  9656. ;;; The mark ring for links jumps
  9657. (defvar org-mark-ring nil
  9658. "Mark ring for positions before jumps in Org mode.")
  9659. (defvar org-mark-ring-last-goto nil
  9660. "Last position in the mark ring used to go back.")
  9661. ;; Fill and close the ring
  9662. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  9663. (dotimes (_ org-mark-ring-length)
  9664. (push (make-marker) org-mark-ring))
  9665. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  9666. org-mark-ring)
  9667. (defun org-mark-ring-push (&optional pos buffer)
  9668. "Put the current position or POS into the mark ring and rotate it."
  9669. (interactive)
  9670. (setq pos (or pos (point)))
  9671. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  9672. (move-marker (car org-mark-ring)
  9673. (or pos (point))
  9674. (or buffer (current-buffer)))
  9675. (message "%s"
  9676. (substitute-command-keys
  9677. "Position saved to mark ring, go back with \
  9678. `\\[org-mark-ring-goto]'.")))
  9679. (defun org-mark-ring-goto (&optional n)
  9680. "Jump to the previous position in the mark ring.
  9681. With prefix arg N, jump back that many stored positions. When
  9682. called several times in succession, walk through the entire ring.
  9683. Org mode commands jumping to a different position in the current file,
  9684. or to another Org file, automatically push the old position onto the ring."
  9685. (interactive "p")
  9686. (let (p m)
  9687. (if (eq last-command this-command)
  9688. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  9689. (setq p org-mark-ring))
  9690. (setq org-mark-ring-last-goto p)
  9691. (setq m (car p))
  9692. (pop-to-buffer-same-window (marker-buffer m))
  9693. (goto-char m)
  9694. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  9695. (defun org-add-angle-brackets (s)
  9696. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  9697. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  9698. s)
  9699. ;;; Following specific links
  9700. (defvar org-agenda-buffer-tmp-name)
  9701. (defvar org-agenda-start-on-weekday)
  9702. (defun org-follow-timestamp-link ()
  9703. "Open an agenda view for the time-stamp date/range at point."
  9704. (cond
  9705. ((org-at-date-range-p t)
  9706. (let ((org-agenda-start-on-weekday)
  9707. (t1 (match-string 1))
  9708. (t2 (match-string 2)) tt1 tt2)
  9709. (setq tt1 (time-to-days (org-time-string-to-time t1))
  9710. tt2 (time-to-days (org-time-string-to-time t2)))
  9711. (let ((org-agenda-buffer-tmp-name
  9712. (format "*Org Agenda(a:%s)"
  9713. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  9714. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  9715. ((org-at-timestamp-p 'lax)
  9716. (let ((org-agenda-buffer-tmp-name
  9717. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  9718. (org-agenda-list nil (time-to-days (org-time-string-to-time
  9719. (substring (match-string 1) 0 10)))
  9720. 1)))
  9721. (t (error "This should not happen"))))
  9722. ;;; Following file links
  9723. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  9724. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  9725. (declare-function mailcap-mime-info
  9726. "mailcap" (string &optional request no-decode))
  9727. (defvar org-wait nil)
  9728. (defun org-open-file (path &optional in-emacs line search)
  9729. "Open the file at PATH.
  9730. First, this expands any special file name abbreviations. Then the
  9731. configuration variable `org-file-apps' is checked if it contains an
  9732. entry for this file type, and if yes, the corresponding command is launched.
  9733. If no application is found, Emacs simply visits the file.
  9734. With optional prefix argument IN-EMACS, Emacs will visit the file.
  9735. With a double \\[universal-argument] \\[universal-argument] \
  9736. prefix arg, Org tries to avoid opening in Emacs
  9737. and to use an external application to visit the file.
  9738. Optional LINE specifies a line to go to, optional SEARCH a string
  9739. to search for. If LINE or SEARCH is given, the file will be
  9740. opened in Emacs, unless an entry from org-file-apps that makes
  9741. use of groups in a regexp matches.
  9742. If you want to change the way frames are used when following a
  9743. link, please customize `org-link-frame-setup'.
  9744. If the file does not exist, an error is thrown."
  9745. (let* ((file (if (equal path "")
  9746. buffer-file-name
  9747. (substitute-in-file-name (expand-file-name path))))
  9748. (file-apps (append org-file-apps (org-default-apps)))
  9749. (apps (cl-remove-if
  9750. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9751. (apps-dlink (cl-remove-if-not
  9752. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9753. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  9754. (dirp (unless remp (file-directory-p file)))
  9755. (file (if (and dirp org-open-directory-means-index-dot-org)
  9756. (concat (file-name-as-directory file) "index.org")
  9757. file))
  9758. (a-m-a-p (assq 'auto-mode apps))
  9759. (dfile (downcase file))
  9760. ;; Reconstruct the original link from the PATH, LINE and
  9761. ;; SEARCH args.
  9762. (link (cond (line (concat file "::" (number-to-string line)))
  9763. (search (concat file "::" search))
  9764. (t file)))
  9765. (dlink (downcase link))
  9766. (ext
  9767. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  9768. (match-string 1 dfile)))
  9769. (save-position-maybe
  9770. (let ((old-buffer (current-buffer))
  9771. (old-pos (point))
  9772. (old-mode major-mode))
  9773. (lambda ()
  9774. (and (derived-mode-p 'org-mode)
  9775. (eq old-mode 'org-mode)
  9776. (or (not (eq old-buffer (current-buffer)))
  9777. (not (eq old-pos (point))))
  9778. (org-mark-ring-push old-pos old-buffer)))))
  9779. cmd link-match-data)
  9780. (cond
  9781. ((member in-emacs '((16) system))
  9782. (setq cmd (cdr (assq 'system apps))))
  9783. (in-emacs (setq cmd 'emacs))
  9784. (t
  9785. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  9786. (and dirp (cdr (assq 'directory apps)))
  9787. ;; First, try matching against apps-dlink if we
  9788. ;; get a match here, store the match data for
  9789. ;; later.
  9790. (let ((match (assoc-default dlink apps-dlink
  9791. 'string-match)))
  9792. (if match
  9793. (progn (setq link-match-data (match-data))
  9794. match)
  9795. (progn (setq in-emacs (or in-emacs line search))
  9796. nil))) ; if we have no match in apps-dlink,
  9797. ; always open the file in emacs if line or search
  9798. ; is given (for backwards compatibility)
  9799. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  9800. 'string-match)
  9801. (cdr (assoc ext apps))
  9802. (cdr (assq t apps))))))
  9803. (when (eq cmd 'system)
  9804. (setq cmd (cdr (assq 'system apps))))
  9805. (when (eq cmd 'default)
  9806. (setq cmd (cdr (assoc t apps))))
  9807. (when (eq cmd 'mailcap)
  9808. (require 'mailcap)
  9809. (mailcap-parse-mailcaps)
  9810. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  9811. (command (mailcap-mime-info mime-type)))
  9812. (if (stringp command)
  9813. (setq cmd command)
  9814. (setq cmd 'emacs))))
  9815. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  9816. (not (file-exists-p file))
  9817. (not org-open-non-existing-files))
  9818. (user-error "No such file: %s" file))
  9819. (cond
  9820. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  9821. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  9822. (while (string-match "['\"]%s['\"]" cmd)
  9823. (setq cmd (replace-match "%s" t t cmd)))
  9824. (setq cmd (replace-regexp-in-string
  9825. "%s"
  9826. (shell-quote-argument (convert-standard-filename file))
  9827. cmd
  9828. nil t))
  9829. ;; Replace "%1", "%2" etc. in command with group matches from regex
  9830. (save-match-data
  9831. (let ((match-index 1)
  9832. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  9833. (set-match-data link-match-data)
  9834. (while (<= match-index number-of-groups)
  9835. (let ((regex (concat "%" (number-to-string match-index)))
  9836. (replace-with (match-string match-index dlink)))
  9837. (while (string-match regex cmd)
  9838. (setq cmd (replace-match replace-with t t cmd))))
  9839. (setq match-index (+ match-index 1)))))
  9840. (save-window-excursion
  9841. (message "Running %s...done" cmd)
  9842. (start-process-shell-command cmd nil cmd)
  9843. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  9844. ((or (stringp cmd)
  9845. (eq cmd 'emacs))
  9846. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  9847. (widen)
  9848. (cond (line (org-goto-line line)
  9849. (when (derived-mode-p 'org-mode) (org-reveal)))
  9850. (search (condition-case err
  9851. (org-link-search search)
  9852. ;; Save position before error-ing out so user
  9853. ;; can easily move back to the original buffer.
  9854. (error (funcall save-position-maybe)
  9855. (error (nth 1 err)))))))
  9856. ((functionp cmd)
  9857. (save-match-data
  9858. (set-match-data link-match-data)
  9859. (condition-case nil
  9860. (funcall cmd file link)
  9861. ;; FIXME: Remove this check when most default installations
  9862. ;; of Emacs have at least Org 9.0.
  9863. ((debug wrong-number-of-arguments wrong-type-argument
  9864. invalid-function)
  9865. (user-error "Please see Org News for version 9.0 about \
  9866. `org-file-apps'--Lisp error: %S" cmd)))))
  9867. ((consp cmd)
  9868. ;; FIXME: Remove this check when most default installations of
  9869. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  9870. ;; fall back to `org-link-frame-setup' for an old usage of
  9871. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  9872. (user-error "Please see Org News for version 9.0 about \
  9873. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  9874. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  9875. (funcall save-position-maybe)))
  9876. (defun org-file-apps-entry-match-against-dlink-p (entry)
  9877. "This function returns non-nil if `entry' uses a regular
  9878. expression which should be matched against the whole link by
  9879. org-open-file.
  9880. It assumes that is the case when the entry uses a regular
  9881. expression which has at least one grouping construct and the
  9882. action is either a lisp form or a command string containing
  9883. `%1', i.e. using at least one subexpression match as a
  9884. parameter."
  9885. (let ((selector (car entry))
  9886. (action (cdr entry)))
  9887. (if (stringp selector)
  9888. (and (> (regexp-opt-depth selector) 0)
  9889. (or (and (stringp action)
  9890. (string-match "%[0-9]" action))
  9891. (consp action)))
  9892. nil)))
  9893. (defun org-default-apps ()
  9894. "Return the default applications for this operating system."
  9895. (cond
  9896. ((eq system-type 'darwin)
  9897. org-file-apps-defaults-macosx)
  9898. ((eq system-type 'windows-nt)
  9899. org-file-apps-defaults-windowsnt)
  9900. (t org-file-apps-defaults-gnu)))
  9901. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  9902. "Convert extensions to regular expressions in the cars of LIST.
  9903. Also, weed out any non-string entries, because the return value is used
  9904. only for regexp matching.
  9905. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  9906. point to the symbol `emacs', indicating that the file should
  9907. be opened in Emacs."
  9908. (append
  9909. (delq nil
  9910. (mapcar (lambda (x)
  9911. (unless (not (stringp (car x)))
  9912. (if (string-match "\\W" (car x))
  9913. x
  9914. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  9915. list))
  9916. (when add-auto-mode
  9917. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  9918. (defvar ange-ftp-name-format)
  9919. (defun org-file-remote-p (file)
  9920. "Test whether FILE specifies a location on a remote system.
  9921. Return non-nil if the location is indeed remote.
  9922. For example, the filename \"/user@host:/foo\" specifies a location
  9923. on the system \"/user@host:\"."
  9924. (cond ((fboundp 'file-remote-p)
  9925. (file-remote-p file))
  9926. ((fboundp 'tramp-handle-file-remote-p)
  9927. (tramp-handle-file-remote-p file))
  9928. ((and (boundp 'ange-ftp-name-format)
  9929. (string-match (car ange-ftp-name-format) file))
  9930. t)))
  9931. ;;;; Refiling
  9932. (defun org-get-org-file ()
  9933. "Read a filename, with default directory `org-directory'."
  9934. (let ((default (or org-default-notes-file remember-data-file)))
  9935. (read-file-name (format "File name [%s]: " default)
  9936. (file-name-as-directory org-directory)
  9937. default)))
  9938. (defun org-notes-order-reversed-p ()
  9939. "Check if the current file should receive notes in reversed order."
  9940. (cond
  9941. ((not org-reverse-note-order) nil)
  9942. ((eq t org-reverse-note-order) t)
  9943. ((not (listp org-reverse-note-order)) nil)
  9944. (t (catch 'exit
  9945. (dolist (entry org-reverse-note-order)
  9946. (when (string-match (car entry) buffer-file-name)
  9947. (throw 'exit (cdr entry))))))))
  9948. (defvar org-refile-target-table nil
  9949. "The list of refile targets, created by `org-refile'.")
  9950. (defvar org-agenda-new-buffers nil
  9951. "Buffers created to visit agenda files.")
  9952. (defvar org-refile-cache nil
  9953. "Cache for refile targets.")
  9954. (defvar org-refile-markers nil
  9955. "All the markers used for caching refile locations.")
  9956. (defun org-refile-marker (pos)
  9957. "Get a new refile marker, but only if caching is in use."
  9958. (if (not org-refile-use-cache)
  9959. pos
  9960. (let ((m (make-marker)))
  9961. (move-marker m pos)
  9962. (push m org-refile-markers)
  9963. m)))
  9964. (defun org-refile-cache-clear ()
  9965. "Clear the refile cache and disable all the markers."
  9966. (dolist (m org-refile-markers) (move-marker m nil))
  9967. (setq org-refile-markers nil)
  9968. (setq org-refile-cache nil)
  9969. (message "Refile cache has been cleared"))
  9970. (defun org-refile-cache-check-set (set)
  9971. "Check if all the markers in the cache still have live buffers."
  9972. (let (marker)
  9973. (catch 'exit
  9974. (while (and set (setq marker (nth 3 (pop set))))
  9975. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  9976. (when (and marker (null (marker-buffer marker)))
  9977. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  9978. (sit-for 3)
  9979. (throw 'exit nil)))
  9980. t)))
  9981. (defun org-refile-cache-put (set &rest identifiers)
  9982. "Push the refile targets SET into the cache, under IDENTIFIERS."
  9983. (let* ((key (sha1 (prin1-to-string identifiers)))
  9984. (entry (assoc key org-refile-cache)))
  9985. (if entry
  9986. (setcdr entry set)
  9987. (push (cons key set) org-refile-cache))))
  9988. (defun org-refile-cache-get (&rest identifiers)
  9989. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  9990. (cond
  9991. ((not org-refile-cache) nil)
  9992. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  9993. (t
  9994. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  9995. org-refile-cache))))
  9996. (and set (org-refile-cache-check-set set) set)))))
  9997. (defvar org-outline-path-cache nil
  9998. "Alist between buffer positions and outline paths.
  9999. It value is an alist (POSITION . PATH) where POSITION is the
  10000. buffer position at the beginning of an entry and PATH is a list
  10001. of strings describing the outline path for that entry, in reverse
  10002. order.")
  10003. (defun org-refile-get-targets (&optional default-buffer)
  10004. "Produce a table with refile targets."
  10005. (let ((case-fold-search nil)
  10006. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10007. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10008. targets tgs files desc descre)
  10009. (message "Getting targets...")
  10010. (with-current-buffer (or default-buffer (current-buffer))
  10011. (dolist (entry entries)
  10012. (setq files (car entry) desc (cdr entry))
  10013. (cond
  10014. ((null files) (setq files (list (current-buffer))))
  10015. ((eq files 'org-agenda-files)
  10016. (setq files (org-agenda-files 'unrestricted)))
  10017. ((and (symbolp files) (fboundp files))
  10018. (setq files (funcall files)))
  10019. ((and (symbolp files) (boundp files))
  10020. (setq files (symbol-value files))))
  10021. (when (stringp files) (setq files (list files)))
  10022. (cond
  10023. ((eq (car desc) :tag)
  10024. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10025. ((eq (car desc) :todo)
  10026. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10027. ((eq (car desc) :regexp)
  10028. (setq descre (cdr desc)))
  10029. ((eq (car desc) :level)
  10030. (setq descre (concat "^\\*\\{" (number-to-string
  10031. (if org-odd-levels-only
  10032. (1- (* 2 (cdr desc)))
  10033. (cdr desc)))
  10034. "\\}[ \t]")))
  10035. ((eq (car desc) :maxlevel)
  10036. (setq descre (concat "^\\*\\{1," (number-to-string
  10037. (if org-odd-levels-only
  10038. (1- (* 2 (cdr desc)))
  10039. (cdr desc)))
  10040. "\\}[ \t]")))
  10041. (t (error "Bad refiling target description %s" desc)))
  10042. (dolist (f files)
  10043. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  10044. (or
  10045. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10046. (progn
  10047. (when (bufferp f)
  10048. (setq f (buffer-file-name (buffer-base-buffer f))))
  10049. (setq f (and f (expand-file-name f)))
  10050. (when (eq org-refile-use-outline-path 'file)
  10051. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10052. (when (eq org-refile-use-outline-path 'buffer-name)
  10053. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  10054. (when (eq org-refile-use-outline-path 'full-file-path)
  10055. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  10056. (org-with-wide-buffer
  10057. (goto-char (point-min))
  10058. (setq org-outline-path-cache nil)
  10059. (while (re-search-forward descre nil t)
  10060. (beginning-of-line)
  10061. (let ((case-fold-search nil))
  10062. (looking-at org-complex-heading-regexp))
  10063. (let ((begin (point))
  10064. (heading (match-string-no-properties 4)))
  10065. (unless (or (and
  10066. org-refile-target-verify-function
  10067. (not
  10068. (funcall org-refile-target-verify-function)))
  10069. (not heading))
  10070. (let ((re (format org-complex-heading-regexp-format
  10071. (regexp-quote heading)))
  10072. (target
  10073. (if (not org-refile-use-outline-path) heading
  10074. (mapconcat
  10075. #'identity
  10076. (append
  10077. (pcase org-refile-use-outline-path
  10078. (`file (list (file-name-nondirectory
  10079. (buffer-file-name
  10080. (buffer-base-buffer)))))
  10081. (`full-file-path
  10082. (list (buffer-file-name
  10083. (buffer-base-buffer))))
  10084. (`buffer-name
  10085. (list (buffer-name
  10086. (buffer-base-buffer))))
  10087. (_ nil))
  10088. (mapcar (lambda (s) (replace-regexp-in-string
  10089. "/" "\\/" s nil t))
  10090. (org-get-outline-path t t)))
  10091. "/"))))
  10092. (push (list target f re (org-refile-marker (point)))
  10093. tgs)))
  10094. (when (= (point) begin)
  10095. ;; Verification function has not moved point.
  10096. (end-of-line)))))))
  10097. (when org-refile-use-cache
  10098. (org-refile-cache-put tgs (buffer-file-name) descre))
  10099. (setq targets (append tgs targets))))))
  10100. (message "Getting targets...done")
  10101. (delete-dups (nreverse targets))))
  10102. (defun org--get-outline-path-1 (&optional use-cache)
  10103. "Return outline path to current headline.
  10104. Outline path is a list of strings, in reverse order. When
  10105. optional argument USE-CACHE is non-nil, make use of a cache. See
  10106. `org-get-outline-path' for details.
  10107. Assume buffer is widened and point is on a headline."
  10108. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  10109. (let ((p (point))
  10110. (heading (let ((case-fold-search nil))
  10111. (looking-at org-complex-heading-regexp)
  10112. (if (not (match-end 4)) ""
  10113. ;; Remove statistics cookies.
  10114. (org-trim
  10115. (org-link-display-format
  10116. (replace-regexp-in-string
  10117. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10118. (match-string-no-properties 4))))))))
  10119. (if (org-up-heading-safe)
  10120. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  10121. (when use-cache
  10122. (push (cons p path) org-outline-path-cache))
  10123. path)
  10124. ;; This is a new root node. Since we assume we are moving
  10125. ;; forward, we can drop previous cache so as to limit number
  10126. ;; of associations there.
  10127. (let ((path (list heading)))
  10128. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10129. path)))))
  10130. (defun org-get-outline-path (&optional with-self use-cache)
  10131. "Return the outline path to the current entry.
  10132. An outline path is a list of ancestors for current headline, as
  10133. a list of strings. Statistics cookies are removed and links are
  10134. replaced with their description, if any, or their path otherwise.
  10135. When optional argument WITH-SELF is non-nil, the path also
  10136. includes the current headline.
  10137. When optional argument USE-CACHE is non-nil, cache outline paths
  10138. between calls to this function so as to avoid backtracking. This
  10139. argument is useful when planning to find more than one outline
  10140. path in the same document. In that case, there are two
  10141. conditions to satisfy:
  10142. - `org-outline-path-cache' is set to nil before starting the
  10143. process;
  10144. - outline paths are computed by increasing buffer positions."
  10145. (org-with-wide-buffer
  10146. (and (or (and with-self (org-back-to-heading t))
  10147. (org-up-heading-safe))
  10148. (reverse (org--get-outline-path-1 use-cache)))))
  10149. (defun org-format-outline-path (path &optional width prefix separator)
  10150. "Format the outline path PATH for display.
  10151. WIDTH is the maximum number of characters that is available.
  10152. PREFIX is a prefix to be included in the returned string,
  10153. such as the file name.
  10154. SEPARATOR is inserted between the different parts of the path,
  10155. the default is \"/\"."
  10156. (setq width (or width 79))
  10157. (setq path (delq nil path))
  10158. (unless (> width 0)
  10159. (user-error "Argument `width' must be positive"))
  10160. (setq separator (or separator "/"))
  10161. (let* ((org-odd-levels-only nil)
  10162. (fpath (concat
  10163. prefix (and prefix path separator)
  10164. (mapconcat
  10165. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10166. (cl-loop for head in path
  10167. for n from 0
  10168. collect (org-add-props
  10169. head nil 'face
  10170. (nth (% n org-n-level-faces) org-level-faces)))
  10171. separator))))
  10172. (when (> (length fpath) width)
  10173. (if (< width 7)
  10174. ;; It's unlikely that `width' will be this small, but don't
  10175. ;; waste characters by adding ".." if it is.
  10176. (setq fpath (substring fpath 0 width))
  10177. (setf (substring fpath (- width 2)) "..")))
  10178. fpath))
  10179. (defun org-display-outline-path (&optional file current separator just-return-string)
  10180. "Display the current outline path in the echo area.
  10181. If FILE is non-nil, prepend the output with the file name.
  10182. If CURRENT is non-nil, append the current heading to the output.
  10183. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10184. the different parts of the path and defaults to \"/\".
  10185. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10186. (interactive "P")
  10187. (let* (case-fold-search
  10188. (bfn (buffer-file-name (buffer-base-buffer)))
  10189. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10190. res)
  10191. (when current (setq path (append path
  10192. (save-excursion
  10193. (org-back-to-heading t)
  10194. (when (looking-at org-complex-heading-regexp)
  10195. (list (match-string 4)))))))
  10196. (setq res
  10197. (org-format-outline-path
  10198. path
  10199. (1- (frame-width))
  10200. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10201. separator))
  10202. (if just-return-string
  10203. (org-no-properties res)
  10204. (org-unlogged-message "%s" res))))
  10205. (defvar org-refile-history nil
  10206. "History for refiling operations.")
  10207. (defvar org-after-refile-insert-hook nil
  10208. "Hook run after `org-refile' has inserted its stuff at the new location.
  10209. Note that this is still *before* the stuff will be removed from
  10210. the *old* location.")
  10211. (defvar org-capture-last-stored-marker)
  10212. (defvar org-refile-keep nil
  10213. "Non-nil means `org-refile' will copy instead of refile.")
  10214. (defun org-copy ()
  10215. "Like `org-refile', but copy."
  10216. (interactive)
  10217. (let ((org-refile-keep t))
  10218. (funcall 'org-refile nil nil nil "Copy")))
  10219. (defun org-refile (&optional arg default-buffer rfloc msg)
  10220. "Move the entry or entries at point to another heading.
  10221. The list of target headings is compiled using the information in
  10222. `org-refile-targets', which see.
  10223. At the target location, the entry is filed as a subitem of the
  10224. target heading. Depending on `org-reverse-note-order', the new
  10225. subitem will either be the first or the last subitem.
  10226. If there is an active region, all entries in that region will be
  10227. refiled. However, the region must fulfill the requirement that
  10228. the first heading sets the top-level of the moved text.
  10229. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10230. location
  10231. and not actually move anything.
  10232. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10233. location where the last
  10234. refiling operation has put the subtree.
  10235. With a numeric prefix argument of `2', refile to the running clock.
  10236. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10237. being set to t and copy to the target location, don't move it.
  10238. Beware that keeping refiled entries may result in duplicated ID
  10239. properties.
  10240. RFLOC can be a refile location obtained in a different way.
  10241. MSG is a string to replace \"Refile\" in the default prompt with
  10242. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10243. See also `org-refile-use-outline-path'.
  10244. If you are using target caching (see `org-refile-use-cache'), you
  10245. have to clear the target cache in order to find new targets.
  10246. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10247. prefix argument (`C-u C-u C-u C-c C-w')."
  10248. (interactive "P")
  10249. (if (member arg '(0 (64)))
  10250. (org-refile-cache-clear)
  10251. (let* ((actionmsg (cond (msg msg)
  10252. ((equal arg 3) "Refile (and keep)")
  10253. (t "Refile")))
  10254. (regionp (org-region-active-p))
  10255. (region-start (and regionp (region-beginning)))
  10256. (region-end (and regionp (region-end)))
  10257. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10258. pos it nbuf file level reversed)
  10259. (setq last-command nil)
  10260. (when regionp
  10261. (goto-char region-start)
  10262. (or (bolp) (goto-char (point-at-bol)))
  10263. (setq region-start (point))
  10264. (unless (or (org-kill-is-subtree-p
  10265. (buffer-substring region-start region-end))
  10266. (prog1 org-refile-active-region-within-subtree
  10267. (let ((s (point-at-eol)))
  10268. (org-toggle-heading)
  10269. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10270. (user-error "The region is not a (sequence of) subtree(s)")))
  10271. (if (equal arg '(16))
  10272. (org-refile-goto-last-stored)
  10273. (when (or
  10274. (and (equal arg 2)
  10275. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10276. (prog1
  10277. (setq it (list (or org-clock-heading "running clock")
  10278. (buffer-file-name
  10279. (marker-buffer org-clock-hd-marker))
  10280. ""
  10281. (marker-position org-clock-hd-marker)))
  10282. (setq arg nil)))
  10283. (setq it
  10284. (or rfloc
  10285. (let (heading-text)
  10286. (save-excursion
  10287. (unless (and arg (listp arg))
  10288. (org-back-to-heading t)
  10289. (setq heading-text
  10290. (replace-regexp-in-string
  10291. org-bracket-link-regexp
  10292. "\\3"
  10293. (or (nth 4 (org-heading-components))
  10294. ""))))
  10295. (org-refile-get-location
  10296. (cond ((and arg (listp arg)) "Goto")
  10297. (regionp (concat actionmsg " region to"))
  10298. (t (concat actionmsg " subtree \""
  10299. heading-text "\" to")))
  10300. default-buffer
  10301. (and (not (equal '(4) arg))
  10302. org-refile-allow-creating-parent-nodes)))))))
  10303. (setq file (nth 1 it)
  10304. pos (nth 3 it))
  10305. (when (and (not arg)
  10306. pos
  10307. (equal (buffer-file-name) file)
  10308. (if regionp
  10309. (and (>= pos region-start)
  10310. (<= pos region-end))
  10311. (and (>= pos (point))
  10312. (< pos (save-excursion
  10313. (org-end-of-subtree t t))))))
  10314. (error "Cannot refile to position inside the tree or region"))
  10315. (setq nbuf (or (find-buffer-visiting file)
  10316. (find-file-noselect file)))
  10317. (if (and arg (not (equal arg 3)))
  10318. (progn
  10319. (pop-to-buffer-same-window nbuf)
  10320. (goto-char (cond (pos)
  10321. ((org-notes-order-reversed-p) (point-min))
  10322. (t (point-max))))
  10323. (org-show-context 'org-goto))
  10324. (if regionp
  10325. (progn
  10326. (org-kill-new (buffer-substring region-start region-end))
  10327. (org-save-markers-in-region region-start region-end))
  10328. (org-copy-subtree 1 nil t))
  10329. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10330. (find-file-noselect file)))
  10331. (setq reversed (org-notes-order-reversed-p))
  10332. (org-with-wide-buffer
  10333. (if pos
  10334. (progn
  10335. (goto-char pos)
  10336. (setq level (org-get-valid-level (funcall outline-level) 1))
  10337. (goto-char
  10338. (if reversed
  10339. (or (outline-next-heading) (point-max))
  10340. (or (save-excursion (org-get-next-sibling))
  10341. (org-end-of-subtree t t)
  10342. (point-max)))))
  10343. (setq level 1)
  10344. (if (not reversed)
  10345. (goto-char (point-max))
  10346. (goto-char (point-min))
  10347. (or (outline-next-heading) (goto-char (point-max)))))
  10348. (unless (bolp) (newline))
  10349. (org-paste-subtree level nil nil t)
  10350. (when org-log-refile
  10351. (org-add-log-setup 'refile nil nil org-log-refile)
  10352. (unless (eq org-log-refile 'note)
  10353. (save-excursion (org-add-log-note))))
  10354. (and org-auto-align-tags
  10355. (let ((org-loop-over-headlines-in-active-region nil))
  10356. (org-set-tags nil t)))
  10357. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10358. :last-refile)))
  10359. (when bookmark-name
  10360. (with-demoted-errors
  10361. (bookmark-set bookmark-name))))
  10362. ;; If we are refiling for capture, make sure that the
  10363. ;; last-capture pointers point here
  10364. (when (bound-and-true-p org-capture-is-refiling)
  10365. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10366. :last-capture-marker)))
  10367. (when bookmark-name
  10368. (with-demoted-errors
  10369. (bookmark-set bookmark-name))))
  10370. (move-marker org-capture-last-stored-marker (point)))
  10371. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10372. (run-hooks 'org-after-refile-insert-hook)))
  10373. (unless org-refile-keep
  10374. (if regionp
  10375. (delete-region (point) (+ (point) (- region-end region-start)))
  10376. (delete-region
  10377. (and (org-back-to-heading t) (point))
  10378. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
  10379. (when (featurep 'org-inlinetask)
  10380. (org-inlinetask-remove-END-maybe))
  10381. (setq org-markers-to-move nil)
  10382. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10383. (defun org-refile-goto-last-stored ()
  10384. "Go to the location where the last refile was stored."
  10385. (interactive)
  10386. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10387. (message "This is the location of the last refile"))
  10388. (defun org-refile--get-location (refloc tbl)
  10389. "When user refile to REFLOC, find the associated target in TBL.
  10390. Also check `org-refile-target-table'."
  10391. (car (delq
  10392. nil
  10393. (mapcar
  10394. (lambda (r) (or (assoc r tbl)
  10395. (assoc r org-refile-target-table)))
  10396. (list (replace-regexp-in-string "/$" "" refloc)
  10397. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10398. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10399. "Prompt the user for a refile location, using PROMPT.
  10400. PROMPT should not be suffixed with a colon and a space, because
  10401. this function appends the default value from
  10402. `org-refile-history' automatically, if that is not empty."
  10403. (let ((org-refile-targets org-refile-targets)
  10404. (org-refile-use-outline-path org-refile-use-outline-path))
  10405. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10406. (unless org-refile-target-table
  10407. (user-error "No refile targets"))
  10408. (let* ((cbuf (current-buffer))
  10409. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10410. (cfunc (if (and org-refile-use-outline-path
  10411. org-outline-path-complete-in-steps)
  10412. #'org-olpath-completing-read
  10413. #'completing-read))
  10414. (extra (if org-refile-use-outline-path "/" ""))
  10415. (cbnex (concat (buffer-name) extra))
  10416. (filename (and cfn (expand-file-name cfn)))
  10417. (tbl (mapcar
  10418. (lambda (x)
  10419. (if (and (not (member org-refile-use-outline-path
  10420. '(file full-file-path)))
  10421. (not (equal filename (nth 1 x))))
  10422. (cons (concat (car x) extra " ("
  10423. (file-name-nondirectory (nth 1 x)) ")")
  10424. (cdr x))
  10425. (cons (concat (car x) extra) (cdr x))))
  10426. org-refile-target-table))
  10427. (completion-ignore-case t)
  10428. cdef
  10429. (prompt (concat prompt
  10430. (or (and (car org-refile-history)
  10431. (concat " (default " (car org-refile-history) ")"))
  10432. (and (assoc cbnex tbl) (setq cdef cbnex)
  10433. (concat " (default " cbnex ")"))) ": "))
  10434. pa answ parent-target child parent old-hist)
  10435. (setq old-hist org-refile-history)
  10436. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10437. nil 'org-refile-history (or cdef (car org-refile-history))))
  10438. (if (setq pa (org-refile--get-location answ tbl))
  10439. (progn
  10440. (org-refile-check-position pa)
  10441. (when (or (not org-refile-history)
  10442. (not (eq old-hist org-refile-history))
  10443. (not (equal (car pa) (car org-refile-history))))
  10444. (setq org-refile-history
  10445. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10446. org-refile-history
  10447. (cdr org-refile-history))))
  10448. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10449. (pop org-refile-history)))
  10450. pa)
  10451. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10452. (progn
  10453. (setq parent (match-string 1 answ)
  10454. child (match-string 2 answ))
  10455. (setq parent-target (org-refile--get-location parent tbl))
  10456. (when (and parent-target
  10457. (or (eq new-nodes t)
  10458. (and (eq new-nodes 'confirm)
  10459. (y-or-n-p (format "Create new node \"%s\"? "
  10460. child)))))
  10461. (org-refile-new-child parent-target child)))
  10462. (user-error "Invalid target location")))))
  10463. (declare-function org-string-nw-p "org-macs" (s))
  10464. (defun org-refile-check-position (refile-pointer)
  10465. "Check if the refile pointer matches the headline to which it points."
  10466. (let* ((file (nth 1 refile-pointer))
  10467. (re (nth 2 refile-pointer))
  10468. (pos (nth 3 refile-pointer))
  10469. buffer)
  10470. (if (and (not (markerp pos)) (not file))
  10471. (user-error "Please indicate a target file in the refile path")
  10472. (when (org-string-nw-p re)
  10473. (setq buffer (if (markerp pos)
  10474. (marker-buffer pos)
  10475. (or (find-buffer-visiting file)
  10476. (find-file-noselect file))))
  10477. (with-current-buffer buffer
  10478. (org-with-wide-buffer
  10479. (goto-char pos)
  10480. (beginning-of-line 1)
  10481. (unless (looking-at-p re)
  10482. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10483. (defun org-refile-new-child (parent-target child)
  10484. "Use refile target PARENT-TARGET to add new CHILD below it."
  10485. (unless parent-target
  10486. (error "Cannot find parent for new node"))
  10487. (let ((file (nth 1 parent-target))
  10488. (pos (nth 3 parent-target))
  10489. level)
  10490. (with-current-buffer (or (find-buffer-visiting file)
  10491. (find-file-noselect file))
  10492. (org-with-wide-buffer
  10493. (if pos
  10494. (goto-char pos)
  10495. (goto-char (point-max))
  10496. (unless (bolp) (newline)))
  10497. (when (looking-at org-outline-regexp)
  10498. (setq level (funcall outline-level))
  10499. (org-end-of-subtree t t))
  10500. (org-back-over-empty-lines)
  10501. (insert "\n" (make-string
  10502. (if pos (org-get-valid-level level 1) 1) ?*)
  10503. " " child "\n")
  10504. (beginning-of-line 0)
  10505. (list (concat (car parent-target) "/" child) file "" (point))))))
  10506. (defun org-olpath-completing-read (prompt collection &rest args)
  10507. "Read an outline path like a file name."
  10508. (let ((thetable collection))
  10509. (apply #'completing-read
  10510. prompt
  10511. (lambda (string predicate &optional flag)
  10512. (cond
  10513. ((eq flag nil) (try-completion string thetable))
  10514. ((eq flag t)
  10515. (let ((l (length string)))
  10516. (mapcar (lambda (x)
  10517. (let ((r (substring x l))
  10518. (f (if (string-match " ([^)]*)$" x)
  10519. (match-string 0 x)
  10520. "")))
  10521. (if (string-match "/" r)
  10522. (concat string (substring r 0 (match-end 0)) f)
  10523. x)))
  10524. (all-completions string thetable predicate))))
  10525. ;; Exact match?
  10526. ((eq flag 'lambda) (assoc string thetable))))
  10527. args)))
  10528. ;;;; Dynamic blocks
  10529. (defun org-find-dblock (name)
  10530. "Find the first dynamic block with name NAME in the buffer.
  10531. If not found, stay at current position and return nil."
  10532. (let ((case-fold-search t) pos)
  10533. (save-excursion
  10534. (goto-char (point-min))
  10535. (setq pos (and (re-search-forward
  10536. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10537. (match-beginning 0))))
  10538. (when pos (goto-char pos))
  10539. pos))
  10540. (defun org-create-dblock (plist)
  10541. "Create a dynamic block section, with parameters taken from PLIST.
  10542. PLIST must contain a :name entry which is used as the name of the block."
  10543. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10544. (end-of-line 1)
  10545. (newline))
  10546. (let ((col (current-column))
  10547. (name (plist-get plist :name)))
  10548. (insert "#+BEGIN: " name)
  10549. (while plist
  10550. (if (eq (car plist) :name)
  10551. (setq plist (cddr plist))
  10552. (insert " " (prin1-to-string (pop plist)))))
  10553. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10554. (beginning-of-line -2)))
  10555. (defun org-prepare-dblock ()
  10556. "Prepare dynamic block for refresh.
  10557. This empties the block, puts the cursor at the insert position and returns
  10558. the property list including an extra property :name with the block name."
  10559. (unless (looking-at org-dblock-start-re)
  10560. (user-error "Not at a dynamic block"))
  10561. (let* ((begdel (1+ (match-end 0)))
  10562. (name (org-no-properties (match-string 1)))
  10563. (params (append (list :name name)
  10564. (read (concat "(" (match-string 3) ")")))))
  10565. (save-excursion
  10566. (beginning-of-line 1)
  10567. (skip-chars-forward " \t")
  10568. (setq params (plist-put params :indentation-column (current-column))))
  10569. (unless (re-search-forward org-dblock-end-re nil t)
  10570. (error "Dynamic block not terminated"))
  10571. (setq params
  10572. (append params
  10573. (list :content (buffer-substring
  10574. begdel (match-beginning 0)))))
  10575. (delete-region begdel (match-beginning 0))
  10576. (goto-char begdel)
  10577. (open-line 1)
  10578. params))
  10579. (defun org-map-dblocks (&optional command)
  10580. "Apply COMMAND to all dynamic blocks in the current buffer.
  10581. If COMMAND is not given, use `org-update-dblock'."
  10582. (let ((cmd (or command 'org-update-dblock)))
  10583. (save-excursion
  10584. (goto-char (point-min))
  10585. (while (re-search-forward org-dblock-start-re nil t)
  10586. (goto-char (match-beginning 0))
  10587. (save-excursion
  10588. (condition-case nil
  10589. (funcall cmd)
  10590. (error (message "Error during update of dynamic block"))))
  10591. (unless (re-search-forward org-dblock-end-re nil t)
  10592. (error "Dynamic block not terminated"))))))
  10593. (defun org-dblock-update (&optional arg)
  10594. "User command for updating dynamic blocks.
  10595. Update the dynamic block at point. With prefix ARG, update all dynamic
  10596. blocks in the buffer."
  10597. (interactive "P")
  10598. (if arg
  10599. (org-update-all-dblocks)
  10600. (or (looking-at org-dblock-start-re)
  10601. (org-beginning-of-dblock))
  10602. (org-update-dblock)))
  10603. (defun org-update-dblock ()
  10604. "Update the dynamic block at point.
  10605. This means to empty the block, parse for parameters and then call
  10606. the correct writing function."
  10607. (interactive)
  10608. (save-excursion
  10609. (let* ((win (selected-window))
  10610. (pos (point))
  10611. (line (org-current-line))
  10612. (params (org-prepare-dblock))
  10613. (name (plist-get params :name))
  10614. (indent (plist-get params :indentation-column))
  10615. (cmd (intern (concat "org-dblock-write:" name))))
  10616. (message "Updating dynamic block `%s' at line %d..." name line)
  10617. (funcall cmd params)
  10618. (message "Updating dynamic block `%s' at line %d...done" name line)
  10619. (goto-char pos)
  10620. (when (and indent (> indent 0))
  10621. (setq indent (make-string indent ?\ ))
  10622. (save-excursion
  10623. (select-window win)
  10624. (org-beginning-of-dblock)
  10625. (forward-line 1)
  10626. (while (not (looking-at org-dblock-end-re))
  10627. (insert indent)
  10628. (beginning-of-line 2))
  10629. (when (looking-at org-dblock-end-re)
  10630. (and (looking-at "[ \t]+")
  10631. (replace-match ""))
  10632. (insert indent)))))))
  10633. (defun org-beginning-of-dblock ()
  10634. "Find the beginning of the dynamic block at point.
  10635. Error if there is no such block at point."
  10636. (let ((pos (point))
  10637. beg)
  10638. (end-of-line 1)
  10639. (if (and (re-search-backward org-dblock-start-re nil t)
  10640. (setq beg (match-beginning 0))
  10641. (re-search-forward org-dblock-end-re nil t)
  10642. (> (match-end 0) pos))
  10643. (goto-char beg)
  10644. (goto-char pos)
  10645. (error "Not in a dynamic block"))))
  10646. (defun org-update-all-dblocks ()
  10647. "Update all dynamic blocks in the buffer.
  10648. This function can be used in a hook."
  10649. (interactive)
  10650. (when (derived-mode-p 'org-mode)
  10651. (org-map-dblocks 'org-update-dblock)))
  10652. ;;;; Completion
  10653. (declare-function org-export-backend-options "ox" (cl-x) t)
  10654. (defun org-get-export-keywords ()
  10655. "Return a list of all currently understood export keywords.
  10656. Export keywords include options, block names, attributes and
  10657. keywords relative to each registered export back-end."
  10658. (let (keywords)
  10659. (dolist (backend
  10660. (bound-and-true-p org-export-registered-backends)
  10661. (delq nil keywords))
  10662. ;; Back-end name (for keywords, like #+LATEX:)
  10663. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  10664. (dolist (option-entry (org-export-backend-options backend))
  10665. ;; Back-end options.
  10666. (push (nth 1 option-entry) keywords)))))
  10667. (defconst org-options-keywords
  10668. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  10669. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  10670. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  10671. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  10672. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  10673. (defcustom org-structure-template-alist
  10674. '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
  10675. ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
  10676. ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
  10677. ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
  10678. ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
  10679. ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
  10680. ("C" "#+BEGIN_COMMENT\n?\n#+END_COMMENT")
  10681. ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
  10682. ("L" "#+LaTeX: ")
  10683. ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
  10684. ("H" "#+HTML: ")
  10685. ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
  10686. ("A" "#+ASCII: ")
  10687. ("i" "#+INDEX: ?")
  10688. ("I" "#+INCLUDE: %file ?"))
  10689. "Structure completion elements.
  10690. This is a list of abbreviation keys and values. The value gets inserted
  10691. if you type `<' followed by the key and then press the completion key,
  10692. usually `TAB'. %file will be replaced by a file name after prompting
  10693. for the file using completion. The cursor will be placed at the position
  10694. of the `?' in the template.
  10695. There are two templates for each key, the first uses the original Org syntax,
  10696. the second uses Emacs Muse-like syntax tags. These Muse-like tags become
  10697. the default when the /org-mtags.el/ module has been loaded. See also the
  10698. variable `org-mtags-prefer-muse-templates'."
  10699. :group 'org-completion
  10700. :type '(repeat
  10701. (list
  10702. (string :tag "Key")
  10703. (string :tag "Template")))
  10704. :version "26.1"
  10705. :package-version '(Org . "8.3"))
  10706. (defun org-try-structure-completion ()
  10707. "Try to complete a structure template before point.
  10708. This looks for strings like \"<e\" on an otherwise empty line and
  10709. expands them."
  10710. (let ((l (buffer-substring (point-at-bol) (point)))
  10711. a)
  10712. (when (and (looking-at "[ \t]*$")
  10713. (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
  10714. (setq a (assoc (match-string 1 l) org-structure-template-alist)))
  10715. (org-complete-expand-structure-template (+ -1 (point-at-bol)
  10716. (match-beginning 1)) a)
  10717. t)))
  10718. (defun org-complete-expand-structure-template (start cell)
  10719. "Expand a structure template."
  10720. (let ((rpl (nth 1 cell))
  10721. (ind ""))
  10722. (delete-region start (point))
  10723. (when (string-match "\\`[ \t]*#\\+" rpl)
  10724. (cond
  10725. ((bolp))
  10726. ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
  10727. (setq ind (buffer-substring (point-at-bol) (point))))
  10728. (t (newline))))
  10729. (setq start (point))
  10730. (when (string-match "%file" rpl)
  10731. (setq rpl (replace-match
  10732. (concat
  10733. "\""
  10734. (save-match-data
  10735. (abbreviate-file-name (read-file-name "Include file: ")))
  10736. "\"")
  10737. t t rpl)))
  10738. (setq rpl (mapconcat 'identity (split-string rpl "\n")
  10739. (concat "\n" ind)))
  10740. (insert rpl)
  10741. (when (re-search-backward "\\?" start t) (delete-char 1))))
  10742. ;;;; TODO, DEADLINE, Comments
  10743. (defun org-toggle-comment ()
  10744. "Change the COMMENT state of an entry."
  10745. (interactive)
  10746. (save-excursion
  10747. (org-back-to-heading)
  10748. (let ((case-fold-search nil))
  10749. (looking-at org-complex-heading-regexp))
  10750. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  10751. (skip-chars-forward " \t")
  10752. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  10753. (if (org-in-commented-heading-p t)
  10754. (delete-region (point)
  10755. (progn (search-forward " " (line-end-position) 'move)
  10756. (skip-chars-forward " \t")
  10757. (point)))
  10758. (insert org-comment-string)
  10759. (unless (eolp) (insert " ")))))
  10760. (defvar org-last-todo-state-is-todo nil
  10761. "This is non-nil when the last TODO state change led to a TODO state.
  10762. If the last change removed the TODO tag or switched to DONE, then
  10763. this is nil.")
  10764. (defvar org-setting-tags nil) ; dynamically skipped
  10765. (defvar org-todo-setup-filter-hook nil
  10766. "Hook for functions that pre-filter todo specs.
  10767. Each function takes a todo spec and returns either nil or the spec
  10768. transformed into canonical form." )
  10769. (defvar org-todo-get-default-hook nil
  10770. "Hook for functions that get a default item for todo.
  10771. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  10772. nil or a string to be used for the todo mark." )
  10773. (defvar org-agenda-headline-snapshot-before-repeat)
  10774. (defun org-current-effective-time ()
  10775. "Return current time adjusted for `org-extend-today-until' variable."
  10776. (let* ((ct (org-current-time))
  10777. (dct (decode-time ct))
  10778. (ct1
  10779. (cond
  10780. (org-use-last-clock-out-time-as-effective-time
  10781. (or (org-clock-get-last-clock-out-time) ct))
  10782. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  10783. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  10784. (t ct))))
  10785. ct1))
  10786. (defun org-todo-yesterday (&optional arg)
  10787. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  10788. (interactive "P")
  10789. (if (eq major-mode 'org-agenda-mode)
  10790. (apply 'org-agenda-todo-yesterday arg)
  10791. (let* ((org-use-effective-time t)
  10792. (hour (nth 2 (decode-time (org-current-time))))
  10793. (org-extend-today-until (1+ hour)))
  10794. (org-todo arg))))
  10795. (defvar org-block-entry-blocking ""
  10796. "First entry preventing the TODO state change.")
  10797. (defun org-cancel-repeater ()
  10798. "Cancel a repeater by setting its numeric value to zero."
  10799. (interactive)
  10800. (save-excursion
  10801. (org-back-to-heading t)
  10802. (let ((bound1 (point))
  10803. (bound0 (save-excursion (outline-next-heading) (point))))
  10804. (when (and (re-search-forward
  10805. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  10806. org-deadline-time-regexp "\\)\\|\\("
  10807. org-ts-regexp "\\)")
  10808. bound0 t)
  10809. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  10810. bound1 t))
  10811. (replace-match "0" t nil nil 1)))))
  10812. (defvar org-state)
  10813. (defvar org-blocked-by-checkboxes)
  10814. (defun org-todo (&optional arg)
  10815. "Change the TODO state of an item.
  10816. The state of an item is given by a keyword at the start of the heading,
  10817. like
  10818. *** TODO Write paper
  10819. *** DONE Call mom
  10820. The different keywords are specified in the variable `org-todo-keywords'.
  10821. By default the available states are \"TODO\" and \"DONE\". So, for this
  10822. example: when the item starts with TODO, it is changed to DONE.
  10823. When it starts with DONE, the DONE is removed. And when neither TODO nor
  10824. DONE are present, add TODO at the beginning of the heading.
  10825. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  10826. state.
  10827. With numeric prefix ARG, switch to that state.
  10828. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  10829. next set of TODO \
  10830. keywords (nextset).
  10831. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  10832. prefix, circumvent any state blocking.
  10833. With a numeric prefix arg of 0, inhibit note taking for the change.
  10834. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  10835. When called through ELisp, arg is also interpreted in the following way:
  10836. `none' -> empty state
  10837. \"\" -> switch to empty state
  10838. `done' -> switch to DONE
  10839. `nextset' -> switch to the next set of keywords
  10840. `previousset' -> switch to the previous set of keywords
  10841. \"WAITING\" -> switch to the specified keyword, but only if it
  10842. really is a member of `org-todo-keywords'."
  10843. (interactive "P")
  10844. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10845. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10846. 'region-start-level 'region))
  10847. org-loop-over-headlines-in-active-region)
  10848. (org-map-entries
  10849. `(org-todo ,arg)
  10850. org-loop-over-headlines-in-active-region
  10851. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  10852. (when (equal arg '(16)) (setq arg 'nextset))
  10853. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  10854. (let ((org-blocker-hook org-blocker-hook)
  10855. commentp
  10856. case-fold-search)
  10857. (when (equal arg '(64))
  10858. (setq arg nil org-blocker-hook nil))
  10859. (when (and org-blocker-hook
  10860. (or org-inhibit-blocking
  10861. (org-entry-get nil "NOBLOCKING")))
  10862. (setq org-blocker-hook nil))
  10863. (save-excursion
  10864. (catch 'exit
  10865. (org-back-to-heading t)
  10866. (when (org-in-commented-heading-p t)
  10867. (org-toggle-comment)
  10868. (setq commentp t))
  10869. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  10870. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  10871. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  10872. (let* ((match-data (match-data))
  10873. (startpos (point-at-bol))
  10874. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  10875. (org-log-done org-log-done)
  10876. (org-log-repeat org-log-repeat)
  10877. (org-todo-log-states org-todo-log-states)
  10878. (org-inhibit-logging
  10879. (if (equal arg 0)
  10880. (progn (setq arg nil) 'note) org-inhibit-logging))
  10881. (this (match-string 1))
  10882. (hl-pos (match-beginning 0))
  10883. (head (org-get-todo-sequence-head this))
  10884. (ass (assoc head org-todo-kwd-alist))
  10885. (interpret (nth 1 ass))
  10886. (done-word (nth 3 ass))
  10887. (final-done-word (nth 4 ass))
  10888. (org-last-state (or this ""))
  10889. (completion-ignore-case t)
  10890. (member (member this org-todo-keywords-1))
  10891. (tail (cdr member))
  10892. (org-state (cond
  10893. ((and org-todo-key-trigger
  10894. (or (and (equal arg '(4))
  10895. (eq org-use-fast-todo-selection 'prefix))
  10896. (and (not arg) org-use-fast-todo-selection
  10897. (not (eq org-use-fast-todo-selection
  10898. 'prefix)))))
  10899. ;; Use fast selection.
  10900. (org-fast-todo-selection))
  10901. ((and (equal arg '(4))
  10902. (or (not org-use-fast-todo-selection)
  10903. (not org-todo-key-trigger)))
  10904. ;; Read a state with completion.
  10905. (completing-read
  10906. "State: " (mapcar #'list org-todo-keywords-1)
  10907. nil t))
  10908. ((eq arg 'right)
  10909. (if this
  10910. (if tail (car tail) nil)
  10911. (car org-todo-keywords-1)))
  10912. ((eq arg 'left)
  10913. (unless (equal member org-todo-keywords-1)
  10914. (if this
  10915. (nth (- (length org-todo-keywords-1)
  10916. (length tail) 2)
  10917. org-todo-keywords-1)
  10918. (org-last org-todo-keywords-1))))
  10919. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  10920. (setq arg nil))) ;hack to fall back to cycling
  10921. (arg
  10922. ;; User or caller requests a specific state.
  10923. (cond
  10924. ((equal arg "") nil)
  10925. ((eq arg 'none) nil)
  10926. ((eq arg 'done) (or done-word (car org-done-keywords)))
  10927. ((eq arg 'nextset)
  10928. (or (car (cdr (member head org-todo-heads)))
  10929. (car org-todo-heads)))
  10930. ((eq arg 'previousset)
  10931. (let ((org-todo-heads (reverse org-todo-heads)))
  10932. (or (car (cdr (member head org-todo-heads)))
  10933. (car org-todo-heads))))
  10934. ((car (member arg org-todo-keywords-1)))
  10935. ((stringp arg)
  10936. (user-error "State `%s' not valid in this file" arg))
  10937. ((nth (1- (prefix-numeric-value arg))
  10938. org-todo-keywords-1))))
  10939. ((null member) (or head (car org-todo-keywords-1)))
  10940. ((equal this final-done-word) nil) ;-> make empty
  10941. ((null tail) nil) ;-> first entry
  10942. ((memq interpret '(type priority))
  10943. (if (eq this-command last-command)
  10944. (car tail)
  10945. (if (> (length tail) 0)
  10946. (or done-word (car org-done-keywords))
  10947. nil)))
  10948. (t
  10949. (car tail))))
  10950. (org-state (or
  10951. (run-hook-with-args-until-success
  10952. 'org-todo-get-default-hook org-state org-last-state)
  10953. org-state))
  10954. (next (if org-state (concat " " org-state " ") " "))
  10955. (change-plist (list :type 'todo-state-change :from this :to org-state
  10956. :position startpos))
  10957. dolog now-done-p)
  10958. (when org-blocker-hook
  10959. (let (org-blocked-by-checkboxes block-reason)
  10960. (setq org-last-todo-state-is-todo
  10961. (not (member this org-done-keywords)))
  10962. (unless (save-excursion
  10963. (save-match-data
  10964. (org-with-wide-buffer
  10965. (run-hook-with-args-until-failure
  10966. 'org-blocker-hook change-plist))))
  10967. (setq block-reason (if org-blocked-by-checkboxes
  10968. "contained checkboxes"
  10969. (format "\"%s\"" org-block-entry-blocking)))
  10970. (if (called-interactively-p 'interactive)
  10971. (user-error "TODO state change from %s to %s blocked (by %s)"
  10972. this org-state block-reason)
  10973. ;; Fail silently.
  10974. (message "TODO state change from %s to %s blocked (by %s)"
  10975. this org-state block-reason)
  10976. (throw 'exit nil)))))
  10977. (store-match-data match-data)
  10978. (replace-match next t t)
  10979. (cond ((equal this org-state)
  10980. (message "TODO state was already %s" (org-trim next)))
  10981. ((not (pos-visible-in-window-p hl-pos))
  10982. (message "TODO state changed to %s" (org-trim next))))
  10983. (unless head
  10984. (setq head (org-get-todo-sequence-head org-state)
  10985. ass (assoc head org-todo-kwd-alist)
  10986. interpret (nth 1 ass)
  10987. done-word (nth 3 ass)
  10988. final-done-word (nth 4 ass)))
  10989. (when (memq arg '(nextset previousset))
  10990. (message "Keyword-Set %d/%d: %s"
  10991. (- (length org-todo-sets) -1
  10992. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  10993. (length org-todo-sets)
  10994. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  10995. (setq org-last-todo-state-is-todo
  10996. (not (member org-state org-done-keywords)))
  10997. (setq now-done-p (and (member org-state org-done-keywords)
  10998. (not (member this org-done-keywords))))
  10999. (and logging (org-local-logging logging))
  11000. (when (and (or org-todo-log-states org-log-done)
  11001. (not (eq org-inhibit-logging t))
  11002. (not (memq arg '(nextset previousset))))
  11003. ;; We need to look at recording a time and note.
  11004. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11005. (nth 2 (assoc this org-todo-log-states))))
  11006. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11007. (setq dolog 'time))
  11008. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11009. (and org-state
  11010. (member org-state org-not-done-keywords)
  11011. (not (member this org-not-done-keywords))))
  11012. ;; This is now a todo state and was not one before
  11013. ;; If there was a CLOSED time stamp, get rid of it.
  11014. (org-add-planning-info nil nil 'closed))
  11015. (when (and now-done-p org-log-done)
  11016. ;; It is now done, and it was not done before.
  11017. (org-add-planning-info 'closed (org-current-effective-time))
  11018. (when (and (not dolog) (eq 'note org-log-done))
  11019. (org-add-log-setup 'done org-state this 'note)))
  11020. (when (and org-state dolog)
  11021. ;; This is a non-nil state, and we need to log it.
  11022. (org-add-log-setup 'state org-state this dolog)))
  11023. ;; Fixup tag positioning.
  11024. (org-todo-trigger-tag-changes org-state)
  11025. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11026. (when org-provide-todo-statistics
  11027. (org-update-parent-todo-statistics))
  11028. (run-hooks 'org-after-todo-state-change-hook)
  11029. (when (and arg (not (member org-state org-done-keywords)))
  11030. (setq head (org-get-todo-sequence-head org-state)))
  11031. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11032. ;; Do we need to trigger a repeat?
  11033. (when now-done-p
  11034. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11035. ;; This is for the agenda, take a snapshot of the headline.
  11036. (save-match-data
  11037. (setq org-agenda-headline-snapshot-before-repeat
  11038. (org-get-heading))))
  11039. (org-auto-repeat-maybe org-state))
  11040. ;; Fixup cursor location if close to the keyword.
  11041. (when (and (outline-on-heading-p)
  11042. (not (bolp))
  11043. (save-excursion (beginning-of-line 1)
  11044. (looking-at org-todo-line-regexp))
  11045. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11046. (goto-char (or (match-end 2) (match-end 1)))
  11047. (and (looking-at " ") (just-one-space)))
  11048. (when org-trigger-hook
  11049. (save-excursion
  11050. (run-hook-with-args 'org-trigger-hook change-plist)))
  11051. (when commentp (org-toggle-comment))))))))
  11052. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11053. "Block turning an entry into a TODO, using the hierarchy.
  11054. This checks whether the current task should be blocked from state
  11055. changes. Such blocking occurs when:
  11056. 1. The task has children which are not all in a completed state.
  11057. 2. A task has a parent with the property :ORDERED:, and there
  11058. are siblings prior to the current task with incomplete
  11059. status.
  11060. 3. The parent of the task is blocked because it has siblings that should
  11061. be done first, or is child of a block grandparent TODO entry."
  11062. (if (not org-enforce-todo-dependencies)
  11063. t ; if locally turned off don't block
  11064. (catch 'dont-block
  11065. ;; If this is not a todo state change, or if this entry is already DONE,
  11066. ;; do not block
  11067. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11068. (member (plist-get change-plist :from)
  11069. (cons 'done org-done-keywords))
  11070. (member (plist-get change-plist :to)
  11071. (cons 'todo org-not-done-keywords))
  11072. (not (plist-get change-plist :to)))
  11073. (throw 'dont-block t))
  11074. ;; If this task has children, and any are undone, it's blocked
  11075. (save-excursion
  11076. (org-back-to-heading t)
  11077. (let ((this-level (funcall outline-level)))
  11078. (outline-next-heading)
  11079. (let ((child-level (funcall outline-level)))
  11080. (while (and (not (eobp))
  11081. (> child-level this-level))
  11082. ;; this todo has children, check whether they are all
  11083. ;; completed
  11084. (when (and (not (org-entry-is-done-p))
  11085. (org-entry-is-todo-p))
  11086. (setq org-block-entry-blocking (org-get-heading))
  11087. (throw 'dont-block nil))
  11088. (outline-next-heading)
  11089. (setq child-level (funcall outline-level))))))
  11090. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11091. ;; any previous siblings are undone, it's blocked
  11092. (save-excursion
  11093. (org-back-to-heading t)
  11094. (let* ((pos (point))
  11095. (parent-pos (and (org-up-heading-safe) (point)))
  11096. (case-fold-search nil))
  11097. (unless parent-pos (throw 'dont-block t)) ; no parent
  11098. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11099. (forward-line 1)
  11100. (re-search-forward org-not-done-heading-regexp pos t))
  11101. (setq org-block-entry-blocking (match-string 0))
  11102. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11103. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11104. (while t
  11105. (goto-char parent-pos)
  11106. (unless (looking-at org-not-done-heading-regexp)
  11107. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11108. (setq pos (point))
  11109. (setq parent-pos (and (org-up-heading-safe) (point)))
  11110. (unless parent-pos (throw 'dont-block t)) ; no parent
  11111. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11112. (forward-line 1)
  11113. (re-search-forward org-not-done-heading-regexp pos t)
  11114. (setq org-block-entry-blocking (org-get-heading)))
  11115. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11116. (defcustom org-track-ordered-property-with-tag nil
  11117. "Should the ORDERED property also be shown as a tag?
  11118. The ORDERED property decides if an entry should require subtasks to be
  11119. completed in sequence. Since a property is not very visible, setting
  11120. this option means that toggling the ORDERED property with the command
  11121. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11122. not relevant for the behavior, but it makes things more visible.
  11123. Note that toggling the tag with tags commands will not change the property
  11124. and therefore not influence behavior!
  11125. This can be t, meaning the tag ORDERED should be used, It can also be a
  11126. string to select a different tag for this task."
  11127. :group 'org-todo
  11128. :type '(choice
  11129. (const :tag "No tracking" nil)
  11130. (const :tag "Track with ORDERED tag" t)
  11131. (string :tag "Use other tag")))
  11132. (defun org-toggle-ordered-property ()
  11133. "Toggle the ORDERED property of the current entry.
  11134. For better visibility, you can track the value of this property with a tag.
  11135. See variable `org-track-ordered-property-with-tag'."
  11136. (interactive)
  11137. (let* ((t1 org-track-ordered-property-with-tag)
  11138. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11139. (save-excursion
  11140. (org-back-to-heading)
  11141. (if (org-entry-get nil "ORDERED")
  11142. (progn
  11143. (org-delete-property "ORDERED")
  11144. (and tag (org-toggle-tag tag 'off))
  11145. (message "Subtasks can be completed in arbitrary order"))
  11146. (org-entry-put nil "ORDERED" "t")
  11147. (and tag (org-toggle-tag tag 'on))
  11148. (message "Subtasks must be completed in sequence")))))
  11149. (defun org-block-todo-from-checkboxes (change-plist)
  11150. "Block turning an entry into a TODO, using checkboxes.
  11151. This checks whether the current task should be blocked from state
  11152. changes because there are unchecked boxes in this entry."
  11153. (if (not org-enforce-todo-checkbox-dependencies)
  11154. t ; if locally turned off don't block
  11155. (catch 'dont-block
  11156. ;; If this is not a todo state change, or if this entry is already DONE,
  11157. ;; do not block
  11158. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11159. (member (plist-get change-plist :from)
  11160. (cons 'done org-done-keywords))
  11161. (member (plist-get change-plist :to)
  11162. (cons 'todo org-not-done-keywords))
  11163. (not (plist-get change-plist :to)))
  11164. (throw 'dont-block t))
  11165. ;; If this task has checkboxes that are not checked, it's blocked
  11166. (save-excursion
  11167. (org-back-to-heading t)
  11168. (let ((beg (point)) end)
  11169. (outline-next-heading)
  11170. (setq end (point))
  11171. (goto-char beg)
  11172. (when (org-list-search-forward
  11173. (concat (org-item-beginning-re)
  11174. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11175. "\\[[- ]\\]")
  11176. end t)
  11177. (when (boundp 'org-blocked-by-checkboxes)
  11178. (setq org-blocked-by-checkboxes t))
  11179. (throw 'dont-block nil))))
  11180. t))) ; do not block
  11181. (defun org-entry-blocked-p ()
  11182. "Non-nil if entry at point is blocked."
  11183. (and (not (org-entry-get nil "NOBLOCKING"))
  11184. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11185. (not (run-hook-with-args-until-failure
  11186. 'org-blocker-hook
  11187. (list :type 'todo-state-change
  11188. :position (point)
  11189. :from 'todo
  11190. :to 'done)))))
  11191. (defun org-update-statistics-cookies (all)
  11192. "Update the statistics cookie, either from TODO or from checkboxes.
  11193. This should be called with the cursor in a line with a statistics
  11194. cookie. When called with a \\[universal-argument] prefix, update
  11195. all statistics cookies in the buffer."
  11196. (interactive "P")
  11197. (if all
  11198. (progn
  11199. (org-update-checkbox-count 'all)
  11200. (org-map-entries 'org-update-parent-todo-statistics))
  11201. (if (not (org-at-heading-p))
  11202. (org-update-checkbox-count)
  11203. (let ((pos (point-marker))
  11204. end l1 l2)
  11205. (ignore-errors (org-back-to-heading t))
  11206. (if (not (org-at-heading-p))
  11207. (org-update-checkbox-count)
  11208. (setq l1 (org-outline-level))
  11209. (setq end (save-excursion
  11210. (outline-next-heading)
  11211. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11212. (point)))
  11213. (if (and (save-excursion
  11214. (re-search-forward
  11215. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11216. (not (save-excursion (re-search-forward
  11217. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11218. (org-update-checkbox-count)
  11219. (if (and l2 (> l2 l1))
  11220. (progn
  11221. (goto-char end)
  11222. (org-update-parent-todo-statistics))
  11223. (goto-char pos)
  11224. (beginning-of-line 1)
  11225. (while (re-search-forward
  11226. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11227. (point-at-eol) t)
  11228. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11229. (goto-char pos)
  11230. (move-marker pos nil)))))
  11231. (defvar org-entry-property-inherited-from) ;; defined below
  11232. (defun org-update-parent-todo-statistics ()
  11233. "Update any statistics cookie in the parent of the current headline.
  11234. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11235. the entire subtree and this will travel up the hierarchy and update
  11236. statistics everywhere."
  11237. (let* ((prop (save-excursion (org-up-heading-safe)
  11238. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11239. (recursive (or (not org-hierarchical-todo-statistics)
  11240. (and prop (string-match "\\<recursive\\>" prop))))
  11241. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11242. 0))
  11243. (first t)
  11244. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11245. level ltoggle l1 new ndel
  11246. (cnt-all 0) (cnt-done 0) is-percent kwd
  11247. checkbox-beg cookie-present)
  11248. (catch 'exit
  11249. (save-excursion
  11250. (beginning-of-line 1)
  11251. (setq ltoggle (funcall outline-level))
  11252. ;; Three situations are to consider:
  11253. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11254. ;; to the top-level ancestor on the headline;
  11255. ;; 2. If parent has "recursive" property, repeat up to the
  11256. ;; headline setting that property, taking inheritance into
  11257. ;; account;
  11258. ;; 3. Else, move up to direct parent and proceed only once.
  11259. (while (and (setq level (org-up-heading-safe))
  11260. (or recursive first)
  11261. (>= (point) lim))
  11262. (setq first nil cookie-present nil)
  11263. (unless (and level
  11264. (not (string-match
  11265. "\\<checkbox\\>"
  11266. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11267. "")))))
  11268. (throw 'exit nil))
  11269. (while (re-search-forward box-re (point-at-eol) t)
  11270. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11271. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11272. (save-match-data
  11273. (unless (outline-next-heading) (throw 'exit nil))
  11274. (while (and (looking-at org-complex-heading-regexp)
  11275. (> (setq l1 (length (match-string 1))) level))
  11276. (setq kwd (and (or recursive (= l1 ltoggle))
  11277. (match-string 2)))
  11278. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11279. (and (eq org-provide-todo-statistics t)
  11280. (or (member kwd org-done-keywords)))
  11281. (and (listp org-provide-todo-statistics)
  11282. (stringp (car org-provide-todo-statistics))
  11283. (or (member kwd org-provide-todo-statistics)
  11284. (member kwd org-done-keywords)))
  11285. (and (listp org-provide-todo-statistics)
  11286. (listp (car org-provide-todo-statistics))
  11287. (or (member kwd (car org-provide-todo-statistics))
  11288. (and (member kwd org-done-keywords)
  11289. (member kwd (cadr org-provide-todo-statistics))))))
  11290. (setq cnt-all (1+ cnt-all))
  11291. (and (eq org-provide-todo-statistics t)
  11292. kwd
  11293. (setq cnt-all (1+ cnt-all))))
  11294. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11295. (member kwd org-done-keywords))
  11296. (and (listp org-provide-todo-statistics)
  11297. (listp (car org-provide-todo-statistics))
  11298. (member kwd org-done-keywords)
  11299. (member kwd (cadr org-provide-todo-statistics)))
  11300. (and (listp org-provide-todo-statistics)
  11301. (stringp (car org-provide-todo-statistics))
  11302. (member kwd org-done-keywords)))
  11303. (setq cnt-done (1+ cnt-done)))
  11304. (outline-next-heading)))
  11305. (setq new
  11306. (if is-percent
  11307. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11308. (max 1 cnt-all)))
  11309. (format "[%d/%d]" cnt-done cnt-all))
  11310. ndel (- (match-end 0) checkbox-beg))
  11311. (goto-char checkbox-beg)
  11312. (insert new)
  11313. (delete-region (point) (+ (point) ndel))
  11314. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11315. (when cookie-present
  11316. (run-hook-with-args 'org-after-todo-statistics-hook
  11317. cnt-done (- cnt-all cnt-done))))))
  11318. (run-hooks 'org-todo-statistics-hook)))
  11319. (defvar org-after-todo-statistics-hook nil
  11320. "Hook that is called after a TODO statistics cookie has been updated.
  11321. Each function is called with two arguments: the number of not-done entries
  11322. and the number of done entries.
  11323. For example, the following function, when added to this hook, will switch
  11324. an entry to DONE when all children are done, and back to TODO when new
  11325. entries are set to a TODO status. Note that this hook is only called
  11326. when there is a statistics cookie in the headline!
  11327. (defun org-summary-todo (n-done n-not-done)
  11328. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11329. (let (org-log-done org-log-states) ; turn off logging
  11330. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11331. ")
  11332. (defvar org-todo-statistics-hook nil
  11333. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11334. This hook runs even if there is no statistics cookie present, in which case
  11335. `org-after-todo-statistics-hook' would not run.")
  11336. (defun org-todo-trigger-tag-changes (state)
  11337. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11338. (let ((l org-todo-state-tags-triggers)
  11339. changes)
  11340. (when (or (not state) (equal state ""))
  11341. (setq changes (append changes (cdr (assoc "" l)))))
  11342. (when (and (stringp state) (> (length state) 0))
  11343. (setq changes (append changes (cdr (assoc state l)))))
  11344. (when (member state org-not-done-keywords)
  11345. (setq changes (append changes (cdr (assq 'todo l)))))
  11346. (when (member state org-done-keywords)
  11347. (setq changes (append changes (cdr (assq 'done l)))))
  11348. (dolist (c changes)
  11349. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11350. (defun org-local-logging (value)
  11351. "Get logging settings from a property VALUE."
  11352. ;; Directly set the variables, they are already local.
  11353. (setq org-log-done nil
  11354. org-log-repeat nil
  11355. org-todo-log-states nil)
  11356. (dolist (w (split-string value))
  11357. (let (a)
  11358. (cond
  11359. ((setq a (assoc w org-startup-options))
  11360. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11361. (set (nth 1 a) (nth 2 a))))
  11362. ((setq a (org-extract-log-state-settings w))
  11363. (and (member (car a) org-todo-keywords-1)
  11364. (push a org-todo-log-states)))))))
  11365. (defun org-get-todo-sequence-head (kwd)
  11366. "Return the head of the TODO sequence to which KWD belongs.
  11367. If KWD is not set, check if there is a text property remembering the
  11368. right sequence."
  11369. (let (p)
  11370. (cond
  11371. ((not kwd)
  11372. (or (get-text-property (point-at-bol) 'org-todo-head)
  11373. (progn
  11374. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11375. nil (point-at-eol)))
  11376. (get-text-property p 'org-todo-head))))
  11377. ((not (member kwd org-todo-keywords-1))
  11378. (car org-todo-keywords-1))
  11379. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11380. (defun org-fast-todo-selection ()
  11381. "Fast TODO keyword selection with single keys.
  11382. Returns the new TODO keyword, or nil if no state change should occur."
  11383. (let* ((fulltable org-todo-key-alist)
  11384. (done-keywords org-done-keywords) ;; needed for the faces.
  11385. (maxlen (apply 'max (mapcar
  11386. (lambda (x)
  11387. (if (stringp (car x)) (string-width (car x)) 0))
  11388. fulltable)))
  11389. (expert nil)
  11390. (fwidth (+ maxlen 3 1 3))
  11391. (ncol (/ (- (window-width) 4) fwidth))
  11392. tg cnt e c tbl
  11393. groups ingroup)
  11394. (save-excursion
  11395. (save-window-excursion
  11396. (if expert
  11397. (set-buffer (get-buffer-create " *Org todo*"))
  11398. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11399. (erase-buffer)
  11400. (setq-local org-done-keywords done-keywords)
  11401. (setq tbl fulltable cnt 0)
  11402. (while (setq e (pop tbl))
  11403. (cond
  11404. ((equal e '(:startgroup))
  11405. (push '() groups) (setq ingroup t)
  11406. (unless (= cnt 0)
  11407. (setq cnt 0)
  11408. (insert "\n"))
  11409. (insert "{ "))
  11410. ((equal e '(:endgroup))
  11411. (setq ingroup nil cnt 0)
  11412. (insert "}\n"))
  11413. ((equal e '(:newline))
  11414. (unless (= cnt 0)
  11415. (setq cnt 0)
  11416. (insert "\n")
  11417. (setq e (car tbl))
  11418. (while (equal (car tbl) '(:newline))
  11419. (insert "\n")
  11420. (setq tbl (cdr tbl)))))
  11421. (t
  11422. (setq tg (car e) c (cdr e))
  11423. (when ingroup (push tg (car groups)))
  11424. (setq tg (org-add-props tg nil 'face
  11425. (org-get-todo-face tg)))
  11426. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11427. (insert "[" c "] " tg (make-string
  11428. (- fwidth 4 (length tg)) ?\ ))
  11429. (when (= (setq cnt (1+ cnt)) ncol)
  11430. (insert "\n")
  11431. (when ingroup (insert " "))
  11432. (setq cnt 0)))))
  11433. (insert "\n")
  11434. (goto-char (point-min))
  11435. (unless expert (org-fit-window-to-buffer))
  11436. (message "[a-z..]:Set [SPC]:clear")
  11437. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11438. (cond
  11439. ((or (= c ?\C-g)
  11440. (and (= c ?q) (not (rassoc c fulltable))))
  11441. (setq quit-flag t))
  11442. ((= c ?\ ) nil)
  11443. ((setq e (rassoc c fulltable) tg (car e))
  11444. tg)
  11445. (t (setq quit-flag t)))))))
  11446. (defun org-entry-is-todo-p ()
  11447. (member (org-get-todo-state) org-not-done-keywords))
  11448. (defun org-entry-is-done-p ()
  11449. (member (org-get-todo-state) org-done-keywords))
  11450. (defun org-get-todo-state ()
  11451. "Return the TODO keyword of the current subtree."
  11452. (save-excursion
  11453. (org-back-to-heading t)
  11454. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11455. (match-end 2)
  11456. (match-string 2))))
  11457. (defun org-at-date-range-p (&optional inactive-ok)
  11458. "Non-nil if point is inside a date range.
  11459. When optional argument INACTIVE-OK is non-nil, also consider
  11460. inactive time ranges.
  11461. When this function returns a non-nil value, match data is set
  11462. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11463. on INACTIVE-OK."
  11464. (interactive)
  11465. (save-excursion
  11466. (catch 'exit
  11467. (let ((pos (point)))
  11468. (skip-chars-backward "^[<\r\n")
  11469. (skip-chars-backward "<[")
  11470. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11471. (>= (match-end 0) pos)
  11472. (throw 'exit t))
  11473. (skip-chars-backward "^<[\r\n")
  11474. (skip-chars-backward "<[")
  11475. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11476. (>= (match-end 0) pos)
  11477. (throw 'exit t)))
  11478. nil)))
  11479. (defun org-get-repeat (&optional timestamp)
  11480. "Check if there is a time-stamp with repeater in this entry.
  11481. Return the repeater, as a string, or nil. Also return nil when
  11482. this function is called before first heading.
  11483. When optional argument TIMESTAMP is a string, extract the
  11484. repeater from there instead."
  11485. (save-match-data
  11486. (cond (timestamp
  11487. (and (string-match org-repeat-re timestamp)
  11488. (match-string-no-properties 1 timestamp)))
  11489. ((org-before-first-heading-p) nil)
  11490. (t
  11491. (save-excursion
  11492. (org-back-to-heading t)
  11493. (let ((end (org-entry-end-position)))
  11494. (catch :repeat
  11495. (while (re-search-forward org-repeat-re end t)
  11496. (when (save-match-data (org-at-timestamp-p 'agenda))
  11497. (throw :repeat (match-string-no-properties 1)))))))))))
  11498. (defvar org-last-changed-timestamp)
  11499. (defvar org-last-inserted-timestamp)
  11500. (defvar org-log-post-message)
  11501. (defvar org-log-note-purpose)
  11502. (defvar org-log-note-how nil)
  11503. (defvar org-log-note-extra)
  11504. (defun org-auto-repeat-maybe (done-word)
  11505. "Check if the current headline contains a repeated time-stamp.
  11506. If yes, set TODO state back to what it was and change the base date
  11507. of repeating deadline/scheduled time stamps to new date.
  11508. This function is run automatically after each state change to a DONE state."
  11509. (let* ((repeat (org-get-repeat))
  11510. (aa (assoc org-last-state org-todo-kwd-alist))
  11511. (interpret (nth 1 aa))
  11512. (head (nth 2 aa))
  11513. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11514. (msg "Entry repeats: ")
  11515. (org-log-done nil)
  11516. (org-todo-log-states nil)
  11517. (end (copy-marker (org-entry-end-position))))
  11518. (unwind-protect
  11519. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11520. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11521. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11522. org-todo-repeat-to-state)))
  11523. (org-todo (cond
  11524. ((and to-state (member to-state org-todo-keywords-1))
  11525. to-state)
  11526. ((eq interpret 'type) org-last-state)
  11527. (head)
  11528. (t 'none))))
  11529. (org-back-to-heading t)
  11530. (org-add-planning-info nil nil 'closed)
  11531. ;; When `org-log-repeat' is non-nil or entry contains
  11532. ;; a clock, set LAST_REPEAT property.
  11533. (when (or org-log-repeat
  11534. (catch :clock
  11535. (save-excursion
  11536. (while (re-search-forward org-clock-line-re end t)
  11537. (when (org-at-clock-log-p) (throw :clock t))))))
  11538. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11539. (org-time-stamp-format t t)
  11540. (current-time))))
  11541. (when org-log-repeat
  11542. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11543. (memq 'org-add-log-note post-command-hook))
  11544. ;; We are already setup for some record.
  11545. (when (eq org-log-repeat 'note)
  11546. ;; Make sure we take a note, not only a time stamp.
  11547. (setq org-log-note-how 'note))
  11548. ;; Set up for taking a record.
  11549. (org-add-log-setup 'state
  11550. (or done-word (car org-done-keywords))
  11551. org-last-state
  11552. org-log-repeat)))
  11553. (let ((planning-re (regexp-opt
  11554. (list org-scheduled-string org-deadline-string))))
  11555. (while (re-search-forward org-ts-regexp end t)
  11556. (let* ((ts (match-string 0))
  11557. (planning? (org-at-planning-p))
  11558. (type (if (not planning?) "Plain:"
  11559. (save-excursion
  11560. (re-search-backward
  11561. planning-re (line-beginning-position) t)
  11562. (match-string 0)))))
  11563. (cond
  11564. ;; Ignore fake time-stamps (e.g., within comments).
  11565. ((not (org-at-timestamp-p 'agenda)))
  11566. ;; Time-stamps without a repeater are usually
  11567. ;; skipped. However, a SCHEDULED time-stamp without
  11568. ;; one is removed, as they are no longer relevant.
  11569. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11570. ts))
  11571. (when (equal type org-scheduled-string)
  11572. (org-remove-timestamp-with-keyword type)))
  11573. (t
  11574. (let ((n (string-to-number (match-string 2 ts)))
  11575. (what (match-string 3 ts)))
  11576. (when (equal what "w") (setq n (* n 7) what "d"))
  11577. (when (and (equal what "h")
  11578. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11579. ts)))
  11580. (user-error
  11581. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11582. has been set"
  11583. n))
  11584. ;; Preparation, see if we need to modify the start
  11585. ;; date for the change.
  11586. (when (match-end 1)
  11587. (let ((time (save-match-data
  11588. (org-time-string-to-time ts))))
  11589. (cond
  11590. ((equal (match-string 1 ts) ".")
  11591. ;; Shift starting date to today
  11592. (org-timestamp-change
  11593. (- (org-today) (time-to-days time))
  11594. 'day))
  11595. ((equal (match-string 1 ts) "+")
  11596. (let ((nshiftmax 10)
  11597. (nshift 0))
  11598. (while (or (= nshift 0)
  11599. (not (time-less-p (current-time) time)))
  11600. (when (= (cl-incf nshift) nshiftmax)
  11601. (or (y-or-n-p
  11602. (format "%d repeater intervals were not \
  11603. enough to shift date past today. Continue? "
  11604. nshift))
  11605. (user-error "Abort")))
  11606. (org-timestamp-change n (cdr (assoc what whata)))
  11607. (org-in-regexp org-ts-regexp3)
  11608. (setq ts (match-string 1))
  11609. (setq time
  11610. (save-match-data
  11611. (org-time-string-to-time ts)))))
  11612. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11613. ;; Rematch, so that we have everything in place
  11614. ;; for the real shift.
  11615. (org-in-regexp org-ts-regexp3)
  11616. (setq ts (match-string 1))
  11617. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11618. ts)))))
  11619. (save-excursion
  11620. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11621. (setq msg
  11622. (concat
  11623. msg type " " org-last-changed-timestamp " "))))))))
  11624. (setq org-log-post-message msg)
  11625. (message "%s" msg))
  11626. (set-marker end nil))))
  11627. (defun org-show-todo-tree (arg)
  11628. "Make a compact tree which shows all headlines marked with TODO.
  11629. The tree will show the lines where the regexp matches, and all higher
  11630. headlines above the match.
  11631. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11632. With a numeric prefix N, construct a sparse tree for the Nth element
  11633. of `org-todo-keywords-1'."
  11634. (interactive "P")
  11635. (let ((case-fold-search nil)
  11636. (kwd-re
  11637. (cond ((null arg) org-not-done-regexp)
  11638. ((equal arg '(4))
  11639. (let ((kwd
  11640. (completing-read "Keyword (or KWD1|KWD2|...): "
  11641. (mapcar #'list org-todo-keywords-1))))
  11642. (concat "\\("
  11643. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11644. "\\)\\>")))
  11645. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11646. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11647. org-todo-keywords-1)))
  11648. (t (user-error "Invalid prefix argument: %s" arg)))))
  11649. (message "%d TODO entries found"
  11650. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11651. (defun org--deadline-or-schedule (arg type time)
  11652. "Insert DEADLINE or SCHEDULE information in current entry.
  11653. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  11654. `org-schedule' for information about ARG and TIME arguments."
  11655. (let* ((deadline? (eq type 'deadline))
  11656. (keyword (if deadline? org-deadline-string org-scheduled-string))
  11657. (log (if deadline? org-log-redeadline org-log-reschedule))
  11658. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  11659. (old-date-time (and old-date (org-time-string-to-time old-date)))
  11660. ;; Save repeater cookie from either TIME or current scheduled
  11661. ;; time stamp. We are going to insert it back at the end of
  11662. ;; the process.
  11663. (repeater (or (and (org-string-nw-p time)
  11664. ;; We use `org-repeat-re' because we need
  11665. ;; to tell the difference between a real
  11666. ;; repeater and a time delta, e.g. "+2d".
  11667. (string-match org-repeat-re time)
  11668. (match-string 1 time))
  11669. (and (org-string-nw-p old-date)
  11670. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  11671. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  11672. old-date)
  11673. (match-string 1 old-date)))))
  11674. (pcase arg
  11675. (`(4)
  11676. (when (and old-date log)
  11677. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  11678. nil old-date log))
  11679. (org-remove-timestamp-with-keyword keyword)
  11680. (message (if deadline? "Item no longer has a deadline."
  11681. "Item is no longer scheduled.")))
  11682. (`(16)
  11683. (save-excursion
  11684. (org-back-to-heading t)
  11685. (let ((regexp (if deadline? org-deadline-time-regexp
  11686. org-scheduled-time-regexp)))
  11687. (if (not (re-search-forward regexp (line-end-position 2) t))
  11688. (user-error (if deadline? "No deadline information to update"
  11689. "No scheduled information to update"))
  11690. (let* ((rpl0 (match-string 1))
  11691. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  11692. (msg (if deadline? "Warn starting from" "Delay until")))
  11693. (replace-match
  11694. (concat keyword
  11695. " <" rpl
  11696. (format " -%dd"
  11697. (abs (- (time-to-days
  11698. (save-match-data
  11699. (org-read-date
  11700. nil t nil msg old-date-time)))
  11701. (time-to-days old-date-time))))
  11702. ">") t t))))))
  11703. (_
  11704. (org-add-planning-info type time 'closed)
  11705. (when (and old-date
  11706. log
  11707. (not (equal old-date org-last-inserted-timestamp)))
  11708. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  11709. org-last-inserted-timestamp
  11710. old-date
  11711. log))
  11712. (when repeater
  11713. (save-excursion
  11714. (org-back-to-heading t)
  11715. (when (re-search-forward
  11716. (concat keyword " " org-last-inserted-timestamp)
  11717. (line-end-position 2)
  11718. t)
  11719. (goto-char (1- (match-end 0)))
  11720. (insert " " repeater)
  11721. (setq org-last-inserted-timestamp
  11722. (concat (substring org-last-inserted-timestamp 0 -1)
  11723. " " repeater
  11724. (substring org-last-inserted-timestamp -1))))))
  11725. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  11726. org-last-inserted-timestamp)))))
  11727. (defun org-deadline (arg &optional time)
  11728. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  11729. With one universal prefix argument, remove any deadline from the item.
  11730. With two universal prefix arguments, prompt for a warning delay.
  11731. With argument TIME, set the deadline at the corresponding date. TIME
  11732. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11733. (interactive "P")
  11734. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11735. (org-map-entries
  11736. (lambda () (org--deadline-or-schedule arg 'deadline time))
  11737. nil
  11738. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11739. 'region-start-level
  11740. 'region)
  11741. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11742. (org--deadline-or-schedule arg 'deadline time)))
  11743. (defun org-schedule (arg &optional time)
  11744. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  11745. With one universal prefix argument, remove any scheduling date from the item.
  11746. With two universal prefix arguments, prompt for a delay cookie.
  11747. With argument TIME, scheduled at the corresponding date. TIME can
  11748. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11749. (interactive "P")
  11750. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11751. (org-map-entries
  11752. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  11753. nil
  11754. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11755. 'region-start-level
  11756. 'region)
  11757. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11758. (org--deadline-or-schedule arg 'scheduled time)))
  11759. (defun org-get-scheduled-time (pom &optional inherit)
  11760. "Get the scheduled time as a time tuple, of a format suitable
  11761. for calling org-schedule with, or if there is no scheduling,
  11762. returns nil."
  11763. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  11764. (when time
  11765. (apply 'encode-time (org-parse-time-string time)))))
  11766. (defun org-get-deadline-time (pom &optional inherit)
  11767. "Get the deadline as a time tuple, of a format suitable for
  11768. calling org-deadline with, or if there is no scheduling, returns
  11769. nil."
  11770. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  11771. (when time
  11772. (apply 'encode-time (org-parse-time-string time)))))
  11773. (defun org-remove-timestamp-with-keyword (keyword)
  11774. "Remove all time stamps with KEYWORD in the current entry."
  11775. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  11776. beg)
  11777. (save-excursion
  11778. (org-back-to-heading t)
  11779. (setq beg (point))
  11780. (outline-next-heading)
  11781. (while (re-search-backward re beg t)
  11782. (replace-match "")
  11783. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  11784. (equal (char-before) ?\ ))
  11785. (backward-delete-char 1)
  11786. (when (string-match "^[ \t]*$" (buffer-substring
  11787. (point-at-bol) (point-at-eol)))
  11788. (delete-region (point-at-bol)
  11789. (min (point-max) (1+ (point-at-eol))))))))))
  11790. (defvar org-time-was-given) ; dynamically scoped parameter
  11791. (defvar org-end-time-was-given) ; dynamically scoped parameter
  11792. (defun org-at-planning-p ()
  11793. "Non-nil when point is on a planning info line."
  11794. ;; This is as accurate and faster than `org-element-at-point' since
  11795. ;; planning info location is fixed in the section.
  11796. (org-with-wide-buffer
  11797. (beginning-of-line)
  11798. (and (looking-at-p org-planning-line-re)
  11799. (eq (point)
  11800. (ignore-errors
  11801. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  11802. (org-back-to-heading t)
  11803. (org-with-limited-levels (org-back-to-heading t)))
  11804. (line-beginning-position 2))))))
  11805. (defun org-add-planning-info (what &optional time &rest remove)
  11806. "Insert new timestamp with keyword in the planning line.
  11807. WHAT indicates what kind of time stamp to add. It is a symbol
  11808. among `closed', `deadline', `scheduled' and nil. TIME indicates
  11809. the time to use. If none is given, the user is prompted for
  11810. a date. REMOVE indicates what kind of entries to remove. An old
  11811. WHAT entry will also be removed."
  11812. (let (org-time-was-given org-end-time-was-given default-time default-input)
  11813. (catch 'exit
  11814. (when (and (memq what '(scheduled deadline))
  11815. (or (not time)
  11816. (and (stringp time)
  11817. (string-match "^[-+]+[0-9]" time))))
  11818. ;; Try to get a default date/time from existing timestamp
  11819. (save-excursion
  11820. (org-back-to-heading t)
  11821. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  11822. (when (re-search-forward (if (eq what 'scheduled)
  11823. org-scheduled-time-regexp
  11824. org-deadline-time-regexp)
  11825. end t)
  11826. (setq ts (match-string 1)
  11827. default-time (apply 'encode-time (org-parse-time-string ts))
  11828. default-input (and ts (org-get-compact-tod ts)))))))
  11829. (when what
  11830. (setq time
  11831. (if (stringp time)
  11832. ;; This is a string (relative or absolute), set
  11833. ;; proper date.
  11834. (apply #'encode-time
  11835. (org-read-date-analyze
  11836. time default-time (decode-time default-time)))
  11837. ;; If necessary, get the time from the user
  11838. (or time (org-read-date nil 'to-time nil nil
  11839. default-time default-input)))))
  11840. (org-with-wide-buffer
  11841. (org-back-to-heading t)
  11842. (forward-line)
  11843. (unless (bolp) (insert "\n"))
  11844. (cond ((looking-at-p org-planning-line-re)
  11845. ;; Move to current indentation.
  11846. (skip-chars-forward " \t")
  11847. ;; Check if we have to remove something.
  11848. (dolist (type (if what (cons what remove) remove))
  11849. (save-excursion
  11850. (when (re-search-forward
  11851. (cl-case type
  11852. (closed org-closed-time-regexp)
  11853. (deadline org-deadline-time-regexp)
  11854. (scheduled org-scheduled-time-regexp)
  11855. (otherwise
  11856. (error "Invalid planning type: %s" type)))
  11857. (line-end-position) t)
  11858. ;; Delete until next keyword or end of line.
  11859. (delete-region
  11860. (match-beginning 0)
  11861. (if (re-search-forward org-keyword-time-not-clock-regexp
  11862. (line-end-position)
  11863. t)
  11864. (match-beginning 0)
  11865. (line-end-position))))))
  11866. ;; If there is nothing more to add and no more keyword
  11867. ;; is left, remove the line completely.
  11868. (if (and (looking-at-p "[ \t]*$") (not what))
  11869. (delete-region (line-beginning-position)
  11870. (line-beginning-position 2))
  11871. ;; If we removed last keyword, do not leave trailing
  11872. ;; white space at the end of line.
  11873. (let ((p (point)))
  11874. (save-excursion
  11875. (end-of-line)
  11876. (unless (= (skip-chars-backward " \t" p) 0)
  11877. (delete-region (point) (line-end-position)))))))
  11878. ((not what) (throw 'exit nil)) ; Nothing to do.
  11879. (t (insert-before-markers "\n")
  11880. (backward-char 1)
  11881. (when org-adapt-indentation
  11882. (indent-to-column (1+ (org-outline-level))))))
  11883. (when what
  11884. ;; Insert planning keyword.
  11885. (insert (cl-case what
  11886. (closed org-closed-string)
  11887. (deadline org-deadline-string)
  11888. (scheduled org-scheduled-string)
  11889. (otherwise (error "Invalid planning type: %s" what)))
  11890. " ")
  11891. ;; Insert associated timestamp.
  11892. (let ((ts (org-insert-time-stamp
  11893. time
  11894. (or org-time-was-given
  11895. (and (eq what 'closed) org-log-done-with-time))
  11896. (eq what 'closed)
  11897. nil nil (list org-end-time-was-given))))
  11898. (unless (eolp) (insert " "))
  11899. ts))))))
  11900. (defvar org-log-note-marker (make-marker)
  11901. "Marker pointing at the entry where the note is to be inserted.")
  11902. (defvar org-log-note-purpose nil)
  11903. (defvar org-log-note-state nil)
  11904. (defvar org-log-note-previous-state nil)
  11905. (defvar org-log-note-extra nil)
  11906. (defvar org-log-note-window-configuration nil)
  11907. (defvar org-log-note-return-to (make-marker))
  11908. (defvar org-log-note-effective-time nil
  11909. "Remembered current time so that dynamically scoped
  11910. `org-extend-today-until' affects timestamps in state change log")
  11911. (defvar org-log-post-message nil
  11912. "Message to be displayed after a log note has been stored.
  11913. The auto-repeater uses this.")
  11914. (defun org-add-note ()
  11915. "Add a note to the current entry.
  11916. This is done in the same way as adding a state change note."
  11917. (interactive)
  11918. (org-add-log-setup 'note))
  11919. (defun org-log-beginning (&optional create)
  11920. "Return expected start of log notes in current entry.
  11921. When optional argument CREATE is non-nil, the function creates
  11922. a drawer to store notes, if necessary. Returned position ignores
  11923. narrowing."
  11924. (org-with-wide-buffer
  11925. (let ((drawer (org-log-into-drawer)))
  11926. (cond
  11927. (drawer
  11928. (org-end-of-meta-data)
  11929. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  11930. (end (if (org-at-heading-p) (point)
  11931. (save-excursion (outline-next-heading) (point))))
  11932. (case-fold-search t))
  11933. (catch 'exit
  11934. ;; Try to find existing drawer.
  11935. (while (re-search-forward regexp end t)
  11936. (let ((element (org-element-at-point)))
  11937. (when (eq (org-element-type element) 'drawer)
  11938. (let ((cend (org-element-property :contents-end element)))
  11939. (when (and (not org-log-states-order-reversed) cend)
  11940. (goto-char cend)))
  11941. (throw 'exit nil))))
  11942. ;; No drawer found. Create one, if permitted.
  11943. (when create
  11944. (unless (bolp) (insert "\n"))
  11945. (let ((beg (point)))
  11946. (insert ":" drawer ":\n:END:\n")
  11947. (org-indent-region beg (point)))
  11948. (end-of-line -1)))))
  11949. (t
  11950. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  11951. (skip-chars-forward " \t\n")
  11952. (beginning-of-line)
  11953. (unless org-log-states-order-reversed
  11954. (org-skip-over-state-notes)
  11955. (skip-chars-backward " \t\n")
  11956. (forward-line)))))
  11957. (if (bolp) (point) (line-beginning-position 2))))
  11958. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  11959. "Set up the post command hook to take a note.
  11960. If this is about to TODO state change, the new state is expected in STATE.
  11961. HOW is an indicator what kind of note should be created.
  11962. EXTRA is additional text that will be inserted into the notes buffer."
  11963. (move-marker org-log-note-marker (point))
  11964. (setq org-log-note-purpose purpose
  11965. org-log-note-state state
  11966. org-log-note-previous-state prev-state
  11967. org-log-note-how how
  11968. org-log-note-extra extra
  11969. org-log-note-effective-time (org-current-effective-time))
  11970. (add-hook 'post-command-hook 'org-add-log-note 'append))
  11971. (defun org-skip-over-state-notes ()
  11972. "Skip past the list of State notes in an entry."
  11973. (when (ignore-errors (goto-char (org-in-item-p)))
  11974. (let* ((struct (org-list-struct))
  11975. (prevs (org-list-prevs-alist struct))
  11976. (regexp
  11977. (concat "[ \t]*- +"
  11978. (replace-regexp-in-string
  11979. " +" " +"
  11980. (org-replace-escapes
  11981. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  11982. `(("%d" . ,org-ts-regexp-inactive)
  11983. ("%D" . ,org-ts-regexp)
  11984. ("%s" . "\"\\S-+\"")
  11985. ("%S" . "\"\\S-+\"")
  11986. ("%t" . ,org-ts-regexp-inactive)
  11987. ("%T" . ,org-ts-regexp)
  11988. ("%u" . ".*?")
  11989. ("%U" . ".*?")))))))
  11990. (while (looking-at-p regexp)
  11991. (goto-char (or (org-list-get-next-item (point) struct prevs)
  11992. (org-list-get-item-end (point) struct)))))))
  11993. (defun org-add-log-note (&optional _purpose)
  11994. "Pop up a window for taking a note, and add this note later."
  11995. (remove-hook 'post-command-hook 'org-add-log-note)
  11996. (setq org-log-note-window-configuration (current-window-configuration))
  11997. (delete-other-windows)
  11998. (move-marker org-log-note-return-to (point))
  11999. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  12000. (goto-char org-log-note-marker)
  12001. (org-switch-to-buffer-other-window "*Org Note*")
  12002. (erase-buffer)
  12003. (if (memq org-log-note-how '(time state))
  12004. (org-store-log-note)
  12005. (let ((org-inhibit-startup t)) (org-mode))
  12006. (insert (format "# Insert note for %s.
  12007. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12008. (cond
  12009. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  12010. ((eq org-log-note-purpose 'done) "closed todo item")
  12011. ((eq org-log-note-purpose 'state)
  12012. (format "state change from \"%s\" to \"%s\""
  12013. (or org-log-note-previous-state "")
  12014. (or org-log-note-state "")))
  12015. ((eq org-log-note-purpose 'reschedule)
  12016. "rescheduling")
  12017. ((eq org-log-note-purpose 'delschedule)
  12018. "no longer scheduled")
  12019. ((eq org-log-note-purpose 'redeadline)
  12020. "changing deadline")
  12021. ((eq org-log-note-purpose 'deldeadline)
  12022. "removing deadline")
  12023. ((eq org-log-note-purpose 'refile)
  12024. "refiling")
  12025. ((eq org-log-note-purpose 'note)
  12026. "this entry")
  12027. (t (error "This should not happen")))))
  12028. (when org-log-note-extra (insert org-log-note-extra))
  12029. (setq-local org-finish-function 'org-store-log-note)
  12030. (run-hooks 'org-log-buffer-setup-hook)))
  12031. (defvar org-note-abort nil) ; dynamically scoped
  12032. (defun org-store-log-note ()
  12033. "Finish taking a log note, and insert it to where it belongs."
  12034. (let ((txt (prog1 (buffer-string)
  12035. (kill-buffer)))
  12036. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12037. lines)
  12038. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12039. (setq txt (replace-match "" t t txt)))
  12040. (when (string-match "\\s-+\\'" txt)
  12041. (setq txt (replace-match "" t t txt)))
  12042. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  12043. (when (org-string-nw-p note)
  12044. (setq note
  12045. (org-replace-escapes
  12046. note
  12047. (list (cons "%u" (user-login-name))
  12048. (cons "%U" user-full-name)
  12049. (cons "%t" (format-time-string
  12050. (org-time-stamp-format 'long 'inactive)
  12051. org-log-note-effective-time))
  12052. (cons "%T" (format-time-string
  12053. (org-time-stamp-format 'long nil)
  12054. org-log-note-effective-time))
  12055. (cons "%d" (format-time-string
  12056. (org-time-stamp-format nil 'inactive)
  12057. org-log-note-effective-time))
  12058. (cons "%D" (format-time-string
  12059. (org-time-stamp-format nil nil)
  12060. org-log-note-effective-time))
  12061. (cons "%s" (cond
  12062. ((not org-log-note-state) "")
  12063. ((string-match-p org-ts-regexp
  12064. org-log-note-state)
  12065. (format "\"[%s]\""
  12066. (substring org-log-note-state 1 -1)))
  12067. (t (format "\"%s\"" org-log-note-state))))
  12068. (cons "%S"
  12069. (cond
  12070. ((not org-log-note-previous-state) "")
  12071. ((string-match-p org-ts-regexp
  12072. org-log-note-previous-state)
  12073. (format "\"[%s]\""
  12074. (substring
  12075. org-log-note-previous-state 1 -1)))
  12076. (t (format "\"%s\""
  12077. org-log-note-previous-state)))))))
  12078. (when lines (setq note (concat note " \\\\")))
  12079. (push note lines))
  12080. (when (and lines (not org-note-abort))
  12081. (with-current-buffer (marker-buffer org-log-note-marker)
  12082. (org-with-wide-buffer
  12083. ;; Find location for the new note.
  12084. (goto-char org-log-note-marker)
  12085. (set-marker org-log-note-marker nil)
  12086. ;; Note associated to a clock is to be located right after
  12087. ;; the clock. Do not move point.
  12088. (unless (eq org-log-note-purpose 'clock-out)
  12089. (goto-char (org-log-beginning t)))
  12090. ;; Make sure point is at the beginning of an empty line.
  12091. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12092. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12093. ;; In an existing list, add a new item at the top level.
  12094. ;; Otherwise, indent line like a regular one.
  12095. (let ((itemp (org-in-item-p)))
  12096. (if itemp
  12097. (indent-line-to
  12098. (let ((struct (save-excursion
  12099. (goto-char itemp) (org-list-struct))))
  12100. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12101. (org-indent-line)))
  12102. (insert (org-list-bullet-string "-") (pop lines))
  12103. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12104. (dolist (line lines)
  12105. (insert "\n")
  12106. (indent-line-to ind)
  12107. (insert line)))
  12108. (message "Note stored")
  12109. (org-back-to-heading t)
  12110. (org-cycle-hide-drawers 'children))
  12111. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12112. ;; from within `org-add-log-note' because `buffer-undo-list'
  12113. ;; is then modified outside of `org-with-remote-undo'.
  12114. (when (eq this-command 'org-agenda-todo)
  12115. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12116. ;; Don't add undo information when called from `org-agenda-todo'.
  12117. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12118. (set-window-configuration org-log-note-window-configuration)
  12119. (with-current-buffer (marker-buffer org-log-note-return-to)
  12120. (goto-char org-log-note-return-to))
  12121. (move-marker org-log-note-return-to nil)
  12122. (when org-log-post-message (message "%s" org-log-post-message))))
  12123. (defun org-remove-empty-drawer-at (pos)
  12124. "Remove an empty drawer at position POS.
  12125. POS may also be a marker."
  12126. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12127. (org-with-wide-buffer
  12128. (goto-char pos)
  12129. (let ((drawer (org-element-at-point)))
  12130. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12131. (not (org-element-property :contents-begin drawer)))
  12132. (delete-region (org-element-property :begin drawer)
  12133. (progn (goto-char (org-element-property :end drawer))
  12134. (skip-chars-backward " \r\t\n")
  12135. (forward-line)
  12136. (point))))))))
  12137. (defvar org-ts-type nil)
  12138. (defun org-sparse-tree (&optional arg type)
  12139. "Create a sparse tree, prompt for the details.
  12140. This command can create sparse trees. You first need to select the type
  12141. of match used to create the tree:
  12142. t Show all TODO entries.
  12143. T Show entries with a specific TODO keyword.
  12144. m Show entries selected by a tags/property match.
  12145. p Enter a property name and its value (both with completion on existing
  12146. names/values) and show entries with that property.
  12147. r Show entries matching a regular expression (`/' can be used as well).
  12148. b Show deadlines and scheduled items before a date.
  12149. a Show deadlines and scheduled items after a date.
  12150. d Show deadlines due within `org-deadline-warning-days'.
  12151. D Show deadlines and scheduled items between a date range."
  12152. (interactive "P")
  12153. (setq type (or type org-sparse-tree-default-date-type))
  12154. (setq org-ts-type type)
  12155. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12156. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12157. \[c]ycle through date types: %s"
  12158. (cl-case type
  12159. (all "all timestamps")
  12160. (scheduled "only scheduled")
  12161. (deadline "only deadline")
  12162. (active "only active timestamps")
  12163. (inactive "only inactive timestamps")
  12164. (closed "with a closed time-stamp")
  12165. (otherwise "scheduled/deadline")))
  12166. (let ((answer (read-char-exclusive)))
  12167. (cl-case answer
  12168. (?c
  12169. (org-sparse-tree
  12170. arg
  12171. (cadr
  12172. (memq type '(nil all scheduled deadline active inactive closed)))))
  12173. (?d (call-interactively 'org-check-deadlines))
  12174. (?b (call-interactively 'org-check-before-date))
  12175. (?a (call-interactively 'org-check-after-date))
  12176. (?D (call-interactively 'org-check-dates-range))
  12177. (?t (call-interactively 'org-show-todo-tree))
  12178. (?T (org-show-todo-tree '(4)))
  12179. (?m (call-interactively 'org-match-sparse-tree))
  12180. ((?p ?P)
  12181. (let* ((kwd (completing-read
  12182. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12183. (value (completing-read
  12184. "Value: " (mapcar #'list (org-property-values kwd)))))
  12185. (unless (string-match "\\`{.*}\\'" value)
  12186. (setq value (concat "\"" value "\"")))
  12187. (org-match-sparse-tree arg (concat kwd "=" value))))
  12188. ((?r ?R ?/) (call-interactively 'org-occur))
  12189. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12190. (defvar-local org-occur-highlights nil
  12191. "List of overlays used for occur matches.")
  12192. (defvar-local org-occur-parameters nil
  12193. "Parameters of the active org-occur calls.
  12194. This is a list, each call to org-occur pushes as cons cell,
  12195. containing the regular expression and the callback, onto the list.
  12196. The list can contain several entries if `org-occur' has been called
  12197. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12198. will only contain one set of parameters. When the highlights are
  12199. removed (for example with `C-c C-c', or with the next edit (depending
  12200. on `org-remove-highlights-with-change'), this variable is emptied
  12201. as well.")
  12202. (defun org-occur (regexp &optional keep-previous callback)
  12203. "Make a compact tree which shows all matches of REGEXP.
  12204. The tree will show the lines where the regexp matches, and any other context
  12205. defined in `org-show-context-detail', which see.
  12206. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12207. done by a previous call to `org-occur' will be kept, to allow stacking of
  12208. calls to this command.
  12209. Optional argument CALLBACK can be a function of no argument. In this case,
  12210. it is called with point at the end of the match, match data being set
  12211. accordingly. Current match is shown only if the return value is non-nil.
  12212. The function must neither move point nor alter narrowing."
  12213. (interactive "sRegexp: \nP")
  12214. (when (equal regexp "")
  12215. (user-error "Regexp cannot be empty"))
  12216. (unless keep-previous
  12217. (org-remove-occur-highlights nil nil t))
  12218. (push (cons regexp callback) org-occur-parameters)
  12219. (let ((cnt 0))
  12220. (save-excursion
  12221. (goto-char (point-min))
  12222. (when (or (not keep-previous) ; do not want to keep
  12223. (not org-occur-highlights)) ; no previous matches
  12224. ;; hide everything
  12225. (org-overview))
  12226. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12227. (isearch-no-upper-case-p regexp t)
  12228. org-occur-case-fold-search)))
  12229. (while (re-search-forward regexp nil t)
  12230. (when (or (not callback)
  12231. (save-match-data (funcall callback)))
  12232. (setq cnt (1+ cnt))
  12233. (when org-highlight-sparse-tree-matches
  12234. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12235. (org-show-context 'occur-tree)))))
  12236. (when org-remove-highlights-with-change
  12237. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12238. nil 'local))
  12239. (unless org-sparse-tree-open-archived-trees
  12240. (org-hide-archived-subtrees (point-min) (point-max)))
  12241. (run-hooks 'org-occur-hook)
  12242. (when (called-interactively-p 'interactive)
  12243. (message "%d match(es) for regexp %s" cnt regexp))
  12244. cnt))
  12245. (defun org-occur-next-match (&optional n _reset)
  12246. "Function for `next-error-function' to find sparse tree matches.
  12247. N is the number of matches to move, when negative move backwards.
  12248. This function always goes back to the starting point when no
  12249. match is found."
  12250. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12251. (search-func (if (< n 0)
  12252. 'previous-single-char-property-change
  12253. 'next-single-char-property-change))
  12254. (n (abs n))
  12255. (pos (point))
  12256. p1)
  12257. (catch 'exit
  12258. (while (setq p1 (funcall search-func (point) 'org-type))
  12259. (when (equal p1 limit)
  12260. (goto-char pos)
  12261. (user-error "No more matches"))
  12262. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12263. (setq n (1- n))
  12264. (when (= n 0)
  12265. (goto-char p1)
  12266. (throw 'exit (point))))
  12267. (goto-char p1))
  12268. (goto-char p1)
  12269. (user-error "No more matches"))))
  12270. (defun org-show-context (&optional key)
  12271. "Make sure point and context are visible.
  12272. Optional argument KEY, when non-nil, is a symbol. See
  12273. `org-show-context-detail' for allowed values and how much is to
  12274. be shown."
  12275. (org-show-set-visibility
  12276. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12277. ((cdr (assq key org-show-context-detail)))
  12278. (t (cdr (assq 'default org-show-context-detail))))))
  12279. (defun org-show-set-visibility (detail)
  12280. "Set visibility around point according to DETAIL.
  12281. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12282. `tree', `canonical' or t. See `org-show-context-detail' for more
  12283. information."
  12284. ;; Show current heading and possibly its entry, following headline
  12285. ;; or all children.
  12286. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12287. (org-flag-heading nil)
  12288. (org-show-entry)
  12289. ;; If point is hidden within a drawer or a block, make sure to
  12290. ;; expose it.
  12291. (dolist (o (overlays-at (point)))
  12292. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  12293. (delete-overlay o)))
  12294. (unless (org-before-first-heading-p)
  12295. (org-with-limited-levels
  12296. (cl-case detail
  12297. ((tree canonical t) (org-show-children))
  12298. ((nil minimal ancestors))
  12299. (t (save-excursion
  12300. (outline-next-heading)
  12301. (org-flag-heading nil)))))))
  12302. ;; Show all siblings.
  12303. (when (eq detail 'lineage) (org-show-siblings))
  12304. ;; Show ancestors, possibly with their children.
  12305. (when (memq detail '(ancestors lineage tree canonical t))
  12306. (save-excursion
  12307. (while (org-up-heading-safe)
  12308. (org-flag-heading nil)
  12309. (when (memq detail '(canonical t)) (org-show-entry))
  12310. (when (memq detail '(tree canonical t)) (org-show-children))))))
  12311. (defvar org-reveal-start-hook nil
  12312. "Hook run before revealing a location.")
  12313. (defun org-reveal (&optional siblings)
  12314. "Show current entry, hierarchy above it, and the following headline.
  12315. This can be used to show a consistent set of context around
  12316. locations exposed with `org-show-context'.
  12317. With optional argument SIBLINGS, on each level of the hierarchy all
  12318. siblings are shown. This repairs the tree structure to what it would
  12319. look like when opened with hierarchical calls to `org-cycle'.
  12320. With a \\[universal-argument] \\[universal-argument] prefix, \
  12321. go to the parent and show the entire tree."
  12322. (interactive "P")
  12323. (run-hooks 'org-reveal-start-hook)
  12324. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12325. ((equal siblings '(16))
  12326. (save-excursion
  12327. (when (org-up-heading-safe)
  12328. (org-show-subtree)
  12329. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12330. (t (org-show-set-visibility 'lineage))))
  12331. (defun org-highlight-new-match (beg end)
  12332. "Highlight from BEG to END and mark the highlight is an occur headline."
  12333. (let ((ov (make-overlay beg end)))
  12334. (overlay-put ov 'face 'secondary-selection)
  12335. (overlay-put ov 'org-type 'org-occur)
  12336. (push ov org-occur-highlights)))
  12337. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12338. "Remove the occur highlights from the buffer.
  12339. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12340. from the `before-change-functions' in the current buffer."
  12341. (interactive)
  12342. (unless org-inhibit-highlight-removal
  12343. (mapc #'delete-overlay org-occur-highlights)
  12344. (setq org-occur-highlights nil)
  12345. (setq org-occur-parameters nil)
  12346. (unless noremove
  12347. (remove-hook 'before-change-functions
  12348. 'org-remove-occur-highlights 'local))))
  12349. ;;;; Priorities
  12350. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12351. "Regular expression matching the priority indicator.")
  12352. (defvar org-remove-priority-next-time nil)
  12353. (defun org-priority-up ()
  12354. "Increase the priority of the current item."
  12355. (interactive)
  12356. (org-priority 'up))
  12357. (defun org-priority-down ()
  12358. "Decrease the priority of the current item."
  12359. (interactive)
  12360. (org-priority 'down))
  12361. (defun org-priority (&optional action _show)
  12362. "Change the priority of an item.
  12363. ACTION can be `set', `up', `down', or a character."
  12364. (interactive "P")
  12365. (if (equal action '(4))
  12366. (org-show-priority)
  12367. (unless org-enable-priority-commands
  12368. (user-error "Priority commands are disabled"))
  12369. (setq action (or action 'set))
  12370. (let (current new news have remove)
  12371. (save-excursion
  12372. (org-back-to-heading t)
  12373. (when (looking-at org-priority-regexp)
  12374. (setq current (string-to-char (match-string 2))
  12375. have t))
  12376. (cond
  12377. ((eq action 'remove)
  12378. (setq remove t new ?\ ))
  12379. ((or (eq action 'set)
  12380. (integerp action))
  12381. (if (not (eq action 'set))
  12382. (setq new action)
  12383. (message "Priority %c-%c, SPC to remove: "
  12384. org-highest-priority org-lowest-priority)
  12385. (save-match-data
  12386. (setq new (read-char-exclusive))))
  12387. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12388. (= (upcase org-lowest-priority) org-lowest-priority))
  12389. (setq new (upcase new)))
  12390. (cond ((equal new ?\ ) (setq remove t))
  12391. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12392. (user-error "Priority must be between `%c' and `%c'"
  12393. org-highest-priority org-lowest-priority))))
  12394. ((eq action 'up)
  12395. (setq new (if have
  12396. (1- current) ; normal cycling
  12397. ;; last priority was empty
  12398. (if (eq last-command this-command)
  12399. org-lowest-priority ; wrap around empty to lowest
  12400. ;; default
  12401. (if org-priority-start-cycle-with-default
  12402. org-default-priority
  12403. (1- org-default-priority))))))
  12404. ((eq action 'down)
  12405. (setq new (if have
  12406. (1+ current) ; normal cycling
  12407. ;; last priority was empty
  12408. (if (eq last-command this-command)
  12409. org-highest-priority ; wrap around empty to highest
  12410. ;; default
  12411. (if org-priority-start-cycle-with-default
  12412. org-default-priority
  12413. (1+ org-default-priority))))))
  12414. (t (user-error "Invalid action")))
  12415. (when (or (< (upcase new) org-highest-priority)
  12416. (> (upcase new) org-lowest-priority))
  12417. (if (and (memq action '(up down))
  12418. (not have) (not (eq last-command this-command)))
  12419. ;; `new' is from default priority
  12420. (error
  12421. "The default can not be set, see `org-default-priority' why")
  12422. ;; normal cycling: `new' is beyond highest/lowest priority
  12423. ;; and is wrapped around to the empty priority
  12424. (setq remove t)))
  12425. (setq news (format "%c" new))
  12426. (if have
  12427. (if remove
  12428. (replace-match "" t t nil 1)
  12429. (replace-match news t t nil 2))
  12430. (if remove
  12431. (user-error "No priority cookie found in line")
  12432. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12433. (if (match-end 2)
  12434. (progn
  12435. (goto-char (match-end 2))
  12436. (insert " [#" news "]"))
  12437. (goto-char (match-beginning 3))
  12438. (insert "[#" news "] "))))
  12439. (org-set-tags nil 'align))
  12440. (if remove
  12441. (message "Priority removed")
  12442. (message "Priority of current item set to %s" news)))))
  12443. (defun org-show-priority ()
  12444. "Show the priority of the current item.
  12445. This priority is composed of the main priority given with the [#A] cookies,
  12446. and by additional input from the age of a schedules or deadline entry."
  12447. (interactive)
  12448. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12449. (org-get-at-bol 'priority)
  12450. (save-excursion
  12451. (save-match-data
  12452. (beginning-of-line)
  12453. (and (looking-at org-heading-regexp)
  12454. (org-get-priority (match-string 0))))))))
  12455. (message "Priority is %d" (if pri pri -1000))))
  12456. (defun org-get-priority (s)
  12457. "Find priority cookie and return priority."
  12458. (save-match-data
  12459. (if (functionp org-get-priority-function)
  12460. (funcall org-get-priority-function)
  12461. (if (not (string-match org-priority-regexp s))
  12462. (* 1000 (- org-lowest-priority org-default-priority))
  12463. (* 1000 (- org-lowest-priority
  12464. (string-to-char (match-string 2 s))))))))
  12465. ;;;; Tags
  12466. (defvar org-agenda-archives-mode)
  12467. (defvar org-map-continue-from nil
  12468. "Position from where mapping should continue.
  12469. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12470. (defvar org-scanner-tags nil
  12471. "The current tag list while the tags scanner is running.")
  12472. (defvar org-trust-scanner-tags nil
  12473. "Should `org-get-tags-at' use the tags for the scanner.
  12474. This is for internal dynamical scoping only.
  12475. When this is non-nil, the function `org-get-tags-at' will return the value
  12476. of `org-scanner-tags' instead of building the list by itself. This
  12477. can lead to large speed-ups when the tags scanner is used in a file with
  12478. many entries, and when the list of tags is retrieved, for example to
  12479. obtain a list of properties. Building the tags list for each entry in such
  12480. a file becomes an N^2 operation - but with this variable set, it scales
  12481. as N.")
  12482. (defvar org--matcher-tags-todo-only nil)
  12483. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12484. "Scan headline tags with inheritance and produce output ACTION.
  12485. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12486. or `agenda' to produce an entry list for an agenda view. It can also be
  12487. a Lisp form or a function that should be called at each matched headline, in
  12488. this case the return value is a list of all return values from these calls.
  12489. MATCHER is a function accepting three arguments, returning
  12490. a non-nil value whenever a given set of tags qualifies a headline
  12491. for inclusion. See `org-make-tags-matcher' for more information.
  12492. As a special case, it can also be set to t (respectively nil) in
  12493. order to match all (respectively none) headline.
  12494. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  12495. included in the output.
  12496. START-LEVEL can be a string with asterisks, reducing the scope to
  12497. headlines matching this string."
  12498. (require 'org-agenda)
  12499. (let* ((re (concat "^"
  12500. (if start-level
  12501. ;; Get the correct level to match
  12502. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12503. org-outline-regexp)
  12504. " *\\(\\<\\("
  12505. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  12506. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  12507. (props (list 'face 'default
  12508. 'done-face 'org-agenda-done
  12509. 'undone-face 'default
  12510. 'mouse-face 'highlight
  12511. 'org-not-done-regexp org-not-done-regexp
  12512. 'org-todo-regexp org-todo-regexp
  12513. 'org-complex-heading-regexp org-complex-heading-regexp
  12514. 'help-echo
  12515. (format "mouse-2 or RET jump to org file %s"
  12516. (abbreviate-file-name
  12517. (or (buffer-file-name (buffer-base-buffer))
  12518. (buffer-name (buffer-base-buffer)))))))
  12519. (org-map-continue-from nil)
  12520. lspos tags tags-list
  12521. (tags-alist (list (cons 0 org-file-tags)))
  12522. (llast 0) rtn rtn1 level category i txt
  12523. todo marker entry priority
  12524. ts-date ts-date-type ts-date-pair)
  12525. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12526. (setq action (list 'lambda nil action)))
  12527. (save-excursion
  12528. (goto-char (point-min))
  12529. (when (eq action 'sparse-tree)
  12530. (org-overview)
  12531. (org-remove-occur-highlights))
  12532. (while (let (case-fold-search)
  12533. (re-search-forward re nil t))
  12534. (setq org-map-continue-from nil)
  12535. (catch :skip
  12536. (setq todo
  12537. ;; TODO: is the 1-2 difference a bug?
  12538. (when (match-end 1) (match-string-no-properties 2))
  12539. tags (when (match-end 4) (match-string-no-properties 4)))
  12540. (goto-char (setq lspos (match-beginning 0)))
  12541. (setq level (org-reduced-level (org-outline-level))
  12542. category (org-get-category))
  12543. (when (eq action 'agenda)
  12544. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12545. ts-date (car ts-date-pair)
  12546. ts-date-type (cdr ts-date-pair)))
  12547. (setq i llast llast level)
  12548. ;; remove tag lists from same and sublevels
  12549. (while (>= i level)
  12550. (when (setq entry (assoc i tags-alist))
  12551. (setq tags-alist (delete entry tags-alist)))
  12552. (setq i (1- i)))
  12553. ;; add the next tags
  12554. (when tags
  12555. (setq tags (org-split-string tags ":")
  12556. tags-alist
  12557. (cons (cons level tags) tags-alist)))
  12558. ;; compile tags for current headline
  12559. (setq tags-list
  12560. (if org-use-tag-inheritance
  12561. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12562. tags)
  12563. org-scanner-tags tags-list)
  12564. (when org-use-tag-inheritance
  12565. (setcdr (car tags-alist)
  12566. (mapcar (lambda (x)
  12567. (setq x (copy-sequence x))
  12568. (org-add-prop-inherited x))
  12569. (cdar tags-alist))))
  12570. (when (and tags org-use-tag-inheritance
  12571. (or (not (eq t org-use-tag-inheritance))
  12572. org-tags-exclude-from-inheritance))
  12573. ;; Selective inheritance, remove uninherited ones.
  12574. (setcdr (car tags-alist)
  12575. (org-remove-uninherited-tags (cdar tags-alist))))
  12576. (when (and
  12577. ;; eval matcher only when the todo condition is OK
  12578. (and (or (not todo-only) (member todo org-todo-keywords-1))
  12579. (if (functionp matcher)
  12580. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12581. (funcall matcher todo tags-list level))
  12582. matcher))
  12583. ;; Call the skipper, but return t if it does not
  12584. ;; skip, so that the `and' form continues evaluating.
  12585. (progn
  12586. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12587. t)
  12588. ;; Check if timestamps are deselecting this entry
  12589. (or (not todo-only)
  12590. (and (member todo org-todo-keywords-1)
  12591. (or (not org-agenda-tags-todo-honor-ignore-options)
  12592. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12593. ;; select this headline
  12594. (cond
  12595. ((eq action 'sparse-tree)
  12596. (and org-highlight-sparse-tree-matches
  12597. (org-get-heading) (match-end 0)
  12598. (org-highlight-new-match
  12599. (match-beginning 1) (match-end 1)))
  12600. (org-show-context 'tags-tree))
  12601. ((eq action 'agenda)
  12602. (setq txt (org-agenda-format-item
  12603. ""
  12604. (concat
  12605. (if (eq org-tags-match-list-sublevels 'indented)
  12606. (make-string (1- level) ?.) "")
  12607. (org-get-heading))
  12608. (make-string level ?\s)
  12609. category
  12610. tags-list)
  12611. priority (org-get-priority txt))
  12612. (goto-char lspos)
  12613. (setq marker (org-agenda-new-marker))
  12614. (org-add-props txt props
  12615. 'org-marker marker 'org-hd-marker marker 'org-category category
  12616. 'todo-state todo
  12617. 'ts-date ts-date
  12618. 'priority priority
  12619. 'type (concat "tagsmatch" ts-date-type))
  12620. (push txt rtn))
  12621. ((functionp action)
  12622. (setq org-map-continue-from nil)
  12623. (save-excursion
  12624. (setq rtn1 (funcall action))
  12625. (push rtn1 rtn)))
  12626. (t (user-error "Invalid action")))
  12627. ;; if we are to skip sublevels, jump to end of subtree
  12628. (unless org-tags-match-list-sublevels
  12629. (org-end-of-subtree t)
  12630. (backward-char 1))))
  12631. ;; Get the correct position from where to continue
  12632. (if org-map-continue-from
  12633. (goto-char org-map-continue-from)
  12634. (and (= (point) lspos) (end-of-line 1)))))
  12635. (when (and (eq action 'sparse-tree)
  12636. (not org-sparse-tree-open-archived-trees))
  12637. (org-hide-archived-subtrees (point-min) (point-max)))
  12638. (nreverse rtn)))
  12639. (defun org-remove-uninherited-tags (tags)
  12640. "Remove all tags that are not inherited from the list TAGS."
  12641. (cond
  12642. ((eq org-use-tag-inheritance t)
  12643. (if org-tags-exclude-from-inheritance
  12644. (org-delete-all org-tags-exclude-from-inheritance tags)
  12645. tags))
  12646. ((not org-use-tag-inheritance) nil)
  12647. ((stringp org-use-tag-inheritance)
  12648. (delq nil (mapcar
  12649. (lambda (x)
  12650. (if (and (string-match org-use-tag-inheritance x)
  12651. (not (member x org-tags-exclude-from-inheritance)))
  12652. x nil))
  12653. tags)))
  12654. ((listp org-use-tag-inheritance)
  12655. (delq nil (mapcar
  12656. (lambda (x)
  12657. (if (member x org-use-tag-inheritance) x nil))
  12658. tags)))))
  12659. (defun org-match-sparse-tree (&optional todo-only match)
  12660. "Create a sparse tree according to tags string MATCH.
  12661. MATCH is a string with match syntax. It can contain a selection
  12662. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  12663. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  12664. those. See the manual for details.
  12665. If optional argument TODO-ONLY is non-nil, only select lines that
  12666. are also TODO tasks."
  12667. (interactive "P")
  12668. (org-agenda-prepare-buffers (list (current-buffer)))
  12669. (let ((org--matcher-tags-todo-only todo-only))
  12670. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  12671. org--matcher-tags-todo-only)))
  12672. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  12673. (defvar org-cached-props nil)
  12674. (defun org-cached-entry-get (pom property)
  12675. (if (or (eq t org-use-property-inheritance)
  12676. (and (stringp org-use-property-inheritance)
  12677. (let ((case-fold-search t))
  12678. (string-match-p org-use-property-inheritance property)))
  12679. (and (listp org-use-property-inheritance)
  12680. (member-ignore-case property org-use-property-inheritance)))
  12681. ;; Caching is not possible, check it directly.
  12682. (org-entry-get pom property 'inherit)
  12683. ;; Get all properties, so we can do complicated checks easily.
  12684. (cdr (assoc-string property
  12685. (or org-cached-props
  12686. (setq org-cached-props (org-entry-properties pom)))
  12687. t))))
  12688. (defun org-global-tags-completion-table (&optional files)
  12689. "Return the list of all tags in all agenda buffer/files.
  12690. Optional FILES argument is a list of files which can be used
  12691. instead of the agenda files."
  12692. (save-excursion
  12693. (org-uniquify
  12694. (delq nil
  12695. (apply #'append
  12696. (mapcar
  12697. (lambda (file)
  12698. (set-buffer (find-file-noselect file))
  12699. (mapcar (lambda (x)
  12700. (and (stringp (car-safe x))
  12701. (list (car-safe x))))
  12702. (or org-current-tag-alist (org-get-buffer-tags))))
  12703. (if (car-safe files) files
  12704. (org-agenda-files))))))))
  12705. (defun org-make-tags-matcher (match)
  12706. "Create the TAGS/TODO matcher form for the selection string MATCH.
  12707. Returns a cons of the selection string MATCH and a function
  12708. implementing the matcher.
  12709. The matcher is to be called at an Org entry, with point on the
  12710. headline, and returns non-nil if the entry matches the selection
  12711. string MATCH. It must be called with three arguments: the TODO
  12712. keyword at the entry (or nil if none), the list of all tags at
  12713. the entry including inherited ones and the reduced level of the
  12714. headline. Additionally, the category of the entry, if any, must
  12715. be specified as the text property `org-category' on the headline.
  12716. This function sets the variable `org--matcher-tags-todo-only' to
  12717. a non-nil value if the matcher restricts matching to TODO
  12718. entries, otherwise it is not touched.
  12719. See also `org-scan-tags'."
  12720. (unless match
  12721. ;; Get a new match request, with completion against the global
  12722. ;; tags table and the local tags in current buffer.
  12723. (let ((org-last-tags-completion-table
  12724. (org-uniquify
  12725. (delq nil (append (org-get-buffer-tags)
  12726. (org-global-tags-completion-table))))))
  12727. (setq match
  12728. (completing-read
  12729. "Match: "
  12730. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  12731. (let ((match0 match)
  12732. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  12733. (start 0)
  12734. tagsmatch todomatch tagsmatcher todomatcher)
  12735. ;; Expand group tags.
  12736. (setq match (org-tags-expand match))
  12737. ;; Check if there is a TODO part of this match, which would be the
  12738. ;; part after a "/". To make sure that this slash is not part of
  12739. ;; a property value to be matched against, we also check that
  12740. ;; there is no / after that slash. First, find the last slash.
  12741. (let ((s 0))
  12742. (while (string-match "/+" match s)
  12743. (setq start (match-beginning 0))
  12744. (setq s (match-end 0))))
  12745. (if (and (string-match "/+" match start)
  12746. (not (string-match-p "\"" match start)))
  12747. ;; Match contains also a TODO-matching request.
  12748. (progn
  12749. (setq tagsmatch (substring match 0 (match-beginning 0)))
  12750. (setq todomatch (substring match (match-end 0)))
  12751. (when (string-prefix-p "!" todomatch)
  12752. (setq org--matcher-tags-todo-only t)
  12753. (setq todomatch (substring todomatch 1)))
  12754. (when (string-match "\\`\\s-*\\'" todomatch)
  12755. (setq todomatch nil)))
  12756. ;; Only matching tags.
  12757. (setq tagsmatch match)
  12758. (setq todomatch nil))
  12759. ;; Make the tags matcher.
  12760. (when (org-string-nw-p tagsmatch)
  12761. (let ((orlist nil)
  12762. (orterms (org-split-string tagsmatch "|"))
  12763. term)
  12764. (while (setq term (pop orterms))
  12765. (while (and (equal (substring term -1) "\\") orterms)
  12766. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  12767. (while (string-match re term)
  12768. (let* ((rest (substring term (match-end 0)))
  12769. (minus (and (match-end 1)
  12770. (equal (match-string 1 term) "-")))
  12771. (tag (save-match-data
  12772. (replace-regexp-in-string
  12773. "\\\\-" "-" (match-string 2 term))))
  12774. (regexp (eq (string-to-char tag) ?{))
  12775. (levelp (match-end 4))
  12776. (propp (match-end 5))
  12777. (mm
  12778. (cond
  12779. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  12780. (levelp
  12781. `(,(org-op-to-function (match-string 3 term))
  12782. level
  12783. ,(string-to-number (match-string 4 term))))
  12784. (propp
  12785. (let* ((gv (pcase (upcase (match-string 5 term))
  12786. ("CATEGORY"
  12787. '(get-text-property (point) 'org-category))
  12788. ("TODO" 'todo)
  12789. (p `(org-cached-entry-get nil ,p))))
  12790. (pv (match-string 7 term))
  12791. (regexp (eq (string-to-char pv) ?{))
  12792. (strp (eq (string-to-char pv) ?\"))
  12793. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  12794. (po (org-op-to-function (match-string 6 term)
  12795. (if timep 'time strp))))
  12796. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  12797. (when timep (setq pv (org-matcher-time pv)))
  12798. (cond ((and regexp (eq po 'org<>))
  12799. `(not (string-match ,pv (or ,gv ""))))
  12800. (regexp `(string-match ,pv (or ,gv "")))
  12801. (strp `(,po (or ,gv "") ,pv))
  12802. (t
  12803. `(,po
  12804. (string-to-number (or ,gv ""))
  12805. ,(string-to-number pv))))))
  12806. (t `(member ,tag tags-list)))))
  12807. (push (if minus `(not ,mm) mm) tagsmatcher)
  12808. (setq term rest)))
  12809. (push `(and ,@tagsmatcher) orlist)
  12810. (setq tagsmatcher nil))
  12811. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  12812. ;; Make the TODO matcher.
  12813. (when (org-string-nw-p todomatch)
  12814. (let ((orlist nil))
  12815. (dolist (term (org-split-string todomatch "|"))
  12816. (while (string-match re term)
  12817. (let* ((minus (and (match-end 1)
  12818. (equal (match-string 1 term) "-")))
  12819. (kwd (match-string 2 term))
  12820. (regexp (eq (string-to-char kwd) ?{))
  12821. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  12822. `(equal todo ,kwd))))
  12823. (push (if minus `(not ,mm) mm) todomatcher))
  12824. (setq term (substring term (match-end 0))))
  12825. (push (if (> (length todomatcher) 1)
  12826. (cons 'and todomatcher)
  12827. (car todomatcher))
  12828. orlist)
  12829. (setq todomatcher nil))
  12830. (setq todomatcher (cons 'or orlist))))
  12831. ;; Return the string and function of the matcher. If no
  12832. ;; tags-specific or todo-specific matcher exists, match
  12833. ;; everything.
  12834. (let ((matcher (if (and tagsmatcher todomatcher)
  12835. `(and ,tagsmatcher ,todomatcher)
  12836. (or tagsmatcher todomatcher t))))
  12837. (when org--matcher-tags-todo-only
  12838. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  12839. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  12840. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  12841. "Expand group tags in MATCH.
  12842. This replaces every group tag in MATCH with a regexp tag search.
  12843. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  12844. will be replaced like this:
  12845. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12846. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12847. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12848. Replacing by a regexp preserves the structure of the match.
  12849. E.g., this expansion
  12850. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  12851. will match anything tagged with \"Lab\" and \"Home\", or tagged
  12852. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  12853. A group tag in MATCH can contain regular expressions of its own.
  12854. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  12855. will be replaced like this:
  12856. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  12857. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  12858. assumed to be a single group tag, and the function will return
  12859. the list of tags in this group.
  12860. When DOWNCASE is non-nil, expand downcased TAGS."
  12861. (if org-group-tags
  12862. (let* ((case-fold-search t)
  12863. (stable org-mode-syntax-table)
  12864. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  12865. (taggroups (if downcased
  12866. (mapcar (lambda (tg) (mapcar #'downcase tg))
  12867. taggroups)
  12868. taggroups))
  12869. (taggroups-keys (mapcar #'car taggroups))
  12870. (return-match (if downcased (downcase match) match))
  12871. (count 0)
  12872. (work-already-expanded tags-already-expanded)
  12873. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  12874. ;; @ and _ are allowed as word-components in tags.
  12875. (modify-syntax-entry ?@ "w" stable)
  12876. (modify-syntax-entry ?_ "w" stable)
  12877. ;; Temporarily replace regexp-expressions in the match-expression.
  12878. (while (string-match "{.+?}" return-match)
  12879. (cl-incf count)
  12880. (push (match-string 0 return-match) regexps-in-match)
  12881. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  12882. (while (and taggroups-keys
  12883. (with-syntax-table stable
  12884. (string-match
  12885. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  12886. (regexp-opt taggroups-keys) "\\>\\)")
  12887. return-match)))
  12888. (let* ((dir (match-string 1 return-match))
  12889. (tag (match-string 2 return-match))
  12890. (tag (if downcased (downcase tag) tag)))
  12891. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  12892. (member tag work-already-expanded))
  12893. (setq tags-in-group (assoc tag taggroups))
  12894. (push tag work-already-expanded)
  12895. ;; Recursively expand each tag in the group, if the tag hasn't
  12896. ;; already been expanded. Restore the match-data after all recursive calls.
  12897. (save-match-data
  12898. (let (tags-expanded)
  12899. (dolist (x (cdr tags-in-group))
  12900. (if (and (member x taggroups-keys)
  12901. (not (member x work-already-expanded)))
  12902. (setq tags-expanded
  12903. (delete-dups
  12904. (append
  12905. (org-tags-expand x t downcased
  12906. work-already-expanded)
  12907. tags-expanded)))
  12908. (setq tags-expanded
  12909. (append (list x) tags-expanded)))
  12910. (setq work-already-expanded
  12911. (delete-dups
  12912. (append tags-expanded
  12913. work-already-expanded))))
  12914. (setq tags-in-group
  12915. (delete-dups (cons (car tags-in-group)
  12916. tags-expanded)))))
  12917. ;; Filter tag-regexps from tags.
  12918. (setq regexp-in-group-escaped
  12919. (delq nil (mapcar (lambda (x)
  12920. (if (stringp x)
  12921. (and (equal "{" (substring x 0 1))
  12922. (equal "}" (substring x -1))
  12923. x)
  12924. x))
  12925. tags-in-group))
  12926. regexp-in-group
  12927. (mapcar (lambda (x)
  12928. (substring x 1 -1))
  12929. regexp-in-group-escaped)
  12930. tags-in-group
  12931. (delq nil (mapcar (lambda (x)
  12932. (if (stringp x)
  12933. (and (not (equal "{" (substring x 0 1)))
  12934. (not (equal "}" (substring x -1)))
  12935. x)
  12936. x))
  12937. tags-in-group)))
  12938. ;; If single-as-list, do no more in the while-loop.
  12939. (if (not single-as-list)
  12940. (progn
  12941. (when regexp-in-group
  12942. (setq regexp-in-group
  12943. (concat "\\|"
  12944. (mapconcat 'identity regexp-in-group
  12945. "\\|"))))
  12946. (setq tags-in-group
  12947. (concat dir
  12948. "{\\<"
  12949. (regexp-opt tags-in-group)
  12950. "\\>"
  12951. regexp-in-group
  12952. "}"))
  12953. (when (stringp tags-in-group)
  12954. (org-add-props tags-in-group '(grouptag t)))
  12955. (setq return-match
  12956. (replace-match tags-in-group t t return-match)))
  12957. (setq tags-in-group
  12958. (append regexp-in-group-escaped tags-in-group))))
  12959. (setq taggroups-keys (delete tag taggroups-keys))))
  12960. ;; Add the regular expressions back into the match-expression again.
  12961. (while regexps-in-match
  12962. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  12963. (pop regexps-in-match)
  12964. return-match t t))
  12965. (cl-decf count))
  12966. (if single-as-list
  12967. (if tags-in-group tags-in-group (list return-match))
  12968. return-match))
  12969. (if single-as-list
  12970. (list (if downcased (downcase match) match))
  12971. match)))
  12972. (defun org-op-to-function (op &optional stringp)
  12973. "Turn an operator into the appropriate function."
  12974. (setq op
  12975. (cond
  12976. ((equal op "<" ) '(< string< org-time<))
  12977. ((equal op ">" ) '(> org-string> org-time>))
  12978. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  12979. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  12980. ((member op '("=" "==")) '(= string= org-time=))
  12981. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  12982. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  12983. (defun org<> (a b) (not (= a b)))
  12984. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  12985. (defun org-string>= (a b) (not (string< a b)))
  12986. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  12987. (defun org-string<> (a b) (not (string= a b)))
  12988. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  12989. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  12990. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  12991. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  12992. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  12993. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  12994. (defun org-2ft (s)
  12995. "Convert S to a floating point time.
  12996. If S is already a number, just return it. If it is a string, parse
  12997. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  12998. (cond
  12999. ((numberp s) s)
  13000. ((stringp s)
  13001. (condition-case nil
  13002. (float-time (apply #'encode-time (org-parse-time-string s nil t)))
  13003. (error 0.)))
  13004. (t 0.)))
  13005. (defun org-time-today ()
  13006. "Time in seconds today at 0:00.
  13007. Returns the float number of seconds since the beginning of the
  13008. epoch to the beginning of today (00:00)."
  13009. (float-time (apply 'encode-time
  13010. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13011. (defun org-matcher-time (s)
  13012. "Interpret a time comparison value."
  13013. (save-match-data
  13014. (cond
  13015. ((string= s "<now>") (float-time))
  13016. ((string= s "<today>") (org-time-today))
  13017. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13018. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13019. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13020. (+ (org-time-today)
  13021. (* (string-to-number (match-string 1 s))
  13022. (cdr (assoc (match-string 2 s)
  13023. '(("d" . 86400.0) ("w" . 604800.0)
  13024. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13025. (t (org-2ft s)))))
  13026. (defun org-match-any-p (re list)
  13027. "Does re match any element of list?"
  13028. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13029. (delq nil list))
  13030. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13031. (defvar org-tags-overlay (make-overlay 1 1))
  13032. (delete-overlay org-tags-overlay)
  13033. (defun org-get-local-tags-at (&optional pos)
  13034. "Get a list of tags defined in the current headline."
  13035. (org-get-tags-at pos 'local))
  13036. (defun org-get-local-tags ()
  13037. "Get a list of tags defined in the current headline."
  13038. (org-get-tags-at nil 'local))
  13039. (defun org-get-tags-at (&optional pos local)
  13040. "Get a list of all headline tags applicable at POS.
  13041. POS defaults to point. If tags are inherited, the list contains
  13042. the targets in the same sequence as the headlines appear, i.e.
  13043. the tags of the current headline come last.
  13044. When LOCAL is non-nil, only return tags from the current headline,
  13045. ignore inherited ones."
  13046. (interactive)
  13047. (if (and org-trust-scanner-tags
  13048. (or (not pos) (equal pos (point)))
  13049. (not local))
  13050. org-scanner-tags
  13051. (let (tags ltags lastpos parent)
  13052. (save-excursion
  13053. (save-restriction
  13054. (widen)
  13055. (goto-char (or pos (point)))
  13056. (save-match-data
  13057. (catch 'done
  13058. (condition-case nil
  13059. (progn
  13060. (org-back-to-heading t)
  13061. (while (not (equal lastpos (point)))
  13062. (setq lastpos (point))
  13063. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13064. (setq ltags (org-split-string
  13065. (match-string-no-properties 1) ":"))
  13066. (when parent
  13067. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13068. (setq tags (append
  13069. (if parent
  13070. (org-remove-uninherited-tags ltags)
  13071. ltags)
  13072. tags)))
  13073. (or org-use-tag-inheritance (throw 'done t))
  13074. (when local (throw 'done t))
  13075. (or (org-up-heading-safe) (error nil))
  13076. (setq parent t)))
  13077. (error nil)))))
  13078. (if local
  13079. tags
  13080. (reverse (delete-dups
  13081. (reverse (append
  13082. (org-remove-uninherited-tags
  13083. org-file-tags)
  13084. tags)))))))))
  13085. (defun org-add-prop-inherited (s)
  13086. (add-text-properties 0 (length s) '(inherited t) s)
  13087. s)
  13088. (defun org-toggle-tag (tag &optional onoff)
  13089. "Toggle the tag TAG for the current line.
  13090. If ONOFF is `on' or `off', don't toggle but set to this state."
  13091. (save-excursion
  13092. (org-back-to-heading t)
  13093. (let ((current
  13094. (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  13095. (line-end-position) t)
  13096. (let ((tags (match-string 1)))
  13097. ;; Clear current tags.
  13098. (replace-match "")
  13099. ;; Reverse the tags list so any new tag is appended to
  13100. ;; the current list of tags.
  13101. (nreverse (org-split-string tags ":")))))
  13102. res)
  13103. (pcase onoff
  13104. (`off (setq current (delete tag current)))
  13105. ((or `on (guard (not (member tag current))))
  13106. (setq res t)
  13107. (cl-pushnew tag current :test #'equal))
  13108. (_ (setq current (delete tag current))))
  13109. (end-of-line)
  13110. (if current
  13111. (progn
  13112. (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
  13113. (org-set-tags nil t))
  13114. (delete-horizontal-space))
  13115. (run-hooks 'org-after-tags-change-hook)
  13116. res)))
  13117. (defun org--align-tags-here (to-col)
  13118. "Align tags on the current headline to TO-COL.
  13119. Assume point is on a headline."
  13120. (let ((pos (point)))
  13121. (beginning-of-line)
  13122. (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13123. (>= pos (match-beginning 2)))
  13124. ;; No tags or point within tags: do not align.
  13125. (goto-char pos)
  13126. (goto-char (match-beginning 1))
  13127. (let ((shift (max (- (if (>= to-col 0) to-col
  13128. (- (abs to-col) (string-width (match-string 2))))
  13129. (current-column))
  13130. 1)))
  13131. (replace-match (make-string shift ?\s) nil nil nil 1)
  13132. ;; Preserve initial position, if possible. In any case, stop
  13133. ;; before tags.
  13134. (when (< pos (point)) (goto-char pos))))))
  13135. (defun org-set-tags-command (&optional arg just-align)
  13136. "Call the set-tags command for the current entry."
  13137. (interactive "P")
  13138. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13139. (org-set-tags arg just-align)
  13140. (save-excursion
  13141. (unless (and (org-region-active-p)
  13142. org-loop-over-headlines-in-active-region)
  13143. (org-back-to-heading t))
  13144. (org-set-tags arg just-align))))
  13145. (defun org-set-tags-to (data)
  13146. "Set the tags of the current entry to DATA, replacing the current tags.
  13147. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13148. If DATA is nil or the empty string, any tags will be removed."
  13149. (interactive "sTags: ")
  13150. (setq data
  13151. (cond
  13152. ((eq data nil) "")
  13153. ((equal data "") "")
  13154. ((stringp data)
  13155. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13156. ":"))
  13157. ((listp data)
  13158. (concat ":" (mapconcat 'identity data ":") ":"))))
  13159. (when data
  13160. (save-excursion
  13161. (org-back-to-heading t)
  13162. (when (let ((case-fold-search nil))
  13163. (looking-at org-complex-heading-regexp))
  13164. (if (match-end 5)
  13165. (progn
  13166. (goto-char (match-beginning 5))
  13167. (insert data)
  13168. (delete-region (point) (point-at-eol))
  13169. (org-set-tags nil 'align))
  13170. (goto-char (point-at-eol))
  13171. (insert " " data)
  13172. (org-set-tags nil 'align)))
  13173. (beginning-of-line 1)
  13174. (when (looking-at ".*?\\([ \t]+\\)$")
  13175. (delete-region (match-beginning 1) (match-end 1))))))
  13176. (defun org-align-all-tags ()
  13177. "Align the tags in all headings."
  13178. (interactive)
  13179. (save-excursion
  13180. (or (ignore-errors (org-back-to-heading t))
  13181. (outline-next-heading))
  13182. (if (org-at-heading-p)
  13183. (org-set-tags t)
  13184. (message "No headings"))))
  13185. (defvar org-indent-indentation-per-level)
  13186. (defun org-set-tags (&optional arg just-align)
  13187. "Set the tags for the current headline.
  13188. With prefix ARG, realign all tags in headings in the current buffer.
  13189. When JUST-ALIGN is non-nil, only align tags."
  13190. (interactive "P")
  13191. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13192. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13193. 'region-start-level
  13194. 'region))
  13195. org-loop-over-headlines-in-active-region)
  13196. (org-map-entries
  13197. ;; We don't use ARG and JUST-ALIGN here because these args
  13198. ;; are not useful when looping over headlines.
  13199. #'org-set-tags
  13200. org-loop-over-headlines-in-active-region
  13201. cl
  13202. '(when (org-invisible-p) (org-end-of-subtree nil t))))
  13203. (let ((org-setting-tags t))
  13204. (if arg
  13205. (save-excursion
  13206. (goto-char (point-min))
  13207. (while (re-search-forward org-outline-regexp-bol nil t)
  13208. (org-set-tags nil t)
  13209. (end-of-line))
  13210. (message "All tags realigned to column %d" org-tags-column))
  13211. (let* ((current (org-get-tags-string))
  13212. (tags
  13213. (if just-align current
  13214. ;; Get a new set of tags from the user.
  13215. (save-excursion
  13216. (let* ((seen)
  13217. (table
  13218. (setq
  13219. org-last-tags-completion-table
  13220. ;; Uniquify tags in alists, yet preserve
  13221. ;; structure (i.e., keywords).
  13222. (delq nil
  13223. (mapcar
  13224. (lambda (pair)
  13225. (let ((head (car pair)))
  13226. (cond ((symbolp head) pair)
  13227. ((member head seen) nil)
  13228. (t (push head seen)
  13229. pair))))
  13230. (append
  13231. (or org-current-tag-alist
  13232. (org-get-buffer-tags))
  13233. (and
  13234. org-complete-tags-always-offer-all-agenda-tags
  13235. (org-global-tags-completion-table
  13236. (org-agenda-files))))))))
  13237. (current-tags (org-split-string current ":"))
  13238. (inherited-tags
  13239. (nreverse (nthcdr (length current-tags)
  13240. (nreverse (org-get-tags-at))))))
  13241. (replace-regexp-in-string
  13242. "\\([-+&]+\\|,\\)"
  13243. ":"
  13244. (if (or (eq t org-use-fast-tag-selection)
  13245. (and org-use-fast-tag-selection
  13246. (delq nil (mapcar #'cdr table))))
  13247. (org-fast-tag-selection
  13248. current-tags inherited-tags table
  13249. (and org-fast-tag-selection-include-todo
  13250. org-todo-key-alist))
  13251. (let ((org-add-colon-after-tag-completion
  13252. (< 1 (length table))))
  13253. (org-trim
  13254. (completing-read
  13255. "Tags: "
  13256. #'org-tags-completion-function
  13257. nil nil current 'org-tags-history))))))))))
  13258. (when org-tags-sort-function
  13259. (setq tags
  13260. (mapconcat
  13261. #'identity
  13262. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  13263. org-tags-sort-function)
  13264. ":")))
  13265. (if (or (string= ":" tags)
  13266. (string= "::" tags))
  13267. (setq tags ""))
  13268. (if (not (org-string-nw-p tags)) (setq tags "")
  13269. (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
  13270. (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
  13271. ;; Insert new tags at the correct column.
  13272. (unless (equal current tags)
  13273. (save-excursion
  13274. (beginning-of-line)
  13275. (let ((case-fold-search nil))
  13276. (looking-at org-complex-heading-regexp))
  13277. ;; Remove current tags, if any.
  13278. (when (match-end 5) (replace-match "" nil nil nil 5))
  13279. ;; Insert new tags, if any. Otherwise, remove trailing
  13280. ;; white spaces.
  13281. (end-of-line)
  13282. (if (not (equal tags ""))
  13283. ;; When text is being inserted on an invisible
  13284. ;; region boundary, it can be inadvertently sucked
  13285. ;; into invisibility.
  13286. (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
  13287. (skip-chars-backward " \t")
  13288. (delete-region (point) (line-end-position)))))
  13289. ;; Align tags, if any. Fix tags column if `org-indent-mode'
  13290. ;; is on.
  13291. (unless (equal tags "")
  13292. (let* ((level (save-excursion
  13293. (beginning-of-line)
  13294. (skip-chars-forward "\\*")))
  13295. (offset (if (bound-and-true-p org-indent-mode)
  13296. (* (1- org-indent-indentation-per-level)
  13297. (1- level))
  13298. 0))
  13299. (tags-column
  13300. (+ org-tags-column
  13301. (if (> org-tags-column 0) (- offset) offset))))
  13302. (org--align-tags-here tags-column))))
  13303. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13304. (defun org-change-tag-in-region (beg end tag off)
  13305. "Add or remove TAG for each entry in the region.
  13306. This works in the agenda, and also in an Org buffer."
  13307. (interactive
  13308. (list (region-beginning) (region-end)
  13309. (let ((org-last-tags-completion-table
  13310. (if (derived-mode-p 'org-mode)
  13311. (org-uniquify
  13312. (delq nil (append (org-get-buffer-tags)
  13313. (org-global-tags-completion-table))))
  13314. (org-global-tags-completion-table))))
  13315. (completing-read
  13316. "Tag: " 'org-tags-completion-function nil nil nil
  13317. 'org-tags-history))
  13318. (progn
  13319. (message "[s]et or [r]emove? ")
  13320. (equal (read-char-exclusive) ?r))))
  13321. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13322. (let ((agendap (equal major-mode 'org-agenda-mode))
  13323. l1 l2 m buf pos newhead (cnt 0))
  13324. (goto-char end)
  13325. (setq l2 (1- (org-current-line)))
  13326. (goto-char beg)
  13327. (setq l1 (org-current-line))
  13328. (cl-loop for l from l1 to l2 do
  13329. (org-goto-line l)
  13330. (setq m (get-text-property (point) 'org-hd-marker))
  13331. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13332. (and agendap m))
  13333. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13334. pos (if agendap m (point)))
  13335. (with-current-buffer buf
  13336. (save-excursion
  13337. (save-restriction
  13338. (goto-char pos)
  13339. (setq cnt (1+ cnt))
  13340. (org-toggle-tag tag (if off 'off 'on))
  13341. (setq newhead (org-get-heading)))))
  13342. (and agendap (org-agenda-change-all-lines newhead m))))
  13343. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13344. (defun org-tags-completion-function (string _predicate &optional flag)
  13345. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13346. (confirm (lambda (x) (stringp (car x)))))
  13347. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13348. (setq s1 (match-string 1 string)
  13349. s2 (match-string 2 string))
  13350. (setq s1 "" s2 string))
  13351. (cond
  13352. ((eq flag nil)
  13353. ;; try completion
  13354. (setq rtn (try-completion s2 ctable confirm))
  13355. (when (stringp rtn)
  13356. (setq rtn
  13357. (concat s1 s2 (substring rtn (length s2))
  13358. (if (and org-add-colon-after-tag-completion
  13359. (assoc rtn ctable))
  13360. ":" ""))))
  13361. rtn)
  13362. ((eq flag t)
  13363. ;; all-completions
  13364. (all-completions s2 ctable confirm))
  13365. ((eq flag 'lambda)
  13366. ;; exact match?
  13367. (assoc s2 ctable)))))
  13368. (defun org-fast-tag-insert (kwd tags face &optional end)
  13369. "Insert KDW, and the TAGS, the latter with face FACE.
  13370. Also insert END."
  13371. (insert (format "%-12s" (concat kwd ":"))
  13372. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13373. (or end "")))
  13374. (defun org-fast-tag-show-exit (flag)
  13375. (save-excursion
  13376. (org-goto-line 3)
  13377. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13378. (replace-match ""))
  13379. (when flag
  13380. (end-of-line 1)
  13381. (org-move-to-column (- (window-width) 19) t)
  13382. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13383. (defun org-set-current-tags-overlay (current prefix)
  13384. "Add an overlay to CURRENT tag with PREFIX."
  13385. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13386. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13387. (org-overlay-display org-tags-overlay (concat prefix s))))
  13388. (defvar org-last-tag-selection-key nil)
  13389. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13390. "Fast tag selection with single keys.
  13391. CURRENT is the current list of tags in the headline, INHERITED is the
  13392. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13393. possibly with grouping information. TODO-TABLE is a similar table with
  13394. TODO keywords, should these have keys assigned to them.
  13395. If the keys are nil, a-z are automatically assigned.
  13396. Returns the new tags string, or nil to not change the current settings."
  13397. (let* ((fulltable (append table todo-table))
  13398. (maxlen (apply 'max (mapcar
  13399. (lambda (x)
  13400. (if (stringp (car x)) (string-width (car x)) 0))
  13401. fulltable)))
  13402. (buf (current-buffer))
  13403. (expert (eq org-fast-tag-selection-single-key 'expert))
  13404. (buffer-tags nil)
  13405. (fwidth (+ maxlen 3 1 3))
  13406. (ncol (/ (- (window-width) 4) fwidth))
  13407. (i-face 'org-done)
  13408. (c-face 'org-todo)
  13409. tg cnt e c char c1 c2 ntable tbl rtn
  13410. ov-start ov-end ov-prefix
  13411. (exit-after-next org-fast-tag-selection-single-key)
  13412. (done-keywords org-done-keywords)
  13413. groups ingroup intaggroup)
  13414. (save-excursion
  13415. (beginning-of-line 1)
  13416. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13417. (setq ov-start (match-beginning 1)
  13418. ov-end (match-end 1)
  13419. ov-prefix "")
  13420. (setq ov-start (1- (point-at-eol))
  13421. ov-end (1+ ov-start))
  13422. (skip-chars-forward "^\n\r")
  13423. (setq ov-prefix
  13424. (concat
  13425. (buffer-substring (1- (point)) (point))
  13426. (if (> (current-column) org-tags-column)
  13427. " "
  13428. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13429. (move-overlay org-tags-overlay ov-start ov-end)
  13430. (save-window-excursion
  13431. (if expert
  13432. (set-buffer (get-buffer-create " *Org tags*"))
  13433. (delete-other-windows)
  13434. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13435. (org-switch-to-buffer-other-window " *Org tags*"))
  13436. (erase-buffer)
  13437. (setq-local org-done-keywords done-keywords)
  13438. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13439. (org-fast-tag-insert "Current" current c-face "\n\n")
  13440. (org-fast-tag-show-exit exit-after-next)
  13441. (org-set-current-tags-overlay current ov-prefix)
  13442. (setq tbl fulltable char ?a cnt 0)
  13443. (while (setq e (pop tbl))
  13444. (cond
  13445. ((eq (car e) :startgroup)
  13446. (push '() groups) (setq ingroup t)
  13447. (unless (zerop cnt)
  13448. (setq cnt 0)
  13449. (insert "\n"))
  13450. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13451. ((eq (car e) :endgroup)
  13452. (setq ingroup nil cnt 0)
  13453. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13454. ((eq (car e) :startgrouptag)
  13455. (setq intaggroup t)
  13456. (unless (zerop cnt)
  13457. (setq cnt 0)
  13458. (insert "\n"))
  13459. (insert "[ "))
  13460. ((eq (car e) :endgrouptag)
  13461. (setq intaggroup nil cnt 0)
  13462. (insert "]\n"))
  13463. ((equal e '(:newline))
  13464. (unless (zerop cnt)
  13465. (setq cnt 0)
  13466. (insert "\n")
  13467. (setq e (car tbl))
  13468. (while (equal (car tbl) '(:newline))
  13469. (insert "\n")
  13470. (setq tbl (cdr tbl)))))
  13471. ((equal e '(:grouptags)) (insert " : "))
  13472. (t
  13473. (setq tg (copy-sequence (car e)) c2 nil)
  13474. (if (cdr e)
  13475. (setq c (cdr e))
  13476. ;; automatically assign a character.
  13477. (setq c1 (string-to-char
  13478. (downcase (substring
  13479. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13480. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13481. (while (or (rassoc char ntable) (rassoc char table))
  13482. (setq char (1+ char)))
  13483. (setq c2 c1))
  13484. (setq c (or c2 char)))
  13485. (when ingroup (push tg (car groups)))
  13486. (setq tg (org-add-props tg nil 'face
  13487. (cond
  13488. ((not (assoc tg table))
  13489. (org-get-todo-face tg))
  13490. ((member tg current) c-face)
  13491. ((member tg inherited) i-face))))
  13492. (when (equal (caar tbl) :grouptags)
  13493. (org-add-props tg nil 'face 'org-tag-group))
  13494. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13495. (insert "[" c "] " tg (make-string
  13496. (- fwidth 4 (length tg)) ?\ ))
  13497. (push (cons tg c) ntable)
  13498. (when (= (cl-incf cnt) ncol)
  13499. (insert "\n")
  13500. (when (or ingroup intaggroup) (insert " "))
  13501. (setq cnt 0)))))
  13502. (setq ntable (nreverse ntable))
  13503. (insert "\n")
  13504. (goto-char (point-min))
  13505. (unless expert (org-fit-window-to-buffer))
  13506. (setq rtn
  13507. (catch 'exit
  13508. (while t
  13509. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  13510. (if (not groups) "no " "")
  13511. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13512. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13513. (setq org-last-tag-selection-key c)
  13514. (cond
  13515. ((= c ?\r) (throw 'exit t))
  13516. ((= c ?!)
  13517. (setq groups (not groups))
  13518. (goto-char (point-min))
  13519. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13520. ((= c ?\C-c)
  13521. (if (not expert)
  13522. (org-fast-tag-show-exit
  13523. (setq exit-after-next (not exit-after-next)))
  13524. (setq expert nil)
  13525. (delete-other-windows)
  13526. (set-window-buffer (split-window-vertically) " *Org tags*")
  13527. (org-switch-to-buffer-other-window " *Org tags*")
  13528. (org-fit-window-to-buffer)))
  13529. ((or (= c ?\C-g)
  13530. (and (= c ?q) (not (rassoc c ntable))))
  13531. (delete-overlay org-tags-overlay)
  13532. (setq quit-flag t))
  13533. ((= c ?\ )
  13534. (setq current nil)
  13535. (when exit-after-next (setq exit-after-next 'now)))
  13536. ((= c ?\t)
  13537. (condition-case nil
  13538. (setq tg (completing-read
  13539. "Tag: "
  13540. (or buffer-tags
  13541. (with-current-buffer buf
  13542. (setq buffer-tags
  13543. (org-get-buffer-tags))))))
  13544. (quit (setq tg "")))
  13545. (when (string-match "\\S-" tg)
  13546. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13547. (if (member tg current)
  13548. (setq current (delete tg current))
  13549. (push tg current)))
  13550. (when exit-after-next (setq exit-after-next 'now)))
  13551. ((setq e (rassoc c todo-table) tg (car e))
  13552. (with-current-buffer buf
  13553. (save-excursion (org-todo tg)))
  13554. (when exit-after-next (setq exit-after-next 'now)))
  13555. ((setq e (rassoc c ntable) tg (car e))
  13556. (if (member tg current)
  13557. (setq current (delete tg current))
  13558. (cl-loop for g in groups do
  13559. (when (member tg g)
  13560. (dolist (x g) (setq current (delete x current)))))
  13561. (push tg current))
  13562. (when exit-after-next (setq exit-after-next 'now))))
  13563. ;; Create a sorted list
  13564. (setq current
  13565. (sort current
  13566. (lambda (a b)
  13567. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13568. (when (eq exit-after-next 'now) (throw 'exit t))
  13569. (goto-char (point-min))
  13570. (beginning-of-line 2)
  13571. (delete-region (point) (point-at-eol))
  13572. (org-fast-tag-insert "Current" current c-face)
  13573. (org-set-current-tags-overlay current ov-prefix)
  13574. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  13575. (setq tg (match-string 1))
  13576. (add-text-properties
  13577. (match-beginning 1) (match-end 1)
  13578. (list 'face
  13579. (cond
  13580. ((member tg current) c-face)
  13581. ((member tg inherited) i-face)
  13582. (t (get-text-property (match-beginning 1) 'face))))))
  13583. (goto-char (point-min)))))
  13584. (delete-overlay org-tags-overlay)
  13585. (if rtn
  13586. (mapconcat 'identity current ":")
  13587. nil))))
  13588. (defun org-get-tags-string ()
  13589. "Get the TAGS string in the current headline."
  13590. (unless (org-at-heading-p t)
  13591. (user-error "Not on a heading"))
  13592. (save-excursion
  13593. (beginning-of-line 1)
  13594. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13595. (match-string-no-properties 1)
  13596. "")))
  13597. (defun org-get-tags ()
  13598. "Get the list of tags specified in the current headline."
  13599. (org-split-string (org-get-tags-string) ":"))
  13600. (defun org-get-buffer-tags ()
  13601. "Get a table of all tags used in the buffer, for completion."
  13602. (org-with-wide-buffer
  13603. (goto-char (point-min))
  13604. (let ((tag-re (concat org-outline-regexp-bol
  13605. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  13606. tags)
  13607. (while (re-search-forward tag-re nil t)
  13608. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  13609. (push tag tags)))
  13610. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  13611. ;;;; The mapping API
  13612. (defvar org-agenda-skip-comment-trees)
  13613. (defvar org-agenda-skip-function)
  13614. (defun org-map-entries (func &optional match scope &rest skip)
  13615. "Call FUNC at each headline selected by MATCH in SCOPE.
  13616. FUNC is a function or a lisp form. The function will be called without
  13617. arguments, with the cursor positioned at the beginning of the headline.
  13618. The return values of all calls to the function will be collected and
  13619. returned as a list.
  13620. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13621. does not need to preserve point. After evaluation, the cursor will be
  13622. moved to the end of the line (presumably of the headline of the
  13623. processed entry) and search continues from there. Under some
  13624. circumstances, this may not produce the wanted results. For example,
  13625. if you have removed (e.g. archived) the current (sub)tree it could
  13626. mean that the next entry will be skipped entirely. In such cases, you
  13627. can specify the position from where search should continue by making
  13628. FUNC set the variable `org-map-continue-from' to the desired buffer
  13629. position.
  13630. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13631. Only headlines that are matched by this query will be considered during
  13632. the iteration. When MATCH is nil or t, all headlines will be
  13633. visited by the iteration.
  13634. SCOPE determines the scope of this command. It can be any of:
  13635. nil The current buffer, respecting the restriction if any
  13636. tree The subtree started with the entry at point
  13637. region The entries within the active region, if any
  13638. region-start-level
  13639. The entries within the active region, but only those at
  13640. the same level than the first one.
  13641. file The current buffer, without restriction
  13642. file-with-archives
  13643. The current buffer, and any archives associated with it
  13644. agenda All agenda files
  13645. agenda-with-archives
  13646. All agenda files with any archive files associated with them
  13647. \(file1 file2 ...)
  13648. If this is a list, all files in the list will be scanned
  13649. The remaining args are treated as settings for the skipping facilities of
  13650. the scanner. The following items can be given here:
  13651. archive skip trees with the archive tag
  13652. comment skip trees with the COMMENT keyword
  13653. function or Emacs Lisp form:
  13654. will be used as value for `org-agenda-skip-function', so
  13655. whenever the function returns a position, FUNC will not be
  13656. called for that entry and search will continue from the
  13657. position returned
  13658. If your function needs to retrieve the tags including inherited tags
  13659. at the *current* entry, you can use the value of the variable
  13660. `org-scanner-tags' which will be much faster than getting the value
  13661. with `org-get-tags-at'. If your function gets properties with
  13662. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  13663. to t around the call to `org-entry-properties' to get the same speedup.
  13664. Note that if your function moves around to retrieve tags and properties at
  13665. a *different* entry, you cannot use these techniques."
  13666. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  13667. (not (org-region-active-p)))
  13668. (let* ((org-agenda-archives-mode nil) ; just to make sure
  13669. (org-agenda-skip-archived-trees (memq 'archive skip))
  13670. (org-agenda-skip-comment-trees (memq 'comment skip))
  13671. (org-agenda-skip-function
  13672. (car (org-delete-all '(comment archive) skip)))
  13673. (org-tags-match-list-sublevels t)
  13674. (start-level (eq scope 'region-start-level))
  13675. matcher res
  13676. org-todo-keywords-for-agenda
  13677. org-done-keywords-for-agenda
  13678. org-todo-keyword-alist-for-agenda
  13679. org-tag-alist-for-agenda
  13680. org--matcher-tags-todo-only)
  13681. (cond
  13682. ((eq match t) (setq matcher t))
  13683. ((eq match nil) (setq matcher t))
  13684. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  13685. (save-excursion
  13686. (save-restriction
  13687. (cond ((eq scope 'tree)
  13688. (org-back-to-heading t)
  13689. (org-narrow-to-subtree)
  13690. (setq scope nil))
  13691. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  13692. (org-region-active-p))
  13693. ;; If needed, set start-level to a string like "2"
  13694. (when start-level
  13695. (save-excursion
  13696. (goto-char (region-beginning))
  13697. (unless (org-at-heading-p) (outline-next-heading))
  13698. (setq start-level (org-current-level))))
  13699. (narrow-to-region (region-beginning)
  13700. (save-excursion
  13701. (goto-char (region-end))
  13702. (unless (and (bolp) (org-at-heading-p))
  13703. (outline-next-heading))
  13704. (point)))
  13705. (setq scope nil)))
  13706. (if (not scope)
  13707. (progn
  13708. (org-agenda-prepare-buffers
  13709. (and buffer-file-name (list buffer-file-name)))
  13710. (setq res
  13711. (org-scan-tags
  13712. func matcher org--matcher-tags-todo-only start-level)))
  13713. ;; Get the right scope
  13714. (cond
  13715. ((and scope (listp scope) (symbolp (car scope)))
  13716. (setq scope (eval scope)))
  13717. ((eq scope 'agenda)
  13718. (setq scope (org-agenda-files t)))
  13719. ((eq scope 'agenda-with-archives)
  13720. (setq scope (org-agenda-files t))
  13721. (setq scope (org-add-archive-files scope)))
  13722. ((eq scope 'file)
  13723. (setq scope (and buffer-file-name (list buffer-file-name))))
  13724. ((eq scope 'file-with-archives)
  13725. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  13726. (org-agenda-prepare-buffers scope)
  13727. (dolist (file scope)
  13728. (with-current-buffer (org-find-base-buffer-visiting file)
  13729. (org-with-wide-buffer
  13730. (goto-char (point-min))
  13731. (setq res
  13732. (append
  13733. res
  13734. (org-scan-tags
  13735. func matcher org--matcher-tags-todo-only)))))))))
  13736. res)))
  13737. ;;; Properties API
  13738. (defconst org-special-properties
  13739. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  13740. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  13741. "The special properties valid in Org mode.
  13742. These are properties that are not defined in the property drawer,
  13743. but in some other way.")
  13744. (defconst org-default-properties
  13745. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  13746. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  13747. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  13748. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  13749. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  13750. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  13751. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  13752. "Some properties that are used by Org mode for various purposes.
  13753. Being in this list makes sure that they are offered for completion.")
  13754. (defun org--valid-property-p (property)
  13755. "Non nil when string PROPERTY is a valid property name."
  13756. (not
  13757. (or (equal property "")
  13758. (string-match-p "\\s-" property))))
  13759. (defun org--update-property-plist (key val props)
  13760. "Associate KEY to VAL in alist PROPS.
  13761. Modifications are made by side-effect. Return new alist."
  13762. (let* ((appending (string= (substring key -1) "+"))
  13763. (key (if appending (substring key 0 -1) key))
  13764. (old (assoc-string key props t)))
  13765. (if (not old) (cons (cons key val) props)
  13766. (setcdr old (if appending (concat (cdr old) " " val) val))
  13767. props)))
  13768. (defun org-get-property-block (&optional beg force)
  13769. "Return the (beg . end) range of the body of the property drawer.
  13770. BEG is the beginning of the current subtree, or of the part
  13771. before the first headline. If it is not given, it will be found.
  13772. If the drawer does not exist, create it if FORCE is non-nil, or
  13773. return nil."
  13774. (org-with-wide-buffer
  13775. (when beg (goto-char beg))
  13776. (unless (org-before-first-heading-p)
  13777. (let ((beg (cond (beg)
  13778. ((or (not (featurep 'org-inlinetask))
  13779. (org-inlinetask-in-task-p))
  13780. (org-back-to-heading t))
  13781. (t (org-with-limited-levels (org-back-to-heading t))))))
  13782. (forward-line)
  13783. (when (looking-at-p org-planning-line-re) (forward-line))
  13784. (cond ((looking-at org-property-drawer-re)
  13785. (forward-line)
  13786. (cons (point) (progn (goto-char (match-end 0))
  13787. (line-beginning-position))))
  13788. (force
  13789. (goto-char beg)
  13790. (org-insert-property-drawer)
  13791. (let ((pos (save-excursion (search-forward ":END:")
  13792. (line-beginning-position))))
  13793. (cons pos pos))))))))
  13794. (defun org-at-property-p ()
  13795. "Non-nil when point is inside a property drawer.
  13796. See `org-property-re' for match data, if applicable."
  13797. (save-excursion
  13798. (beginning-of-line)
  13799. (and (looking-at org-property-re)
  13800. (let ((property-drawer (save-match-data (org-get-property-block))))
  13801. (and property-drawer
  13802. (>= (point) (car property-drawer))
  13803. (< (point) (cdr property-drawer)))))))
  13804. (defun org-property-action ()
  13805. "Do an action on properties."
  13806. (interactive)
  13807. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  13808. (let ((c (read-char-exclusive)))
  13809. (cl-case c
  13810. (?s (call-interactively #'org-set-property))
  13811. (?d (call-interactively #'org-delete-property))
  13812. (?D (call-interactively #'org-delete-property-globally))
  13813. (?c (call-interactively #'org-compute-property-at-point))
  13814. (otherwise (user-error "No such property action %c" c)))))
  13815. (defun org-inc-effort ()
  13816. "Increment the value of the effort property in the current entry."
  13817. (interactive)
  13818. (org-set-effort nil t))
  13819. (defvar org-clock-effort) ; Defined in org-clock.el.
  13820. (defvar org-clock-current-task) ; Defined in org-clock.el.
  13821. (defun org-set-effort (&optional value increment)
  13822. "Set the effort property of the current entry.
  13823. With numerical prefix arg, use the nth allowed value, 0 stands for the
  13824. 10th allowed value.
  13825. When INCREMENT is non-nil, set the property to the next allowed value."
  13826. (interactive "P")
  13827. (when (equal value 0) (setq value 10))
  13828. (let* ((completion-ignore-case t)
  13829. (prop org-effort-property)
  13830. (cur (org-entry-get nil prop))
  13831. (allowed (org-property-get-allowed-values nil prop 'table))
  13832. (existing (mapcar 'list (org-property-values prop)))
  13833. (heading (nth 4 (org-heading-components)))
  13834. rpl
  13835. (val (cond
  13836. ((stringp value) value)
  13837. ((and allowed (integerp value))
  13838. (or (car (nth (1- value) allowed))
  13839. (car (org-last allowed))))
  13840. ((and allowed increment)
  13841. (or (cl-caadr (member (list cur) allowed))
  13842. (user-error "Allowed effort values are not set")))
  13843. (allowed
  13844. (message "Select 1-9,0, [RET%s]: %s"
  13845. (if cur (concat "=" cur) "")
  13846. (mapconcat 'car allowed " "))
  13847. (setq rpl (read-char-exclusive))
  13848. (if (equal rpl ?\r)
  13849. cur
  13850. (setq rpl (- rpl ?0))
  13851. (when (equal rpl 0) (setq rpl 10))
  13852. (if (and (> rpl 0) (<= rpl (length allowed)))
  13853. (car (nth (1- rpl) allowed))
  13854. (org-completing-read "Effort: " allowed nil))))
  13855. (t
  13856. (org-completing-read
  13857. (concat "Effort" (and cur (string-match "\\S-" cur)
  13858. (concat " [" cur "]"))
  13859. ": ")
  13860. existing nil nil "" nil cur)))))
  13861. (unless (equal (org-entry-get nil prop) val)
  13862. (org-entry-put nil prop val))
  13863. (org-refresh-property
  13864. '((effort . identity)
  13865. (effort-minutes . org-duration-to-minutes))
  13866. val)
  13867. (when (equal heading (bound-and-true-p org-clock-current-task))
  13868. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  13869. (org-clock-update-mode-line))
  13870. (message "%s is now %s" prop val)))
  13871. (defun org-entry-properties (&optional pom which)
  13872. "Get all properties of the current entry.
  13873. When POM is a buffer position, get all properties from the entry
  13874. there instead.
  13875. This includes the TODO keyword, the tags, time strings for
  13876. deadline, scheduled, and clocking, and any additional properties
  13877. defined in the entry.
  13878. If WHICH is nil or `all', get all properties. If WHICH is
  13879. `special' or `standard', only get that subclass. If WHICH is
  13880. a string, only get that property.
  13881. Return value is an alist. Keys are properties, as upcased
  13882. strings."
  13883. (org-with-point-at pom
  13884. (when (and (derived-mode-p 'org-mode)
  13885. (ignore-errors (org-back-to-heading t)))
  13886. (catch 'exit
  13887. (let* ((beg (point))
  13888. (specific (and (stringp which) (upcase which)))
  13889. (which (cond ((not specific) which)
  13890. ((member specific org-special-properties) 'special)
  13891. (t 'standard)))
  13892. props)
  13893. ;; Get the special properties, like TODO and TAGS.
  13894. (when (memq which '(nil all special))
  13895. (when (or (not specific) (string= specific "CLOCKSUM"))
  13896. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  13897. (when clocksum
  13898. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  13899. props)))
  13900. (when specific (throw 'exit props)))
  13901. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  13902. (let ((clocksumt (get-text-property (point)
  13903. :org-clock-minutes-today)))
  13904. (when clocksumt
  13905. (push (cons "CLOCKSUM_T"
  13906. (org-duration-from-minutes clocksumt))
  13907. props)))
  13908. (when specific (throw 'exit props)))
  13909. (when (or (not specific) (string= specific "ITEM"))
  13910. (let ((case-fold-search nil))
  13911. (when (looking-at org-complex-heading-regexp)
  13912. (push (cons "ITEM"
  13913. (let ((title (match-string-no-properties 4)))
  13914. (if (org-string-nw-p title)
  13915. (org-remove-tabs title)
  13916. "")))
  13917. props)))
  13918. (when specific (throw 'exit props)))
  13919. (when (or (not specific) (string= specific "TODO"))
  13920. (let ((case-fold-search nil))
  13921. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  13922. (push (cons "TODO" (match-string-no-properties 2)) props)))
  13923. (when specific (throw 'exit props)))
  13924. (when (or (not specific) (string= specific "PRIORITY"))
  13925. (push (cons "PRIORITY"
  13926. (if (looking-at org-priority-regexp)
  13927. (match-string-no-properties 2)
  13928. (char-to-string org-default-priority)))
  13929. props)
  13930. (when specific (throw 'exit props)))
  13931. (when (or (not specific) (string= specific "FILE"))
  13932. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  13933. props)
  13934. (when specific (throw 'exit props)))
  13935. (when (or (not specific) (string= specific "TAGS"))
  13936. (let ((value (org-string-nw-p (org-get-tags-string))))
  13937. (when value (push (cons "TAGS" value) props)))
  13938. (when specific (throw 'exit props)))
  13939. (when (or (not specific) (string= specific "ALLTAGS"))
  13940. (let ((value (org-get-tags-at)))
  13941. (when value
  13942. (push (cons "ALLTAGS"
  13943. (format ":%s:" (mapconcat #'identity value ":")))
  13944. props)))
  13945. (when specific (throw 'exit props)))
  13946. (when (or (not specific) (string= specific "BLOCKED"))
  13947. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  13948. (when specific (throw 'exit props)))
  13949. (when (or (not specific)
  13950. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  13951. (forward-line)
  13952. (when (looking-at-p org-planning-line-re)
  13953. (end-of-line)
  13954. (let ((bol (line-beginning-position))
  13955. ;; Backward compatibility: time keywords used to
  13956. ;; be configurable (before 8.3). Make sure we
  13957. ;; get the correct keyword.
  13958. (key-assoc `(("CLOSED" . ,org-closed-string)
  13959. ("DEADLINE" . ,org-deadline-string)
  13960. ("SCHEDULED" . ,org-scheduled-string))))
  13961. (dolist (pair (if specific (list (assoc specific key-assoc))
  13962. key-assoc))
  13963. (save-excursion
  13964. (when (search-backward (cdr pair) bol t)
  13965. (goto-char (match-end 0))
  13966. (skip-chars-forward " \t")
  13967. (and (looking-at org-ts-regexp-both)
  13968. (push (cons (car pair)
  13969. (match-string-no-properties 0))
  13970. props)))))))
  13971. (when specific (throw 'exit props)))
  13972. (when (or (not specific)
  13973. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  13974. (let ((find-ts
  13975. (lambda (end ts)
  13976. ;; Fix next time-stamp before END. TS is the
  13977. ;; list of time-stamps found so far.
  13978. (let ((ts ts)
  13979. (regexp (cond
  13980. ((string= specific "TIMESTAMP")
  13981. org-ts-regexp)
  13982. ((string= specific "TIMESTAMP_IA")
  13983. org-ts-regexp-inactive)
  13984. ((assoc "TIMESTAMP_IA" ts)
  13985. org-ts-regexp)
  13986. ((assoc "TIMESTAMP" ts)
  13987. org-ts-regexp-inactive)
  13988. (t org-ts-regexp-both))))
  13989. (catch 'next
  13990. (while (re-search-forward regexp end t)
  13991. (backward-char)
  13992. (let ((object (org-element-context)))
  13993. ;; Accept to match timestamps in node
  13994. ;; properties, too.
  13995. (when (memq (org-element-type object)
  13996. '(node-property timestamp))
  13997. (let ((type
  13998. (org-element-property :type object)))
  13999. (cond
  14000. ((and (memq type '(active active-range))
  14001. (not (equal specific "TIMESTAMP_IA")))
  14002. (unless (assoc "TIMESTAMP" ts)
  14003. (push (cons "TIMESTAMP"
  14004. (org-element-property
  14005. :raw-value object))
  14006. ts)
  14007. (when specific (throw 'exit ts))))
  14008. ((and (memq type '(inactive inactive-range))
  14009. (not (string= specific "TIMESTAMP")))
  14010. (unless (assoc "TIMESTAMP_IA" ts)
  14011. (push (cons "TIMESTAMP_IA"
  14012. (org-element-property
  14013. :raw-value object))
  14014. ts)
  14015. (when specific (throw 'exit ts))))))
  14016. ;; Both timestamp types are found,
  14017. ;; move to next part.
  14018. (when (= (length ts) 2) (throw 'next ts)))))
  14019. ts)))))
  14020. (goto-char beg)
  14021. ;; First look for timestamps within headline.
  14022. (let ((ts (funcall find-ts (line-end-position) nil)))
  14023. (if (= (length ts) 2) (setq props (nconc ts props))
  14024. ;; Then find timestamps in the section, skipping
  14025. ;; planning line.
  14026. (let ((end (save-excursion (outline-next-heading))))
  14027. (forward-line)
  14028. (when (looking-at-p org-planning-line-re) (forward-line))
  14029. (setq props (nconc (funcall find-ts end ts) props))))))))
  14030. ;; Get the standard properties, like :PROP:.
  14031. (when (memq which '(nil all standard))
  14032. ;; If we are looking after a specific property, delegate
  14033. ;; to `org-entry-get', which is faster. However, make an
  14034. ;; exception for "CATEGORY", since it can be also set
  14035. ;; through keywords (i.e. #+CATEGORY).
  14036. (if (and specific (not (equal specific "CATEGORY")))
  14037. (let ((value (org-entry-get beg specific nil t)))
  14038. (throw 'exit (and value (list (cons specific value)))))
  14039. (let ((range (org-get-property-block beg)))
  14040. (when range
  14041. (let ((end (cdr range)) seen-base)
  14042. (goto-char (car range))
  14043. ;; Unlike to `org--update-property-plist', we
  14044. ;; handle the case where base values is found
  14045. ;; after its extension. We also forbid standard
  14046. ;; properties to be named as special properties.
  14047. (while (re-search-forward org-property-re end t)
  14048. (let* ((key (upcase (match-string-no-properties 2)))
  14049. (extendp (string-match-p "\\+\\'" key))
  14050. (key-base (if extendp (substring key 0 -1) key))
  14051. (value (match-string-no-properties 3)))
  14052. (cond
  14053. ((member-ignore-case key-base org-special-properties))
  14054. (extendp
  14055. (setq props
  14056. (org--update-property-plist key value props)))
  14057. ((member key seen-base))
  14058. (t (push key seen-base)
  14059. (let ((p (assoc-string key props t)))
  14060. (if p (setcdr p (concat value " " (cdr p)))
  14061. (push (cons key value) props))))))))))))
  14062. (unless (assoc "CATEGORY" props)
  14063. (push (cons "CATEGORY" (org-get-category beg)) props)
  14064. (when (string= specific "CATEGORY") (throw 'exit props)))
  14065. ;; Return value.
  14066. props)))))
  14067. (defun org--property-local-values (property literal-nil)
  14068. "Return value for PROPERTY in current entry.
  14069. Value is a list whose car is the base value for PROPERTY and cdr
  14070. a list of accumulated values. Return nil if neither is found in
  14071. the entry. Also return nil when PROPERTY is set to \"nil\",
  14072. unless LITERAL-NIL is non-nil."
  14073. (let ((range (org-get-property-block)))
  14074. (when range
  14075. (goto-char (car range))
  14076. (let* ((case-fold-search t)
  14077. (end (cdr range))
  14078. (value
  14079. ;; Base value.
  14080. (save-excursion
  14081. (let ((v (and (re-search-forward
  14082. (org-re-property property nil t) end t)
  14083. (match-string-no-properties 3))))
  14084. (list (if literal-nil v (org-not-nil v)))))))
  14085. ;; Find additional values.
  14086. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14087. (while (re-search-forward property+ end t)
  14088. (push (match-string-no-properties 3) value)))
  14089. ;; Return final values.
  14090. (and (not (equal value '(nil))) (nreverse value))))))
  14091. (defun org--property-global-value (property literal-nil)
  14092. "Return value for PROPERTY in current buffer.
  14093. Return value is a string. Return nil if property is not set
  14094. globally. Also return nil when PROPERTY is set to \"nil\",
  14095. unless LITERAL-NIL is non-nil."
  14096. (let ((global
  14097. (cdr (or (assoc-string property org-file-properties t)
  14098. (assoc-string property org-global-properties t)
  14099. (assoc-string property org-global-properties-fixed t)))))
  14100. (if literal-nil global (org-not-nil global))))
  14101. (defun org-entry-get (pom property &optional inherit literal-nil)
  14102. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14103. If INHERIT is non-nil and the entry does not have the property,
  14104. then also check higher levels of the hierarchy. If INHERIT is
  14105. the symbol `selective', use inheritance only if the setting in
  14106. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14107. If the property is present but empty, the return value is the
  14108. empty string. If the property is not present at all, nil is
  14109. returned. In any other case, return the value as a string.
  14110. Search is case-insensitive.
  14111. If LITERAL-NIL is set, return the string value \"nil\" as
  14112. a string, do not interpret it as the list atom nil. This is used
  14113. for inheritance when a \"nil\" value can supersede a non-nil
  14114. value higher up the hierarchy."
  14115. (org-with-point-at pom
  14116. (cond
  14117. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14118. ;; We need a special property. Use `org-entry-properties' to
  14119. ;; retrieve it, but specify the wanted property.
  14120. (cdr (assoc-string property (org-entry-properties nil property))))
  14121. ((and inherit
  14122. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14123. (org-entry-get-with-inheritance property literal-nil))
  14124. (t
  14125. (let* ((local (org--property-local-values property literal-nil))
  14126. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14127. (if literal-nil value (org-not-nil value)))))))
  14128. (defun org-property-or-variable-value (var &optional inherit)
  14129. "Check if there is a property fixing the value of VAR.
  14130. If yes, return this value. If not, return the current value of the variable."
  14131. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14132. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14133. (read prop)
  14134. (symbol-value var))))
  14135. (defun org-entry-delete (pom property)
  14136. "Delete PROPERTY from entry at point-or-marker POM.
  14137. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14138. non-nil when a property was removed."
  14139. (org-with-point-at pom
  14140. (pcase (org-get-property-block)
  14141. (`(,begin . ,origin)
  14142. (let* ((end (copy-marker origin))
  14143. (re (org-re-property
  14144. (concat (regexp-quote property) "\\+?") t t)))
  14145. (goto-char begin)
  14146. (while (re-search-forward re end t)
  14147. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14148. ;; If drawer is empty, remove it altogether.
  14149. (when (= begin end)
  14150. (delete-region (line-beginning-position 0)
  14151. (line-beginning-position 2)))
  14152. ;; Return non-nil if some property was removed.
  14153. (prog1 (/= end origin) (set-marker end nil))))
  14154. (_ nil))))
  14155. ;; Multi-values properties are properties that contain multiple values
  14156. ;; These values are assumed to be single words, separated by whitespace.
  14157. (defun org-entry-add-to-multivalued-property (pom property value)
  14158. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14159. (let* ((old (org-entry-get pom property))
  14160. (values (and old (split-string old))))
  14161. (setq value (org-entry-protect-space value))
  14162. (unless (member value values)
  14163. (setq values (append values (list value)))
  14164. (org-entry-put pom property (mapconcat #'identity values " ")))))
  14165. (defun org-entry-remove-from-multivalued-property (pom property value)
  14166. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14167. (let* ((old (org-entry-get pom property))
  14168. (values (and old (split-string old))))
  14169. (setq value (org-entry-protect-space value))
  14170. (when (member value values)
  14171. (setq values (delete value values))
  14172. (org-entry-put pom property (mapconcat #'identity values " ")))))
  14173. (defun org-entry-member-in-multivalued-property (pom property value)
  14174. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14175. (let* ((old (org-entry-get pom property))
  14176. (values (and old (split-string old))))
  14177. (setq value (org-entry-protect-space value))
  14178. (member value values)))
  14179. (defun org-entry-get-multivalued-property (pom property)
  14180. "Return a list of values in a multivalued property."
  14181. (let* ((value (org-entry-get pom property))
  14182. (values (and value (split-string value))))
  14183. (mapcar #'org-entry-restore-space values)))
  14184. (defun org-entry-put-multivalued-property (pom property &rest values)
  14185. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14186. VALUES should be a list of strings. Spaces will be protected."
  14187. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  14188. (let* ((value (org-entry-get pom property))
  14189. (values (and value (split-string value))))
  14190. (mapcar #'org-entry-restore-space values)))
  14191. (defun org-entry-protect-space (s)
  14192. "Protect spaces and newline in string S."
  14193. (while (string-match " " s)
  14194. (setq s (replace-match "%20" t t s)))
  14195. (while (string-match "\n" s)
  14196. (setq s (replace-match "%0A" t t s)))
  14197. s)
  14198. (defun org-entry-restore-space (s)
  14199. "Restore spaces and newline in string S."
  14200. (while (string-match "%20" s)
  14201. (setq s (replace-match " " t t s)))
  14202. (while (string-match "%0A" s)
  14203. (setq s (replace-match "\n" t t s)))
  14204. s)
  14205. (defvar org-entry-property-inherited-from (make-marker)
  14206. "Marker pointing to the entry from where a property was inherited.
  14207. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14208. location of the entry where the inheritance search matched. If there was
  14209. no match, the marker will point nowhere.
  14210. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14211. is set.")
  14212. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14213. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14214. The search will stop at the first ancestor which has the property defined.
  14215. If the value found is \"nil\", return nil to show that the property
  14216. should be considered as undefined (this is the meaning of nil here).
  14217. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14218. (move-marker org-entry-property-inherited-from nil)
  14219. (org-with-wide-buffer
  14220. (let (value)
  14221. (catch 'exit
  14222. (while t
  14223. (let ((v (org--property-local-values property literal-nil)))
  14224. (when v
  14225. (setq value
  14226. (concat (mapconcat #'identity (delq nil v) " ")
  14227. (and value " ")
  14228. value)))
  14229. (cond
  14230. ((car v)
  14231. (org-back-to-heading t)
  14232. (move-marker org-entry-property-inherited-from (point))
  14233. (throw 'exit nil))
  14234. ((org-up-heading-safe))
  14235. (t
  14236. (let ((global (org--property-global-value property literal-nil)))
  14237. (cond ((not global))
  14238. (value (setq value (concat global " " value)))
  14239. (t (setq value global))))
  14240. (throw 'exit nil))))))
  14241. (if literal-nil value (org-not-nil value)))))
  14242. (defvar org-property-changed-functions nil
  14243. "Hook called when the value of a property has changed.
  14244. Each hook function should accept two arguments, the name of the property
  14245. and the new value.")
  14246. (defun org-entry-put (pom property value)
  14247. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14248. If the value is nil, it is converted to the empty string. If it
  14249. is not a string, an error is raised. Also raise an error on
  14250. invalid property names.
  14251. PROPERTY can be any regular property (see
  14252. `org-special-properties'). It can also be \"TODO\",
  14253. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14254. For the last two properties, VALUE may have any of the special
  14255. values \"earlier\" and \"later\". The function then increases or
  14256. decreases scheduled or deadline date by one day."
  14257. (cond ((null value) (setq value ""))
  14258. ((not (stringp value)) (error "Properties values should be strings"))
  14259. ((not (org--valid-property-p property))
  14260. (user-error "Invalid property name: \"%s\"" property)))
  14261. (org-with-point-at pom
  14262. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14263. (org-back-to-heading t)
  14264. (org-with-limited-levels (org-back-to-heading t)))
  14265. (let ((beg (point)))
  14266. (cond
  14267. ((equal property "TODO")
  14268. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14269. ((not (member value org-todo-keywords-1))
  14270. (user-error "\"%s\" is not a valid TODO state" value)))
  14271. (org-todo value)
  14272. (org-set-tags nil 'align))
  14273. ((equal property "PRIORITY")
  14274. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14275. (org-set-tags nil 'align))
  14276. ((equal property "SCHEDULED")
  14277. (forward-line)
  14278. (if (and (looking-at-p org-planning-line-re)
  14279. (re-search-forward
  14280. org-scheduled-time-regexp (line-end-position) t))
  14281. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14282. ((string= value "later") (org-timestamp-change 1 'day))
  14283. ((string= value "") (org-schedule '(4)))
  14284. (t (org-schedule nil value)))
  14285. (if (member value '("earlier" "later" ""))
  14286. (call-interactively #'org-schedule)
  14287. (org-schedule nil value))))
  14288. ((equal property "DEADLINE")
  14289. (forward-line)
  14290. (if (and (looking-at-p org-planning-line-re)
  14291. (re-search-forward
  14292. org-deadline-time-regexp (line-end-position) t))
  14293. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14294. ((string= value "later") (org-timestamp-change 1 'day))
  14295. ((string= value "") (org-deadline '(4)))
  14296. (t (org-deadline nil value)))
  14297. (if (member value '("earlier" "later" ""))
  14298. (call-interactively #'org-deadline)
  14299. (org-deadline nil value))))
  14300. ((member property org-special-properties)
  14301. (error "The %s property cannot be set with `org-entry-put'" property))
  14302. (t
  14303. (let* ((range (org-get-property-block beg 'force))
  14304. (end (cdr range))
  14305. (case-fold-search t))
  14306. (goto-char (car range))
  14307. (if (re-search-forward (org-re-property property nil t) end t)
  14308. (progn (delete-region (match-beginning 0) (match-end 0))
  14309. (goto-char (match-beginning 0)))
  14310. (goto-char end)
  14311. (insert "\n")
  14312. (backward-char))
  14313. (insert ":" property ":")
  14314. (when value (insert " " value))
  14315. (org-indent-line)))))
  14316. (run-hook-with-args 'org-property-changed-functions property value)))
  14317. (defun org-buffer-property-keys (&optional specials defaults columns)
  14318. "Get all property keys in the current buffer.
  14319. When SPECIALS is non-nil, also list the special properties that
  14320. reflect things like tags and TODO state.
  14321. When DEFAULTS is non-nil, also include properties that has
  14322. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14323. DESCRIPTION, LOCATION, and LOGGING and others.
  14324. When COLUMNS in non-nil, also include property names given in
  14325. COLUMN formats in the current buffer."
  14326. (let ((case-fold-search t)
  14327. (props (append
  14328. (and specials org-special-properties)
  14329. (and defaults (cons org-effort-property org-default-properties))
  14330. nil)))
  14331. (org-with-wide-buffer
  14332. (goto-char (point-min))
  14333. (while (re-search-forward org-property-start-re nil t)
  14334. (catch :skip
  14335. (let ((range (org-get-property-block)))
  14336. (unless range (throw :skip nil))
  14337. (goto-char (car range))
  14338. (let ((begin (car range))
  14339. (end (cdr range)))
  14340. ;; Make sure that found property block is not located
  14341. ;; before current point, as it would generate an infloop.
  14342. ;; It can happen, for example, in the following
  14343. ;; situation:
  14344. ;;
  14345. ;; * Headline
  14346. ;; :PROPERTIES:
  14347. ;; ...
  14348. ;; :END:
  14349. ;; *************** Inlinetask
  14350. ;; #+BEGIN_EXAMPLE
  14351. ;; :PROPERTIES:
  14352. ;; #+END_EXAMPLE
  14353. ;;
  14354. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  14355. (while (< (point) end)
  14356. (let ((p (progn (looking-at org-property-re)
  14357. (match-string-no-properties 2))))
  14358. ;; Only add true property name, not extension symbol.
  14359. (push (if (not (string-match-p "\\+\\'" p)) p
  14360. (substring p 0 -1))
  14361. props))
  14362. (forward-line))))
  14363. (outline-next-heading)))
  14364. (when columns
  14365. (goto-char (point-min))
  14366. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14367. (let ((element (org-element-at-point)))
  14368. (when (memq (org-element-type element) '(keyword node-property))
  14369. (let ((value (org-element-property :value element))
  14370. (start 0))
  14371. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  14372. \\(?:{[^}]+}\\)?"
  14373. value start)
  14374. (setq start (match-end 0))
  14375. (let ((p (match-string-no-properties 1 value)))
  14376. (unless (member-ignore-case p org-special-properties)
  14377. (push p props))))))))))
  14378. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14379. (defun org-property-values (key)
  14380. "List all non-nil values of property KEY in current buffer."
  14381. (org-with-wide-buffer
  14382. (goto-char (point-min))
  14383. (let ((case-fold-search t)
  14384. (re (org-re-property key))
  14385. values)
  14386. (while (re-search-forward re nil t)
  14387. (push (org-entry-get (point) key) values))
  14388. (delete-dups values))))
  14389. (defun org-insert-property-drawer ()
  14390. "Insert a property drawer into the current entry."
  14391. (org-with-wide-buffer
  14392. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14393. (org-back-to-heading t)
  14394. (org-with-limited-levels (org-back-to-heading t)))
  14395. (forward-line)
  14396. (when (looking-at-p org-planning-line-re) (forward-line))
  14397. (unless (looking-at-p org-property-drawer-re)
  14398. ;; Make sure we start editing a line from current entry, not from
  14399. ;; next one. It prevents extending text properties or overlays
  14400. ;; belonging to the latter.
  14401. (when (bolp) (backward-char))
  14402. (let ((begin (1+ (point)))
  14403. (inhibit-read-only t))
  14404. (insert "\n:PROPERTIES:\n:END:")
  14405. (when (eobp) (insert "\n"))
  14406. (org-indent-region begin (point))))))
  14407. (defun org-insert-drawer (&optional arg drawer)
  14408. "Insert a drawer at point.
  14409. When optional argument ARG is non-nil, insert a property drawer.
  14410. Optional argument DRAWER, when non-nil, is a string representing
  14411. drawer's name. Otherwise, the user is prompted for a name.
  14412. If a region is active, insert the drawer around that region
  14413. instead.
  14414. Point is left between drawer's boundaries."
  14415. (interactive "P")
  14416. (let* ((drawer (if arg "PROPERTIES"
  14417. (or drawer (read-from-minibuffer "Drawer: ")))))
  14418. (cond
  14419. ;; With C-u, fall back on `org-insert-property-drawer'
  14420. (arg (org-insert-property-drawer))
  14421. ;; Check validity of suggested drawer's name.
  14422. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14423. (user-error "Invalid drawer name"))
  14424. ;; With an active region, insert a drawer at point.
  14425. ((not (org-region-active-p))
  14426. (progn
  14427. (unless (bolp) (insert "\n"))
  14428. (insert (format ":%s:\n\n:END:\n" drawer))
  14429. (forward-line -2)))
  14430. ;; Otherwise, insert the drawer at point
  14431. (t
  14432. (let ((rbeg (region-beginning))
  14433. (rend (copy-marker (region-end))))
  14434. (unwind-protect
  14435. (progn
  14436. (goto-char rbeg)
  14437. (beginning-of-line)
  14438. (when (save-excursion
  14439. (re-search-forward org-outline-regexp-bol rend t))
  14440. (user-error "Drawers cannot contain headlines"))
  14441. ;; Position point at the beginning of the first
  14442. ;; non-blank line in region. Insert drawer's opening
  14443. ;; there, then indent it.
  14444. (org-skip-whitespace)
  14445. (beginning-of-line)
  14446. (insert ":" drawer ":\n")
  14447. (forward-line -1)
  14448. (indent-for-tab-command)
  14449. ;; Move point to the beginning of the first blank line
  14450. ;; after the last non-blank line in region. Insert
  14451. ;; drawer's closing, then indent it.
  14452. (goto-char rend)
  14453. (skip-chars-backward " \r\t\n")
  14454. (insert "\n:END:")
  14455. (deactivate-mark t)
  14456. (indent-for-tab-command)
  14457. (unless (eolp) (insert "\n")))
  14458. ;; Clear marker, whatever the outcome of insertion is.
  14459. (set-marker rend nil)))))))
  14460. (defvar org-property-set-functions-alist nil
  14461. "Property set function alist.
  14462. Each entry should have the following format:
  14463. (PROPERTY . READ-FUNCTION)
  14464. The read function will be called with the same argument as
  14465. `org-completing-read'.")
  14466. (defun org-set-property-function (property)
  14467. "Get the function that should be used to set PROPERTY.
  14468. This is computed according to `org-property-set-functions-alist'."
  14469. (or (cdr (assoc property org-property-set-functions-alist))
  14470. 'org-completing-read))
  14471. (defun org-read-property-value (property)
  14472. "Read PROPERTY value from user."
  14473. (let* ((completion-ignore-case t)
  14474. (allowed (org-property-get-allowed-values nil property 'table))
  14475. (cur (org-entry-get nil property))
  14476. (prompt (concat property " value"
  14477. (if (and cur (string-match "\\S-" cur))
  14478. (concat " [" cur "]") "") ": "))
  14479. (set-function (org-set-property-function property))
  14480. (val (if allowed
  14481. (funcall set-function prompt allowed nil
  14482. (not (get-text-property 0 'org-unrestricted
  14483. (caar allowed))))
  14484. (funcall set-function prompt
  14485. (mapcar 'list (org-property-values property))
  14486. nil nil "" nil cur))))
  14487. (org-trim val)))
  14488. (defvar org-last-set-property nil)
  14489. (defvar org-last-set-property-value nil)
  14490. (defun org-read-property-name ()
  14491. "Read a property name."
  14492. (let ((completion-ignore-case t)
  14493. (default-prop (or (and (org-at-property-p)
  14494. (match-string-no-properties 2))
  14495. org-last-set-property)))
  14496. (org-completing-read
  14497. (concat "Property"
  14498. (if default-prop (concat " [" default-prop "]") "")
  14499. ": ")
  14500. (mapcar #'list (org-buffer-property-keys nil t t))
  14501. nil nil nil nil default-prop)))
  14502. (defun org-set-property-and-value (use-last)
  14503. "Allow to set [PROPERTY]: [value] direction from prompt.
  14504. When use-default, don't even ask, just use the last
  14505. \"[PROPERTY]: [value]\" string from the history."
  14506. (interactive "P")
  14507. (let* ((completion-ignore-case t)
  14508. (pv (or (and use-last org-last-set-property-value)
  14509. (org-completing-read
  14510. "Enter a \"[Property]: [value]\" pair: "
  14511. nil nil nil nil nil
  14512. org-last-set-property-value)))
  14513. prop val)
  14514. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14515. (setq prop (match-string 1 pv)
  14516. val (match-string 2 pv))
  14517. (org-set-property prop val))))
  14518. (defun org-set-property (property value)
  14519. "In the current entry, set PROPERTY to VALUE.
  14520. When called interactively, this will prompt for a property name, offering
  14521. completion on existing and default properties. And then it will prompt
  14522. for a value, offering completion either on allowed values (via an inherited
  14523. xxx_ALL property) or on existing values in other instances of this property
  14524. in the current file.
  14525. Throw an error when trying to set a property with an invalid name."
  14526. (interactive (list nil nil))
  14527. (let ((property (or property (org-read-property-name))))
  14528. ;; `org-entry-put' also makes the following check, but this one
  14529. ;; avoids polluting `org-last-set-property' and
  14530. ;; `org-last-set-property-value' needlessly.
  14531. (unless (org--valid-property-p property)
  14532. (user-error "Invalid property name: \"%s\"" property))
  14533. (let ((value (or value (org-read-property-value property)))
  14534. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14535. (setq org-last-set-property property)
  14536. (setq org-last-set-property-value (concat property ": " value))
  14537. ;; Possibly postprocess the inserted value:
  14538. (when fn (setq value (funcall fn value)))
  14539. (unless (equal (org-entry-get nil property) value)
  14540. (org-entry-put nil property value)))))
  14541. (defun org-find-property (property &optional value)
  14542. "Find first entry in buffer that sets PROPERTY.
  14543. When optional argument VALUE is non-nil, only consider an entry
  14544. if it contains PROPERTY set to this value. If PROPERTY should be
  14545. explicitly set to nil, use string \"nil\" for VALUE.
  14546. Return position where the entry begins, or nil if there is no
  14547. such entry. If narrowing is in effect, only search the visible
  14548. part of the buffer."
  14549. (save-excursion
  14550. (goto-char (point-min))
  14551. (let ((case-fold-search t)
  14552. (re (org-re-property property nil (not value) value)))
  14553. (catch 'exit
  14554. (while (re-search-forward re nil t)
  14555. (when (if value (org-at-property-p)
  14556. (org-entry-get (point) property nil t))
  14557. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14558. (defun org-delete-property (property)
  14559. "In the current entry, delete PROPERTY."
  14560. (interactive
  14561. (let* ((completion-ignore-case t)
  14562. (cat (org-entry-get (point) "CATEGORY"))
  14563. (props0 (org-entry-properties nil 'standard))
  14564. (props (if cat props0
  14565. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14566. (prop (if (< 1 (length props))
  14567. (completing-read "Property: " props nil t)
  14568. (caar props))))
  14569. (list prop)))
  14570. (if (not property)
  14571. (message "No property to delete in this entry")
  14572. (org-entry-delete nil property)
  14573. (message "Property \"%s\" deleted" property)))
  14574. (defun org-delete-property-globally (property)
  14575. "Remove PROPERTY globally, from all entries.
  14576. This function ignores narrowing, if any."
  14577. (interactive
  14578. (let* ((completion-ignore-case t)
  14579. (prop (completing-read
  14580. "Globally remove property: "
  14581. (mapcar #'list (org-buffer-property-keys)))))
  14582. (list prop)))
  14583. (org-with-wide-buffer
  14584. (goto-char (point-min))
  14585. (let ((count 0)
  14586. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14587. (while (re-search-forward re nil t)
  14588. (when (org-entry-delete (point) property) (cl-incf count)))
  14589. (message "Property \"%s\" removed from %d entries" property count))))
  14590. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14591. (defun org-compute-property-at-point ()
  14592. "Compute the property at point.
  14593. This looks for an enclosing column format, extracts the operator and
  14594. then applies it to the property in the column format's scope."
  14595. (interactive)
  14596. (unless (org-at-property-p)
  14597. (user-error "Not at a property"))
  14598. (let ((prop (match-string-no-properties 2)))
  14599. (org-columns-get-format-and-top-level)
  14600. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14601. (user-error "No operator defined for property %s" prop))
  14602. (org-columns-compute prop)))
  14603. (defvar org-property-allowed-value-functions nil
  14604. "Hook for functions supplying allowed values for a specific property.
  14605. The functions must take a single argument, the name of the property, and
  14606. return a flat list of allowed values. If \":ETC\" is one of
  14607. the values, this means that these values are intended as defaults for
  14608. completion, but that other values should be allowed too.
  14609. The functions must return nil if they are not responsible for this
  14610. property.")
  14611. (defun org-property-get-allowed-values (pom property &optional table)
  14612. "Get allowed values for the property PROPERTY.
  14613. When TABLE is non-nil, return an alist that can directly be used for
  14614. completion."
  14615. (let (vals)
  14616. (cond
  14617. ((equal property "TODO")
  14618. (setq vals (org-with-point-at pom
  14619. (append org-todo-keywords-1 '("")))))
  14620. ((equal property "PRIORITY")
  14621. (let ((n org-lowest-priority))
  14622. (while (>= n org-highest-priority)
  14623. (push (char-to-string n) vals)
  14624. (setq n (1- n)))))
  14625. ((equal property "CATEGORY"))
  14626. ((member property org-special-properties))
  14627. ((setq vals (run-hook-with-args-until-success
  14628. 'org-property-allowed-value-functions property)))
  14629. (t
  14630. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14631. (when (and vals (string-match "\\S-" vals))
  14632. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14633. (setq vals (mapcar (lambda (x)
  14634. (cond ((stringp x) x)
  14635. ((numberp x) (number-to-string x))
  14636. ((symbolp x) (symbol-name x))
  14637. (t "???")))
  14638. vals)))))
  14639. (when (member ":ETC" vals)
  14640. (setq vals (remove ":ETC" vals))
  14641. (org-add-props (car vals) '(org-unrestricted t)))
  14642. (if table (mapcar 'list vals) vals)))
  14643. (defun org-property-previous-allowed-value (&optional _previous)
  14644. "Switch to the next allowed value for this property."
  14645. (interactive)
  14646. (org-property-next-allowed-value t))
  14647. (defun org-property-next-allowed-value (&optional previous)
  14648. "Switch to the next allowed value for this property."
  14649. (interactive)
  14650. (unless (org-at-property-p)
  14651. (user-error "Not at a property"))
  14652. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  14653. (key (match-string 2))
  14654. (value (match-string 3))
  14655. (allowed (or (org-property-get-allowed-values (point) key)
  14656. (and (member value '("[ ]" "[-]" "[X]"))
  14657. '("[ ]" "[X]"))))
  14658. (heading (save-match-data (nth 4 (org-heading-components))))
  14659. nval)
  14660. (unless allowed
  14661. (user-error "Allowed values for this property have not been defined"))
  14662. (when previous (setq allowed (reverse allowed)))
  14663. (when (member value allowed)
  14664. (setq nval (car (cdr (member value allowed)))))
  14665. (setq nval (or nval (car allowed)))
  14666. (when (equal nval value)
  14667. (user-error "Only one allowed value for this property"))
  14668. (org-at-property-p)
  14669. (replace-match (concat " :" key ": " nval) t t)
  14670. (org-indent-line)
  14671. (beginning-of-line 1)
  14672. (skip-chars-forward " \t")
  14673. (when (equal prop org-effort-property)
  14674. (org-refresh-property
  14675. '((effort . identity)
  14676. (effort-minutes . org-duration-to-minutes))
  14677. nval)
  14678. (when (string= org-clock-current-task heading)
  14679. (setq org-clock-effort nval)
  14680. (org-clock-update-mode-line)))
  14681. (run-hook-with-args 'org-property-changed-functions key nval)))
  14682. (defun org-find-olp (path &optional this-buffer)
  14683. "Return a marker pointing to the entry at outline path OLP.
  14684. If anything goes wrong, throw an error.
  14685. You can wrap this call to catch the error like this:
  14686. (condition-case msg
  14687. (org-mobile-locate-entry (match-string 4))
  14688. (error (nth 1 msg)))
  14689. The return value will then be either a string with the error message,
  14690. or a marker if everything is OK.
  14691. If THIS-BUFFER is set, the outline path does not contain a file,
  14692. only headings."
  14693. (let* ((file (if this-buffer buffer-file-name (pop path)))
  14694. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  14695. (level 1)
  14696. (lmin 1)
  14697. (lmax 1)
  14698. end found flevel)
  14699. (unless buffer (error "File not found :%s" file))
  14700. (with-current-buffer buffer
  14701. (unless (derived-mode-p 'org-mode)
  14702. (error "Buffer %s needs to be in Org mode" buffer))
  14703. (org-with-wide-buffer
  14704. (goto-char (point-min))
  14705. (dolist (heading path)
  14706. (let ((re (format org-complex-heading-regexp-format
  14707. (regexp-quote heading)))
  14708. (cnt 0))
  14709. (while (re-search-forward re end t)
  14710. (setq level (- (match-end 1) (match-beginning 1)))
  14711. (when (and (>= level lmin) (<= level lmax))
  14712. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  14713. (when (= cnt 0)
  14714. (error "Heading not found on level %d: %s" lmax heading))
  14715. (when (> cnt 1)
  14716. (error "Heading not unique on level %d: %s" lmax heading))
  14717. (goto-char found)
  14718. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  14719. (setq end (save-excursion (org-end-of-subtree t t)))))
  14720. (when (org-at-heading-p)
  14721. (point-marker))))))
  14722. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  14723. "Find node HEADING in BUFFER.
  14724. Return a marker to the heading if it was found, or nil if not.
  14725. If POS-ONLY is set, return just the position instead of a marker.
  14726. The heading text must match exact, but it may have a TODO keyword,
  14727. a priority cookie and tags in the standard locations."
  14728. (with-current-buffer (or buffer (current-buffer))
  14729. (org-with-wide-buffer
  14730. (goto-char (point-min))
  14731. (let (case-fold-search)
  14732. (when (re-search-forward
  14733. (format org-complex-heading-regexp-format
  14734. (regexp-quote heading)) nil t)
  14735. (if pos-only
  14736. (match-beginning 0)
  14737. (move-marker (make-marker) (match-beginning 0))))))))
  14738. (defun org-find-exact-heading-in-directory (heading &optional dir)
  14739. "Find Org node headline HEADING in all .org files in directory DIR.
  14740. When the target headline is found, return a marker to this location."
  14741. (let ((files (directory-files (or dir default-directory)
  14742. t "\\`[^.#].*\\.org\\'"))
  14743. visiting m buffer)
  14744. (catch 'found
  14745. (dolist (file files)
  14746. (message "trying %s" file)
  14747. (setq visiting (org-find-base-buffer-visiting file))
  14748. (setq buffer (or visiting (find-file-noselect file)))
  14749. (setq m (org-find-exact-headline-in-buffer
  14750. heading buffer))
  14751. (when (and (not m) (not visiting)) (kill-buffer buffer))
  14752. (and m (throw 'found m))))))
  14753. (defun org-find-entry-with-id (ident)
  14754. "Locate the entry that contains the ID property with exact value IDENT.
  14755. IDENT can be a string, a symbol or a number, this function will search for
  14756. the string representation of it.
  14757. Return the position where this entry starts, or nil if there is no such entry."
  14758. (interactive "sID: ")
  14759. (let ((id (cond
  14760. ((stringp ident) ident)
  14761. ((symbolp ident) (symbol-name ident))
  14762. ((numberp ident) (number-to-string ident))
  14763. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  14764. (org-with-wide-buffer (org-find-property "ID" id))))
  14765. ;;;; Timestamps
  14766. (defvar org-last-changed-timestamp nil)
  14767. (defvar org-last-inserted-timestamp nil
  14768. "The last time stamp inserted with `org-insert-time-stamp'.")
  14769. (defun org-time-stamp (arg &optional inactive)
  14770. "Prompt for a date/time and insert a time stamp.
  14771. If the user specifies a time like HH:MM or if this command is
  14772. called with at least one prefix argument, the time stamp contains
  14773. the date and the time. Otherwise, only the date is included.
  14774. All parts of a date not specified by the user are filled in from
  14775. the timestamp at point, if any, or the current date/time
  14776. otherwise.
  14777. If there is already a timestamp at the cursor, it is replaced.
  14778. With two universal prefix arguments, insert an active timestamp
  14779. with the current time without prompting the user.
  14780. When called from lisp, the timestamp is inactive if INACTIVE is
  14781. non-nil."
  14782. (interactive "P")
  14783. (let* ((ts (cond
  14784. ((org-at-date-range-p t)
  14785. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  14786. ((org-at-timestamp-p 'lax) (match-string 0))))
  14787. ;; Default time is either the timestamp at point or today.
  14788. ;; When entering a range, only the range start is considered.
  14789. (default-time (if (not ts) (current-time)
  14790. (apply #'encode-time (org-parse-time-string ts))))
  14791. (default-input (and ts (org-get-compact-tod ts)))
  14792. (repeater (and ts
  14793. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  14794. (match-string 0 ts)))
  14795. org-time-was-given
  14796. org-end-time-was-given
  14797. (time
  14798. (and (if (equal arg '(16)) (current-time)
  14799. ;; Preserve `this-command' and `last-command'.
  14800. (let ((this-command this-command)
  14801. (last-command last-command))
  14802. (org-read-date
  14803. arg 'totime nil nil default-time default-input
  14804. inactive))))))
  14805. (cond
  14806. ((and ts
  14807. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  14808. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  14809. (insert "--")
  14810. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  14811. (ts
  14812. ;; Make sure we're on a timestamp. When in the middle of a date
  14813. ;; range, move arbitrarily to range end.
  14814. (unless (org-at-timestamp-p 'lax)
  14815. (skip-chars-forward "-")
  14816. (org-at-timestamp-p 'lax))
  14817. (replace-match "")
  14818. (setq org-last-changed-timestamp
  14819. (org-insert-time-stamp
  14820. time (or org-time-was-given arg)
  14821. inactive nil nil (list org-end-time-was-given)))
  14822. (when repeater
  14823. (backward-char)
  14824. (insert " " repeater)
  14825. (setq org-last-changed-timestamp
  14826. (concat (substring org-last-inserted-timestamp 0 -1)
  14827. " " repeater ">")))
  14828. (message "Timestamp updated"))
  14829. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  14830. (t (org-insert-time-stamp
  14831. time (or org-time-was-given arg) inactive nil nil
  14832. (list org-end-time-was-given))))))
  14833. ;; FIXME: can we use this for something else, like computing time differences?
  14834. (defun org-get-compact-tod (s)
  14835. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  14836. (let* ((t1 (match-string 1 s))
  14837. (h1 (string-to-number (match-string 2 s)))
  14838. (m1 (string-to-number (match-string 3 s)))
  14839. (t2 (and (match-end 4) (match-string 5 s)))
  14840. (h2 (and t2 (string-to-number (match-string 6 s))))
  14841. (m2 (and t2 (string-to-number (match-string 7 s))))
  14842. dh dm)
  14843. (if (not t2)
  14844. t1
  14845. (setq dh (- h2 h1) dm (- m2 m1))
  14846. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  14847. (concat t1 "+" (number-to-string dh)
  14848. (and (/= 0 dm) (format ":%02d" dm)))))))
  14849. (defun org-time-stamp-inactive (&optional arg)
  14850. "Insert an inactive time stamp.
  14851. An inactive time stamp is enclosed in square brackets instead of angle
  14852. brackets. It is inactive in the sense that it does not trigger agenda entries,
  14853. does not link to the calendar and cannot be changed with the S-cursor keys.
  14854. So these are more for recording a certain time/date."
  14855. (interactive "P")
  14856. (org-time-stamp arg 'inactive))
  14857. (defvar org-date-ovl (make-overlay 1 1))
  14858. (overlay-put org-date-ovl 'face 'org-date-selected)
  14859. (delete-overlay org-date-ovl)
  14860. (defvar org-ans1) ; dynamically scoped parameter
  14861. (defvar org-ans2) ; dynamically scoped parameter
  14862. (defvar org-plain-time-of-day-regexp) ; defined below
  14863. (defvar org-overriding-default-time nil) ; dynamically scoped
  14864. (defvar org-read-date-overlay nil)
  14865. (defvar org-dcst nil) ; dynamically scoped
  14866. (defvar org-read-date-history nil)
  14867. (defvar org-read-date-final-answer nil)
  14868. (defvar org-read-date-analyze-futurep nil)
  14869. (defvar org-read-date-analyze-forced-year nil)
  14870. (defvar org-read-date-inactive)
  14871. (defvar org-read-date-minibuffer-local-map
  14872. (let* ((map (make-sparse-keymap)))
  14873. (set-keymap-parent map minibuffer-local-map)
  14874. (org-defkey map (kbd ".")
  14875. (lambda () (interactive)
  14876. ;; Are we at the beginning of the prompt?
  14877. (if (looking-back "^[^:]+: "
  14878. (let ((inhibit-field-text-motion t))
  14879. (line-beginning-position)))
  14880. (org-eval-in-calendar '(calendar-goto-today))
  14881. (insert "."))))
  14882. (org-defkey map (kbd "C-.")
  14883. (lambda () (interactive)
  14884. (org-eval-in-calendar '(calendar-goto-today))))
  14885. (org-defkey map [(meta shift left)]
  14886. (lambda () (interactive)
  14887. (org-eval-in-calendar '(calendar-backward-month 1))))
  14888. (org-defkey map [(meta shift right)]
  14889. (lambda () (interactive)
  14890. (org-eval-in-calendar '(calendar-forward-month 1))))
  14891. (org-defkey map [(meta shift up)]
  14892. (lambda () (interactive)
  14893. (org-eval-in-calendar '(calendar-backward-year 1))))
  14894. (org-defkey map [(meta shift down)]
  14895. (lambda () (interactive)
  14896. (org-eval-in-calendar '(calendar-forward-year 1))))
  14897. (org-defkey map [?\e (shift left)]
  14898. (lambda () (interactive)
  14899. (org-eval-in-calendar '(calendar-backward-month 1))))
  14900. (org-defkey map [?\e (shift right)]
  14901. (lambda () (interactive)
  14902. (org-eval-in-calendar '(calendar-forward-month 1))))
  14903. (org-defkey map [?\e (shift up)]
  14904. (lambda () (interactive)
  14905. (org-eval-in-calendar '(calendar-backward-year 1))))
  14906. (org-defkey map [?\e (shift down)]
  14907. (lambda () (interactive)
  14908. (org-eval-in-calendar '(calendar-forward-year 1))))
  14909. (org-defkey map [(shift up)]
  14910. (lambda () (interactive)
  14911. (org-eval-in-calendar '(calendar-backward-week 1))))
  14912. (org-defkey map [(shift down)]
  14913. (lambda () (interactive)
  14914. (org-eval-in-calendar '(calendar-forward-week 1))))
  14915. (org-defkey map [(shift left)]
  14916. (lambda () (interactive)
  14917. (org-eval-in-calendar '(calendar-backward-day 1))))
  14918. (org-defkey map [(shift right)]
  14919. (lambda () (interactive)
  14920. (org-eval-in-calendar '(calendar-forward-day 1))))
  14921. (org-defkey map "!"
  14922. (lambda () (interactive)
  14923. (org-eval-in-calendar '(diary-view-entries))
  14924. (message "")))
  14925. (org-defkey map ">"
  14926. (lambda () (interactive)
  14927. (org-eval-in-calendar '(calendar-scroll-left 1))))
  14928. (org-defkey map "<"
  14929. (lambda () (interactive)
  14930. (org-eval-in-calendar '(calendar-scroll-right 1))))
  14931. (org-defkey map "\C-v"
  14932. (lambda () (interactive)
  14933. (org-eval-in-calendar
  14934. '(calendar-scroll-left-three-months 1))))
  14935. (org-defkey map "\M-v"
  14936. (lambda () (interactive)
  14937. (org-eval-in-calendar
  14938. '(calendar-scroll-right-three-months 1))))
  14939. map)
  14940. "Keymap for minibuffer commands when using `org-read-date'.")
  14941. (defvar org-def)
  14942. (defvar org-defdecode)
  14943. (defvar org-with-time)
  14944. (defvar calendar-setup) ; Dynamically scoped.
  14945. (defun org-read-date (&optional with-time to-time from-string prompt
  14946. default-time default-input inactive)
  14947. "Read a date, possibly a time, and make things smooth for the user.
  14948. The prompt will suggest to enter an ISO date, but you can also enter anything
  14949. which will at least partially be understood by `parse-time-string'.
  14950. Unrecognized parts of the date will default to the current day, month, year,
  14951. hour and minute. If this command is called to replace a timestamp at point,
  14952. or to enter the second timestamp of a range, the default time is taken
  14953. from the existing stamp. Furthermore, the command prefers the future,
  14954. so if you are giving a date where the year is not given, and the day-month
  14955. combination is already past in the current year, it will assume you
  14956. mean next year. For details, see the manual. A few examples:
  14957. 3-2-5 --> 2003-02-05
  14958. feb 15 --> currentyear-02-15
  14959. 2/15 --> currentyear-02-15
  14960. sep 12 9 --> 2009-09-12
  14961. 12:45 --> today 12:45
  14962. 22 sept 0:34 --> currentyear-09-22 0:34
  14963. 12 --> currentyear-currentmonth-12
  14964. Fri --> nearest Friday after today
  14965. -Tue --> last Tuesday
  14966. etc.
  14967. Furthermore you can specify a relative date by giving, as the *first* thing
  14968. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  14969. change in days weeks, months, years.
  14970. With a single plus or minus, the date is relative to today. With a double
  14971. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  14972. +4d --> four days from today
  14973. +4 --> same as above
  14974. +2w --> two weeks from today
  14975. ++5 --> five days from default date
  14976. The function understands only English month and weekday abbreviations.
  14977. While prompting, a calendar is popped up - you can also select the
  14978. date with the mouse (button 1). The calendar shows a period of three
  14979. months. To scroll it to other months, use the keys `>' and `<'.
  14980. If you don't like the calendar, turn it off with
  14981. (setq org-read-date-popup-calendar nil)
  14982. With optional argument TO-TIME, the date will immediately be converted
  14983. to an internal time.
  14984. With an optional argument WITH-TIME, the prompt will suggest to
  14985. also insert a time. Note that when WITH-TIME is not set, you can
  14986. still enter a time, and this function will inform the calling routine
  14987. about this change. The calling routine may then choose to change the
  14988. format used to insert the time stamp into the buffer to include the time.
  14989. With optional argument FROM-STRING, read from this string instead from
  14990. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  14991. the time/date that is used for everything that is not specified by the
  14992. user."
  14993. (require 'parse-time)
  14994. (let* ((org-with-time with-time)
  14995. (org-time-stamp-rounding-minutes
  14996. (if (equal org-with-time '(16))
  14997. '(0 0)
  14998. org-time-stamp-rounding-minutes))
  14999. (org-dcst org-display-custom-times)
  15000. (ct (org-current-time))
  15001. (org-def (or org-overriding-default-time default-time ct))
  15002. (org-defdecode (decode-time org-def))
  15003. (cur-frame (selected-frame))
  15004. (mouse-autoselect-window nil) ; Don't let the mouse jump
  15005. (calendar-setup
  15006. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  15007. (calendar-move-hook nil)
  15008. (calendar-view-diary-initially-flag nil)
  15009. (calendar-view-holidays-initially-flag nil)
  15010. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15011. ;; Rationalize `org-def' and `org-defdecode', if required.
  15012. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15013. (setf (nth 2 org-defdecode) -1)
  15014. (setf (nth 1 org-defdecode) 59)
  15015. (setq org-def (apply #'encode-time org-defdecode))
  15016. (setq org-defdecode (decode-time org-def)))
  15017. (let* ((timestr (format-time-string
  15018. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  15019. org-def))
  15020. (prompt (concat (if prompt (concat prompt " ") "")
  15021. (format "Date+time [%s]: " timestr))))
  15022. (cond
  15023. (from-string (setq ans from-string))
  15024. (org-read-date-popup-calendar
  15025. (save-excursion
  15026. (save-window-excursion
  15027. (calendar)
  15028. (when (eq calendar-setup 'calendar-only)
  15029. (setq cal-frame
  15030. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15031. (select-frame cal-frame))
  15032. (org-eval-in-calendar '(setq cursor-type nil) t)
  15033. (unwind-protect
  15034. (progn
  15035. (calendar-forward-day (- (time-to-days org-def)
  15036. (calendar-absolute-from-gregorian
  15037. (calendar-current-date))))
  15038. (org-eval-in-calendar nil t)
  15039. (let* ((old-map (current-local-map))
  15040. (map (copy-keymap calendar-mode-map))
  15041. (minibuffer-local-map
  15042. (copy-keymap org-read-date-minibuffer-local-map)))
  15043. (org-defkey map (kbd "RET") 'org-calendar-select)
  15044. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15045. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15046. (unwind-protect
  15047. (progn
  15048. (use-local-map map)
  15049. (setq org-read-date-inactive inactive)
  15050. (add-hook 'post-command-hook 'org-read-date-display)
  15051. (setq org-ans0
  15052. (read-string prompt
  15053. default-input
  15054. 'org-read-date-history
  15055. nil))
  15056. ;; org-ans0: from prompt
  15057. ;; org-ans1: from mouse click
  15058. ;; org-ans2: from calendar motion
  15059. (setq ans
  15060. (concat org-ans0 " " (or org-ans1 org-ans2))))
  15061. (remove-hook 'post-command-hook 'org-read-date-display)
  15062. (use-local-map old-map)
  15063. (when org-read-date-overlay
  15064. (delete-overlay org-read-date-overlay)
  15065. (setq org-read-date-overlay nil)))))
  15066. (bury-buffer "*Calendar*")
  15067. (when cal-frame
  15068. (delete-frame cal-frame)
  15069. (select-frame-set-input-focus cur-frame))))))
  15070. (t ; Naked prompt only
  15071. (unwind-protect
  15072. (setq ans (read-string prompt default-input
  15073. 'org-read-date-history timestr))
  15074. (when org-read-date-overlay
  15075. (delete-overlay org-read-date-overlay)
  15076. (setq org-read-date-overlay nil))))))
  15077. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15078. (when org-read-date-analyze-forced-year
  15079. (message "Year was forced into %s"
  15080. (if org-read-date-force-compatible-dates
  15081. "compatible range (1970-2037)"
  15082. "range representable on this machine"))
  15083. (ding))
  15084. ;; One round trip to get rid of 34th of August and stuff like that....
  15085. (setq final (decode-time (apply 'encode-time final)))
  15086. (setq org-read-date-final-answer ans)
  15087. (if to-time
  15088. (apply 'encode-time final)
  15089. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15090. (format "%04d-%02d-%02d %02d:%02d"
  15091. (nth 5 final) (nth 4 final) (nth 3 final)
  15092. (nth 2 final) (nth 1 final))
  15093. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15094. (defun org-read-date-display ()
  15095. "Display the current date prompt interpretation in the minibuffer."
  15096. (when org-read-date-display-live
  15097. (when org-read-date-overlay
  15098. (delete-overlay org-read-date-overlay))
  15099. (when (minibufferp (current-buffer))
  15100. (save-excursion
  15101. (end-of-line 1)
  15102. (while (not (equal (buffer-substring
  15103. (max (point-min) (- (point) 4)) (point))
  15104. " "))
  15105. (insert " ")))
  15106. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15107. " " (or org-ans1 org-ans2)))
  15108. (org-end-time-was-given nil)
  15109. (f (org-read-date-analyze ans org-def org-defdecode))
  15110. (fmts (if org-dcst
  15111. org-time-stamp-custom-formats
  15112. org-time-stamp-formats))
  15113. (fmt (if (or org-with-time
  15114. (and (boundp 'org-time-was-given) org-time-was-given))
  15115. (cdr fmts)
  15116. (car fmts)))
  15117. (txt (format-time-string fmt (apply 'encode-time f)))
  15118. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15119. (txt (concat "=> " txt)))
  15120. (when (and org-end-time-was-given
  15121. (string-match org-plain-time-of-day-regexp txt))
  15122. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15123. org-end-time-was-given
  15124. (substring txt (match-end 0)))))
  15125. (when org-read-date-analyze-futurep
  15126. (setq txt (concat txt " (=>F)")))
  15127. (setq org-read-date-overlay
  15128. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15129. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15130. (defun org-read-date-analyze (ans def defdecode)
  15131. "Analyze the combined answer of the date prompt."
  15132. ;; FIXME: cleanup and comment
  15133. ;; Pass `current-time' result to `decode-time' (instead of calling
  15134. ;; without arguments) so that only `current-time' has to be
  15135. ;; overridden in tests.
  15136. (let ((org-def def)
  15137. (org-defdecode defdecode)
  15138. (nowdecode (decode-time (current-time)))
  15139. delta deltan deltaw deltadef year month day
  15140. hour minute second wday pm h2 m2 tl wday1
  15141. iso-year iso-weekday iso-week iso-date futurep kill-year)
  15142. (setq org-read-date-analyze-futurep nil
  15143. org-read-date-analyze-forced-year nil)
  15144. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15145. (setq ans "+0"))
  15146. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15147. (setq ans (replace-match "" t t ans)
  15148. deltan (car delta)
  15149. deltaw (nth 1 delta)
  15150. deltadef (nth 2 delta)))
  15151. ;; Check if there is an iso week date in there. If yes, store the
  15152. ;; info and postpone interpreting it until the rest of the parsing
  15153. ;; is done.
  15154. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15155. (setq iso-year (when (match-end 1)
  15156. (org-small-year-to-year
  15157. (string-to-number (match-string 1 ans))))
  15158. iso-weekday (when (match-end 3)
  15159. (string-to-number (match-string 3 ans)))
  15160. iso-week (string-to-number (match-string 2 ans)))
  15161. (setq ans (replace-match "" t t ans)))
  15162. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15163. (when (string-match
  15164. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15165. (setq year (if (match-end 2)
  15166. (string-to-number (match-string 2 ans))
  15167. (progn (setq kill-year t)
  15168. (string-to-number (format-time-string "%Y"))))
  15169. month (string-to-number (match-string 3 ans))
  15170. day (string-to-number (match-string 4 ans)))
  15171. (setq year (org-small-year-to-year year))
  15172. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15173. t nil ans)))
  15174. ;; Help matching dotted european dates
  15175. (when (string-match
  15176. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15177. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15178. (setq kill-year t)
  15179. (string-to-number (format-time-string "%Y")))
  15180. day (string-to-number (match-string 1 ans))
  15181. month (string-to-number (match-string 2 ans))
  15182. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15183. t nil ans)))
  15184. ;; Help matching american dates, like 5/30 or 5/30/7
  15185. (when (string-match
  15186. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15187. (setq year (if (match-end 4)
  15188. (string-to-number (match-string 4 ans))
  15189. (progn (setq kill-year t)
  15190. (string-to-number (format-time-string "%Y"))))
  15191. month (string-to-number (match-string 1 ans))
  15192. day (string-to-number (match-string 2 ans)))
  15193. (setq year (org-small-year-to-year year))
  15194. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15195. t nil ans)))
  15196. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15197. ;; If there is a time with am/pm, and *no* time without it, we convert
  15198. ;; so that matching will be successful.
  15199. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  15200. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15201. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15202. (setq hour (string-to-number (match-string 1 ans))
  15203. minute (if (match-end 3)
  15204. (string-to-number (match-string 3 ans))
  15205. 0)
  15206. pm (equal ?p
  15207. (string-to-char (downcase (match-string 4 ans)))))
  15208. (if (and (= hour 12) (not pm))
  15209. (setq hour 0)
  15210. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15211. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15212. t t ans))))
  15213. ;; Check if a time range is given as a duration
  15214. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15215. (setq hour (string-to-number (match-string 1 ans))
  15216. h2 (+ hour (string-to-number (match-string 3 ans)))
  15217. minute (string-to-number (match-string 2 ans))
  15218. m2 (+ minute (if (match-end 5) (string-to-number
  15219. (match-string 5 ans))0)))
  15220. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15221. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15222. t t ans)))
  15223. ;; Check if there is a time range
  15224. (when (boundp 'org-end-time-was-given)
  15225. (setq org-time-was-given nil)
  15226. (when (and (string-match org-plain-time-of-day-regexp ans)
  15227. (match-end 8))
  15228. (setq org-end-time-was-given (match-string 8 ans))
  15229. (setq ans (concat (substring ans 0 (match-beginning 7))
  15230. (substring ans (match-end 7))))))
  15231. (setq tl (parse-time-string ans)
  15232. day (or (nth 3 tl) (nth 3 org-defdecode))
  15233. month
  15234. (cond ((nth 4 tl))
  15235. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15236. ;; Day was specified. Make sure DAY+MONTH
  15237. ;; combination happens in the future.
  15238. ((nth 3 tl)
  15239. (setq futurep t)
  15240. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15241. (nth 4 nowdecode)))
  15242. (t (nth 4 org-defdecode)))
  15243. year
  15244. (cond ((and (not kill-year) (nth 5 tl)))
  15245. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15246. ;; Month was guessed in the future and is at least
  15247. ;; equal to NOWDECODE's. Fix year accordingly.
  15248. (futurep
  15249. (if (or (> month (nth 4 nowdecode))
  15250. (>= day (nth 3 nowdecode)))
  15251. (nth 5 nowdecode)
  15252. (1+ (nth 5 nowdecode))))
  15253. ;; Month was specified. Make sure MONTH+YEAR
  15254. ;; combination happens in the future.
  15255. ((nth 4 tl)
  15256. (setq futurep t)
  15257. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15258. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15259. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15260. (t (nth 5 nowdecode))))
  15261. (t (nth 5 org-defdecode)))
  15262. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15263. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15264. second (or (nth 0 tl) 0)
  15265. wday (nth 6 tl))
  15266. (when (and (eq org-read-date-prefer-future 'time)
  15267. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15268. (equal day (nth 3 nowdecode))
  15269. (equal month (nth 4 nowdecode))
  15270. (equal year (nth 5 nowdecode))
  15271. (nth 2 tl)
  15272. (or (< (nth 2 tl) (nth 2 nowdecode))
  15273. (and (= (nth 2 tl) (nth 2 nowdecode))
  15274. (nth 1 tl)
  15275. (< (nth 1 tl) (nth 1 nowdecode)))))
  15276. (setq day (1+ day)
  15277. futurep t))
  15278. ;; Special date definitions below
  15279. (cond
  15280. (iso-week
  15281. ;; There was an iso week
  15282. (require 'cal-iso)
  15283. (setq futurep nil)
  15284. (setq year (or iso-year year)
  15285. day (or iso-weekday wday 1)
  15286. wday nil ; to make sure that the trigger below does not match
  15287. iso-date (calendar-gregorian-from-absolute
  15288. (calendar-iso-to-absolute
  15289. (list iso-week day year))))
  15290. ; FIXME: Should we also push ISO weeks into the future?
  15291. ; (when (and org-read-date-prefer-future
  15292. ; (not iso-year)
  15293. ; (< (calendar-absolute-from-gregorian iso-date)
  15294. ; (time-to-days (current-time))))
  15295. ; (setq year (1+ year)
  15296. ; iso-date (calendar-gregorian-from-absolute
  15297. ; (calendar-iso-to-absolute
  15298. ; (list iso-week day year)))))
  15299. (setq month (car iso-date)
  15300. year (nth 2 iso-date)
  15301. day (nth 1 iso-date)))
  15302. (deltan
  15303. (setq futurep nil)
  15304. (unless deltadef
  15305. ;; Pass `current-time' result to `decode-time' (instead of
  15306. ;; calling without arguments) so that only `current-time' has
  15307. ;; to be overridden in tests.
  15308. (let ((now (decode-time (current-time))))
  15309. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15310. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15311. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15312. ((equal deltaw "m") (setq month (+ month deltan)))
  15313. ((equal deltaw "y") (setq year (+ year deltan)))))
  15314. ((and wday (not (nth 3 tl)))
  15315. ;; Weekday was given, but no day, so pick that day in the week
  15316. ;; on or after the derived date.
  15317. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15318. (unless (equal wday wday1)
  15319. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15320. (when (and (boundp 'org-time-was-given)
  15321. (nth 2 tl))
  15322. (setq org-time-was-given t))
  15323. (when (< year 100) (setq year (+ 2000 year)))
  15324. ;; Check of the date is representable
  15325. (if org-read-date-force-compatible-dates
  15326. (progn
  15327. (when (< year 1970)
  15328. (setq year 1970 org-read-date-analyze-forced-year t))
  15329. (when (> year 2037)
  15330. (setq year 2037 org-read-date-analyze-forced-year t)))
  15331. (condition-case nil
  15332. (ignore (encode-time second minute hour day month year))
  15333. (error
  15334. (setq year (nth 5 org-defdecode))
  15335. (setq org-read-date-analyze-forced-year t))))
  15336. (setq org-read-date-analyze-futurep futurep)
  15337. (list second minute hour day month year)))
  15338. (defvar parse-time-weekdays)
  15339. (defun org-read-date-get-relative (s today default)
  15340. "Check string S for special relative date string.
  15341. TODAY and DEFAULT are internal times, for today and for a default.
  15342. Return shift list (N what def-flag)
  15343. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15344. N is the number of WHATs to shift.
  15345. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15346. the DEFAULT date rather than TODAY."
  15347. (require 'parse-time)
  15348. (when (and
  15349. (string-match
  15350. (concat
  15351. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15352. "\\([0-9]+\\)?"
  15353. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15354. "\\([ \t]\\|$\\)") s)
  15355. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15356. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15357. (string-to-char (substring (match-string 1 s) -1))
  15358. ?+))
  15359. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15360. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15361. (what (if (match-end 3) (match-string 3 s) "d"))
  15362. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15363. (date (if rel default today))
  15364. (wday (nth 6 (decode-time date)))
  15365. delta)
  15366. (if wday1
  15367. (progn
  15368. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15369. (when (= delta 0) (setq delta 7))
  15370. (when (= dir ?-)
  15371. (setq delta (- delta 7))
  15372. (when (= delta 0) (setq delta -7)))
  15373. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15374. (list delta "d" rel))
  15375. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15376. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15377. "Turn a user-specified date into the internal representation.
  15378. The internal representation needed by the calendar is (month day year).
  15379. This is a wrapper to handle the brain-dead convention in calendar that
  15380. user function argument order change dependent on argument order."
  15381. (pcase calendar-date-style
  15382. (`american (list arg1 arg2 arg3))
  15383. (`european (list arg2 arg1 arg3))
  15384. (`iso (list arg2 arg3 arg1))))
  15385. (defun org-eval-in-calendar (form &optional keepdate)
  15386. "Eval FORM in the calendar window and return to current window.
  15387. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15388. (let ((sf (selected-frame))
  15389. (sw (selected-window)))
  15390. (select-window (get-buffer-window "*Calendar*" t))
  15391. (eval form)
  15392. (when (and (not keepdate) (calendar-cursor-to-date))
  15393. (let* ((date (calendar-cursor-to-date))
  15394. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15395. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15396. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15397. (select-window sw)
  15398. (select-frame-set-input-focus sf)))
  15399. (defun org-calendar-select ()
  15400. "Return to `org-read-date' with the date currently selected.
  15401. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15402. (interactive)
  15403. (when (calendar-cursor-to-date)
  15404. (let* ((date (calendar-cursor-to-date))
  15405. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15406. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15407. (when (active-minibuffer-window) (exit-minibuffer))))
  15408. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15409. "Insert a date stamp for the date given by the internal TIME.
  15410. See `format-time-string' for the format of TIME.
  15411. WITH-HM means use the stamp format that includes the time of the day.
  15412. INACTIVE means use square brackets instead of angular ones, so that the
  15413. stamp will not contribute to the agenda.
  15414. PRE and POST are optional strings to be inserted before and after the
  15415. stamp.
  15416. The command returns the inserted time stamp."
  15417. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15418. stamp)
  15419. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15420. (insert-before-markers (or pre ""))
  15421. (when (listp extra)
  15422. (setq extra (car extra))
  15423. (if (and (stringp extra)
  15424. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15425. (setq extra (format "-%02d:%02d"
  15426. (string-to-number (match-string 1 extra))
  15427. (string-to-number (match-string 2 extra))))
  15428. (setq extra nil)))
  15429. (when extra
  15430. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15431. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15432. (insert-before-markers (or post ""))
  15433. (setq org-last-inserted-timestamp stamp)))
  15434. (defun org-toggle-time-stamp-overlays ()
  15435. "Toggle the use of custom time stamp formats."
  15436. (interactive)
  15437. (setq org-display-custom-times (not org-display-custom-times))
  15438. (unless org-display-custom-times
  15439. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15440. (while (setq p (next-single-property-change p 'display))
  15441. (when (and (get-text-property p 'display)
  15442. (eq (get-text-property p 'face) 'org-date))
  15443. (remove-text-properties
  15444. p (setq p (next-single-property-change p 'display))
  15445. '(display t))))
  15446. (set-buffer-modified-p bmp)))
  15447. (org-restart-font-lock)
  15448. (setq org-table-may-need-update t)
  15449. (if org-display-custom-times
  15450. (message "Time stamps are overlaid with custom format")
  15451. (message "Time stamp overlays removed")))
  15452. (defun org-display-custom-time (beg end)
  15453. "Overlay modified time stamp format over timestamp between BEG and END."
  15454. (let* ((ts (buffer-substring beg end))
  15455. t1 with-hm tf time str (off 0))
  15456. (save-match-data
  15457. (setq t1 (org-parse-time-string ts t))
  15458. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15459. (setq off (- (match-end 0) (match-beginning 0)))))
  15460. (setq end (- end off))
  15461. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  15462. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15463. time (org-fix-decoded-time t1)
  15464. str (org-add-props
  15465. (format-time-string
  15466. (substring tf 1 -1) (apply 'encode-time time))
  15467. nil 'mouse-face 'highlight))
  15468. (put-text-property beg end 'display str)))
  15469. (defun org-fix-decoded-time (time)
  15470. "Set 0 instead of nil for the first 6 elements of time.
  15471. Don't touch the rest."
  15472. (let ((n 0))
  15473. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15474. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15475. "Difference between TIMESTAMP-STRING and now in days.
  15476. If SECONDS is non-nil, return the difference in seconds."
  15477. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15478. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15479. (funcall fdiff (current-time)))))
  15480. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15481. "Is the time in TIMESTAMP-STRING close to the current date?"
  15482. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15483. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15484. (not (org-entry-is-done-p))))
  15485. (defun org-get-wdays (ts &optional delay zero-delay)
  15486. "Get the deadline lead time appropriate for timestring TS.
  15487. When DELAY is non-nil, get the delay time for scheduled items
  15488. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15489. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15490. don't try to find the delay cookie in the scheduled timestamp."
  15491. (let ((tv (if delay org-scheduled-delay-days
  15492. org-deadline-warning-days)))
  15493. (cond
  15494. ((or (and delay (< tv 0))
  15495. (and delay zero-delay (<= tv 0))
  15496. (and (not delay) (<= tv 0)))
  15497. ;; Enforce this value no matter what
  15498. (- tv))
  15499. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15500. ;; lead time is specified.
  15501. (floor (* (string-to-number (match-string 1 ts))
  15502. (cdr (assoc (match-string 2 ts)
  15503. '(("d" . 1) ("w" . 7)
  15504. ("m" . 30.4) ("y" . 365.25)
  15505. ("h" . 0.041667)))))))
  15506. ;; go for the default.
  15507. (t tv))))
  15508. (defun org-calendar-select-mouse (ev)
  15509. "Return to `org-read-date' with the date currently selected.
  15510. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15511. (interactive "e")
  15512. (mouse-set-point ev)
  15513. (when (calendar-cursor-to-date)
  15514. (let* ((date (calendar-cursor-to-date))
  15515. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15516. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15517. (when (active-minibuffer-window) (exit-minibuffer))))
  15518. (defun org-check-deadlines (ndays)
  15519. "Check if there are any deadlines due or past due.
  15520. A deadline is considered due if it happens within `org-deadline-warning-days'
  15521. days from today's date. If the deadline appears in an entry marked DONE,
  15522. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15523. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15524. are shown."
  15525. (interactive "P")
  15526. (let* ((org-warn-days
  15527. (cond
  15528. ((equal ndays '(4)) 100000)
  15529. (ndays (prefix-numeric-value ndays))
  15530. (t (abs org-deadline-warning-days))))
  15531. (case-fold-search nil)
  15532. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15533. (callback
  15534. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15535. (message "%d deadlines past-due or due within %d days"
  15536. (org-occur regexp nil callback)
  15537. org-warn-days)))
  15538. (defsubst org-re-timestamp (type)
  15539. "Return a regexp for timestamp TYPE.
  15540. Allowed values for TYPE are:
  15541. all: all timestamps
  15542. active: only active timestamps (<...>)
  15543. inactive: only inactive timestamps ([...])
  15544. scheduled: only scheduled timestamps
  15545. deadline: only deadline timestamps
  15546. closed: only closed time-stamps
  15547. When TYPE is nil, fall back on returning a regexp that matches
  15548. both scheduled and deadline timestamps."
  15549. (cl-case type
  15550. (all org-ts-regexp-both)
  15551. (active org-ts-regexp)
  15552. (inactive org-ts-regexp-inactive)
  15553. (scheduled org-scheduled-time-regexp)
  15554. (deadline org-deadline-time-regexp)
  15555. (closed org-closed-time-regexp)
  15556. (otherwise
  15557. (concat "\\<"
  15558. (regexp-opt (list org-deadline-string org-scheduled-string))
  15559. " *<\\([^>]+\\)>"))))
  15560. (defun org-check-before-date (d)
  15561. "Check if there are deadlines or scheduled entries before date D."
  15562. (interactive (list (org-read-date)))
  15563. (let* ((case-fold-search nil)
  15564. (regexp (org-re-timestamp org-ts-type))
  15565. (ts-type org-ts-type)
  15566. (callback
  15567. (lambda ()
  15568. (let ((match (match-string 1)))
  15569. (and (if (memq ts-type '(active inactive all))
  15570. (eq (org-element-type (save-excursion
  15571. (backward-char)
  15572. (org-element-context)))
  15573. 'timestamp)
  15574. (org-at-planning-p))
  15575. (time-less-p
  15576. (org-time-string-to-time match t)
  15577. (org-time-string-to-time d t)))))))
  15578. (message "%d entries before %s"
  15579. (org-occur regexp nil callback)
  15580. d)))
  15581. (defun org-check-after-date (d)
  15582. "Check if there are deadlines or scheduled entries after date D."
  15583. (interactive (list (org-read-date)))
  15584. (let* ((case-fold-search nil)
  15585. (regexp (org-re-timestamp org-ts-type))
  15586. (ts-type org-ts-type)
  15587. (callback
  15588. (lambda ()
  15589. (let ((match (match-string 1)))
  15590. (and (if (memq ts-type '(active inactive all))
  15591. (eq (org-element-type (save-excursion
  15592. (backward-char)
  15593. (org-element-context)))
  15594. 'timestamp)
  15595. (org-at-planning-p))
  15596. (not (time-less-p
  15597. (org-time-string-to-time match t)
  15598. (org-time-string-to-time d t))))))))
  15599. (message "%d entries after %s"
  15600. (org-occur regexp nil callback)
  15601. d)))
  15602. (defun org-check-dates-range (start-date end-date)
  15603. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15604. (interactive (list (org-read-date nil nil nil "Range starts")
  15605. (org-read-date nil nil nil "Range end")))
  15606. (let ((case-fold-search nil)
  15607. (regexp (org-re-timestamp org-ts-type))
  15608. (callback
  15609. (let ((type org-ts-type))
  15610. (lambda ()
  15611. (let ((match (match-string 1)))
  15612. (and
  15613. (if (memq type '(active inactive all))
  15614. (eq (org-element-type (save-excursion
  15615. (backward-char)
  15616. (org-element-context)))
  15617. 'timestamp)
  15618. (org-at-planning-p))
  15619. (not (time-less-p
  15620. (org-time-string-to-time match t)
  15621. (org-time-string-to-time start-date t)))
  15622. (time-less-p
  15623. (org-time-string-to-time match t)
  15624. (org-time-string-to-time end-date t))))))))
  15625. (message "%d entries between %s and %s"
  15626. (org-occur regexp nil callback) start-date end-date)))
  15627. (defun org-evaluate-time-range (&optional to-buffer)
  15628. "Evaluate a time range by computing the difference between start and end.
  15629. Normally the result is just printed in the echo area, but with prefix arg
  15630. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15631. If the time range is actually in a table, the result is inserted into the
  15632. next column.
  15633. For time difference computation, a year is assumed to be exactly 365
  15634. days in order to avoid rounding problems."
  15635. (interactive "P")
  15636. (or
  15637. (org-clock-update-time-maybe)
  15638. (save-excursion
  15639. (unless (org-at-date-range-p t)
  15640. (goto-char (point-at-bol))
  15641. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  15642. (unless (org-at-date-range-p t)
  15643. (user-error "Not at a time-stamp range, and none found in current line")))
  15644. (let* ((ts1 (match-string 1))
  15645. (ts2 (match-string 2))
  15646. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  15647. (match-end (match-end 0))
  15648. (time1 (org-time-string-to-time ts1))
  15649. (time2 (org-time-string-to-time ts2))
  15650. (t1 (float-time time1))
  15651. (t2 (float-time time2))
  15652. (diff (abs (- t2 t1)))
  15653. (negative (< (- t2 t1) 0))
  15654. ;; (ys (floor (* 365 24 60 60)))
  15655. (ds (* 24 60 60))
  15656. (hs (* 60 60))
  15657. (fy "%dy %dd %02d:%02d")
  15658. (fy1 "%dy %dd")
  15659. (fd "%dd %02d:%02d")
  15660. (fd1 "%dd")
  15661. (fh "%02d:%02d")
  15662. y d h m align)
  15663. (if havetime
  15664. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15665. y 0
  15666. d (floor (/ diff ds)) diff (mod diff ds)
  15667. h (floor (/ diff hs)) diff (mod diff hs)
  15668. m (floor (/ diff 60)))
  15669. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15670. y 0
  15671. d (floor (+ (/ diff ds) 0.5))
  15672. h 0 m 0))
  15673. (if (not to-buffer)
  15674. (message "%s" (org-make-tdiff-string y d h m))
  15675. (if (org-at-table-p)
  15676. (progn
  15677. (goto-char match-end)
  15678. (setq align t)
  15679. (and (looking-at " *|") (goto-char (match-end 0))))
  15680. (goto-char match-end))
  15681. (when (looking-at
  15682. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  15683. (replace-match ""))
  15684. (when negative (insert " -"))
  15685. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  15686. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  15687. (insert " " (format fh h m))))
  15688. (when align (org-table-align))
  15689. (message "Time difference inserted")))))
  15690. (defun org-make-tdiff-string (y d h m)
  15691. (let ((fmt "")
  15692. (l nil))
  15693. (when (> y 0)
  15694. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  15695. (push y l))
  15696. (when (> d 0)
  15697. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  15698. (push d l))
  15699. (when (> h 0)
  15700. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  15701. (push h l))
  15702. (when (> m 0)
  15703. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  15704. (push m l))
  15705. (apply 'format fmt (nreverse l))))
  15706. (defun org-time-string-to-time (s &optional zone)
  15707. "Convert timestamp string S into internal time.
  15708. The optional ZONE is omitted or nil for Emacs local time, t for
  15709. Universal Time, ‘wall’ for system wall clock time, or a string as
  15710. in the TZ environment variable."
  15711. (apply #'encode-time (org-parse-time-string s nil zone)))
  15712. (defun org-time-string-to-seconds (s &optional zone)
  15713. "Convert a timestamp string S into a number of seconds.
  15714. The optional ZONE is omitted or nil for Emacs local time, t for
  15715. Universal Time, ‘wall’ for system wall clock time, or a string as
  15716. in the TZ environment variable."
  15717. (float-time (org-time-string-to-time s zone)))
  15718. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  15719. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  15720. "Convert time stamp S to an absolute day number.
  15721. If DAYNR in non-nil, and there is a specifier for a cyclic time
  15722. stamp, get the closest date to DAYNR. If PREFER is
  15723. `past' (respectively `future') return a date past (respectively
  15724. after) or equal to DAYNR.
  15725. POS is the location of time stamp S, as a buffer position in
  15726. BUFFER.
  15727. Diary sexp timestamps are matched against DAYNR, when non-nil.
  15728. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  15729. signaled."
  15730. (cond
  15731. ((string-match "\\`%%\\((.*)\\)" s)
  15732. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  15733. ;; only able to match individual dates. If it fails, raise an
  15734. ;; error.
  15735. (if (and daynr
  15736. (org-diary-sexp-entry
  15737. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  15738. daynr
  15739. (signal 'org-diary-sexp-no-match (list s))))
  15740. (daynr (org-closest-date s daynr prefer))
  15741. (t (time-to-days
  15742. (condition-case errdata
  15743. (apply #'encode-time (org-parse-time-string s))
  15744. (error (error "Bad timestamp `%s'%s\nError was: %s"
  15745. s
  15746. (if (not (and buffer pos)) ""
  15747. (format-message " at %d in buffer `%s'" pos buffer))
  15748. (cdr errdata))))))))
  15749. (defun org-days-to-iso-week (days)
  15750. "Return the iso week number."
  15751. (require 'cal-iso)
  15752. (car (calendar-iso-from-absolute days)))
  15753. (defun org-small-year-to-year (year)
  15754. "Convert 2-digit years into 4-digit years.
  15755. YEAR is expanded into one of the 30 next years, if possible, or
  15756. into a past one. Any year larger than 99 is returned unchanged."
  15757. (if (>= year 100) year
  15758. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  15759. (century (/ current 100))
  15760. (offset (- year (% current 100))))
  15761. (cond ((> offset 30) (+ (* (1- century) 100) year))
  15762. ((> offset -70) (+ (* century 100) year))
  15763. (t (+ (* (1+ century) 100) year))))))
  15764. (defun org-time-from-absolute (d)
  15765. "Return the time corresponding to date D.
  15766. D may be an absolute day number, or a calendar-type list (month day year)."
  15767. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  15768. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  15769. (defvar org-agenda-current-date)
  15770. (defun org-calendar-holiday ()
  15771. "List of holidays, for Diary display in Org mode."
  15772. (require 'holidays)
  15773. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  15774. (and hl (mapconcat #'identity hl "; "))))
  15775. (defun org-diary-sexp-entry (sexp entry d)
  15776. "Process a SEXP diary ENTRY for date D."
  15777. (require 'diary-lib)
  15778. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  15779. ;; dynamically.
  15780. (let* ((sexp `(let ((entry ,entry)
  15781. (date ',d))
  15782. ,(car (read-from-string sexp))))
  15783. (result (if calendar-debug-sexp (eval sexp)
  15784. (condition-case nil
  15785. (eval sexp)
  15786. (error
  15787. (beep)
  15788. (message "Bad sexp at line %d in %s: %s"
  15789. (org-current-line)
  15790. (buffer-file-name) sexp)
  15791. (sleep-for 2))))))
  15792. (cond ((stringp result) (split-string result "; "))
  15793. ((and (consp result)
  15794. (not (consp (cdr result)))
  15795. (stringp (cdr result))) (cdr result))
  15796. ((and (consp result)
  15797. (stringp (car result))) result)
  15798. (result entry))))
  15799. (defun org-diary-to-ical-string (frombuf)
  15800. "Get iCalendar entries from diary entries in buffer FROMBUF.
  15801. This uses the icalendar.el library."
  15802. (let* ((tmpdir temporary-file-directory)
  15803. (tmpfile (make-temp-name
  15804. (expand-file-name "orgics" tmpdir)))
  15805. buf rtn b e)
  15806. (with-current-buffer frombuf
  15807. (icalendar-export-region (point-min) (point-max) tmpfile)
  15808. (setq buf (find-buffer-visiting tmpfile))
  15809. (set-buffer buf)
  15810. (goto-char (point-min))
  15811. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  15812. (setq b (match-beginning 0)))
  15813. (goto-char (point-max))
  15814. (when (re-search-backward "^END:VEVENT" nil t)
  15815. (setq e (match-end 0)))
  15816. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  15817. (kill-buffer buf)
  15818. (delete-file tmpfile)
  15819. rtn))
  15820. (defun org-closest-date (start current prefer)
  15821. "Return closest date to CURRENT starting from START.
  15822. CURRENT and START are both time stamps.
  15823. When PREFER is `past', return a date that is either CURRENT or
  15824. past. When PREFER is `future', return a date that is either
  15825. CURRENT or future.
  15826. Only time stamps with a repeater are modified. Any other time
  15827. stamp stay unchanged. In any case, return value is an absolute
  15828. day number."
  15829. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  15830. ;; No repeater. Do not shift time stamp.
  15831. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15832. (let ((value (string-to-number (match-string 1 start)))
  15833. (type (match-string 2 start)))
  15834. (if (= 0 value)
  15835. ;; Repeater with a 0-value is considered as void.
  15836. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15837. (let* ((base (org-date-to-gregorian start))
  15838. (target (org-date-to-gregorian current))
  15839. (sday (calendar-absolute-from-gregorian base))
  15840. (cday (calendar-absolute-from-gregorian target))
  15841. n1 n2)
  15842. ;; If START is already past CURRENT, just return START.
  15843. (if (<= cday sday) sday
  15844. ;; Compute closest date before (N1) and closest date past
  15845. ;; (N2) CURRENT.
  15846. (pcase type
  15847. ("h"
  15848. (let ((missing-hours
  15849. (mod (+ (- (* 24 (- cday sday))
  15850. (nth 2 (org-parse-time-string start)))
  15851. org-extend-today-until)
  15852. value)))
  15853. (setf n1 (if (= missing-hours 0) cday
  15854. (- cday (1+ (/ missing-hours 24)))))
  15855. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  15856. ((or "d" "w")
  15857. (let ((value (if (equal type "w") (* 7 value) value)))
  15858. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  15859. (setf n2 (+ n1 value))))
  15860. ("m"
  15861. (let* ((add-months
  15862. (lambda (d n)
  15863. ;; Add N months to gregorian date D, i.e.,
  15864. ;; a list (MONTH DAY YEAR). Return a valid
  15865. ;; gregorian date.
  15866. (let ((m (+ (nth 0 d) n)))
  15867. (list (mod m 12)
  15868. (nth 1 d)
  15869. (+ (/ m 12) (nth 2 d))))))
  15870. (months ; Complete months to TARGET.
  15871. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  15872. (- (nth 0 target) (nth 0 base))
  15873. ;; If START's day is greater than
  15874. ;; TARGET's, remove incomplete month.
  15875. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  15876. value)
  15877. value))
  15878. (before (funcall add-months base months)))
  15879. (setf n1 (calendar-absolute-from-gregorian before))
  15880. (setf n2
  15881. (calendar-absolute-from-gregorian
  15882. (funcall add-months before value)))))
  15883. (_
  15884. (let* ((d (nth 1 base))
  15885. (m (nth 0 base))
  15886. (y (nth 2 base))
  15887. (years ; Complete years to TARGET.
  15888. (* (/ (- (nth 2 target)
  15889. y
  15890. ;; If START's month and day are
  15891. ;; greater than TARGET's, remove
  15892. ;; incomplete year.
  15893. (if (or (> (nth 0 target) m)
  15894. (and (= (nth 0 target) m)
  15895. (> (nth 1 target) d)))
  15896. 0
  15897. 1))
  15898. value)
  15899. value))
  15900. (before (list m d (+ y years))))
  15901. (setf n1 (calendar-absolute-from-gregorian before))
  15902. (setf n2 (calendar-absolute-from-gregorian
  15903. (list m d (+ (nth 2 before) value)))))))
  15904. ;; Handle PREFER parameter, if any.
  15905. (cond
  15906. ((eq prefer 'past) (if (= cday n2) n2 n1))
  15907. ((eq prefer 'future) (if (= cday n1) n1 n2))
  15908. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  15909. (defun org-date-to-gregorian (d)
  15910. "Turn any specification of date D into a Gregorian date for the calendar."
  15911. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  15912. ((and (listp d) (= (length d) 3)) d)
  15913. ((stringp d)
  15914. (let ((d (org-parse-time-string d)))
  15915. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  15916. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  15917. (defun org-parse-time-string (s &optional nodefault zone)
  15918. "Parse the standard Org time string.
  15919. This should be a lot faster than the normal `parse-time-string'.
  15920. If time is not given, defaults to 0:00. However, with optional
  15921. NODEFAULT, hour and minute fields will be nil if not given.
  15922. The optional ZONE is omitted or nil for Emacs local time, t for
  15923. Universal Time, ‘wall’ for system wall clock time, or a string as
  15924. in the TZ environment variable."
  15925. (cond ((string-match org-ts-regexp0 s)
  15926. (list 0
  15927. (when (or (match-beginning 8) (not nodefault))
  15928. (string-to-number (or (match-string 8 s) "0")))
  15929. (when (or (match-beginning 7) (not nodefault))
  15930. (string-to-number (or (match-string 7 s) "0")))
  15931. (string-to-number (match-string 4 s))
  15932. (string-to-number (match-string 3 s))
  15933. (string-to-number (match-string 2 s))
  15934. nil nil zone))
  15935. ((string-match "^<[^>]+>$" s)
  15936. ;; FIXME: `decode-time' needs to be called with ZONE as its
  15937. ;; second argument. However, this requires at least Emacs
  15938. ;; 25.1. We can do it when we switch to this version as our
  15939. ;; minimal requirement.
  15940. (decode-time (seconds-to-time (org-matcher-time s))))
  15941. (t (error "Not a standard Org time string: %s" s))))
  15942. (defun org-timestamp-up (&optional arg)
  15943. "Increase the date item at the cursor by one.
  15944. If the cursor is on the year, change the year. If it is on the month,
  15945. the day or the time, change that.
  15946. With prefix ARG, change by that many units."
  15947. (interactive "p")
  15948. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  15949. (defun org-timestamp-down (&optional arg)
  15950. "Decrease the date item at the cursor by one.
  15951. If the cursor is on the year, change the year. If it is on the month,
  15952. the day or the time, change that.
  15953. With prefix ARG, change by that many units."
  15954. (interactive "p")
  15955. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  15956. (defun org-timestamp-up-day (&optional arg)
  15957. "Increase the date in the time stamp by one day.
  15958. With prefix ARG, change that many days."
  15959. (interactive "p")
  15960. (if (and (not (org-at-timestamp-p 'lax))
  15961. (org-at-heading-p))
  15962. (org-todo 'up)
  15963. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  15964. (defun org-timestamp-down-day (&optional arg)
  15965. "Decrease the date in the time stamp by one day.
  15966. With prefix ARG, change that many days."
  15967. (interactive "p")
  15968. (if (and (not (org-at-timestamp-p 'lax))
  15969. (org-at-heading-p))
  15970. (org-todo 'down)
  15971. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  15972. (defun org-at-timestamp-p (&optional extended)
  15973. "Non-nil if point is inside a timestamp.
  15974. By default, the function only consider syntactically valid active
  15975. timestamps. However, the caller may have a broader definition
  15976. for timestamps. As a consequence, optional argument EXTENDED can
  15977. be set to the following values
  15978. `inactive'
  15979. Include also syntactically valid inactive timestamps.
  15980. `agenda'
  15981. Include timestamps allowed in Agenda, i.e., those in
  15982. properties drawers, planning lines and clock lines.
  15983. `lax'
  15984. Ignore context. The function matches any part of the
  15985. document looking like a timestamp. This includes comments,
  15986. example blocks...
  15987. For backward-compatibility with Org 9.0, every other non-nil
  15988. value is equivalent to `inactive'.
  15989. When at a timestamp, return the position of the point as a symbol
  15990. among `bracket', `after', `year', `month', `hour', `minute',
  15991. `day' or a number of character from the last know part of the
  15992. time stamp.
  15993. When matching, the match groups are the following:
  15994. group 1: year
  15995. group 2: month
  15996. group 3: day number
  15997. group 4: day name
  15998. group 5: hours, if any
  15999. group 6: minutes, if any"
  16000. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  16001. (pos (point))
  16002. (match?
  16003. (let ((boundaries (org-in-regexp regexp)))
  16004. (save-match-data
  16005. (cond ((null boundaries) nil)
  16006. ((eq extended 'lax) t)
  16007. (t
  16008. (or (and (eq extended 'agenda)
  16009. (or (org-at-planning-p)
  16010. (org-at-property-p)
  16011. (and (bound-and-true-p
  16012. org-agenda-include-inactive-timestamps)
  16013. (org-at-clock-log-p))))
  16014. (eq 'timestamp
  16015. (save-excursion
  16016. (when (= pos (cdr boundaries)) (forward-char -1))
  16017. (org-element-type (org-element-context)))))))))))
  16018. (cond
  16019. ((not match?) nil)
  16020. ((= pos (match-beginning 0)) 'bracket)
  16021. ;; Distinguish location right before the closing bracket from
  16022. ;; right after it.
  16023. ((= pos (1- (match-end 0))) 'bracket)
  16024. ((= pos (match-end 0)) 'after)
  16025. ((org-pos-in-match-range pos 2) 'year)
  16026. ((org-pos-in-match-range pos 3) 'month)
  16027. ((org-pos-in-match-range pos 7) 'hour)
  16028. ((org-pos-in-match-range pos 8) 'minute)
  16029. ((or (org-pos-in-match-range pos 4)
  16030. (org-pos-in-match-range pos 5)) 'day)
  16031. ((and (> pos (or (match-end 8) (match-end 5)))
  16032. (< pos (match-end 0)))
  16033. (- pos (or (match-end 8) (match-end 5))))
  16034. (t 'day))))
  16035. (defun org-toggle-timestamp-type ()
  16036. "Toggle the type (<active> or [inactive]) of a time stamp."
  16037. (interactive)
  16038. (when (org-at-timestamp-p 'lax)
  16039. (let ((beg (match-beginning 0)) (end (match-end 0))
  16040. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16041. (save-excursion
  16042. (goto-char beg)
  16043. (while (re-search-forward "[][<>]" end t)
  16044. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16045. t t)))
  16046. (message "Timestamp is now %sactive"
  16047. (if (equal (char-after beg) ?<) "" "in")))))
  16048. (defun org-at-clock-log-p ()
  16049. "Non-nil if point is on a clock log line."
  16050. (and (org-match-line org-clock-line-re)
  16051. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  16052. (defvar org-clock-history) ; defined in org-clock.el
  16053. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16054. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16055. "Change the date in the time stamp at point.
  16056. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16057. `year', `minute', `second'. If WHAT is not given, the cursor position
  16058. in the timestamp determines what will be changed.
  16059. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16060. (let ((origin (point))
  16061. (timestamp? (org-at-timestamp-p 'lax))
  16062. origin-cat
  16063. with-hm inactive
  16064. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16065. extra rem
  16066. ts time time0 fixnext clrgx)
  16067. (unless timestamp? (user-error "Not at a timestamp"))
  16068. (if (and (not what) (eq timestamp? 'bracket))
  16069. (org-toggle-timestamp-type)
  16070. ;; Point isn't on brackets. Remember the part of the time-stamp
  16071. ;; the point was in. Indeed, size of time-stamps may change,
  16072. ;; but point must be kept in the same category nonetheless.
  16073. (setq origin-cat timestamp?)
  16074. (when (and (not what) (not (eq timestamp? 'day))
  16075. org-display-custom-times
  16076. (get-text-property (point) 'display)
  16077. (not (get-text-property (1- (point)) 'display)))
  16078. (setq timestamp? 'day))
  16079. (setq timestamp? (or what timestamp?)
  16080. inactive (= (char-after (match-beginning 0)) ?\[)
  16081. ts (match-string 0))
  16082. (replace-match "")
  16083. (when (string-match
  16084. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16085. ts)
  16086. (setq extra (match-string 1 ts))
  16087. (when suppress-tmp-delay
  16088. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16089. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16090. (setq with-hm t))
  16091. (setq time0 (org-parse-time-string ts))
  16092. (when (and updown
  16093. (eq timestamp? 'minute)
  16094. (not current-prefix-arg))
  16095. ;; This looks like s-up and s-down. Change by one rounding step.
  16096. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16097. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16098. (setcar (cdr time0) (+ (nth 1 time0)
  16099. (if (> n 0) (- rem) (- dm rem))))))
  16100. (setq time
  16101. (apply #'encode-time
  16102. (or (car time0) 0)
  16103. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  16104. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  16105. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  16106. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  16107. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  16108. (nthcdr 6 time0)))
  16109. (when (and (memq timestamp? '(hour minute))
  16110. extra
  16111. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16112. (setq extra (org-modify-ts-extra
  16113. extra
  16114. (if (eq timestamp? 'hour) 2 5)
  16115. n dm)))
  16116. (when (integerp timestamp?)
  16117. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  16118. (when (eq what 'calendar)
  16119. (let ((cal-date (org-get-date-from-calendar)))
  16120. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16121. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16122. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16123. (setcar time0 (or (car time0) 0))
  16124. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16125. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16126. (setq time (apply 'encode-time time0))))
  16127. ;; Insert the new time-stamp, and ensure point stays in the same
  16128. ;; category as before (i.e. not after the last position in that
  16129. ;; category).
  16130. (let ((pos (point)))
  16131. ;; Stay before inserted string. `save-excursion' is of no use.
  16132. (setq org-last-changed-timestamp
  16133. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16134. (goto-char pos))
  16135. (save-match-data
  16136. (looking-at org-ts-regexp3)
  16137. (goto-char
  16138. (pcase origin-cat
  16139. ;; `day' category ends before `hour' if any, or at the end
  16140. ;; of the day name.
  16141. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16142. (`hour (min (match-end 7) origin))
  16143. (`minute (min (1- (match-end 8)) origin))
  16144. ((pred integerp) (min (1- (match-end 0)) origin))
  16145. ;; Point was right after the time-stamp. However, the
  16146. ;; time-stamp length might have changed, so refer to
  16147. ;; (match-end 0) instead.
  16148. (`after (match-end 0))
  16149. ;; `year' and `month' have both fixed size: point couldn't
  16150. ;; have moved into another part.
  16151. (_ origin))))
  16152. ;; Update clock if on a CLOCK line.
  16153. (org-clock-update-time-maybe)
  16154. ;; Maybe adjust the closest clock in `org-clock-history'
  16155. (when org-clock-adjust-closest
  16156. (if (not (and (org-at-clock-log-p)
  16157. (< 1 (length (delq nil (mapcar 'marker-position
  16158. org-clock-history))))))
  16159. (message "No clock to adjust")
  16160. (cond ((save-excursion ; fix previous clock?
  16161. (re-search-backward org-ts-regexp0 nil t)
  16162. (looking-back (concat org-clock-string " \\[")
  16163. (line-beginning-position)))
  16164. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16165. ((save-excursion ; fix next clock?
  16166. (re-search-backward org-ts-regexp0 nil t)
  16167. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16168. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16169. (save-window-excursion
  16170. ;; Find closest clock to point, adjust the previous/next one in history
  16171. (let* ((p (save-excursion (org-back-to-heading t)))
  16172. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16173. (clfixnth
  16174. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16175. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16176. (if (not clfixpos)
  16177. (message "No clock to adjust")
  16178. (save-excursion
  16179. (org-goto-marker-or-bmk clfixpos)
  16180. (org-show-subtree)
  16181. (when (re-search-forward clrgx nil t)
  16182. (goto-char (match-beginning 1))
  16183. (let (org-clock-adjust-closest)
  16184. (org-timestamp-change n timestamp? updown))
  16185. (message "Clock adjusted in %s for heading: %s"
  16186. (file-name-nondirectory (buffer-file-name))
  16187. (org-get-heading t t)))))))))
  16188. ;; Try to recenter the calendar window, if any.
  16189. (when (and org-calendar-follow-timestamp-change
  16190. (get-buffer-window "*Calendar*" t)
  16191. (memq timestamp? '(day month year)))
  16192. (org-recenter-calendar (time-to-days time))))))
  16193. (defun org-modify-ts-extra (s pos n dm)
  16194. "Change the different parts of the lead-time and repeat fields in timestamp."
  16195. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16196. ng h m new rem)
  16197. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16198. (cond
  16199. ((or (org-pos-in-match-range pos 2)
  16200. (org-pos-in-match-range pos 3))
  16201. (setq m (string-to-number (match-string 3 s))
  16202. h (string-to-number (match-string 2 s)))
  16203. (if (org-pos-in-match-range pos 2)
  16204. (setq h (+ h n))
  16205. (setq n (* dm (with-no-warnings (signum n))))
  16206. (unless (= 0 (setq rem (% m dm)))
  16207. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16208. (setq m (+ m n)))
  16209. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16210. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16211. (setq h (mod h 24))
  16212. (setq ng 1 new (format "-%02d:%02d" h m)))
  16213. ((org-pos-in-match-range pos 6)
  16214. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16215. ((org-pos-in-match-range pos 5)
  16216. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16217. ((org-pos-in-match-range pos 9)
  16218. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16219. ((org-pos-in-match-range pos 8)
  16220. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16221. (when ng
  16222. (setq s (concat
  16223. (substring s 0 (match-beginning ng))
  16224. new
  16225. (substring s (match-end ng))))))
  16226. s))
  16227. (defun org-recenter-calendar (d)
  16228. "If the calendar is visible, recenter it to date D."
  16229. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16230. (when cwin
  16231. (let ((calendar-move-hook nil))
  16232. (with-selected-window cwin
  16233. (calendar-goto-date
  16234. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  16235. (defun org-goto-calendar (&optional arg)
  16236. "Go to the Emacs calendar at the current date.
  16237. If there is a time stamp in the current line, go to that date.
  16238. A prefix ARG can be used to force the current date."
  16239. (interactive "P")
  16240. (let ((calendar-move-hook nil)
  16241. (calendar-view-holidays-initially-flag nil)
  16242. (calendar-view-diary-initially-flag nil)
  16243. diff)
  16244. (when (or (org-at-timestamp-p 'lax)
  16245. (org-match-line (concat ".*" org-ts-regexp)))
  16246. (let ((d1 (time-to-days (current-time)))
  16247. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  16248. (setq diff (- d2 d1))))
  16249. (calendar)
  16250. (calendar-goto-today)
  16251. (when (and diff (not arg)) (calendar-forward-day diff))))
  16252. (defun org-get-date-from-calendar ()
  16253. "Return a list (month day year) of date at point in calendar."
  16254. (with-current-buffer "*Calendar*"
  16255. (save-match-data
  16256. (calendar-cursor-to-date))))
  16257. (defun org-date-from-calendar ()
  16258. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16259. If there is already a time stamp at the cursor position, update it."
  16260. (interactive)
  16261. (if (org-at-timestamp-p 'lax)
  16262. (org-timestamp-change 0 'calendar)
  16263. (let ((cal-date (org-get-date-from-calendar)))
  16264. (org-insert-time-stamp
  16265. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16266. (defcustom org-effort-durations
  16267. `(("min" . 1)
  16268. ("h" . 60)
  16269. ("d" . ,(* 60 8))
  16270. ("w" . ,(* 60 8 5))
  16271. ("m" . ,(* 60 8 5 4))
  16272. ("y" . ,(* 60 8 5 40)))
  16273. "Conversion factor to minutes for an effort modifier.
  16274. Each entry has the form (MODIFIER . MINUTES).
  16275. In an effort string, a number followed by MODIFIER is multiplied
  16276. by the specified number of MINUTES to obtain an effort in
  16277. minutes.
  16278. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16279. effort string \"2hours\" is equivalent to 120 minutes."
  16280. :group 'org-agenda
  16281. :version "26.1"
  16282. :package-version '(Org . "8.3")
  16283. :type '(alist :key-type (string :tag "Modifier")
  16284. :value-type (number :tag "Minutes")))
  16285. (defcustom org-image-actual-width t
  16286. "Should we use the actual width of images when inlining them?
  16287. When set to t, always use the image width.
  16288. When set to a number, use imagemagick (when available) to set
  16289. the image's width to this value.
  16290. When set to a number in a list, try to get the width from any
  16291. #+ATTR.* keyword if it matches a width specification like
  16292. #+ATTR_HTML: :width 300px
  16293. and fall back on that number if none is found.
  16294. When set to nil, try to get the width from an #+ATTR.* keyword
  16295. and fall back on the original width if none is found.
  16296. This requires Emacs >= 24.1, build with imagemagick support."
  16297. :group 'org-appearance
  16298. :version "24.4"
  16299. :package-version '(Org . "8.0")
  16300. :type '(choice
  16301. (const :tag "Use the image width" t)
  16302. (integer :tag "Use a number of pixels")
  16303. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16304. (const :tag "Use #+ATTR* or don't resize" nil)))
  16305. (defcustom org-agenda-inhibit-startup nil
  16306. "Inhibit startup when preparing agenda buffers.
  16307. When this variable is t, the initialization of the Org agenda
  16308. buffers is inhibited: e.g. the visibility state is not set, the
  16309. tables are not re-aligned, etc."
  16310. :type 'boolean
  16311. :version "24.3"
  16312. :group 'org-agenda)
  16313. (defcustom org-agenda-ignore-properties nil
  16314. "Avoid updating text properties when building the agenda.
  16315. Properties are used to prepare buffers for effort estimates,
  16316. appointments, statistics and subtree-local categories.
  16317. If you don't use these in the agenda, you can add them to this
  16318. list and agenda building will be a bit faster.
  16319. The value is a list, with zero or more of the symbols `effort', `appt',
  16320. `stats' or `category'."
  16321. :type '(set :greedy t
  16322. (const effort)
  16323. (const appt)
  16324. (const stats)
  16325. (const category))
  16326. :version "26.1"
  16327. :package-version '(Org . "8.3")
  16328. :group 'org-agenda)
  16329. ;;;; Files
  16330. (defun org-save-all-org-buffers ()
  16331. "Save all Org buffers without user confirmation."
  16332. (interactive)
  16333. (message "Saving all Org buffers...")
  16334. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16335. (when (featurep 'org-id) (org-id-locations-save))
  16336. (message "Saving all Org buffers... done"))
  16337. (defun org-revert-all-org-buffers ()
  16338. "Revert all Org buffers.
  16339. Prompt for confirmation when there are unsaved changes.
  16340. Be sure you know what you are doing before letting this function
  16341. overwrite your changes.
  16342. This function is useful in a setup where one tracks org files
  16343. with a version control system, to revert on one machine after pulling
  16344. changes from another. I believe the procedure must be like this:
  16345. 1. M-x org-save-all-org-buffers
  16346. 2. Pull changes from the other machine, resolve conflicts
  16347. 3. M-x org-revert-all-org-buffers"
  16348. (interactive)
  16349. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16350. (user-error "Abort"))
  16351. (save-excursion
  16352. (save-window-excursion
  16353. (dolist (b (buffer-list))
  16354. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16355. (with-current-buffer b buffer-file-name))
  16356. (pop-to-buffer-same-window b)
  16357. (revert-buffer t 'no-confirm)))
  16358. (when (and (featurep 'org-id) org-id-track-globally)
  16359. (org-id-locations-load)))))
  16360. ;;;; Agenda files
  16361. ;;;###autoload
  16362. (defun org-switchb (&optional arg)
  16363. "Switch between Org buffers.
  16364. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16365. With `\\[universal-argument] \\[universal-argument]' \
  16366. prefix, restrict available buffers to agenda files."
  16367. (interactive "P")
  16368. (let ((blist (org-buffer-list
  16369. (cond ((equal arg '(4)) 'files)
  16370. ((equal arg '(16)) 'agenda)))))
  16371. (pop-to-buffer-same-window
  16372. (completing-read "Org buffer: "
  16373. (mapcar #'list (mapcar #'buffer-name blist))
  16374. nil t))))
  16375. (defun org-buffer-list (&optional predicate exclude-tmp)
  16376. "Return a list of Org buffers.
  16377. PREDICATE can be `export', `files' or `agenda'.
  16378. export restrict the list to Export buffers.
  16379. files restrict the list to buffers visiting Org files.
  16380. agenda restrict the list to buffers visiting agenda files.
  16381. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16382. (let* ((bfn nil)
  16383. (agenda-files (and (eq predicate 'agenda)
  16384. (mapcar 'file-truename (org-agenda-files t))))
  16385. (filter
  16386. (cond
  16387. ((eq predicate 'files)
  16388. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16389. ((eq predicate 'export)
  16390. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16391. ((eq predicate 'agenda)
  16392. (lambda (b)
  16393. (with-current-buffer b
  16394. (and (derived-mode-p 'org-mode)
  16395. (setq bfn (buffer-file-name b))
  16396. (member (file-truename bfn) agenda-files)))))
  16397. (t (lambda (b) (with-current-buffer b
  16398. (or (derived-mode-p 'org-mode)
  16399. (string-match "\\*Org .*Export"
  16400. (buffer-name b)))))))))
  16401. (delq nil
  16402. (mapcar
  16403. (lambda(b)
  16404. (if (and (funcall filter b)
  16405. (or (not exclude-tmp)
  16406. (not (string-match "tmp" (buffer-name b)))))
  16407. b
  16408. nil))
  16409. (buffer-list)))))
  16410. (defun org-agenda-files (&optional unrestricted archives)
  16411. "Get the list of agenda files.
  16412. Optional UNRESTRICTED means return the full list even if a restriction
  16413. is currently in place.
  16414. When ARCHIVES is t, include all archive files that are really being
  16415. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16416. `org-agenda-archives-mode' is t."
  16417. (let ((files
  16418. (cond
  16419. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16420. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16421. ((listp org-agenda-files) org-agenda-files)
  16422. (t (error "Invalid value of `org-agenda-files'")))))
  16423. (setq files (apply 'append
  16424. (mapcar (lambda (f)
  16425. (if (file-directory-p f)
  16426. (directory-files
  16427. f t org-agenda-file-regexp)
  16428. (list f)))
  16429. files)))
  16430. (when org-agenda-skip-unavailable-files
  16431. (setq files (delq nil
  16432. (mapcar (function
  16433. (lambda (file)
  16434. (and (file-readable-p file) file)))
  16435. files))))
  16436. (when (or (eq archives t)
  16437. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16438. (setq files (org-add-archive-files files)))
  16439. files))
  16440. (defun org-agenda-file-p (&optional file)
  16441. "Return non-nil, if FILE is an agenda file.
  16442. If FILE is omitted, use the file associated with the current
  16443. buffer."
  16444. (let ((fname (or file (buffer-file-name))))
  16445. (and fname
  16446. (member (file-truename fname)
  16447. (mapcar #'file-truename (org-agenda-files t))))))
  16448. (defun org-edit-agenda-file-list ()
  16449. "Edit the list of agenda files.
  16450. Depending on setup, this either uses customize to edit the variable
  16451. `org-agenda-files', or it visits the file that is holding the list. In the
  16452. latter case, the buffer is set up in a way that saving it automatically kills
  16453. the buffer and restores the previous window configuration."
  16454. (interactive)
  16455. (if (stringp org-agenda-files)
  16456. (let ((cw (current-window-configuration)))
  16457. (find-file org-agenda-files)
  16458. (setq-local org-window-configuration cw)
  16459. (add-hook 'after-save-hook
  16460. (lambda ()
  16461. (set-window-configuration
  16462. (prog1 org-window-configuration
  16463. (kill-buffer (current-buffer))))
  16464. (org-install-agenda-files-menu)
  16465. (message "New agenda file list installed"))
  16466. nil 'local)
  16467. (message "%s" (substitute-command-keys
  16468. "Edit list and finish with \\[save-buffer]")))
  16469. (customize-variable 'org-agenda-files)))
  16470. (defun org-store-new-agenda-file-list (list)
  16471. "Set new value for the agenda file list and save it correctly."
  16472. (if (stringp org-agenda-files)
  16473. (let ((fe (org-read-agenda-file-list t)) b u)
  16474. (while (setq b (find-buffer-visiting org-agenda-files))
  16475. (kill-buffer b))
  16476. (with-temp-file org-agenda-files
  16477. (insert
  16478. (mapconcat
  16479. (lambda (f) ;; Keep un-expanded entries.
  16480. (if (setq u (assoc f fe))
  16481. (cdr u)
  16482. f))
  16483. list "\n")
  16484. "\n")))
  16485. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16486. (org-insert-mode-line-in-empty-file nil))
  16487. (setq org-agenda-files list)
  16488. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16489. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16490. "Read the list of agenda files from a file.
  16491. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16492. filenames, used by `org-store-new-agenda-file-list' to write back
  16493. un-expanded file names."
  16494. (when (file-directory-p org-agenda-files)
  16495. (error "`org-agenda-files' cannot be a single directory"))
  16496. (when (stringp org-agenda-files)
  16497. (with-temp-buffer
  16498. (insert-file-contents org-agenda-files)
  16499. (mapcar
  16500. (lambda (f)
  16501. (let ((e (expand-file-name (substitute-in-file-name f)
  16502. org-directory)))
  16503. (if pair-with-expansion
  16504. (cons e f)
  16505. e)))
  16506. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16507. ;;;###autoload
  16508. (defun org-cycle-agenda-files ()
  16509. "Cycle through the files in `org-agenda-files'.
  16510. If the current buffer visits an agenda file, find the next one in the list.
  16511. If the current buffer does not, find the first agenda file."
  16512. (interactive)
  16513. (let* ((fs (or (org-agenda-files t)
  16514. (user-error "No agenda files")))
  16515. (files (copy-sequence fs))
  16516. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16517. file)
  16518. (when tcf
  16519. (while (and (setq file (pop files))
  16520. (not (equal (file-truename file) tcf)))))
  16521. (find-file (car (or files fs)))
  16522. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16523. (defun org-agenda-file-to-front (&optional to-end)
  16524. "Move/add the current file to the top of the agenda file list.
  16525. If the file is not present in the list, it is added to the front. If it is
  16526. present, it is moved there. With optional argument TO-END, add/move to the
  16527. end of the list."
  16528. (interactive "P")
  16529. (let ((org-agenda-skip-unavailable-files nil)
  16530. (file-alist (mapcar (lambda (x)
  16531. (cons (file-truename x) x))
  16532. (org-agenda-files t)))
  16533. (ctf (file-truename
  16534. (or buffer-file-name
  16535. (user-error "Please save the current buffer to a file"))))
  16536. x had)
  16537. (setq x (assoc ctf file-alist) had x)
  16538. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16539. (if to-end
  16540. (setq file-alist (append (delq x file-alist) (list x)))
  16541. (setq file-alist (cons x (delq x file-alist))))
  16542. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16543. (org-install-agenda-files-menu)
  16544. (message "File %s to %s of agenda file list"
  16545. (if had "moved" "added") (if to-end "end" "front"))))
  16546. (defun org-remove-file (&optional file)
  16547. "Remove current file from the list of files in variable `org-agenda-files'.
  16548. These are the files which are being checked for agenda entries.
  16549. Optional argument FILE means use this file instead of the current."
  16550. (interactive)
  16551. (let* ((org-agenda-skip-unavailable-files nil)
  16552. (file (or file buffer-file-name
  16553. (user-error "Current buffer does not visit a file")))
  16554. (true-file (file-truename file))
  16555. (afile (abbreviate-file-name file))
  16556. (files (delq nil (mapcar
  16557. (lambda (x)
  16558. (unless (equal true-file
  16559. (file-truename x))
  16560. x))
  16561. (org-agenda-files t)))))
  16562. (if (not (= (length files) (length (org-agenda-files t))))
  16563. (progn
  16564. (org-store-new-agenda-file-list files)
  16565. (org-install-agenda-files-menu)
  16566. (message "Removed from Org Agenda list: %s" afile))
  16567. (message "File was not in list: %s (not removed)" afile))))
  16568. (defun org-file-menu-entry (file)
  16569. (vector file (list 'find-file file) t))
  16570. (defun org-check-agenda-file (file)
  16571. "Make sure FILE exists. If not, ask user what to do."
  16572. (unless (file-exists-p file)
  16573. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16574. (abbreviate-file-name file))
  16575. (let ((r (downcase (read-char-exclusive))))
  16576. (cond
  16577. ((equal r ?r)
  16578. (org-remove-file file)
  16579. (throw 'nextfile t))
  16580. (t (user-error "Abort"))))))
  16581. (defun org-get-agenda-file-buffer (file)
  16582. "Get an agenda buffer visiting FILE.
  16583. If the buffer needs to be created, add it to the list of buffers
  16584. which might be released later."
  16585. (let ((buf (org-find-base-buffer-visiting file)))
  16586. (if buf
  16587. buf ; just return it
  16588. ;; Make a new buffer and remember it
  16589. (setq buf (find-file-noselect file))
  16590. (when buf (push buf org-agenda-new-buffers))
  16591. buf)))
  16592. (defun org-release-buffers (blist)
  16593. "Release all buffers in list, asking the user for confirmation when needed.
  16594. When a buffer is unmodified, it is just killed. When modified, it is saved
  16595. \(if the user agrees) and then killed."
  16596. (let (file)
  16597. (dolist (buf blist)
  16598. (setq file (buffer-file-name buf))
  16599. (when (and (buffer-modified-p buf)
  16600. file
  16601. (y-or-n-p (format "Save file %s? " file)))
  16602. (with-current-buffer buf (save-buffer)))
  16603. (kill-buffer buf))))
  16604. (defun org-agenda-prepare-buffers (files)
  16605. "Create buffers for all agenda files, protect archived trees and comments."
  16606. (interactive)
  16607. (let ((pa '(:org-archived t))
  16608. (pc '(:org-comment t))
  16609. (pall '(:org-archived t :org-comment t))
  16610. (inhibit-read-only t)
  16611. (org-inhibit-startup org-agenda-inhibit-startup)
  16612. (rea (concat ":" org-archive-tag ":"))
  16613. re pos)
  16614. (setq org-tag-alist-for-agenda nil
  16615. org-tag-groups-alist-for-agenda nil)
  16616. (save-excursion
  16617. (save-restriction
  16618. (dolist (file files)
  16619. (catch 'nextfile
  16620. (if (bufferp file)
  16621. (set-buffer file)
  16622. (org-check-agenda-file file)
  16623. (set-buffer (org-get-agenda-file-buffer file)))
  16624. (widen)
  16625. (org-set-regexps-and-options 'tags-only)
  16626. (setq pos (point))
  16627. (or (memq 'category org-agenda-ignore-properties)
  16628. (org-refresh-category-properties))
  16629. (or (memq 'stats org-agenda-ignore-properties)
  16630. (org-refresh-stats-properties))
  16631. (or (memq 'effort org-agenda-ignore-properties)
  16632. (org-refresh-effort-properties))
  16633. (or (memq 'appt org-agenda-ignore-properties)
  16634. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16635. (setq org-todo-keywords-for-agenda
  16636. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16637. (setq org-done-keywords-for-agenda
  16638. (append org-done-keywords-for-agenda org-done-keywords))
  16639. (setq org-todo-keyword-alist-for-agenda
  16640. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16641. (setq org-tag-alist-for-agenda
  16642. (org-uniquify
  16643. (append org-tag-alist-for-agenda
  16644. org-current-tag-alist)))
  16645. ;; Merge current file's tag groups into global
  16646. ;; `org-tag-groups-alist-for-agenda'.
  16647. (when org-group-tags
  16648. (dolist (alist org-tag-groups-alist)
  16649. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  16650. (if old
  16651. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  16652. (push alist org-tag-groups-alist-for-agenda)))))
  16653. (org-with-silent-modifications
  16654. (save-excursion
  16655. (remove-text-properties (point-min) (point-max) pall)
  16656. (when org-agenda-skip-archived-trees
  16657. (goto-char (point-min))
  16658. (while (re-search-forward rea nil t)
  16659. (when (org-at-heading-p t)
  16660. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  16661. (goto-char (point-min))
  16662. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  16663. (while (re-search-forward re nil t)
  16664. (when (save-match-data (org-in-commented-heading-p t))
  16665. (add-text-properties
  16666. (match-beginning 0) (org-end-of-subtree t) pc)))))
  16667. (goto-char pos)))))
  16668. (setq org-todo-keywords-for-agenda
  16669. (org-uniquify org-todo-keywords-for-agenda))
  16670. (setq org-todo-keyword-alist-for-agenda
  16671. (org-uniquify org-todo-keyword-alist-for-agenda))))
  16672. ;;;; CDLaTeX minor mode
  16673. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  16674. "Keymap for the minor `org-cdlatex-mode'.")
  16675. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  16676. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  16677. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  16678. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  16679. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  16680. (defvar org-cdlatex-texmathp-advice-is-done nil
  16681. "Flag remembering if we have applied the advice to texmathp already.")
  16682. (define-minor-mode org-cdlatex-mode
  16683. "Toggle the minor `org-cdlatex-mode'.
  16684. This mode supports entering LaTeX environment and math in LaTeX fragments
  16685. in Org mode.
  16686. \\{org-cdlatex-mode-map}"
  16687. nil " OCDL" nil
  16688. (when org-cdlatex-mode
  16689. (require 'cdlatex)
  16690. (run-hooks 'cdlatex-mode-hook)
  16691. (cdlatex-compute-tables))
  16692. (unless org-cdlatex-texmathp-advice-is-done
  16693. (setq org-cdlatex-texmathp-advice-is-done t)
  16694. (defadvice texmathp (around org-math-always-on activate)
  16695. "Always return t in Org buffers.
  16696. This is because we want to insert math symbols without dollars even outside
  16697. the LaTeX math segments. If Org mode thinks that point is actually inside
  16698. an embedded LaTeX fragment, let `texmathp' do its job.
  16699. `\\[org-cdlatex-mode-map]'"
  16700. (interactive)
  16701. (let (p)
  16702. (cond
  16703. ((not (derived-mode-p 'org-mode)) ad-do-it)
  16704. ((eq this-command 'cdlatex-math-symbol)
  16705. (setq ad-return-value t
  16706. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  16707. (t
  16708. (let ((p (org-inside-LaTeX-fragment-p)))
  16709. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  16710. (setq ad-return-value t
  16711. texmathp-why '("Org mode embedded math" . 0))
  16712. (when p ad-do-it)))))))))
  16713. (defun turn-on-org-cdlatex ()
  16714. "Unconditionally turn on `org-cdlatex-mode'."
  16715. (org-cdlatex-mode 1))
  16716. (defun org-try-cdlatex-tab ()
  16717. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  16718. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  16719. - inside a LaTeX fragment, or
  16720. - after the first word in a line, where an abbreviation expansion could
  16721. insert a LaTeX environment."
  16722. (when org-cdlatex-mode
  16723. (cond
  16724. ;; Before any word on the line: No expansion possible.
  16725. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  16726. ;; Just after first word on the line: Expand it. Make sure it
  16727. ;; cannot happen on headlines, though.
  16728. ((save-excursion
  16729. (skip-chars-backward "a-zA-Z0-9*")
  16730. (skip-chars-backward " \t")
  16731. (and (bolp) (not (org-at-heading-p))))
  16732. (cdlatex-tab) t)
  16733. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  16734. (defun org-cdlatex-underscore-caret (&optional _arg)
  16735. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  16736. Revert to the normal definition outside of these fragments."
  16737. (interactive "P")
  16738. (if (org-inside-LaTeX-fragment-p)
  16739. (call-interactively 'cdlatex-sub-superscript)
  16740. (let (org-cdlatex-mode)
  16741. (call-interactively (key-binding (vector last-input-event))))))
  16742. (defun org-cdlatex-math-modify (&optional _arg)
  16743. "Execute `cdlatex-math-modify' in LaTeX fragments.
  16744. Revert to the normal definition outside of these fragments."
  16745. (interactive "P")
  16746. (if (org-inside-LaTeX-fragment-p)
  16747. (call-interactively 'cdlatex-math-modify)
  16748. (let (org-cdlatex-mode)
  16749. (call-interactively (key-binding (vector last-input-event))))))
  16750. (defun org-cdlatex-environment-indent (&optional environment item)
  16751. "Execute `cdlatex-environment' and indent the inserted environment.
  16752. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  16753. The inserted environment is indented to current indentation
  16754. unless point is at the beginning of the line, in which the
  16755. environment remains unintended."
  16756. (interactive)
  16757. ;; cdlatex-environment always return nil. Therefore, capture output
  16758. ;; first and determine if an environment was selected.
  16759. (let* ((beg (point-marker))
  16760. (end (copy-marker (point) t))
  16761. (inserted (progn
  16762. (ignore-errors (cdlatex-environment environment item))
  16763. (< beg end)))
  16764. ;; Figure out how many lines to move forward after the
  16765. ;; environment has been inserted.
  16766. (lines (when inserted
  16767. (save-excursion
  16768. (- (cl-loop while (< beg (point))
  16769. with x = 0
  16770. do (forward-line -1)
  16771. (cl-incf x)
  16772. finally return x)
  16773. (if (progn (goto-char beg)
  16774. (and (progn (skip-chars-forward " \t") (eolp))
  16775. (progn (skip-chars-backward " \t") (bolp))))
  16776. 1 0)))))
  16777. (env (org-trim (delete-and-extract-region beg end))))
  16778. (when inserted
  16779. ;; Get indentation of next line unless at column 0.
  16780. (let ((ind (if (bolp) 0
  16781. (save-excursion
  16782. (org-return-indent)
  16783. (prog1 (org-get-indentation)
  16784. (when (progn (skip-chars-forward " \t") (eolp))
  16785. (delete-region beg (point)))))))
  16786. (bol (progn (skip-chars-backward " \t") (bolp))))
  16787. ;; Insert a newline before environment unless at column zero
  16788. ;; to "escape" the current line. Insert a newline if
  16789. ;; something is one the same line as \end{ENVIRONMENT}.
  16790. (insert
  16791. (concat (unless bol "\n") env
  16792. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  16793. (unless (zerop ind)
  16794. (save-excursion
  16795. (goto-char beg)
  16796. (while (< (point) end)
  16797. (unless (eolp) (indent-line-to ind))
  16798. (forward-line))))
  16799. (goto-char beg)
  16800. (forward-line lines)
  16801. (indent-line-to ind)))
  16802. (set-marker beg nil)
  16803. (set-marker end nil)))
  16804. ;;;; LaTeX fragments
  16805. (defun org-inside-LaTeX-fragment-p ()
  16806. "Test if point is inside a LaTeX fragment.
  16807. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  16808. sequence appearing also before point.
  16809. Even though the matchers for math are configurable, this function assumes
  16810. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  16811. delimiters are skipped when they have been removed by customization.
  16812. The return value is nil, or a cons cell with the delimiter and the
  16813. position of this delimiter.
  16814. This function does a reasonably good job, but can locally be fooled by
  16815. for example currency specifications. For example it will assume being in
  16816. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  16817. fragments that are properly closed, but during editing, we have to live
  16818. with the uncertainty caused by missing closing delimiters. This function
  16819. looks only before point, not after."
  16820. (catch 'exit
  16821. (let ((pos (point))
  16822. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  16823. (lim (save-excursion (org-backward-paragraph) (point)))
  16824. dd-on str (start 0) m re)
  16825. (goto-char pos)
  16826. (when dodollar
  16827. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  16828. re (nth 1 (assoc "$" org-latex-regexps)))
  16829. (while (string-match re str start)
  16830. (cond
  16831. ((= (match-end 0) (length str))
  16832. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  16833. ((= (match-end 0) (- (length str) 5))
  16834. (throw 'exit nil))
  16835. (t (setq start (match-end 0))))))
  16836. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  16837. (goto-char pos)
  16838. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  16839. (and (match-beginning 2) (throw 'exit nil))
  16840. ;; count $$
  16841. (while (re-search-backward "\\$\\$" lim t)
  16842. (setq dd-on (not dd-on)))
  16843. (goto-char pos)
  16844. (when dd-on (cons "$$" m))))))
  16845. (defun org-inside-latex-macro-p ()
  16846. "Is point inside a LaTeX macro or its arguments?"
  16847. (save-match-data
  16848. (org-in-regexp
  16849. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  16850. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  16851. "Build an overlay between BEG and END using IMAGE file.
  16852. Argument IMAGETYPE is the extension of the displayed image,
  16853. as a string. It defaults to \"png\"."
  16854. (let ((ov (make-overlay beg end))
  16855. (imagetype (or (intern imagetype) 'png)))
  16856. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  16857. (overlay-put ov 'evaporate t)
  16858. (overlay-put ov
  16859. 'modification-hooks
  16860. (list (lambda (o _flag _beg _end &optional _l)
  16861. (delete-overlay o))))
  16862. (overlay-put ov
  16863. 'display
  16864. (list 'image :type imagetype :file image :ascent 'center))))
  16865. (defun org--list-latex-overlays (&optional beg end)
  16866. "List all Org LaTeX overlays in current buffer.
  16867. Limit to overlays between BEG and END when those are provided."
  16868. (cl-remove-if-not
  16869. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  16870. (overlays-in (or beg (point-min)) (or end (point-max)))))
  16871. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  16872. "Remove all overlays with LaTeX fragment images in current buffer.
  16873. When optional arguments BEG and END are non-nil, remove all
  16874. overlays between them instead. Return a non-nil value when some
  16875. overlays were removed, nil otherwise."
  16876. (let ((overlays (org--list-latex-overlays beg end)))
  16877. (mapc #'delete-overlay overlays)
  16878. overlays))
  16879. (defun org-toggle-latex-fragment (&optional arg)
  16880. "Preview the LaTeX fragment at point, or all locally or globally.
  16881. If the cursor is on a LaTeX fragment, create the image and overlay
  16882. it over the source code, if there is none. Remove it otherwise.
  16883. If there is no fragment at point, display all fragments in the
  16884. current section.
  16885. With prefix ARG, preview or clear image for all fragments in the
  16886. current subtree or in the whole buffer when used before the first
  16887. headline. With a prefix ARG `\\[universal-argument] \
  16888. \\[universal-argument]' preview or clear images
  16889. for all fragments in the buffer."
  16890. (interactive "P")
  16891. (when (display-graphic-p)
  16892. (catch 'exit
  16893. (save-excursion
  16894. (let (beg end msg)
  16895. (cond
  16896. ((or (equal arg '(16))
  16897. (and (equal arg '(4))
  16898. (org-with-limited-levels (org-before-first-heading-p))))
  16899. (if (org-remove-latex-fragment-image-overlays)
  16900. (progn (message "LaTeX fragments images removed from buffer")
  16901. (throw 'exit nil))
  16902. (setq msg "Creating images for buffer...")))
  16903. ((equal arg '(4))
  16904. (org-with-limited-levels (org-back-to-heading t))
  16905. (setq beg (point))
  16906. (setq end (progn (org-end-of-subtree t) (point)))
  16907. (if (org-remove-latex-fragment-image-overlays beg end)
  16908. (progn
  16909. (message "LaTeX fragment images removed from subtree")
  16910. (throw 'exit nil))
  16911. (setq msg "Creating images for subtree...")))
  16912. ((let ((datum (org-element-context)))
  16913. (when (memq (org-element-type datum)
  16914. '(latex-environment latex-fragment))
  16915. (setq beg (org-element-property :begin datum))
  16916. (setq end (org-element-property :end datum))
  16917. (if (org-remove-latex-fragment-image-overlays beg end)
  16918. (progn (message "LaTeX fragment image removed")
  16919. (throw 'exit nil))
  16920. (setq msg "Creating image...")))))
  16921. (t
  16922. (org-with-limited-levels
  16923. (setq beg (if (org-at-heading-p) (line-beginning-position)
  16924. (outline-previous-heading)
  16925. (point)))
  16926. (setq end (progn (outline-next-heading) (point)))
  16927. (if (org-remove-latex-fragment-image-overlays beg end)
  16928. (progn
  16929. (message "LaTeX fragment images removed from section")
  16930. (throw 'exit nil))
  16931. (setq msg "Creating images for section...")))))
  16932. (let ((file (buffer-file-name (buffer-base-buffer))))
  16933. (org-format-latex
  16934. (concat org-preview-latex-image-directory "org-ltximg")
  16935. beg end
  16936. ;; Emacs cannot overlay images from remote hosts. Create
  16937. ;; it in `temporary-file-directory' instead.
  16938. (if (or (not file) (file-remote-p file))
  16939. temporary-file-directory
  16940. default-directory)
  16941. 'overlays msg 'forbuffer org-preview-latex-default-process))
  16942. (message (concat msg "done")))))))
  16943. (defun org-format-latex
  16944. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  16945. "Replace LaTeX fragments with links to an image.
  16946. The function takes care of creating the replacement image.
  16947. Only consider fragments between BEG and END when those are
  16948. provided.
  16949. When optional argument OVERLAYS is non-nil, display the image on
  16950. top of the fragment instead of replacing it.
  16951. PROCESSING-TYPE is the conversion method to use, as a symbol.
  16952. Some of the options can be changed using the variable
  16953. `org-format-latex-options', which see."
  16954. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  16955. (unless (eq processing-type 'verbatim)
  16956. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  16957. (cnt 0)
  16958. checkdir-flag)
  16959. (goto-char (or beg (point-min)))
  16960. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  16961. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  16962. (overlay-recenter (or end (point-max))))
  16963. (while (re-search-forward math-regexp end t)
  16964. (unless (and overlays
  16965. (eq (get-char-property (point) 'org-overlay-type)
  16966. 'org-latex-overlay))
  16967. (let* ((context (org-element-context))
  16968. (type (org-element-type context)))
  16969. (when (memq type '(latex-environment latex-fragment))
  16970. (let ((block-type (eq type 'latex-environment))
  16971. (value (org-element-property :value context))
  16972. (beg (org-element-property :begin context))
  16973. (end (save-excursion
  16974. (goto-char (org-element-property :end context))
  16975. (skip-chars-backward " \r\t\n")
  16976. (point))))
  16977. (cond
  16978. ((eq processing-type 'mathjax)
  16979. ;; Prepare for MathJax processing.
  16980. (if (not (string-match "\\`\\$\\$?" value))
  16981. (goto-char end)
  16982. (delete-region beg end)
  16983. (if (string= (match-string 0 value) "$$")
  16984. (insert "\\[" (substring value 2 -2) "\\]")
  16985. (insert "\\(" (substring value 1 -1) "\\)"))))
  16986. ((assq processing-type org-preview-latex-process-alist)
  16987. ;; Process to an image.
  16988. (cl-incf cnt)
  16989. (goto-char beg)
  16990. (let* ((processing-info
  16991. (cdr (assq processing-type org-preview-latex-process-alist)))
  16992. (face (face-at-point))
  16993. ;; Get the colors from the face at point.
  16994. (fg
  16995. (let ((color (plist-get org-format-latex-options
  16996. :foreground)))
  16997. (if (and forbuffer (eq color 'auto))
  16998. (face-attribute face :foreground nil 'default)
  16999. color)))
  17000. (bg
  17001. (let ((color (plist-get org-format-latex-options
  17002. :background)))
  17003. (if (and forbuffer (eq color 'auto))
  17004. (face-attribute face :background nil 'default)
  17005. color)))
  17006. (hash (sha1 (prin1-to-string
  17007. (list org-format-latex-header
  17008. org-latex-default-packages-alist
  17009. org-latex-packages-alist
  17010. org-format-latex-options
  17011. forbuffer value fg bg))))
  17012. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  17013. (absprefix (expand-file-name prefix dir))
  17014. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  17015. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  17016. (sep (and block-type "\n\n"))
  17017. (link (concat sep "[[file:" linkfile "]]" sep))
  17018. (options
  17019. (org-combine-plists
  17020. org-format-latex-options
  17021. `(:foreground ,fg :background ,bg))))
  17022. (when msg (message msg cnt))
  17023. (unless checkdir-flag ; Ensure the directory exists.
  17024. (setq checkdir-flag t)
  17025. (let ((todir (file-name-directory absprefix)))
  17026. (unless (file-directory-p todir)
  17027. (make-directory todir t))))
  17028. (unless (file-exists-p movefile)
  17029. (org-create-formula-image
  17030. value movefile options forbuffer processing-type))
  17031. (if overlays
  17032. (progn
  17033. (dolist (o (overlays-in beg end))
  17034. (when (eq (overlay-get o 'org-overlay-type)
  17035. 'org-latex-overlay)
  17036. (delete-overlay o)))
  17037. (org--format-latex-make-overlay beg end movefile imagetype)
  17038. (goto-char end))
  17039. (delete-region beg end)
  17040. (insert
  17041. (org-add-props link
  17042. (list 'org-latex-src
  17043. (replace-regexp-in-string "\"" "" value)
  17044. 'org-latex-src-embed-type
  17045. (if block-type 'paragraph 'character)))))))
  17046. ((eq processing-type 'mathml)
  17047. ;; Process to MathML.
  17048. (unless (org-format-latex-mathml-available-p)
  17049. (user-error "LaTeX to MathML converter not configured"))
  17050. (cl-incf cnt)
  17051. (when msg (message msg cnt))
  17052. (goto-char beg)
  17053. (delete-region beg end)
  17054. (insert (org-format-latex-as-mathml
  17055. value block-type prefix dir)))
  17056. (t
  17057. (error "Unknown conversion process %s for LaTeX fragments"
  17058. processing-type)))))))))))
  17059. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17060. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17061. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17062. sucessful, return the portion between \"<math...> </math>\"
  17063. elements otherwise return nil. When MATHML-FILE is specified,
  17064. write the results in to that file. When invoked as an
  17065. interactive command, prompt for LATEX-FRAG, with initial value
  17066. set to the current active region and echo the results for user
  17067. inspection."
  17068. (interactive (list (let ((frag (when (org-region-active-p)
  17069. (buffer-substring-no-properties
  17070. (region-beginning) (region-end)))))
  17071. (read-string "LaTeX Fragment: " frag nil frag))))
  17072. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17073. (let* ((tmp-in-file
  17074. (let ((file (file-relative-name
  17075. (make-temp-name (expand-file-name "ltxmathml-in")))))
  17076. (write-region latex-frag nil file)
  17077. file))
  17078. (tmp-out-file (file-relative-name
  17079. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17080. (cmd (format-spec
  17081. org-latex-to-mathml-convert-command
  17082. `((?j . ,(and org-latex-to-mathml-jar-file
  17083. (shell-quote-argument
  17084. (expand-file-name
  17085. org-latex-to-mathml-jar-file))))
  17086. (?I . ,(shell-quote-argument tmp-in-file))
  17087. (?i . ,latex-frag)
  17088. (?o . ,(shell-quote-argument tmp-out-file)))))
  17089. mathml shell-command-output)
  17090. (when (called-interactively-p 'any)
  17091. (unless (org-format-latex-mathml-available-p)
  17092. (user-error "LaTeX to MathML converter not configured")))
  17093. (message "Running %s" cmd)
  17094. (setq shell-command-output (shell-command-to-string cmd))
  17095. (setq mathml
  17096. (when (file-readable-p tmp-out-file)
  17097. (with-current-buffer (find-file-noselect tmp-out-file t)
  17098. (goto-char (point-min))
  17099. (when (re-search-forward
  17100. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  17101. (regexp-quote
  17102. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  17103. nil t)
  17104. (prog1 (match-string 0) (kill-buffer))))))
  17105. (cond
  17106. (mathml
  17107. (setq mathml
  17108. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17109. (when mathml-file
  17110. (write-region mathml nil mathml-file))
  17111. (when (called-interactively-p 'any)
  17112. (message mathml)))
  17113. ((message "LaTeX to MathML conversion failed")
  17114. (message shell-command-output)))
  17115. (delete-file tmp-in-file)
  17116. (when (file-exists-p tmp-out-file)
  17117. (delete-file tmp-out-file))
  17118. mathml))
  17119. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17120. prefix &optional dir)
  17121. "Use `org-create-math-formula' but check local cache first."
  17122. (let* ((absprefix (expand-file-name prefix dir))
  17123. (print-length nil) (print-level nil)
  17124. (formula-id (concat
  17125. "formula-"
  17126. (sha1
  17127. (prin1-to-string
  17128. (list latex-frag
  17129. org-latex-to-mathml-convert-command)))))
  17130. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17131. (formula-cache-dir (file-name-directory formula-cache)))
  17132. (unless (file-directory-p formula-cache-dir)
  17133. (make-directory formula-cache-dir t))
  17134. (unless (file-exists-p formula-cache)
  17135. (org-create-math-formula latex-frag formula-cache))
  17136. (if (file-exists-p formula-cache)
  17137. ;; Successful conversion. Return the link to MathML file.
  17138. (org-add-props
  17139. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17140. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17141. 'org-latex-src-embed-type (if latex-frag-type
  17142. 'paragraph 'character)))
  17143. ;; Failed conversion. Return the LaTeX fragment verbatim
  17144. latex-frag)))
  17145. (defun org--get-display-dpi ()
  17146. "Get the DPI of the display.
  17147. The function assumes that the display has the same pixel width in
  17148. the horizontal and vertical directions."
  17149. (if (display-graphic-p)
  17150. (round (/ (display-pixel-height)
  17151. (/ (display-mm-height) 25.4)))
  17152. (error "Attempt to calculate the dpi of a non-graphic display")))
  17153. (defun org-create-formula-image
  17154. (string tofile options buffer &optional processing-type)
  17155. "Create an image from LaTeX source using external processes.
  17156. The LaTeX STRING is saved to a temporary LaTeX file, then
  17157. converted to an image file by process PROCESSING-TYPE defined in
  17158. `org-preview-latex-process-alist'. A nil value defaults to
  17159. `org-preview-latex-default-process'.
  17160. The generated image file is eventually moved to TOFILE.
  17161. The OPTIONS argument controls the size, foreground color and
  17162. background color of the generated image.
  17163. When BUFFER non-nil, this function is used for LaTeX previewing.
  17164. Otherwise, it is used to deal with LaTeX snippets showed in
  17165. a HTML file."
  17166. (let* ((processing-type (or processing-type
  17167. org-preview-latex-default-process))
  17168. (processing-info
  17169. (cdr (assq processing-type org-preview-latex-process-alist)))
  17170. (programs (plist-get processing-info :programs))
  17171. (error-message (or (plist-get processing-info :message) ""))
  17172. (use-xcolor (plist-get processing-info :use-xcolor))
  17173. (image-input-type (plist-get processing-info :image-input-type))
  17174. (image-output-type (plist-get processing-info :image-output-type))
  17175. (post-clean (or (plist-get processing-info :post-clean)
  17176. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  17177. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  17178. (latex-header
  17179. (or (plist-get processing-info :latex-header)
  17180. (org-latex-make-preamble
  17181. (org-export-get-environment (org-export-get-backend 'latex))
  17182. org-format-latex-header
  17183. 'snippet)))
  17184. (latex-compiler (plist-get processing-info :latex-compiler))
  17185. (image-converter (plist-get processing-info :image-converter))
  17186. (tmpdir temporary-file-directory)
  17187. (texfilebase (make-temp-name
  17188. (expand-file-name "orgtex" tmpdir)))
  17189. (texfile (concat texfilebase ".tex"))
  17190. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  17191. '(1.0 . 1.0)))
  17192. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  17193. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  17194. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  17195. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17196. "Black"))
  17197. (bg (or (plist-get options (if buffer :background :html-background))
  17198. "Transparent"))
  17199. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  17200. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  17201. (dolist (program programs)
  17202. (org-check-external-command program error-message))
  17203. (if use-xcolor
  17204. (progn (if (eq fg 'default)
  17205. (setq fg (org-latex-color :foreground))
  17206. (setq fg (org-latex-color-format fg)))
  17207. (if (eq bg 'default)
  17208. (setq bg (org-latex-color :background))
  17209. (setq bg (org-latex-color-format
  17210. (if (string= bg "Transparent") "white" bg))))
  17211. (with-temp-file texfile
  17212. (insert latex-header)
  17213. (insert "\n\\begin{document}\n"
  17214. "\\definecolor{fg}{rgb}{" fg "}\n"
  17215. "\\definecolor{bg}{rgb}{" bg "}\n"
  17216. "\n\\pagecolor{bg}\n"
  17217. "\n{\\color{fg}\n"
  17218. string
  17219. "\n}\n"
  17220. "\n\\end{document}\n")))
  17221. (if (eq fg 'default)
  17222. (setq fg (org-dvipng-color :foreground))
  17223. (unless (string= fg "Transparent")
  17224. (setq fg (org-dvipng-color-format fg))))
  17225. (if (eq bg 'default)
  17226. (setq bg (org-dvipng-color :background))
  17227. (unless (string= bg "Transparent")
  17228. (setq bg (org-dvipng-color-format bg))))
  17229. (with-temp-file texfile
  17230. (insert latex-header)
  17231. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17232. (let* ((err-msg (format "Please adjust `%s' part of \
  17233. `org-preview-latex-process-alist'."
  17234. processing-type))
  17235. (image-input-file
  17236. (org-compile-file
  17237. texfile latex-compiler image-input-type err-msg log-buf))
  17238. (image-output-file
  17239. (org-compile-file
  17240. image-input-file image-converter image-output-type err-msg log-buf
  17241. `((?F . ,(shell-quote-argument fg))
  17242. (?B . ,(shell-quote-argument bg))
  17243. (?D . ,(shell-quote-argument (format "%s" dpi)))
  17244. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  17245. (copy-file image-output-file tofile 'replace)
  17246. (dolist (e post-clean)
  17247. (when (file-exists-p (concat texfilebase e))
  17248. (delete-file (concat texfilebase e))))
  17249. image-output-file)))
  17250. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17251. "Fill a LaTeX header template TPL.
  17252. In the template, the following place holders will be recognized:
  17253. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17254. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17255. [PACKAGES] \\usepackage statements for PKG
  17256. [NO-PACKAGES] do not include PKG
  17257. [EXTRA] the string EXTRA
  17258. [NO-EXTRA] do not include EXTRA
  17259. For backward compatibility, if both the positive and the negative place
  17260. holder is missing, the positive one (without the \"NO-\") will be
  17261. assumed to be present at the end of the template.
  17262. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17263. EXTRA is a string.
  17264. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17265. (let (rpl (end ""))
  17266. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17267. (setq rpl (if (or (match-end 1) (not def-pkg))
  17268. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17269. tpl (replace-match rpl t t tpl))
  17270. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17271. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17272. (setq rpl (if (or (match-end 1) (not pkg))
  17273. "" (org-latex-packages-to-string pkg snippets-p t))
  17274. tpl (replace-match rpl t t tpl))
  17275. (when pkg (setq end
  17276. (concat end "\n"
  17277. (org-latex-packages-to-string pkg snippets-p)))))
  17278. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17279. (setq rpl (if (or (match-end 1) (not extra))
  17280. "" (concat extra "\n"))
  17281. tpl (replace-match rpl t t tpl))
  17282. (when (and extra (string-match "\\S-" extra))
  17283. (setq end (concat end "\n" extra))))
  17284. (if (string-match "\\S-" end)
  17285. (concat tpl "\n" end)
  17286. tpl)))
  17287. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17288. "Turn an alist of packages into a string with the \\usepackage macros."
  17289. (setq pkg (mapconcat (lambda(p)
  17290. (cond
  17291. ((stringp p) p)
  17292. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17293. (format "%% Package %s omitted" (cadr p)))
  17294. ((equal "" (car p))
  17295. (format "\\usepackage{%s}" (cadr p)))
  17296. (t
  17297. (format "\\usepackage[%s]{%s}"
  17298. (car p) (cadr p)))))
  17299. pkg
  17300. "\n"))
  17301. (if newline (concat pkg "\n") pkg))
  17302. (defun org-dvipng-color (attr)
  17303. "Return a RGB color specification for dvipng."
  17304. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17305. (defun org-dvipng-color-format (color-name)
  17306. "Convert COLOR-NAME to a RGB color value for dvipng."
  17307. (apply #'format "rgb %s %s %s"
  17308. (mapcar 'org-normalize-color
  17309. (color-values color-name))))
  17310. (defun org-latex-color (attr)
  17311. "Return a RGB color for the LaTeX color package."
  17312. (org-latex-color-format (face-attribute 'default attr nil)))
  17313. (defun org-latex-color-format (color-name)
  17314. "Convert COLOR-NAME to a RGB color value."
  17315. (apply #'format "%s,%s,%s"
  17316. (mapcar 'org-normalize-color
  17317. (color-values color-name))))
  17318. (defun org-normalize-color (value)
  17319. "Return string to be used as color value for an RGB component."
  17320. (format "%g" (/ value 65535.0)))
  17321. ;; Image display
  17322. (defvar-local org-inline-image-overlays nil)
  17323. (defun org-toggle-inline-images (&optional include-linked)
  17324. "Toggle the display of inline images.
  17325. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17326. (interactive "P")
  17327. (if org-inline-image-overlays
  17328. (progn
  17329. (org-remove-inline-images)
  17330. (when (called-interactively-p 'interactive)
  17331. (message "Inline image display turned off")))
  17332. (org-display-inline-images include-linked)
  17333. (when (called-interactively-p 'interactive)
  17334. (message (if org-inline-image-overlays
  17335. (format "%d images displayed inline"
  17336. (length org-inline-image-overlays))
  17337. "No images to display inline")))))
  17338. (defun org-redisplay-inline-images ()
  17339. "Refresh the display of inline images."
  17340. (interactive)
  17341. (if (not org-inline-image-overlays)
  17342. (org-toggle-inline-images)
  17343. (org-toggle-inline-images)
  17344. (org-toggle-inline-images)))
  17345. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17346. "Display inline images.
  17347. An inline image is a link which follows either of these
  17348. conventions:
  17349. 1. Its path is a file with an extension matching return value
  17350. from `image-file-name-regexp' and it has no contents.
  17351. 2. Its description consists in a single link of the previous
  17352. type.
  17353. When optional argument INCLUDE-LINKED is non-nil, also links with
  17354. a text description part will be inlined. This can be nice for
  17355. a quick look at those images, but it does not reflect what
  17356. exported files will look like.
  17357. When optional argument REFRESH is non-nil, refresh existing
  17358. images between BEG and END. This will create new image displays
  17359. only if necessary. BEG and END default to the buffer
  17360. boundaries."
  17361. (interactive "P")
  17362. (when (display-graphic-p)
  17363. (unless refresh
  17364. (org-remove-inline-images)
  17365. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17366. (org-with-wide-buffer
  17367. (goto-char (or beg (point-min)))
  17368. (let* ((case-fold-search t)
  17369. (file-extension-re (image-file-name-regexp))
  17370. (link-abbrevs (mapcar #'car
  17371. (append org-link-abbrev-alist-local
  17372. org-link-abbrev-alist)))
  17373. ;; Check absolute, relative file names and explicit
  17374. ;; "file:" links. Also check link abbreviations since
  17375. ;; some might expand to "file" links.
  17376. (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
  17377. (if (not link-abbrevs) ""
  17378. (format "\\|\\(?:%s:\\)"
  17379. (regexp-opt link-abbrevs))))))
  17380. (while (re-search-forward file-types-re end t)
  17381. (let ((link (save-match-data (org-element-context))))
  17382. ;; Check if we're at an inline image, i.e., an image file
  17383. ;; link without a description (unless INCLUDE-LINKED is
  17384. ;; non-nil).
  17385. (when (and (equal "file" (org-element-property :type link))
  17386. (or include-linked
  17387. (null (org-element-contents link)))
  17388. (string-match-p file-extension-re
  17389. (org-element-property :path link)))
  17390. (let ((file (expand-file-name
  17391. (org-link-unescape
  17392. (org-element-property :path link)))))
  17393. (when (file-exists-p file)
  17394. (let ((width
  17395. ;; Apply `org-image-actual-width' specifications.
  17396. (cond
  17397. ((not (image-type-available-p 'imagemagick)) nil)
  17398. ((eq org-image-actual-width t) nil)
  17399. ((listp org-image-actual-width)
  17400. (or
  17401. ;; First try to find a width among
  17402. ;; attributes associated to the paragraph
  17403. ;; containing link.
  17404. (let ((paragraph
  17405. (let ((e link))
  17406. (while (and (setq e (org-element-property
  17407. :parent e))
  17408. (not (eq (org-element-type e)
  17409. 'paragraph))))
  17410. e)))
  17411. (when paragraph
  17412. (save-excursion
  17413. (goto-char (org-element-property :begin paragraph))
  17414. (when
  17415. (re-search-forward
  17416. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17417. (org-element-property
  17418. :post-affiliated paragraph)
  17419. t)
  17420. (string-to-number (match-string 1))))))
  17421. ;; Otherwise, fall-back to provided number.
  17422. (car org-image-actual-width)))
  17423. ((numberp org-image-actual-width)
  17424. org-image-actual-width)))
  17425. (old (get-char-property-and-overlay
  17426. (org-element-property :begin link)
  17427. 'org-image-overlay)))
  17428. (if (and (car-safe old) refresh)
  17429. (image-refresh (overlay-get (cdr old) 'display))
  17430. (let ((image (create-image file
  17431. (and width 'imagemagick)
  17432. nil
  17433. :width width)))
  17434. (when image
  17435. (let ((ov (make-overlay
  17436. (org-element-property :begin link)
  17437. (progn
  17438. (goto-char
  17439. (org-element-property :end link))
  17440. (skip-chars-backward " \t")
  17441. (point)))))
  17442. (overlay-put ov 'display image)
  17443. (overlay-put ov 'face 'default)
  17444. (overlay-put ov 'org-image-overlay t)
  17445. (overlay-put
  17446. ov 'modification-hooks
  17447. (list 'org-display-inline-remove-overlay))
  17448. (push ov org-inline-image-overlays)))))))))))))))
  17449. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17450. "Remove inline-display overlay if a corresponding region is modified."
  17451. (let ((inhibit-modification-hooks t))
  17452. (when (and ov after)
  17453. (delete ov org-inline-image-overlays)
  17454. (delete-overlay ov))))
  17455. (defun org-remove-inline-images ()
  17456. "Remove inline display of images."
  17457. (interactive)
  17458. (mapc #'delete-overlay org-inline-image-overlays)
  17459. (setq org-inline-image-overlays nil))
  17460. ;;;; Key bindings
  17461. (defun org-remap (map &rest commands)
  17462. "In MAP, remap the functions given in COMMANDS.
  17463. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  17464. (let (new old)
  17465. (while commands
  17466. (setq old (pop commands) new (pop commands))
  17467. (org-defkey map (vector 'remap old) new))))
  17468. ;; Outline functions from `outline-mode-prefix-map'
  17469. ;; that can be remapped in Org:
  17470. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  17471. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  17472. (define-key org-mode-map [remap outline-forward-same-level]
  17473. 'org-forward-heading-same-level)
  17474. (define-key org-mode-map [remap outline-backward-same-level]
  17475. 'org-backward-heading-same-level)
  17476. (define-key org-mode-map [remap outline-show-branches]
  17477. 'org-kill-note-or-show-branches)
  17478. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  17479. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  17480. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  17481. (define-key org-mode-map [remap outline-next-visible-heading]
  17482. 'org-next-visible-heading)
  17483. (define-key org-mode-map [remap outline-previous-visible-heading]
  17484. 'org-previous-visible-heading)
  17485. (define-key org-mode-map [remap show-children] 'org-show-children)
  17486. ;; Outline functions from `outline-mode-prefix-map' that can not
  17487. ;; be remapped in Org:
  17488. ;; - the column "key binding" shows whether the Outline function is still
  17489. ;; available in Org mode on the same key that it has been bound to in
  17490. ;; Outline mode:
  17491. ;; - "overridden": key used for a different functionality in Org mode
  17492. ;; - else: key still bound to the same Outline function in Org mode
  17493. ;; | Outline function | key binding | Org replacement |
  17494. ;; |------------------------------------+-------------+--------------------------|
  17495. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  17496. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  17497. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  17498. ;; | `show-entry' | overridden | no replacement |
  17499. ;; | `show-branches' | `C-c C-k' | still same function |
  17500. ;; | `show-subtree' | overridden | visibility cycling |
  17501. ;; | `show-all' | overridden | no replacement |
  17502. ;; | `hide-subtree' | overridden | visibility cycling |
  17503. ;; | `hide-body' | overridden | no replacement |
  17504. ;; | `hide-entry' | overridden | visibility cycling |
  17505. ;; | `hide-leaves' | overridden | no replacement |
  17506. ;; | `hide-sublevels' | overridden | no replacement |
  17507. ;; | `hide-other' | overridden | no replacement |
  17508. ;; Make `C-c C-x' a prefix key
  17509. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  17510. ;; TAB key with modifiers
  17511. (org-defkey org-mode-map "\C-i" 'org-cycle)
  17512. (org-defkey org-mode-map [(tab)] 'org-cycle)
  17513. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  17514. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  17515. ;; The following line is necessary under Suse GNU/Linux
  17516. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
  17517. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  17518. (define-key org-mode-map [backtab] 'org-shifttab)
  17519. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  17520. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  17521. (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
  17522. ;; Cursor keys with modifiers
  17523. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  17524. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  17525. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  17526. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  17527. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  17528. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  17529. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  17530. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  17531. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  17532. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  17533. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  17534. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  17535. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  17536. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  17537. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  17538. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  17539. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  17540. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  17541. ;; Babel keys
  17542. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  17543. (dolist (pair org-babel-key-bindings)
  17544. (define-key org-babel-map (car pair) (cdr pair)))
  17545. ;;; Extra keys for tty access.
  17546. ;; We only set them when really needed because otherwise the
  17547. ;; menus don't show the simple keys
  17548. (when (or org-use-extra-keys (not window-system))
  17549. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  17550. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  17551. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  17552. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  17553. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  17554. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  17555. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  17556. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  17557. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  17558. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  17559. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  17560. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  17561. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  17562. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  17563. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  17564. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  17565. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  17566. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  17567. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  17568. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  17569. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  17570. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  17571. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  17572. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  17573. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  17574. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  17575. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  17576. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  17577. ;; All the other keys
  17578. (org-remap org-mode-map
  17579. 'self-insert-command 'org-self-insert-command
  17580. 'delete-char 'org-delete-char
  17581. 'delete-backward-char 'org-delete-backward-char)
  17582. (org-defkey org-mode-map "|" 'org-force-self-insert)
  17583. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  17584. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  17585. (if (boundp 'narrow-map)
  17586. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  17587. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  17588. (if (boundp 'narrow-map)
  17589. (org-defkey narrow-map "b" 'org-narrow-to-block)
  17590. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  17591. (if (boundp 'narrow-map)
  17592. (org-defkey narrow-map "e" 'org-narrow-to-element)
  17593. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  17594. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  17595. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  17596. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  17597. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  17598. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  17599. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  17600. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  17601. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  17602. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  17603. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  17604. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  17605. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  17606. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  17607. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  17608. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  17609. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  17610. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  17611. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  17612. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  17613. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  17614. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  17615. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  17616. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  17617. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  17618. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  17619. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  17620. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  17621. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  17622. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  17623. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  17624. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  17625. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  17626. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  17627. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  17628. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  17629. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  17630. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  17631. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  17632. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  17633. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  17634. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  17635. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  17636. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  17637. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  17638. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  17639. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  17640. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  17641. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  17642. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  17643. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  17644. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  17645. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  17646. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  17647. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  17648. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  17649. (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
  17650. (org-defkey org-mode-map "\C-c^" 'org-sort)
  17651. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  17652. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  17653. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  17654. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  17655. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  17656. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  17657. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  17658. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  17659. (org-defkey org-mode-map "\C-m" 'org-return)
  17660. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  17661. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  17662. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  17663. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  17664. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  17665. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  17666. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  17667. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  17668. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  17669. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  17670. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  17671. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  17672. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  17673. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  17674. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  17675. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  17676. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  17677. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  17678. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  17679. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  17680. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  17681. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  17682. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  17683. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  17684. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  17685. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  17686. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  17687. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  17688. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  17689. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  17690. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  17691. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  17692. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  17693. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  17694. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  17695. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  17696. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  17697. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  17698. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  17699. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  17700. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  17701. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  17702. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  17703. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  17704. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  17705. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  17706. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  17707. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  17708. (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
  17709. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  17710. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  17711. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  17712. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  17713. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  17714. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  17715. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  17716. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  17717. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  17718. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  17719. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  17720. (defconst org-speed-commands-default
  17721. '(
  17722. ("Outline Navigation")
  17723. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  17724. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  17725. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  17726. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  17727. ("F" . org-next-block)
  17728. ("B" . org-previous-block)
  17729. ("u" . (org-speed-move-safe 'outline-up-heading))
  17730. ("j" . org-goto)
  17731. ("g" . (org-refile t))
  17732. ("Outline Visibility")
  17733. ("c" . org-cycle)
  17734. ("C" . org-shifttab)
  17735. (" " . org-display-outline-path)
  17736. ("s" . org-narrow-to-subtree)
  17737. ("=" . org-columns)
  17738. ("Outline Structure Editing")
  17739. ("U" . org-metaup)
  17740. ("D" . org-metadown)
  17741. ("r" . org-metaright)
  17742. ("l" . org-metaleft)
  17743. ("R" . org-shiftmetaright)
  17744. ("L" . org-shiftmetaleft)
  17745. ("i" . (progn (forward-char 1) (call-interactively
  17746. 'org-insert-heading-respect-content)))
  17747. ("^" . org-sort)
  17748. ("w" . org-refile)
  17749. ("a" . org-archive-subtree-default-with-confirmation)
  17750. ("@" . org-mark-subtree)
  17751. ("#" . org-toggle-comment)
  17752. ("Clock Commands")
  17753. ("I" . org-clock-in)
  17754. ("O" . org-clock-out)
  17755. ("Meta Data Editing")
  17756. ("t" . org-todo)
  17757. ("," . (org-priority))
  17758. ("0" . (org-priority ?\ ))
  17759. ("1" . (org-priority ?A))
  17760. ("2" . (org-priority ?B))
  17761. ("3" . (org-priority ?C))
  17762. (":" . org-set-tags-command)
  17763. ("e" . org-set-effort)
  17764. ("E" . org-inc-effort)
  17765. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  17766. (org-entry-put (point) "APPT_WARNTIME" m)))
  17767. ("Agenda Views etc")
  17768. ("v" . org-agenda)
  17769. ("/" . org-sparse-tree)
  17770. ("Misc")
  17771. ("o" . org-open-at-point)
  17772. ("?" . org-speed-command-help)
  17773. ("<" . (org-agenda-set-restriction-lock 'subtree))
  17774. (">" . (org-agenda-remove-restriction-lock))
  17775. )
  17776. "The default speed commands.")
  17777. (defun org-print-speed-command (e)
  17778. (if (> (length (car e)) 1)
  17779. (progn
  17780. (princ "\n")
  17781. (princ (car e))
  17782. (princ "\n")
  17783. (princ (make-string (length (car e)) ?-))
  17784. (princ "\n"))
  17785. (princ (car e))
  17786. (princ " ")
  17787. (if (symbolp (cdr e))
  17788. (princ (symbol-name (cdr e)))
  17789. (prin1 (cdr e)))
  17790. (princ "\n")))
  17791. (defun org-speed-command-help ()
  17792. "Show the available speed commands."
  17793. (interactive)
  17794. (if (not org-use-speed-commands)
  17795. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  17796. (with-output-to-temp-buffer "*Help*"
  17797. (princ "User-defined Speed commands\n===========================\n")
  17798. (mapc #'org-print-speed-command org-speed-commands-user)
  17799. (princ "\n")
  17800. (princ "Built-in Speed commands\n=======================\n")
  17801. (mapc #'org-print-speed-command org-speed-commands-default))
  17802. (with-current-buffer "*Help*"
  17803. (setq truncate-lines t))))
  17804. (defun org-speed-move-safe (cmd)
  17805. "Execute CMD, but make sure that the cursor always ends up in a headline.
  17806. If not, return to the original position and throw an error."
  17807. (interactive)
  17808. (let ((pos (point)))
  17809. (call-interactively cmd)
  17810. (unless (and (bolp) (org-at-heading-p))
  17811. (goto-char pos)
  17812. (error "Boundary reached while executing %s" cmd))))
  17813. (defvar org-self-insert-command-undo-counter 0)
  17814. (defvar org-table-auto-blank-field) ; defined in org-table.el
  17815. (defvar org-speed-command nil)
  17816. (defun org-speed-command-activate (keys)
  17817. "Hook for activating single-letter speed commands.
  17818. `org-speed-commands-default' specifies a minimal command set.
  17819. Use `org-speed-commands-user' for further customization."
  17820. (when (or (and (bolp) (looking-at org-outline-regexp))
  17821. (and (functionp org-use-speed-commands)
  17822. (funcall org-use-speed-commands)))
  17823. (cdr (assoc keys (append org-speed-commands-user
  17824. org-speed-commands-default)))))
  17825. (defun org-babel-speed-command-activate (keys)
  17826. "Hook for activating single-letter code block commands."
  17827. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  17828. (cdr (assoc keys org-babel-key-bindings))))
  17829. (defcustom org-speed-command-hook
  17830. '(org-speed-command-activate org-babel-speed-command-activate)
  17831. "Hook for activating speed commands at strategic locations.
  17832. Hook functions are called in sequence until a valid handler is
  17833. found.
  17834. Each hook takes a single argument, a user-pressed command key
  17835. which is also a `self-insert-command' from the global map.
  17836. Within the hook, examine the cursor position and the command key
  17837. and return nil or a valid handler as appropriate. Handler could
  17838. be one of an interactive command, a function, or a form.
  17839. Set `org-use-speed-commands' to non-nil value to enable this
  17840. hook. The default setting is `org-speed-command-activate'."
  17841. :group 'org-structure
  17842. :version "24.1"
  17843. :type 'hook)
  17844. (defun org-self-insert-command (N)
  17845. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  17846. If the cursor is in a table looking at whitespace, the whitespace is
  17847. overwritten, and the table is not marked as requiring realignment."
  17848. (interactive "p")
  17849. (org-check-before-invisible-edit 'insert)
  17850. (cond
  17851. ((and org-use-speed-commands
  17852. (let ((kv (this-command-keys-vector)))
  17853. (setq org-speed-command
  17854. (run-hook-with-args-until-success
  17855. 'org-speed-command-hook
  17856. (make-string 1 (aref kv (1- (length kv))))))))
  17857. (cond
  17858. ((commandp org-speed-command)
  17859. (setq this-command org-speed-command)
  17860. (call-interactively org-speed-command))
  17861. ((functionp org-speed-command)
  17862. (funcall org-speed-command))
  17863. ((and org-speed-command (listp org-speed-command))
  17864. (eval org-speed-command))
  17865. (t (let (org-use-speed-commands)
  17866. (call-interactively 'org-self-insert-command)))))
  17867. ((and
  17868. (org-at-table-p)
  17869. (eq N 1)
  17870. (not (org-region-active-p))
  17871. (progn
  17872. ;; Check if we blank the field, and if that triggers align.
  17873. (and (featurep 'org-table) org-table-auto-blank-field
  17874. (memq last-command
  17875. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  17876. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  17877. ;; Got extra space, this field does not determine
  17878. ;; column width.
  17879. (let (org-table-may-need-update) (org-table-blank-field))
  17880. ;; No extra space, this field may determine column
  17881. ;; width.
  17882. (org-table-blank-field)))
  17883. t)
  17884. (looking-at "[^|\n]* \\( \\)|"))
  17885. ;; There is room for insertion without re-aligning the table.
  17886. (delete-region (match-beginning 1) (match-end 1))
  17887. (self-insert-command N))
  17888. (t
  17889. (setq org-table-may-need-update t)
  17890. (self-insert-command N)
  17891. (org-fix-tags-on-the-fly)
  17892. (when org-self-insert-cluster-for-undo
  17893. (if (not (eq last-command 'org-self-insert-command))
  17894. (setq org-self-insert-command-undo-counter 1)
  17895. (if (>= org-self-insert-command-undo-counter 20)
  17896. (setq org-self-insert-command-undo-counter 1)
  17897. (and (> org-self-insert-command-undo-counter 0)
  17898. buffer-undo-list (listp buffer-undo-list)
  17899. (not (cadr buffer-undo-list)) ; remove nil entry
  17900. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  17901. (setq org-self-insert-command-undo-counter
  17902. (1+ org-self-insert-command-undo-counter))))))))
  17903. (defun org-check-before-invisible-edit (kind)
  17904. "Check is editing if kind KIND would be dangerous with invisible text around.
  17905. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  17906. ;; First, try to get out of here as quickly as possible, to reduce overhead
  17907. (when (and org-catch-invisible-edits
  17908. (or (not (boundp 'visible-mode)) (not visible-mode))
  17909. (or (get-char-property (point) 'invisible)
  17910. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  17911. ;; OK, we need to take a closer look. Do not consider
  17912. ;; invisibility obtained through text properties (e.g., link
  17913. ;; fontification), as it cannot be toggled.
  17914. (let* ((invisible-at-point
  17915. (pcase (get-char-property-and-overlay (point) 'invisible)
  17916. (`(,_ . ,(and (pred overlayp) o)) o)))
  17917. ;; Assume that point cannot land in the middle of an
  17918. ;; overlay, or between two overlays.
  17919. (invisible-before-point
  17920. (and (not invisible-at-point)
  17921. (not (bobp))
  17922. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  17923. (`(,_ . ,(and (pred overlayp) o)) o))))
  17924. (border-and-ok-direction
  17925. (or
  17926. ;; Check if we are acting predictably before invisible
  17927. ;; text.
  17928. (and invisible-at-point
  17929. (memq kind '(insert delete-backward)))
  17930. ;; Check if we are acting predictably after invisible text
  17931. ;; This works not well, and I have turned it off. It seems
  17932. ;; better to always show and stop after invisible text.
  17933. ;; (and (not invisible-at-point) invisible-before-point
  17934. ;; (memq kind '(insert delete)))
  17935. )))
  17936. (when (or invisible-at-point invisible-before-point)
  17937. (when (eq org-catch-invisible-edits 'error)
  17938. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  17939. (if (and org-custom-properties-overlays
  17940. (y-or-n-p "Display invisible properties in this buffer? "))
  17941. (org-toggle-custom-properties-visibility)
  17942. ;; Make the area visible
  17943. (save-excursion
  17944. (when invisible-before-point
  17945. (goto-char
  17946. (previous-single-char-property-change (point) 'invisible)))
  17947. ;; Remove whatever overlay is currently making yet-to-be
  17948. ;; edited text invisible. Also remove nested invisibility
  17949. ;; related overlays.
  17950. (delete-overlay (or invisible-at-point invisible-before-point))
  17951. (let ((origin (if invisible-at-point (point) (1- (point)))))
  17952. (while (pcase (get-char-property-and-overlay origin 'invisible)
  17953. (`(,_ . ,(and (pred overlayp) o))
  17954. (delete-overlay o)
  17955. t)))))
  17956. (cond
  17957. ((eq org-catch-invisible-edits 'show)
  17958. ;; That's it, we do the edit after showing
  17959. (message
  17960. "Unfolding invisible region around point before editing")
  17961. (sit-for 1))
  17962. ((and (eq org-catch-invisible-edits 'smart)
  17963. border-and-ok-direction)
  17964. (message "Unfolding invisible region around point before editing"))
  17965. (t
  17966. ;; Don't do the edit, make the user repeat it in full visibility
  17967. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  17968. (defun org-fix-tags-on-the-fly ()
  17969. "Align tags in headline at point.
  17970. Unlike to `org-set-tags', it ignores region and sorting."
  17971. (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
  17972. (org-at-heading-p))
  17973. (let ((org-ignore-region t)
  17974. (org-tags-sort-function nil))
  17975. (org-set-tags nil t))))
  17976. (defun org-delete-backward-char (N)
  17977. "Like `delete-backward-char', insert whitespace at field end in tables.
  17978. When deleting backwards, in tables this function will insert whitespace in
  17979. front of the next \"|\" separator, to keep the table aligned. The table will
  17980. still be marked for re-alignment if the field did fill the entire column,
  17981. because, in this case the deletion might narrow the column."
  17982. (interactive "p")
  17983. (save-match-data
  17984. (org-check-before-invisible-edit 'delete-backward)
  17985. (if (and (org-at-table-p)
  17986. (eq N 1)
  17987. (not (org-region-active-p))
  17988. (string-match "|" (buffer-substring (point-at-bol) (point)))
  17989. (looking-at ".*?|"))
  17990. (let ((pos (point))
  17991. (noalign (looking-at "[^|\n\r]* |"))
  17992. (c org-table-may-need-update))
  17993. (backward-delete-char N)
  17994. (unless overwrite-mode
  17995. (skip-chars-forward "^|")
  17996. (insert " ")
  17997. (goto-char (1- pos)))
  17998. ;; noalign: if there were two spaces at the end, this field
  17999. ;; does not determine the width of the column.
  18000. (when noalign (setq org-table-may-need-update c)))
  18001. (backward-delete-char N)
  18002. (org-fix-tags-on-the-fly))))
  18003. (defun org-delete-char (N)
  18004. "Like `delete-char', but insert whitespace at field end in tables.
  18005. When deleting characters, in tables this function will insert whitespace in
  18006. front of the next \"|\" separator, to keep the table aligned. The table will
  18007. still be marked for re-alignment if the field did fill the entire column,
  18008. because, in this case the deletion might narrow the column."
  18009. (interactive "p")
  18010. (save-match-data
  18011. (org-check-before-invisible-edit 'delete)
  18012. (if (and (org-at-table-p)
  18013. (not (bolp))
  18014. (not (= (char-after) ?|))
  18015. (eq N 1))
  18016. (if (looking-at ".*?|")
  18017. (let ((pos (point))
  18018. (noalign (looking-at "[^|\n\r]* |"))
  18019. (c org-table-may-need-update))
  18020. (replace-match
  18021. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18022. (goto-char pos)
  18023. ;; noalign: if there were two spaces at the end, this field
  18024. ;; does not determine the width of the column.
  18025. (when noalign (setq org-table-may-need-update c)))
  18026. (delete-char N))
  18027. (delete-char N)
  18028. (org-fix-tags-on-the-fly))))
  18029. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  18030. (put 'org-self-insert-command 'delete-selection
  18031. (lambda ()
  18032. (not (run-hook-with-args-until-success
  18033. 'self-insert-uses-region-functions))))
  18034. (put 'orgtbl-self-insert-command 'delete-selection
  18035. (lambda ()
  18036. (not (run-hook-with-args-until-success
  18037. 'self-insert-uses-region-functions))))
  18038. (put 'org-delete-char 'delete-selection 'supersede)
  18039. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18040. (put 'org-yank 'delete-selection 'yank)
  18041. ;; Make `flyspell-mode' delay after some commands
  18042. (put 'org-self-insert-command 'flyspell-delayed t)
  18043. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18044. (put 'org-delete-char 'flyspell-delayed t)
  18045. (put 'org-delete-backward-char 'flyspell-delayed t)
  18046. ;; Make pabbrev-mode expand after Org mode commands
  18047. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18048. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18049. (defun org-transpose-words ()
  18050. "Transpose words for Org.
  18051. This uses the `org-mode-transpose-word-syntax-table' syntax
  18052. table, which interprets characters in `org-emphasis-alist' as
  18053. word constituents."
  18054. (interactive)
  18055. (with-syntax-table org-mode-transpose-word-syntax-table
  18056. (call-interactively 'transpose-words)))
  18057. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18058. (defvar org-ctrl-c-ctrl-c-hook nil
  18059. "Hook for functions attaching themselves to `C-c C-c'.
  18060. This can be used to add additional functionality to the C-c C-c
  18061. key which executes context-dependent commands. This hook is run
  18062. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18063. run after the last test.
  18064. Each function will be called with no arguments. The function
  18065. must check if the context is appropriate for it to act. If yes,
  18066. it should do its thing and then return a non-nil value. If the
  18067. context is wrong, just do nothing and return nil.")
  18068. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18069. "Hook for functions attaching themselves to `C-c C-c'.
  18070. This can be used to add additional functionality to the C-c C-c
  18071. key which executes context-dependent commands. This hook is run
  18072. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18073. before the first test.
  18074. Each function will be called with no arguments. The function
  18075. must check if the context is appropriate for it to act. If yes,
  18076. it should do its thing and then return a non-nil value. If the
  18077. context is wrong, just do nothing and return nil.")
  18078. (defvar org-tab-first-hook nil
  18079. "Hook for functions to attach themselves to TAB.
  18080. See `org-ctrl-c-ctrl-c-hook' for more information.
  18081. This hook runs as the first action when TAB is pressed, even before
  18082. `org-cycle' messes around with the `outline-regexp' to cater for
  18083. inline tasks and plain list item folding.
  18084. If any function in this hook returns t, any other actions that
  18085. would have been caused by TAB (such as table field motion or visibility
  18086. cycling) will not occur.")
  18087. (defvar org-tab-after-check-for-table-hook nil
  18088. "Hook for functions to attach themselves to TAB.
  18089. See `org-ctrl-c-ctrl-c-hook' for more information.
  18090. This hook runs after it has been established that the cursor is not in a
  18091. table, but before checking if the cursor is in a headline or if global cycling
  18092. should be done.
  18093. If any function in this hook returns t, not other actions like visibility
  18094. cycling will be done.")
  18095. (defvar org-tab-after-check-for-cycling-hook nil
  18096. "Hook for functions to attach themselves to TAB.
  18097. See `org-ctrl-c-ctrl-c-hook' for more information.
  18098. This hook runs after it has been established that not table field motion and
  18099. not visibility should be done because of current context. This is probably
  18100. the place where a package like yasnippets can hook in.")
  18101. (defvar org-tab-before-tab-emulation-hook nil
  18102. "Hook for functions to attach themselves to TAB.
  18103. See `org-ctrl-c-ctrl-c-hook' for more information.
  18104. This hook runs after every other options for TAB have been exhausted, but
  18105. before indentation and \t insertion takes place.")
  18106. (defvar org-metaleft-hook nil
  18107. "Hook for functions attaching themselves to `M-left'.
  18108. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18109. (defvar org-metaright-hook nil
  18110. "Hook for functions attaching themselves to `M-right'.
  18111. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18112. (defvar org-metaup-hook nil
  18113. "Hook for functions attaching themselves to `M-up'.
  18114. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18115. (defvar org-metadown-hook nil
  18116. "Hook for functions attaching themselves to `M-down'.
  18117. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18118. (defvar org-shiftmetaleft-hook nil
  18119. "Hook for functions attaching themselves to `M-S-left'.
  18120. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18121. (defvar org-shiftmetaright-hook nil
  18122. "Hook for functions attaching themselves to `M-S-right'.
  18123. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18124. (defvar org-shiftmetaup-hook nil
  18125. "Hook for functions attaching themselves to `M-S-up'.
  18126. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18127. (defvar org-shiftmetadown-hook nil
  18128. "Hook for functions attaching themselves to `M-S-down'.
  18129. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18130. (defvar org-metareturn-hook nil
  18131. "Hook for functions attaching themselves to `M-RET'.
  18132. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18133. (defvar org-shiftup-hook nil
  18134. "Hook for functions attaching themselves to `S-up'.
  18135. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18136. (defvar org-shiftup-final-hook nil
  18137. "Hook for functions attaching themselves to `S-up'.
  18138. This one runs after all other options except shift-select have been excluded.
  18139. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18140. (defvar org-shiftdown-hook nil
  18141. "Hook for functions attaching themselves to `S-down'.
  18142. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18143. (defvar org-shiftdown-final-hook nil
  18144. "Hook for functions attaching themselves to `S-down'.
  18145. This one runs after all other options except shift-select have been excluded.
  18146. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18147. (defvar org-shiftleft-hook nil
  18148. "Hook for functions attaching themselves to `S-left'.
  18149. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18150. (defvar org-shiftleft-final-hook nil
  18151. "Hook for functions attaching themselves to `S-left'.
  18152. This one runs after all other options except shift-select have been excluded.
  18153. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18154. (defvar org-shiftright-hook nil
  18155. "Hook for functions attaching themselves to `S-right'.
  18156. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18157. (defvar org-shiftright-final-hook nil
  18158. "Hook for functions attaching themselves to `S-right'.
  18159. This one runs after all other options except shift-select have been excluded.
  18160. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18161. (defun org-modifier-cursor-error ()
  18162. "Throw an error, a modified cursor command was applied in wrong context."
  18163. (user-error "This command is active in special context like tables, headlines or items"))
  18164. (defun org-shiftselect-error ()
  18165. "Throw an error because Shift-Cursor command was applied in wrong context."
  18166. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18167. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  18168. (user-error "This command works only in special context like headlines or timestamps")))
  18169. (defun org-call-for-shift-select (cmd)
  18170. (let ((this-command-keys-shift-translated t))
  18171. (call-interactively cmd)))
  18172. (defun org-shifttab (&optional arg)
  18173. "Global visibility cycling or move to previous table field.
  18174. Call `org-table-previous-field' within a table.
  18175. When ARG is nil, cycle globally through visibility states.
  18176. When ARG is a numeric prefix, show contents of this level."
  18177. (interactive "P")
  18178. (cond
  18179. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18180. ((integerp arg)
  18181. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18182. (message "Content view to level: %d" arg)
  18183. (org-content (prefix-numeric-value arg2))
  18184. (org-cycle-show-empty-lines t)
  18185. (setq org-cycle-global-status 'overview)))
  18186. (t (call-interactively 'org-global-cycle))))
  18187. (defun org-shiftmetaleft ()
  18188. "Promote subtree or delete table column.
  18189. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18190. `org-table-delete-column', depending on context. See the
  18191. individual commands for more information."
  18192. (interactive)
  18193. (cond
  18194. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18195. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18196. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18197. ((if (not (org-region-active-p)) (org-at-item-p)
  18198. (save-excursion (goto-char (region-beginning))
  18199. (org-at-item-p)))
  18200. (call-interactively 'org-outdent-item-tree))
  18201. (t (org-modifier-cursor-error))))
  18202. (defun org-shiftmetaright ()
  18203. "Demote subtree or insert table column.
  18204. Calls `org-demote-subtree', `org-indent-item-tree', or
  18205. `org-table-insert-column', depending on context. See the
  18206. individual commands for more information."
  18207. (interactive)
  18208. (cond
  18209. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18210. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18211. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18212. ((if (not (org-region-active-p)) (org-at-item-p)
  18213. (save-excursion (goto-char (region-beginning))
  18214. (org-at-item-p)))
  18215. (call-interactively 'org-indent-item-tree))
  18216. (t (org-modifier-cursor-error))))
  18217. (defun org-shiftmetaup (&optional _arg)
  18218. "Drag the line at point up.
  18219. In a table, kill the current row.
  18220. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18221. but also adjust the previous clocked item in the clock history.
  18222. Everywhere else, drag the line at point up."
  18223. (interactive "P")
  18224. (cond
  18225. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18226. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18227. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18228. (call-interactively 'org-timestamp-up)))
  18229. (t (call-interactively 'org-drag-line-backward))))
  18230. (defun org-shiftmetadown (&optional _arg)
  18231. "Drag the line at point down.
  18232. In a table, insert an empty row at the current line.
  18233. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18234. but also adjust the previous clocked item in the clock history.
  18235. Everywhere else, drag the line at point down."
  18236. (interactive "P")
  18237. (cond
  18238. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18239. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18240. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18241. (call-interactively 'org-timestamp-down)))
  18242. (t (call-interactively 'org-drag-line-forward))))
  18243. (defsubst org-hidden-tree-error ()
  18244. (user-error
  18245. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18246. (defun org-metaleft (&optional _arg)
  18247. "Promote heading, list item at point or move table column left.
  18248. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18249. depending on context. With no specific context, calls the Emacs
  18250. default `backward-word'. See the individual commands for more
  18251. information.
  18252. This function runs the hook `org-metaleft-hook' as a first step,
  18253. and returns at first non-nil value."
  18254. (interactive "P")
  18255. (cond
  18256. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18257. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18258. ((org-with-limited-levels
  18259. (or (org-at-heading-p)
  18260. (and (org-region-active-p)
  18261. (save-excursion
  18262. (goto-char (region-beginning))
  18263. (org-at-heading-p)))))
  18264. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18265. (call-interactively 'org-do-promote))
  18266. ;; At an inline task.
  18267. ((org-at-heading-p)
  18268. (call-interactively 'org-inlinetask-promote))
  18269. ((or (org-at-item-p)
  18270. (and (org-region-active-p)
  18271. (save-excursion
  18272. (goto-char (region-beginning))
  18273. (org-at-item-p))))
  18274. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18275. (call-interactively 'org-outdent-item))
  18276. (t (call-interactively 'backward-word))))
  18277. (defun org-metaright (&optional _arg)
  18278. "Demote heading, list item at point or move table column right.
  18279. In front of a drawer or a block keyword, indent it correctly.
  18280. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18281. `org-indent-drawer' or `org-indent-block' depending on context.
  18282. With no specific context, calls the Emacs default `forward-word'.
  18283. See the individual commands for more information.
  18284. This function runs the hook `org-metaright-hook' as a first step,
  18285. and returns at first non-nil value."
  18286. (interactive "P")
  18287. (cond
  18288. ((run-hook-with-args-until-success 'org-metaright-hook))
  18289. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18290. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18291. ((org-at-block-p) (call-interactively 'org-indent-block))
  18292. ((org-with-limited-levels
  18293. (or (org-at-heading-p)
  18294. (and (org-region-active-p)
  18295. (save-excursion
  18296. (goto-char (region-beginning))
  18297. (org-at-heading-p)))))
  18298. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18299. (call-interactively 'org-do-demote))
  18300. ;; At an inline task.
  18301. ((org-at-heading-p)
  18302. (call-interactively 'org-inlinetask-demote))
  18303. ((or (org-at-item-p)
  18304. (and (org-region-active-p)
  18305. (save-excursion
  18306. (goto-char (region-beginning))
  18307. (org-at-item-p))))
  18308. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18309. (call-interactively 'org-indent-item))
  18310. (t (call-interactively 'forward-word))))
  18311. (defun org-check-for-hidden (what)
  18312. "Check if there are hidden headlines/items in the current visual line.
  18313. WHAT can be either `headlines' or `items'. If the current line is
  18314. an outline or item heading and it has a folded subtree below it,
  18315. this function returns t, nil otherwise."
  18316. (let ((re (cond
  18317. ((eq what 'headlines) org-outline-regexp-bol)
  18318. ((eq what 'items) (org-item-beginning-re))
  18319. (t (error "This should not happen"))))
  18320. beg end)
  18321. (save-excursion
  18322. (catch 'exit
  18323. (unless (org-region-active-p)
  18324. (setq beg (point-at-bol))
  18325. (beginning-of-line 2)
  18326. (while (and (not (eobp)) ;; this is like `next-line'
  18327. (get-char-property (1- (point)) 'invisible))
  18328. (beginning-of-line 2))
  18329. (setq end (point))
  18330. (goto-char beg)
  18331. (goto-char (point-at-eol))
  18332. (setq end (max end (point)))
  18333. (while (re-search-forward re end t)
  18334. (when (get-char-property (match-beginning 0) 'invisible)
  18335. (throw 'exit t))))
  18336. nil))))
  18337. (defun org-metaup (&optional _arg)
  18338. "Move subtree up or move table row up.
  18339. Calls `org-move-subtree-up' or `org-table-move-row' or
  18340. `org-move-item-up', depending on context. See the individual commands
  18341. for more information."
  18342. (interactive "P")
  18343. (cond
  18344. ((run-hook-with-args-until-success 'org-metaup-hook))
  18345. ((org-region-active-p)
  18346. (let* ((a (min (region-beginning) (region-end)))
  18347. (b (1- (max (region-beginning) (region-end))))
  18348. (c (save-excursion (goto-char a)
  18349. (move-beginning-of-line 0)))
  18350. (d (save-excursion (goto-char a)
  18351. (move-end-of-line 0) (point))))
  18352. (transpose-regions a b c d)
  18353. (goto-char c)))
  18354. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18355. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18356. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18357. (t (org-drag-element-backward))))
  18358. (defun org-metadown (&optional _arg)
  18359. "Move subtree down or move table row down.
  18360. Calls `org-move-subtree-down' or `org-table-move-row' or
  18361. `org-move-item-down', depending on context. See the individual
  18362. commands for more information."
  18363. (interactive "P")
  18364. (cond
  18365. ((run-hook-with-args-until-success 'org-metadown-hook))
  18366. ((org-region-active-p)
  18367. (let* ((a (min (region-beginning) (region-end)))
  18368. (b (max (region-beginning) (region-end)))
  18369. (c (save-excursion (goto-char b)
  18370. (move-beginning-of-line 1)))
  18371. (d (save-excursion (goto-char b)
  18372. (move-end-of-line 1) (1+ (point)))))
  18373. (transpose-regions a b c d)
  18374. (goto-char d)))
  18375. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18376. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18377. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18378. (t (org-drag-element-forward))))
  18379. (defun org-shiftup (&optional arg)
  18380. "Increase item in timestamp or increase priority of current headline.
  18381. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18382. depending on context. See the individual commands for more information."
  18383. (interactive "P")
  18384. (cond
  18385. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18386. ((and org-support-shift-select (org-region-active-p))
  18387. (org-call-for-shift-select 'previous-line))
  18388. ((org-at-timestamp-p 'lax)
  18389. (call-interactively (if org-edit-timestamp-down-means-later
  18390. 'org-timestamp-down 'org-timestamp-up)))
  18391. ((and (not (eq org-support-shift-select 'always))
  18392. org-enable-priority-commands
  18393. (org-at-heading-p))
  18394. (call-interactively 'org-priority-up))
  18395. ((and (not org-support-shift-select) (org-at-item-p))
  18396. (call-interactively 'org-previous-item))
  18397. ((org-clocktable-try-shift 'up arg))
  18398. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18399. (org-support-shift-select
  18400. (org-call-for-shift-select 'previous-line))
  18401. (t (org-shiftselect-error))))
  18402. (defun org-shiftdown (&optional arg)
  18403. "Decrease item in timestamp or decrease priority of current headline.
  18404. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18405. depending on context. See the individual commands for more information."
  18406. (interactive "P")
  18407. (cond
  18408. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18409. ((and org-support-shift-select (org-region-active-p))
  18410. (org-call-for-shift-select 'next-line))
  18411. ((org-at-timestamp-p 'lax)
  18412. (call-interactively (if org-edit-timestamp-down-means-later
  18413. 'org-timestamp-up 'org-timestamp-down)))
  18414. ((and (not (eq org-support-shift-select 'always))
  18415. org-enable-priority-commands
  18416. (org-at-heading-p))
  18417. (call-interactively 'org-priority-down))
  18418. ((and (not org-support-shift-select) (org-at-item-p))
  18419. (call-interactively 'org-next-item))
  18420. ((org-clocktable-try-shift 'down arg))
  18421. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18422. (org-support-shift-select
  18423. (org-call-for-shift-select 'next-line))
  18424. (t (org-shiftselect-error))))
  18425. (defun org-shiftright (&optional arg)
  18426. "Cycle the thing at point or in the current line, depending on context.
  18427. Depending on context, this does one of the following:
  18428. - switch a timestamp at point one day into the future
  18429. - on a headline, switch to the next TODO keyword.
  18430. - on an item, switch entire list to the next bullet type
  18431. - on a property line, switch to the next allowed value
  18432. - on a clocktable definition line, move time block into the future"
  18433. (interactive "P")
  18434. (cond
  18435. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18436. ((and org-support-shift-select (org-region-active-p))
  18437. (org-call-for-shift-select 'forward-char))
  18438. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  18439. ((and (not (eq org-support-shift-select 'always))
  18440. (org-at-heading-p))
  18441. (let ((org-inhibit-logging
  18442. (not org-treat-S-cursor-todo-selection-as-state-change))
  18443. (org-inhibit-blocking
  18444. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18445. (org-call-with-arg 'org-todo 'right)))
  18446. ((or (and org-support-shift-select
  18447. (not (eq org-support-shift-select 'always))
  18448. (org-at-item-bullet-p))
  18449. (and (not org-support-shift-select) (org-at-item-p)))
  18450. (org-call-with-arg 'org-cycle-list-bullet nil))
  18451. ((and (not (eq org-support-shift-select 'always))
  18452. (org-at-property-p))
  18453. (call-interactively 'org-property-next-allowed-value))
  18454. ((org-clocktable-try-shift 'right arg))
  18455. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18456. (org-support-shift-select
  18457. (org-call-for-shift-select 'forward-char))
  18458. (t (org-shiftselect-error))))
  18459. (defun org-shiftleft (&optional arg)
  18460. "Cycle the thing at point or in the current line, depending on context.
  18461. Depending on context, this does one of the following:
  18462. - switch a timestamp at point one day into the past
  18463. - on a headline, switch to the previous TODO keyword.
  18464. - on an item, switch entire list to the previous bullet type
  18465. - on a property line, switch to the previous allowed value
  18466. - on a clocktable definition line, move time block into the past"
  18467. (interactive "P")
  18468. (cond
  18469. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18470. ((and org-support-shift-select (org-region-active-p))
  18471. (org-call-for-shift-select 'backward-char))
  18472. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  18473. ((and (not (eq org-support-shift-select 'always))
  18474. (org-at-heading-p))
  18475. (let ((org-inhibit-logging
  18476. (not org-treat-S-cursor-todo-selection-as-state-change))
  18477. (org-inhibit-blocking
  18478. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18479. (org-call-with-arg 'org-todo 'left)))
  18480. ((or (and org-support-shift-select
  18481. (not (eq org-support-shift-select 'always))
  18482. (org-at-item-bullet-p))
  18483. (and (not org-support-shift-select) (org-at-item-p)))
  18484. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  18485. ((and (not (eq org-support-shift-select 'always))
  18486. (org-at-property-p))
  18487. (call-interactively 'org-property-previous-allowed-value))
  18488. ((org-clocktable-try-shift 'left arg))
  18489. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  18490. (org-support-shift-select
  18491. (org-call-for-shift-select 'backward-char))
  18492. (t (org-shiftselect-error))))
  18493. (defun org-shiftcontrolright ()
  18494. "Switch to next TODO set."
  18495. (interactive)
  18496. (cond
  18497. ((and org-support-shift-select (org-region-active-p))
  18498. (org-call-for-shift-select 'forward-word))
  18499. ((and (not (eq org-support-shift-select 'always))
  18500. (org-at-heading-p))
  18501. (org-call-with-arg 'org-todo 'nextset))
  18502. (org-support-shift-select
  18503. (org-call-for-shift-select 'forward-word))
  18504. (t (org-shiftselect-error))))
  18505. (defun org-shiftcontrolleft ()
  18506. "Switch to previous TODO set."
  18507. (interactive)
  18508. (cond
  18509. ((and org-support-shift-select (org-region-active-p))
  18510. (org-call-for-shift-select 'backward-word))
  18511. ((and (not (eq org-support-shift-select 'always))
  18512. (org-at-heading-p))
  18513. (org-call-with-arg 'org-todo 'previousset))
  18514. (org-support-shift-select
  18515. (org-call-for-shift-select 'backward-word))
  18516. (t (org-shiftselect-error))))
  18517. (defun org-shiftcontrolup (&optional n)
  18518. "Change timestamps synchronously up in CLOCK log lines.
  18519. Optional argument N tells to change by that many units."
  18520. (interactive "P")
  18521. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18522. (let (org-support-shift-select)
  18523. (org-clock-timestamps-up n))
  18524. (user-error "Not at a clock log")))
  18525. (defun org-shiftcontroldown (&optional n)
  18526. "Change timestamps synchronously down in CLOCK log lines.
  18527. Optional argument N tells to change by that many units."
  18528. (interactive "P")
  18529. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18530. (let (org-support-shift-select)
  18531. (org-clock-timestamps-down n))
  18532. (user-error "Not at a clock log")))
  18533. (defun org-increase-number-at-point (&optional inc)
  18534. "Increment the number at point.
  18535. With an optional prefix numeric argument INC, increment using
  18536. this numeric value."
  18537. (interactive "p")
  18538. (if (not (number-at-point))
  18539. (user-error "Not on a number")
  18540. (unless inc (setq inc 1))
  18541. (let ((pos (point))
  18542. (beg (skip-chars-backward "-+^/*0-9eE."))
  18543. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  18544. (setq nap (buffer-substring-no-properties
  18545. (+ pos beg) (+ pos beg end)))
  18546. (delete-region (+ pos beg) (+ pos beg end))
  18547. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  18548. (when (org-at-table-p)
  18549. (org-table-align)
  18550. (org-table-end-of-field 1))))
  18551. (defun org-decrease-number-at-point (&optional inc)
  18552. "Decrement the number at point.
  18553. With an optional prefix numeric argument INC, decrement using
  18554. this numeric value."
  18555. (interactive "p")
  18556. (org-increase-number-at-point (- (or inc 1))))
  18557. (defun org-ctrl-c-ret ()
  18558. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  18559. (interactive)
  18560. (cond
  18561. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  18562. (t (call-interactively 'org-insert-heading))))
  18563. (defun org-find-visible ()
  18564. (let ((s (point)))
  18565. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18566. (get-char-property s 'invisible)))
  18567. s))
  18568. (defun org-find-invisible ()
  18569. (let ((s (point)))
  18570. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18571. (not (get-char-property s 'invisible))))
  18572. s))
  18573. (defun org-copy-visible (beg end)
  18574. "Copy the visible parts of the region."
  18575. (interactive "r")
  18576. (let ((result ""))
  18577. (while (/= beg end)
  18578. (when (get-char-property beg 'invisible)
  18579. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  18580. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  18581. (setq result (concat result (buffer-substring beg next)))
  18582. (setq beg next)))
  18583. (kill-new result)))
  18584. (defun org-copy-special ()
  18585. "Copy region in table or copy current subtree.
  18586. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  18587. context. See the individual commands for more information."
  18588. (interactive)
  18589. (call-interactively
  18590. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  18591. (defun org-cut-special ()
  18592. "Cut region in table or cut current subtree.
  18593. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  18594. context. See the individual commands for more information."
  18595. (interactive)
  18596. (call-interactively
  18597. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  18598. (defun org-paste-special (arg)
  18599. "Paste rectangular region into table, or past subtree relative to level.
  18600. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  18601. See the individual commands for more information."
  18602. (interactive "P")
  18603. (if (org-at-table-p)
  18604. (org-table-paste-rectangle)
  18605. (org-paste-subtree arg)))
  18606. (defun org-edit-special (&optional arg)
  18607. "Call a special editor for the element at point.
  18608. When at a table, call the formula editor with `org-table-edit-formulas'.
  18609. When in a source code block, call `org-edit-src-code'.
  18610. When in a fixed-width region, call `org-edit-fixed-width-region'.
  18611. When in an export block, call `org-edit-export-block'.
  18612. When in a LaTeX environment, call `org-edit-latex-environment'.
  18613. When at an #+INCLUDE keyword, visit the included file.
  18614. When at a footnote reference, call `org-edit-footnote-reference'
  18615. On a link, call `ffap' to visit the link at point.
  18616. Otherwise, return a user error."
  18617. (interactive "P")
  18618. (let ((element (org-element-at-point)))
  18619. (barf-if-buffer-read-only)
  18620. (pcase (org-element-type element)
  18621. (`src-block
  18622. (if (not arg) (org-edit-src-code)
  18623. (let* ((info (org-babel-get-src-block-info))
  18624. (lang (nth 0 info))
  18625. (params (nth 2 info))
  18626. (session (cdr (assq :session params))))
  18627. (if (not session) (org-edit-src-code)
  18628. ;; At a src-block with a session and function called with
  18629. ;; an ARG: switch to the buffer related to the inferior
  18630. ;; process.
  18631. (switch-to-buffer
  18632. (funcall (intern (concat "org-babel-prep-session:" lang))
  18633. session params))))))
  18634. (`keyword
  18635. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  18636. (org-open-link-from-string
  18637. (format "[[%s]]"
  18638. (expand-file-name
  18639. (let ((value (org-element-property :value element)))
  18640. (cond ((org-file-url-p value)
  18641. (user-error "The file is specified as a URL, cannot be edited"))
  18642. ((not (org-string-nw-p value))
  18643. (user-error "No file to edit"))
  18644. ((string-match "\\`\"\\(.*?\\)\"" value)
  18645. (match-string 1 value))
  18646. ((string-match "\\`[^ \t\"]\\S-*" value)
  18647. (match-string 0 value))
  18648. (t (user-error "No valid file specified")))))))
  18649. (user-error "No special environment to edit here")))
  18650. (`table
  18651. (if (eq (org-element-property :type element) 'table.el)
  18652. (org-edit-table.el)
  18653. (call-interactively 'org-table-edit-formulas)))
  18654. ;; Only Org tables contain `table-row' type elements.
  18655. (`table-row (call-interactively 'org-table-edit-formulas))
  18656. (`example-block (org-edit-src-code))
  18657. (`export-block (org-edit-export-block))
  18658. (`fixed-width (org-edit-fixed-width-region))
  18659. (`latex-environment (org-edit-latex-environment))
  18660. (_
  18661. ;; No notable element at point. Though, we may be at a link or
  18662. ;; a footnote reference, which are objects. Thus, scan deeper.
  18663. (let ((context (org-element-context element)))
  18664. (pcase (org-element-type context)
  18665. (`footnote-reference (org-edit-footnote-reference))
  18666. (`inline-src-block (org-edit-inline-src-code))
  18667. (`link (call-interactively #'ffap))
  18668. (_ (user-error "No special environment to edit here"))))))))
  18669. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  18670. (defun org-ctrl-c-ctrl-c (&optional arg)
  18671. "Set tags in headline, or update according to changed information at point.
  18672. This command does many different things, depending on context:
  18673. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  18674. this is what we do.
  18675. - If the cursor is on a statistics cookie, update it.
  18676. - If the cursor is in a headline, prompt for tags and insert them
  18677. into the current line, aligned to `org-tags-column'. When called
  18678. with prefix arg, realign all tags in the current buffer.
  18679. - If the cursor is in one of the special #+KEYWORD lines, this
  18680. triggers scanning the buffer for these lines and updating the
  18681. information.
  18682. - If the cursor is inside a table, realign the table. This command
  18683. works even if the automatic table editor has been turned off.
  18684. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  18685. the entire table.
  18686. - If the cursor is at a footnote reference or definition, jump to
  18687. the corresponding definition or references, respectively.
  18688. - If the cursor is a the beginning of a dynamic block, update it.
  18689. - If the current buffer is a capture buffer, close note and file it.
  18690. - If the cursor is on a <<<target>>>, update radio targets and
  18691. corresponding links in this buffer.
  18692. - If the cursor is on a numbered item in a plain list, renumber the
  18693. ordered list.
  18694. - If the cursor is on a checkbox, toggle it.
  18695. - If the cursor is on a code block, evaluate it. The variable
  18696. `org-confirm-babel-evaluate' can be used to control prompting
  18697. before code block evaluation, by default every code block
  18698. evaluation requires confirmation. Code block evaluation can be
  18699. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  18700. (interactive "P")
  18701. (cond
  18702. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  18703. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  18704. (org-remove-occur-highlights)
  18705. (message "Temporary highlights/overlays removed from current buffer"))
  18706. ((and (local-variable-p 'org-finish-function)
  18707. (fboundp org-finish-function))
  18708. (funcall org-finish-function))
  18709. ((org-babel-hash-at-point))
  18710. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  18711. (t
  18712. (let* ((context
  18713. (org-element-lineage
  18714. (org-element-context)
  18715. ;; Limit to supported contexts.
  18716. '(babel-call clock dynamic-block footnote-definition
  18717. footnote-reference inline-babel-call inline-src-block
  18718. inlinetask item keyword node-property paragraph
  18719. plain-list planning property-drawer radio-target
  18720. src-block statistics-cookie table table-cell table-row
  18721. timestamp)
  18722. t))
  18723. (type (org-element-type context)))
  18724. ;; For convenience: at the first line of a paragraph on the same
  18725. ;; line as an item, apply function on that item instead.
  18726. (when (eq type 'paragraph)
  18727. (let ((parent (org-element-property :parent context)))
  18728. (when (and (eq (org-element-type parent) 'item)
  18729. (= (line-beginning-position)
  18730. (org-element-property :begin parent)))
  18731. (setq context parent)
  18732. (setq type 'item))))
  18733. ;; Act according to type of element or object at point.
  18734. ;;
  18735. ;; Do nothing on a blank line, except if it is contained in
  18736. ;; a src block. Hence, we first check if point is in such
  18737. ;; a block and then if it is at a blank line.
  18738. (pcase type
  18739. ((or `inline-src-block `src-block)
  18740. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  18741. (org-babel-eval-wipe-error-buffer)
  18742. (org-babel-execute-src-block
  18743. current-prefix-arg (org-babel-get-src-block-info nil context))))
  18744. ((guard (org-match-line "[ \t]*$"))
  18745. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  18746. (user-error
  18747. (substitute-command-keys
  18748. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  18749. ((or `babel-call `inline-babel-call)
  18750. (let ((info (org-babel-lob-get-info context)))
  18751. (when info (org-babel-execute-src-block nil info))))
  18752. (`clock (org-clock-update-time-maybe))
  18753. (`dynamic-block
  18754. (save-excursion
  18755. (goto-char (org-element-property :post-affiliated context))
  18756. (org-update-dblock)))
  18757. (`footnote-definition
  18758. (goto-char (org-element-property :post-affiliated context))
  18759. (call-interactively 'org-footnote-action))
  18760. (`footnote-reference (call-interactively #'org-footnote-action))
  18761. ((or `headline `inlinetask)
  18762. (save-excursion (goto-char (org-element-property :begin context))
  18763. (call-interactively #'org-set-tags)))
  18764. (`item
  18765. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  18766. ;; unconditionally, whereas `C-u' will toggle its presence.
  18767. ;; Without a universal argument, if the item has a checkbox,
  18768. ;; toggle it. Otherwise repair the list.
  18769. (let* ((box (org-element-property :checkbox context))
  18770. (struct (org-element-property :structure context))
  18771. (old-struct (copy-tree struct))
  18772. (parents (org-list-parents-alist struct))
  18773. (prevs (org-list-prevs-alist struct))
  18774. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  18775. (org-list-set-checkbox
  18776. (org-element-property :begin context) struct
  18777. (cond ((equal arg '(16)) "[-]")
  18778. ((and (not box) (equal arg '(4))) "[ ]")
  18779. ((or (not box) (equal arg '(4))) nil)
  18780. ((eq box 'on) "[ ]")
  18781. (t "[X]")))
  18782. ;; Mimic `org-list-write-struct' but with grabbing a return
  18783. ;; value from `org-list-struct-fix-box'.
  18784. (org-list-struct-fix-ind struct parents 2)
  18785. (org-list-struct-fix-item-end struct)
  18786. (org-list-struct-fix-bul struct prevs)
  18787. (org-list-struct-fix-ind struct parents)
  18788. (let ((block-item
  18789. (org-list-struct-fix-box struct parents prevs orderedp)))
  18790. (if (and box (equal struct old-struct))
  18791. (if (equal arg '(16))
  18792. (message "Checkboxes already reset")
  18793. (user-error "Cannot toggle this checkbox: %s"
  18794. (if (eq box 'on)
  18795. "all subitems checked"
  18796. "unchecked subitems")))
  18797. (org-list-struct-apply-struct struct old-struct)
  18798. (org-update-checkbox-count-maybe))
  18799. (when block-item
  18800. (message "Checkboxes were removed due to empty box at line %d"
  18801. (org-current-line block-item))))))
  18802. (`keyword
  18803. (let ((org-inhibit-startup-visibility-stuff t)
  18804. (org-startup-align-all-tables nil))
  18805. (when (boundp 'org-table-coordinate-overlays)
  18806. (mapc #'delete-overlay org-table-coordinate-overlays)
  18807. (setq org-table-coordinate-overlays nil))
  18808. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  18809. (message "Local setup has been refreshed"))
  18810. (`plain-list
  18811. ;; At a plain list, with a double C-u argument, set
  18812. ;; checkboxes of each item to "[-]", whereas a single one
  18813. ;; will toggle their presence according to the state of the
  18814. ;; first item in the list. Without an argument, repair the
  18815. ;; list.
  18816. (let* ((begin (org-element-property :contents-begin context))
  18817. (beginm (move-marker (make-marker) begin))
  18818. (struct (org-element-property :structure context))
  18819. (old-struct (copy-tree struct))
  18820. (first-box (save-excursion
  18821. (goto-char begin)
  18822. (looking-at org-list-full-item-re)
  18823. (match-string-no-properties 3)))
  18824. (new-box (cond ((equal arg '(16)) "[-]")
  18825. ((equal arg '(4)) (unless first-box "[ ]"))
  18826. ((equal first-box "[X]") "[ ]")
  18827. (t "[X]"))))
  18828. (cond
  18829. (arg
  18830. (dolist (pos
  18831. (org-list-get-all-items
  18832. begin struct (org-list-prevs-alist struct)))
  18833. (org-list-set-checkbox pos struct new-box)))
  18834. ((and first-box (eq (point) begin))
  18835. ;; For convenience, when point is at bol on the first
  18836. ;; item of the list and no argument is provided, simply
  18837. ;; toggle checkbox of that item, if any.
  18838. (org-list-set-checkbox begin struct new-box)))
  18839. (org-list-write-struct
  18840. struct (org-list-parents-alist struct) old-struct)
  18841. (org-update-checkbox-count-maybe)
  18842. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  18843. ((or `property-drawer `node-property)
  18844. (call-interactively #'org-property-action))
  18845. (`radio-target
  18846. (call-interactively #'org-update-radio-target-regexp))
  18847. (`statistics-cookie
  18848. (call-interactively #'org-update-statistics-cookies))
  18849. ((or `table `table-cell `table-row)
  18850. ;; At a table, recalculate every field and align it. Also
  18851. ;; send the table if necessary. If the table has
  18852. ;; a `table.el' type, just give up. At a table row or cell,
  18853. ;; maybe recalculate line but always align table.
  18854. (if (eq (org-element-property :type context) 'table.el)
  18855. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  18856. Use `\\[org-edit-special]' to edit table.el tables"))
  18857. (if (or (eq type 'table)
  18858. ;; Check if point is at a TBLFM line.
  18859. (and (eq type 'table-row)
  18860. (= (point) (org-element-property :end context))))
  18861. (save-excursion
  18862. (if (org-at-TBLFM-p)
  18863. (progn (require 'org-table)
  18864. (org-table-calc-current-TBLFM))
  18865. (goto-char (org-element-property :contents-begin context))
  18866. (org-call-with-arg 'org-table-recalculate (or arg t))
  18867. (orgtbl-send-table 'maybe)))
  18868. (org-table-maybe-eval-formula)
  18869. (cond (arg (call-interactively #'org-table-recalculate))
  18870. ((org-table-maybe-recalculate-line))
  18871. (t (org-table-align))))))
  18872. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  18873. (org-timestamp-change 0 'day))
  18874. ((and `nil (guard (org-at-heading-p)))
  18875. ;; When point is on an unsupported object type, we can miss
  18876. ;; the fact that it also is at a heading. Handle it here.
  18877. (call-interactively #'org-set-tags))
  18878. ((guard
  18879. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  18880. (_
  18881. (user-error
  18882. (substitute-command-keys
  18883. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  18884. (defun org-mode-restart ()
  18885. (interactive)
  18886. (let ((indent-status (bound-and-true-p org-indent-mode)))
  18887. (funcall major-mode)
  18888. (hack-local-variables)
  18889. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  18890. (org-indent-mode -1))
  18891. (org-reset-file-cache))
  18892. (message "%s restarted" major-mode))
  18893. (defun org-kill-note-or-show-branches ()
  18894. "Abort storing current note, or call `outline-show-branches'."
  18895. (interactive)
  18896. (if (not org-finish-function)
  18897. (progn
  18898. (outline-hide-subtree)
  18899. (call-interactively 'outline-show-branches))
  18900. (let ((org-note-abort t))
  18901. (funcall org-finish-function))))
  18902. (defun org-delete-indentation (&optional arg)
  18903. "Join current line to previous and fix whitespace at join.
  18904. If previous line is a headline add to headline title. Otherwise
  18905. the function calls `delete-indentation'.
  18906. With a non-nil optional argument, join it to the following one."
  18907. (interactive "*P")
  18908. (if (save-excursion
  18909. (beginning-of-line (if arg 1 0))
  18910. (let ((case-fold-search nil))
  18911. (looking-at org-complex-heading-regexp)))
  18912. ;; At headline.
  18913. (let ((tags-column (when (match-beginning 5)
  18914. (save-excursion (goto-char (match-beginning 5))
  18915. (current-column))))
  18916. (string (concat " " (progn (when arg (forward-line 1))
  18917. (org-trim (delete-and-extract-region
  18918. (line-beginning-position)
  18919. (line-end-position)))))))
  18920. (unless (bobp) (delete-region (point) (1- (point))))
  18921. (goto-char (or (match-end 4)
  18922. (match-beginning 5)
  18923. (match-end 0)))
  18924. (skip-chars-backward " \t")
  18925. (save-excursion (insert string))
  18926. ;; Adjust alignment of tags.
  18927. (cond
  18928. ((not tags-column)) ;no tags
  18929. (org-auto-align-tags (org-set-tags nil t))
  18930. (t (org--align-tags-here tags-column)))) ;preserve tags column
  18931. (delete-indentation arg)))
  18932. (defun org-open-line (n)
  18933. "Insert a new row in tables, call `open-line' elsewhere.
  18934. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  18935. As a special case, when a document starts with a table, allow to
  18936. call `open-line' on the very first character."
  18937. (interactive "*p")
  18938. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  18939. (org-table-insert-row)
  18940. (open-line n)))
  18941. (defun org-return (&optional indent)
  18942. "Goto next table row or insert a newline.
  18943. Calls `org-table-next-row' or `newline', depending on context.
  18944. When optional INDENT argument is non-nil, call
  18945. `newline-and-indent' instead of `newline'.
  18946. When `org-return-follows-link' is non-nil and point is on
  18947. a timestamp or a link, call `org-open-at-point'. However, it
  18948. will not happen if point is in a table or on a \"dead\"
  18949. object (e.g., within a comment). In these case, you need to use
  18950. `org-open-at-point' directly."
  18951. (interactive)
  18952. (let ((context (if org-return-follows-link (org-element-context)
  18953. (org-element-at-point))))
  18954. (cond
  18955. ;; In a table, call `org-table-next-row'.
  18956. ((or (and (eq (org-element-type context) 'table)
  18957. (>= (point) (org-element-property :contents-begin context))
  18958. (< (point) (org-element-property :contents-end context)))
  18959. (org-element-lineage context '(table-row table-cell) t))
  18960. (org-table-justify-field-maybe)
  18961. (call-interactively #'org-table-next-row))
  18962. ;; On a link or a timestamp, call `org-open-at-point' if
  18963. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  18964. ;; locations, e.g., in a comment, as `org-open-at-point'.
  18965. ((and org-return-follows-link
  18966. (or (org-in-regexp org-ts-regexp-both nil t)
  18967. (org-in-regexp org-tsr-regexp-both nil t)
  18968. (org-in-regexp org-any-link-re nil t)))
  18969. (call-interactively #'org-open-at-point))
  18970. ;; Insert newline in heading, but preserve tags.
  18971. ((and (not (bolp))
  18972. (save-excursion (beginning-of-line)
  18973. (let ((case-fold-search nil))
  18974. (looking-at org-complex-heading-regexp))))
  18975. ;; At headline. Split line. However, if point is on keyword,
  18976. ;; priority cookie or tags, do not break any of them: add
  18977. ;; a newline after the headline instead.
  18978. (let ((tags-column (and (match-beginning 5)
  18979. (save-excursion (goto-char (match-beginning 5))
  18980. (current-column))))
  18981. (string
  18982. (when (and (match-end 4) (org-point-in-group (point) 4))
  18983. (delete-and-extract-region (point) (match-end 4)))))
  18984. ;; Adjust tag alignment.
  18985. (cond
  18986. ((not (and tags-column string)))
  18987. (org-auto-align-tags (org-set-tags nil t))
  18988. (t (org--align-tags-here tags-column))) ;preserve tags column
  18989. (end-of-line)
  18990. (org-show-entry)
  18991. (if indent (newline-and-indent) (newline))
  18992. (when string (save-excursion (insert (org-trim string))))))
  18993. ;; In a list, make sure indenting keeps trailing text within.
  18994. ((and indent
  18995. (not (eolp))
  18996. (org-element-lineage context '(item)))
  18997. (let ((trailing-data
  18998. (delete-and-extract-region (point) (line-end-position))))
  18999. (newline-and-indent)
  19000. (save-excursion (insert trailing-data))))
  19001. (t (if indent (newline-and-indent) (newline))))))
  19002. (defun org-return-indent ()
  19003. "Goto next table row or insert a newline and indent.
  19004. Calls `org-table-next-row' or `newline-and-indent', depending on
  19005. context. See the individual commands for more information."
  19006. (interactive)
  19007. (org-return t))
  19008. (defun org-ctrl-c-tab (&optional _arg)
  19009. "Toggle columns width in a table, or show children.
  19010. Call `org-table-toggle-column-width' if point is in a table.
  19011. Otherwise, call `org-show-children'."
  19012. (interactive "p")
  19013. (call-interactively
  19014. (if (org-at-table-p) #'org-table-toggle-column-width
  19015. #'org-show-children)))
  19016. (defun org-ctrl-c-star ()
  19017. "Compute table, or change heading status of lines.
  19018. Calls `org-table-recalculate' or `org-toggle-heading',
  19019. depending on context."
  19020. (interactive)
  19021. (cond
  19022. ((org-at-table-p)
  19023. (call-interactively 'org-table-recalculate))
  19024. (t
  19025. ;; Convert all lines in region to list items
  19026. (call-interactively 'org-toggle-heading))))
  19027. (defun org-ctrl-c-minus ()
  19028. "Insert separator line in table or modify bullet status of line.
  19029. Also turns a plain line or a region of lines into list items.
  19030. Calls `org-table-insert-hline', `org-toggle-item', or
  19031. `org-cycle-list-bullet', depending on context."
  19032. (interactive)
  19033. (cond
  19034. ((org-at-table-p)
  19035. (call-interactively 'org-table-insert-hline))
  19036. ((org-region-active-p)
  19037. (call-interactively 'org-toggle-item))
  19038. ((org-in-item-p)
  19039. (call-interactively 'org-cycle-list-bullet))
  19040. (t
  19041. (call-interactively 'org-toggle-item))))
  19042. (defun org-toggle-heading (&optional nstars)
  19043. "Convert headings to normal text, or items or text to headings.
  19044. If there is no active region, only convert the current line.
  19045. With a `\\[universal-argument]' prefix, convert the whole list at
  19046. point into heading.
  19047. In a region:
  19048. - If the first non blank line is a headline, remove the stars
  19049. from all headlines in the region.
  19050. - If it is a normal line, turn each and every normal line (i.e.,
  19051. not an heading or an item) in the region into headings. If you
  19052. want to convert only the first line of this region, use one
  19053. universal prefix argument.
  19054. - If it is a plain list item, turn all plain list items into headings.
  19055. When converting a line into a heading, the number of stars is chosen
  19056. such that the lines become children of the current entry. However,
  19057. when a numeric prefix argument is given, its value determines the
  19058. number of stars to add."
  19059. (interactive "P")
  19060. (let ((skip-blanks
  19061. (function
  19062. ;; Return beginning of first non-blank line, starting from
  19063. ;; line at POS.
  19064. (lambda (pos)
  19065. (save-excursion
  19066. (goto-char pos)
  19067. (while (org-at-comment-p) (forward-line))
  19068. (skip-chars-forward " \r\t\n")
  19069. (point-at-bol)))))
  19070. beg end toggled)
  19071. ;; Determine boundaries of changes. If a universal prefix has
  19072. ;; been given, put the list in a region. If region ends at a bol,
  19073. ;; do not consider the last line to be in the region.
  19074. (when (and current-prefix-arg (org-at-item-p))
  19075. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19076. (org-mark-element))
  19077. (if (org-region-active-p)
  19078. (setq beg (funcall skip-blanks (region-beginning))
  19079. end (copy-marker (save-excursion
  19080. (goto-char (region-end))
  19081. (if (bolp) (point) (point-at-eol)))))
  19082. (setq beg (funcall skip-blanks (point-at-bol))
  19083. end (copy-marker (point-at-eol))))
  19084. ;; Ensure inline tasks don't count as headings.
  19085. (org-with-limited-levels
  19086. (save-excursion
  19087. (goto-char beg)
  19088. (cond
  19089. ;; Case 1. Started at an heading: de-star headings.
  19090. ((org-at-heading-p)
  19091. (while (< (point) end)
  19092. (when (org-at-heading-p t)
  19093. (looking-at org-outline-regexp) (replace-match "")
  19094. (setq toggled t))
  19095. (forward-line)))
  19096. ;; Case 2. Started at an item: change items into headlines.
  19097. ;; One star will be added by `org-list-to-subtree'.
  19098. ((org-at-item-p)
  19099. (while (< (point) end)
  19100. (when (org-at-item-p)
  19101. ;; Pay attention to cases when region ends before list.
  19102. (let* ((struct (org-list-struct))
  19103. (list-end
  19104. (min (org-list-get-bottom-point struct) (1+ end))))
  19105. (save-restriction
  19106. (narrow-to-region (point) list-end)
  19107. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  19108. (setq toggled t))
  19109. (forward-line)))
  19110. ;; Case 3. Started at normal text: make every line an heading,
  19111. ;; skipping headlines and items.
  19112. (t (let* ((stars
  19113. (make-string
  19114. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19115. (add-stars
  19116. (cond (nstars "") ; stars from prefix only
  19117. ((equal stars "") "*") ; before first heading
  19118. (org-odd-levels-only "**") ; inside heading, odd
  19119. (t "*"))) ; inside heading, oddeven
  19120. (rpl (concat stars add-stars " "))
  19121. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19122. (while (< (point) (if (equal nstars '(4)) lend end))
  19123. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19124. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19125. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19126. (forward-line)))))))
  19127. (unless toggled (message "Cannot toggle heading from here"))))
  19128. (defun org-meta-return (&optional arg)
  19129. "Insert a new heading or wrap a region in a table.
  19130. Calls `org-insert-heading', `org-insert-item' or
  19131. `org-table-wrap-region', depending on context. When called with
  19132. an argument, unconditionally call `org-insert-heading'."
  19133. (interactive "P")
  19134. (org-check-before-invisible-edit 'insert)
  19135. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19136. (call-interactively (cond (arg #'org-insert-heading)
  19137. ((org-at-table-p) #'org-table-wrap-region)
  19138. ((org-in-item-p) #'org-insert-item)
  19139. (t #'org-insert-heading)))))
  19140. ;;; Menu entries
  19141. (defsubst org-in-subtree-not-table-p ()
  19142. "Are we in a subtree and not in a table?"
  19143. (and (not (org-before-first-heading-p))
  19144. (not (org-at-table-p))))
  19145. ;; Define the Org mode menus
  19146. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19147. '("Tbl"
  19148. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19149. ["Next Field" org-cycle (org-at-table-p)]
  19150. ["Previous Field" org-shifttab (org-at-table-p)]
  19151. ["Next Row" org-return (org-at-table-p)]
  19152. "--"
  19153. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19154. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19155. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19156. "--"
  19157. ("Column"
  19158. ["Move Column Left" org-metaleft (org-at-table-p)]
  19159. ["Move Column Right" org-metaright (org-at-table-p)]
  19160. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19161. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  19162. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  19163. ("Row"
  19164. ["Move Row Up" org-metaup (org-at-table-p)]
  19165. ["Move Row Down" org-metadown (org-at-table-p)]
  19166. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19167. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19168. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19169. "--"
  19170. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19171. ("Rectangle"
  19172. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19173. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19174. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19175. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19176. "--"
  19177. ("Calculate"
  19178. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19179. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19180. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19181. "--"
  19182. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19183. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19184. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19185. "--"
  19186. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19187. "--"
  19188. ["Sum Column/Rectangle" org-table-sum
  19189. (or (org-at-table-p) (org-region-active-p))]
  19190. ["Which Column?" org-table-current-column (org-at-table-p)])
  19191. ["Debug Formulas"
  19192. org-table-toggle-formula-debugger
  19193. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  19194. ["Show Col/Row Numbers"
  19195. org-table-toggle-coordinate-overlays
  19196. :style toggle
  19197. :selected (bound-and-true-p org-table-overlay-coordinates)]
  19198. "--"
  19199. ["Create" org-table-create (not (org-at-table-p))]
  19200. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19201. ["Import from File" org-table-import (not (org-at-table-p))]
  19202. ["Export to File" org-table-export (org-at-table-p)]
  19203. "--"
  19204. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19205. "--"
  19206. ("Plot"
  19207. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19208. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19209. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19210. '("Org"
  19211. ("Show/Hide"
  19212. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19213. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19214. ["Sparse Tree..." org-sparse-tree t]
  19215. ["Reveal Context" org-reveal t]
  19216. ["Show All" outline-show-all t]
  19217. "--"
  19218. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19219. "--"
  19220. ["New Heading" org-insert-heading t]
  19221. ("Navigate Headings"
  19222. ["Up" outline-up-heading t]
  19223. ["Next" outline-next-visible-heading t]
  19224. ["Previous" outline-previous-visible-heading t]
  19225. ["Next Same Level" outline-forward-same-level t]
  19226. ["Previous Same Level" outline-backward-same-level t]
  19227. "--"
  19228. ["Jump" org-goto t])
  19229. ("Edit Structure"
  19230. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19231. "--"
  19232. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19233. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19234. "--"
  19235. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19236. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19237. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19238. "--"
  19239. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19240. "--"
  19241. ["Copy visible text" org-copy-visible t]
  19242. "--"
  19243. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19244. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19245. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19246. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19247. "--"
  19248. ["Sort Region/Children" org-sort t]
  19249. "--"
  19250. ["Convert to odd levels" org-convert-to-odd-levels t]
  19251. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19252. ("Editing"
  19253. ["Emphasis..." org-emphasize t]
  19254. ["Edit Source Example" org-edit-special t]
  19255. "--"
  19256. ["Footnote new/jump" org-footnote-action t]
  19257. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19258. ("Archive"
  19259. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19260. "--"
  19261. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19262. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19263. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19264. )
  19265. "--"
  19266. ("Hyperlinks"
  19267. ["Store Link (Global)" org-store-link t]
  19268. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19269. ["Insert Link" org-insert-link t]
  19270. ["Follow Link" org-open-at-point t]
  19271. "--"
  19272. ["Next link" org-next-link t]
  19273. ["Previous link" org-previous-link t]
  19274. "--"
  19275. ["Descriptive Links"
  19276. org-toggle-link-display
  19277. :style radio
  19278. :selected org-descriptive-links
  19279. ]
  19280. ["Literal Links"
  19281. org-toggle-link-display
  19282. :style radio
  19283. :selected (not org-descriptive-links)])
  19284. "--"
  19285. ("TODO Lists"
  19286. ["TODO/DONE/-" org-todo t]
  19287. ("Select keyword"
  19288. ["Next keyword" org-shiftright (org-at-heading-p)]
  19289. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19290. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19291. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19292. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19293. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19294. ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
  19295. "--"
  19296. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19297. :selected org-enforce-todo-dependencies :style toggle :active t]
  19298. "Settings for tree at point"
  19299. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19300. :selected (org-entry-get nil "ORDERED")
  19301. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19302. ["Do Children parallel" org-toggle-ordered-property :style radio
  19303. :selected (not (org-entry-get nil "ORDERED"))
  19304. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19305. "--"
  19306. ["Set Priority" org-priority t]
  19307. ["Priority Up" org-shiftup t]
  19308. ["Priority Down" org-shiftdown t]
  19309. "--"
  19310. ["Get news from all feeds" org-feed-update-all t]
  19311. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19312. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19313. ("TAGS and Properties"
  19314. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19315. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19316. "--"
  19317. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19318. ["Column view of properties" org-columns t]
  19319. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19320. ("Dates and Scheduling"
  19321. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19322. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19323. ("Change Date"
  19324. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  19325. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  19326. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  19327. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  19328. ["Compute Time Range" org-evaluate-time-range t]
  19329. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19330. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19331. "--"
  19332. ["Custom time format" org-toggle-time-stamp-overlays
  19333. :style radio :selected org-display-custom-times]
  19334. "--"
  19335. ["Goto Calendar" org-goto-calendar t]
  19336. ["Date from Calendar" org-date-from-calendar t]
  19337. "--"
  19338. ["Start/Restart Timer" org-timer-start t]
  19339. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19340. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19341. ["Insert Timer String" org-timer t]
  19342. ["Insert Timer Item" org-timer-item t])
  19343. ("Logging work"
  19344. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19345. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19346. ["Clock out" org-clock-out t]
  19347. ["Clock cancel" org-clock-cancel t]
  19348. "--"
  19349. ["Mark as default task" org-clock-mark-default-task t]
  19350. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19351. ["Goto running clock" org-clock-goto t]
  19352. "--"
  19353. ["Display times" org-clock-display t]
  19354. ["Create clock table" org-clock-report t]
  19355. "--"
  19356. ["Record DONE time"
  19357. (progn (setq org-log-done (not org-log-done))
  19358. (message "Switching to %s will %s record a timestamp"
  19359. (car org-done-keywords)
  19360. (if org-log-done "automatically" "not")))
  19361. :style toggle :selected org-log-done])
  19362. "--"
  19363. ["Agenda Command..." org-agenda t]
  19364. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19365. ("File List for Agenda")
  19366. ("Special views current file"
  19367. ["TODO Tree" org-show-todo-tree t]
  19368. ["Check Deadlines" org-check-deadlines t]
  19369. ["Tags/Property tree" org-match-sparse-tree t])
  19370. "--"
  19371. ["Export/Publish..." org-export-dispatch t]
  19372. ("LaTeX"
  19373. ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
  19374. :selected org-cdlatex-mode]
  19375. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19376. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19377. ["Modify math symbol" org-cdlatex-math-modify
  19378. (org-inside-LaTeX-fragment-p)]
  19379. ["Insert citation" org-reftex-citation t])
  19380. "--"
  19381. ("MobileOrg"
  19382. ["Push Files and Views" org-mobile-push t]
  19383. ["Get Captured and Flagged" org-mobile-pull t]
  19384. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
  19385. "--"
  19386. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19387. "--"
  19388. ("Documentation"
  19389. ["Show Version" org-version t]
  19390. ["Info Documentation" org-info t])
  19391. ("Customize"
  19392. ["Browse Org Group" org-customize t]
  19393. "--"
  19394. ["Expand This Menu" org-create-customize-menu
  19395. (fboundp 'customize-menu-create)])
  19396. ["Send bug report" org-submit-bug-report t]
  19397. "--"
  19398. ("Refresh/Reload"
  19399. ["Refresh setup current buffer" org-mode-restart t]
  19400. ["Reload Org (after update)" org-reload t]
  19401. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  19402. ))
  19403. (defun org-info (&optional node)
  19404. "Read documentation for Org in the info system.
  19405. With optional NODE, go directly to that node."
  19406. (interactive)
  19407. (info (format "(org)%s" (or node ""))))
  19408. ;;;###autoload
  19409. (defun org-submit-bug-report ()
  19410. "Submit a bug report on Org via mail.
  19411. Don't hesitate to report any problems or inaccurate documentation.
  19412. If you don't have setup sending mail from (X)Emacs, please copy the
  19413. output buffer into your mail program, as it gives us important
  19414. information about your Org version and configuration."
  19415. (interactive)
  19416. (require 'reporter)
  19417. (defvar reporter-prompt-for-summary-p)
  19418. (org-load-modules-maybe)
  19419. (org-require-autoloaded-modules)
  19420. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19421. (reporter-submit-bug-report
  19422. "emacs-orgmode@gnu.org"
  19423. (org-version nil 'full)
  19424. (let (list)
  19425. (save-window-excursion
  19426. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19427. (delete-other-windows)
  19428. (erase-buffer)
  19429. (insert "You are about to submit a bug report to the Org mailing list.
  19430. We would like to add your full Org and Outline configuration to the
  19431. bug report. This greatly simplifies the work of the maintainer and
  19432. other experts on the mailing list.
  19433. HOWEVER, some variables you have customized may contain private
  19434. information. The names of customers, colleagues, or friends, might
  19435. appear in the form of file names, tags, todo states, or search strings.
  19436. If you answer yes to the prompt, you might want to check and remove
  19437. such private information before sending the email.")
  19438. (add-text-properties (point-min) (point-max) '(face org-warning))
  19439. (when (yes-or-no-p "Include your Org configuration ")
  19440. (mapatoms
  19441. (lambda (v)
  19442. (and (boundp v)
  19443. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19444. (or (and (symbol-value v)
  19445. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19446. (and
  19447. (get v 'custom-type) (get v 'standard-value)
  19448. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19449. (push v list)))))
  19450. (kill-buffer (get-buffer "*Warn about privacy*"))
  19451. list))
  19452. nil nil
  19453. "Remember to cover the basics, that is, what you expected to happen and
  19454. what in fact did happen. You don't know how to make a good report? See
  19455. http://orgmode.org/manual/Feedback.html#Feedback
  19456. Your bug report will be posted to the Org mailing list.
  19457. ------------------------------------------------------------------------")
  19458. (save-excursion
  19459. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19460. (replace-match "\\1Bug: \\3 [\\2]")))))
  19461. (defun org-install-agenda-files-menu ()
  19462. (let ((bl (buffer-list)))
  19463. (save-excursion
  19464. (while bl
  19465. (set-buffer (pop bl))
  19466. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19467. (when (derived-mode-p 'org-mode)
  19468. (easy-menu-change
  19469. '("Org") "File List for Agenda"
  19470. (append
  19471. (list
  19472. ["Edit File List" (org-edit-agenda-file-list) t]
  19473. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19474. ["Remove Current File from List" org-remove-file t]
  19475. ["Cycle through agenda files" org-cycle-agenda-files t]
  19476. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19477. "--")
  19478. (mapcar 'org-file-menu-entry
  19479. ;; Prevent initialization from failing.
  19480. (ignore-errors (org-agenda-files t)))))))))
  19481. ;;;; Documentation
  19482. (defun org-require-autoloaded-modules ()
  19483. (interactive)
  19484. (mapc #'require
  19485. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19486. org-table org-timer)))
  19487. ;;;###autoload
  19488. (defun org-reload (&optional uncompiled)
  19489. "Reload all org lisp files.
  19490. With prefix arg UNCOMPILED, load the uncompiled versions."
  19491. (interactive "P")
  19492. (require 'loadhist)
  19493. (let* ((org-dir (org-find-library-dir "org"))
  19494. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  19495. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  19496. (remove-re (format "\\`%s\\'"
  19497. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  19498. (feats (delete-dups
  19499. (mapcar 'file-name-sans-extension
  19500. (mapcar 'file-name-nondirectory
  19501. (delq nil
  19502. (mapcar 'feature-file
  19503. features))))))
  19504. (lfeat (append
  19505. (sort
  19506. (setq feats
  19507. (delq nil (mapcar
  19508. (lambda (f)
  19509. (if (and (string-match feature-re f)
  19510. (not (string-match remove-re f)))
  19511. f nil))
  19512. feats)))
  19513. 'string-lessp)
  19514. (list "org-version" "org")))
  19515. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  19516. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  19517. load-uncore load-misses)
  19518. (setq load-misses
  19519. (delq 't
  19520. (mapcar (lambda (f)
  19521. (or (org-load-noerror-mustsuffix (concat org-dir f))
  19522. (and (string= org-dir contrib-dir)
  19523. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  19524. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  19525. (add-to-list 'load-uncore f 'append)
  19526. 't)
  19527. f))
  19528. lfeat)))
  19529. (when load-uncore
  19530. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  19531. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  19532. (if load-misses
  19533. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  19534. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  19535. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  19536. ;;;###autoload
  19537. (defun org-customize ()
  19538. "Call the customize function with org as argument."
  19539. (interactive)
  19540. (org-load-modules-maybe)
  19541. (org-require-autoloaded-modules)
  19542. (customize-browse 'org))
  19543. (defun org-create-customize-menu ()
  19544. "Create a full customization menu for Org mode, insert it into the menu."
  19545. (interactive)
  19546. (org-load-modules-maybe)
  19547. (org-require-autoloaded-modules)
  19548. (if (fboundp 'customize-menu-create)
  19549. (progn
  19550. (easy-menu-change
  19551. '("Org") "Customize"
  19552. `(["Browse Org group" org-customize t]
  19553. "--"
  19554. ,(customize-menu-create 'org)
  19555. ["Set" Custom-set t]
  19556. ["Save" Custom-save t]
  19557. ["Reset to Current" Custom-reset-current t]
  19558. ["Reset to Saved" Custom-reset-saved t]
  19559. ["Reset to Standard Settings" Custom-reset-standard t]))
  19560. (message "\"Org\"-menu now contains full customization menu"))
  19561. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  19562. ;;;; Miscellaneous stuff
  19563. ;;; Generally useful functions
  19564. (defun org-link-display-format (s)
  19565. "Replace links in string S with their description.
  19566. If there is no description, use the link target."
  19567. (save-match-data
  19568. (replace-regexp-in-string
  19569. org-bracket-link-analytic-regexp
  19570. (lambda (m)
  19571. (if (match-end 5) (match-string 5 m)
  19572. (concat (match-string 1 m) (match-string 3 m))))
  19573. s nil t)))
  19574. (defun org-toggle-link-display ()
  19575. "Toggle the literal or descriptive display of links."
  19576. (interactive)
  19577. (if org-descriptive-links
  19578. (progn (org-remove-from-invisibility-spec '(org-link))
  19579. (org-restart-font-lock)
  19580. (setq org-descriptive-links nil))
  19581. (progn (add-to-invisibility-spec '(org-link))
  19582. (org-restart-font-lock)
  19583. (setq org-descriptive-links t))))
  19584. (defun org-in-clocktable-p ()
  19585. "Check if the cursor is in a clocktable."
  19586. (let ((pos (point)) start)
  19587. (save-excursion
  19588. (end-of-line 1)
  19589. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  19590. (setq start (match-beginning 0))
  19591. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  19592. (>= (match-end 0) pos)
  19593. start))))
  19594. (defun org-in-verbatim-emphasis ()
  19595. (save-match-data
  19596. (and (org-in-regexp org-verbatim-re 2)
  19597. (>= (point) (match-beginning 3))
  19598. (<= (point) (match-end 4)))))
  19599. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  19600. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  19601. (if (and marker (marker-buffer marker)
  19602. (buffer-live-p (marker-buffer marker)))
  19603. (progn
  19604. (pop-to-buffer-same-window (marker-buffer marker))
  19605. (when (or (> marker (point-max)) (< marker (point-min)))
  19606. (widen))
  19607. (goto-char marker)
  19608. (org-show-context 'org-goto))
  19609. (if bookmark
  19610. (bookmark-jump bookmark)
  19611. (error "Cannot find location"))))
  19612. (defun org-quote-csv-field (s)
  19613. "Quote field for inclusion in CSV material."
  19614. (if (string-match "[\",]" s)
  19615. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  19616. s))
  19617. (defun org-force-self-insert (N)
  19618. "Needed to enforce self-insert under remapping."
  19619. (interactive "p")
  19620. (self-insert-command N))
  19621. (defun org-get-indentation (&optional line)
  19622. "Get the indentation of the current line, interpreting tabs.
  19623. When LINE is given, assume it represents a line and compute its indentation."
  19624. (if line
  19625. (when (string-match "^ *" (org-remove-tabs line))
  19626. (match-end 0))
  19627. (save-excursion
  19628. (beginning-of-line 1)
  19629. (skip-chars-forward " \t")
  19630. (current-column))))
  19631. (defun org-get-string-indentation (s)
  19632. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  19633. (let ((n -1) (i 0) (w tab-width) c)
  19634. (catch 'exit
  19635. (while (< (setq n (1+ n)) (length s))
  19636. (setq c (aref s n))
  19637. (cond ((= c ?\ ) (setq i (1+ i)))
  19638. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  19639. (t (throw 'exit t)))))
  19640. i))
  19641. (defun org-fix-indentation (line ind)
  19642. "Fix indentation in LINE.
  19643. IND is a cons cell with target and minimum indentation.
  19644. If the current indentation in LINE is smaller than the minimum,
  19645. leave it alone. If it is larger than ind, set it to the target."
  19646. (let* ((l (org-remove-tabs line))
  19647. (i (org-get-indentation l))
  19648. (i1 (car ind)) (i2 (cdr ind)))
  19649. (when (>= i i2) (setq l (substring line i2)))
  19650. (if (> i1 0)
  19651. (concat (make-string i1 ?\ ) l)
  19652. l)))
  19653. (defun org-fill-template (template alist)
  19654. "Find each %key of ALIST in TEMPLATE and replace it."
  19655. (let ((case-fold-search nil))
  19656. (dolist (entry (sort (copy-sequence alist)
  19657. (lambda (a b) (< (length (car a)) (length (car b))))))
  19658. (setq template
  19659. (replace-regexp-in-string
  19660. (concat "%" (regexp-quote (car entry)))
  19661. (or (cdr entry) "") template t t)))
  19662. template))
  19663. (defun org-quote-vert (s)
  19664. "Replace \"|\" with \"\\vert\"."
  19665. (while (string-match "|" s)
  19666. (setq s (replace-match "\\vert" t t s)))
  19667. s)
  19668. (defun org-uuidgen-p (s)
  19669. "Is S an ID created by UUIDGEN?"
  19670. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  19671. (defun org-in-src-block-p (&optional inside)
  19672. "Whether point is in a code source block.
  19673. When INSIDE is non-nil, don't consider we are within a src block
  19674. when point is at #+BEGIN_SRC or #+END_SRC."
  19675. (let ((case-fold-search t))
  19676. (or (and (eq (get-char-property (point) 'src-block) t))
  19677. (and (not inside)
  19678. (save-match-data
  19679. (save-excursion
  19680. (beginning-of-line)
  19681. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  19682. (defun org-context ()
  19683. "Return a list of contexts of the current cursor position.
  19684. If several contexts apply, all are returned.
  19685. Each context entry is a list with a symbol naming the context, and
  19686. two positions indicating start and end of the context. Possible
  19687. contexts are:
  19688. :headline anywhere in a headline
  19689. :headline-stars on the leading stars in a headline
  19690. :todo-keyword on a TODO keyword (including DONE) in a headline
  19691. :tags on the TAGS in a headline
  19692. :priority on the priority cookie in a headline
  19693. :item on the first line of a plain list item
  19694. :item-bullet on the bullet/number of a plain list item
  19695. :checkbox on the checkbox in a plain list item
  19696. :table in an Org table
  19697. :table-special on a special filed in a table
  19698. :table-table in a table.el table
  19699. :clocktable in a clocktable
  19700. :src-block in a source block
  19701. :link on a hyperlink
  19702. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  19703. :target on a <<target>>
  19704. :radio-target on a <<<radio-target>>>
  19705. :latex-fragment on a LaTeX fragment
  19706. :latex-preview on a LaTeX fragment with overlaid preview image
  19707. This function expects the position to be visible because it uses font-lock
  19708. faces as a help to recognize the following contexts: :table-special, :link,
  19709. and :keyword."
  19710. (let* ((f (get-text-property (point) 'face))
  19711. (faces (if (listp f) f (list f)))
  19712. (case-fold-search t)
  19713. (p (point)) clist o)
  19714. ;; First the large context
  19715. (cond
  19716. ((org-at-heading-p t)
  19717. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  19718. (when (progn
  19719. (beginning-of-line 1)
  19720. (looking-at org-todo-line-tags-regexp))
  19721. (push (org-point-in-group p 1 :headline-stars) clist)
  19722. (push (org-point-in-group p 2 :todo-keyword) clist)
  19723. (push (org-point-in-group p 4 :tags) clist))
  19724. (goto-char p)
  19725. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  19726. (when (looking-at "\\[#[A-Z0-9]\\]")
  19727. (push (org-point-in-group p 0 :priority) clist)))
  19728. ((org-at-item-p)
  19729. (push (org-point-in-group p 2 :item-bullet) clist)
  19730. (push (list :item (point-at-bol)
  19731. (save-excursion (org-end-of-item) (point)))
  19732. clist)
  19733. (and (org-at-item-checkbox-p)
  19734. (push (org-point-in-group p 0 :checkbox) clist)))
  19735. ((org-at-table-p)
  19736. (push (list :table (org-table-begin) (org-table-end)) clist)
  19737. (when (memq 'org-formula faces)
  19738. (push (list :table-special
  19739. (previous-single-property-change p 'face)
  19740. (next-single-property-change p 'face)) clist)))
  19741. ((org-at-table-p 'any)
  19742. (push (list :table-table) clist)))
  19743. (goto-char p)
  19744. (let ((case-fold-search t))
  19745. ;; New the "medium" contexts: clocktables, source blocks
  19746. (cond ((org-in-clocktable-p)
  19747. (push (list :clocktable
  19748. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  19749. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  19750. (match-beginning 1))
  19751. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  19752. (match-end 0))) clist))
  19753. ((org-in-src-block-p)
  19754. (push (list :src-block
  19755. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  19756. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  19757. (match-beginning 1))
  19758. (and (search-forward "#+END_SRC" nil t)
  19759. (match-beginning 0))) clist))))
  19760. (goto-char p)
  19761. ;; Now the small context
  19762. (cond
  19763. ((org-at-timestamp-p)
  19764. (push (org-point-in-group p 0 :timestamp) clist))
  19765. ((memq 'org-link faces)
  19766. (push (list :link
  19767. (previous-single-property-change p 'face)
  19768. (next-single-property-change p 'face)) clist))
  19769. ((memq 'org-special-keyword faces)
  19770. (push (list :keyword
  19771. (previous-single-property-change p 'face)
  19772. (next-single-property-change p 'face)) clist))
  19773. ((org-at-target-p)
  19774. (push (org-point-in-group p 0 :target) clist)
  19775. (goto-char (1- (match-beginning 0)))
  19776. (when (looking-at org-radio-target-regexp)
  19777. (push (org-point-in-group p 0 :radio-target) clist))
  19778. (goto-char p))
  19779. ((setq o (cl-some
  19780. (lambda (o)
  19781. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  19782. o))
  19783. (overlays-at (point))))
  19784. (push (list :latex-fragment
  19785. (overlay-start o) (overlay-end o)) clist)
  19786. (push (list :latex-preview
  19787. (overlay-start o) (overlay-end o)) clist))
  19788. ((org-inside-LaTeX-fragment-p)
  19789. ;; FIXME: positions wrong.
  19790. (push (list :latex-fragment (point) (point)) clist)))
  19791. (setq clist (nreverse (delq nil clist)))
  19792. clist))
  19793. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  19794. "Non-nil when point is between matches of START-RE and END-RE.
  19795. Also return a non-nil value when point is on one of the matches.
  19796. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  19797. buffer positions. Default values are the positions of headlines
  19798. surrounding the point.
  19799. The functions returns a cons cell whose car (resp. cdr) is the
  19800. position before START-RE (resp. after END-RE)."
  19801. (save-match-data
  19802. (let ((pos (point))
  19803. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  19804. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  19805. beg end)
  19806. (save-excursion
  19807. ;; Point is on a block when on START-RE or if START-RE can be
  19808. ;; found before it...
  19809. (and (or (org-in-regexp start-re)
  19810. (re-search-backward start-re limit-up t))
  19811. (setq beg (match-beginning 0))
  19812. ;; ... and END-RE after it...
  19813. (goto-char (match-end 0))
  19814. (re-search-forward end-re limit-down t)
  19815. (> (setq end (match-end 0)) pos)
  19816. ;; ... without another START-RE in-between.
  19817. (goto-char (match-beginning 0))
  19818. (not (re-search-backward start-re (1+ beg) t))
  19819. ;; Return value.
  19820. (cons beg end))))))
  19821. (defun org-in-block-p (names)
  19822. "Non-nil when point belongs to a block whose name belongs to NAMES.
  19823. NAMES is a list of strings containing names of blocks.
  19824. Return first block name matched, or nil. Beware that in case of
  19825. nested blocks, the returned name may not belong to the closest
  19826. block from point."
  19827. (save-match-data
  19828. (catch 'exit
  19829. (let ((case-fold-search t)
  19830. (lim-up (save-excursion (outline-previous-heading)))
  19831. (lim-down (save-excursion (outline-next-heading))))
  19832. (dolist (name names)
  19833. (let ((n (regexp-quote name)))
  19834. (when (org-between-regexps-p
  19835. (concat "^[ \t]*#\\+begin_" n)
  19836. (concat "^[ \t]*#\\+end_" n)
  19837. lim-up lim-down)
  19838. (throw 'exit n)))))
  19839. nil)))
  19840. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  19841. "Call `multi-occur' with buffers for all agenda files."
  19842. (interactive "sOrg-files matching: ")
  19843. (let* ((files (org-agenda-files))
  19844. (tnames (mapcar #'file-truename files))
  19845. (extra org-agenda-text-search-extra-files))
  19846. (when (eq (car extra) 'agenda-archives)
  19847. (setq extra (cdr extra))
  19848. (setq files (org-add-archive-files files)))
  19849. (dolist (f extra)
  19850. (unless (member (file-truename f) tnames)
  19851. (unless (member f files) (setq files (append files (list f))))
  19852. (setq tnames (append tnames (list (file-truename f))))))
  19853. (multi-occur
  19854. (mapcar (lambda (x)
  19855. (with-current-buffer
  19856. ;; FIXME: Why not just (find-file-noselect x)?
  19857. ;; Is it to avoid the "revert buffer" prompt?
  19858. (or (get-file-buffer x) (find-file-noselect x))
  19859. (widen)
  19860. (current-buffer)))
  19861. files)
  19862. regexp)))
  19863. (add-hook 'occur-mode-find-occurrence-hook
  19864. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  19865. (defun org-occur-link-in-agenda-files ()
  19866. "Create a link and search for it in the agendas.
  19867. The link is not stored in `org-stored-links', it is just created
  19868. for the search purpose."
  19869. (interactive)
  19870. (let ((link (condition-case nil
  19871. (org-store-link nil)
  19872. (error "Unable to create a link to here"))))
  19873. (org-occur-in-agenda-files (regexp-quote link))))
  19874. (defun org-back-over-empty-lines ()
  19875. "Move backwards over whitespace, to the beginning of the first empty line.
  19876. Returns the number of empty lines passed."
  19877. (let ((pos (point)))
  19878. (if (cdr (assq 'heading org-blank-before-new-entry))
  19879. (skip-chars-backward " \t\n\r")
  19880. (unless (eobp)
  19881. (forward-line -1)))
  19882. (beginning-of-line 2)
  19883. (goto-char (min (point) pos))
  19884. (count-lines (point) pos)))
  19885. (defun org-switch-to-buffer-other-window (&rest args)
  19886. "Switch to buffer in a second window on the current frame.
  19887. In particular, do not allow pop-up frames.
  19888. Returns the newly created buffer."
  19889. (org-no-popups
  19890. (apply 'switch-to-buffer-other-window args)))
  19891. (defun org-replace-escapes (string table)
  19892. "Replace %-escapes in STRING with values in TABLE.
  19893. TABLE is an association list with keys like \"%a\" and string values.
  19894. The sequences in STRING may contain normal field width and padding information,
  19895. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  19896. so values can contain further %-escapes if they are define later in TABLE."
  19897. (let ((tbl (copy-alist table))
  19898. (case-fold-search nil)
  19899. (pchg 0)
  19900. re rpl)
  19901. (dolist (e tbl)
  19902. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  19903. (when (and (cdr e) (string-match re (cdr e)))
  19904. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  19905. (safe "SREF"))
  19906. (add-text-properties 0 3 (list 'sref sref) safe)
  19907. (setcdr e (replace-match safe t t (cdr e)))))
  19908. (while (string-match re string)
  19909. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  19910. (cdr e)))
  19911. (setq string (replace-match rpl t t string))))
  19912. (while (setq pchg (next-property-change pchg string))
  19913. (let ((sref (get-text-property pchg 'sref string)))
  19914. (when (and sref (string-match "SREF" string pchg))
  19915. (setq string (replace-match sref t t string)))))
  19916. string))
  19917. ;;; TODO: Only called once, from ox-odt which should probably use
  19918. ;;; org-export-inline-image-p or something.
  19919. (defun org-file-image-p (file)
  19920. "Return non-nil if FILE is an image."
  19921. (save-match-data
  19922. (string-match (image-file-name-regexp) file)))
  19923. (defun org-get-cursor-date (&optional with-time)
  19924. "Return the date at cursor in as a time.
  19925. This works in the calendar and in the agenda, anywhere else it just
  19926. returns the current time.
  19927. If WITH-TIME is non-nil, returns the time of the event at point (in
  19928. the agenda) or the current time of the day."
  19929. (let (date day defd tp hod mod)
  19930. (when with-time
  19931. (setq tp (get-text-property (point) 'time))
  19932. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  19933. (setq hod (string-to-number (match-string 1 tp))
  19934. mod (string-to-number (match-string 2 tp))))
  19935. (or tp (let ((now (decode-time)))
  19936. (setq hod (nth 2 now)
  19937. mod (nth 1 now)))))
  19938. (cond
  19939. ((eq major-mode 'calendar-mode)
  19940. (setq date (calendar-cursor-to-date)
  19941. defd (encode-time 0 (or mod 0) (or hod 0)
  19942. (nth 1 date) (nth 0 date) (nth 2 date))))
  19943. ((eq major-mode 'org-agenda-mode)
  19944. (setq day (get-text-property (point) 'day))
  19945. (when day
  19946. (setq date (calendar-gregorian-from-absolute day)
  19947. defd (encode-time 0 (or mod 0) (or hod 0)
  19948. (nth 1 date) (nth 0 date) (nth 2 date))))))
  19949. (or defd (current-time))))
  19950. (defun org-mark-subtree (&optional up)
  19951. "Mark the current subtree.
  19952. This puts point at the start of the current subtree, and mark at
  19953. the end. If a numeric prefix UP is given, move up into the
  19954. hierarchy of headlines by UP levels before marking the subtree."
  19955. (interactive "P")
  19956. (org-with-limited-levels
  19957. (cond ((org-at-heading-p) (beginning-of-line))
  19958. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  19959. (t (outline-previous-visible-heading 1))))
  19960. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  19961. (if (called-interactively-p 'any)
  19962. (call-interactively 'org-mark-element)
  19963. (org-mark-element)))
  19964. (defun org-file-newer-than-p (file time)
  19965. "Non-nil if FILE is newer than TIME.
  19966. FILE is a filename, as a string, TIME is a list of integers, as
  19967. returned by, e.g., `current-time'."
  19968. (and (file-exists-p file)
  19969. ;; Only compare times up to whole seconds as some file-systems
  19970. ;; (e.g. HFS+) do not retain any finer granularity. As
  19971. ;; a consequence, make sure we return non-nil when the two
  19972. ;; times are equal.
  19973. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  19974. (cl-subseq time 0 2)))))
  19975. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  19976. "Compile a SOURCE file using PROCESS.
  19977. PROCESS is either a function or a list of shell commands, as
  19978. strings. EXT is a file extension, without the leading dot, as
  19979. a string. It is used to check if the process actually succeeded.
  19980. PROCESS must create a file with the same base name and directory
  19981. as SOURCE, but ending with EXT. The function then returns its
  19982. filename. Otherwise, it raises an error. The error message can
  19983. then be refined by providing string ERR-MSG, which is appended to
  19984. the standard message.
  19985. If PROCESS is a function, it is called with a single argument:
  19986. the SOURCE file.
  19987. If it is a list of commands, each of them is called using
  19988. `shell-command'. By default, in each command, %b, %f, %F, %o and
  19989. %O are replaced with, respectively, SOURCE base name, name, full
  19990. name, directory and absolute output file name. It is possible,
  19991. however, to use more place-holders by specifying them in optional
  19992. argument SPEC, as an alist following the pattern
  19993. (CHARACTER . REPLACEMENT-STRING).
  19994. When PROCESS is a list of commands, optional argument LOG-BUF can
  19995. be set to a buffer or a buffer name. `shell-command' then uses
  19996. it for output."
  19997. (let* ((base-name (file-name-base source))
  19998. (full-name (file-truename source))
  19999. (out-dir (or (file-name-directory source) "./"))
  20000. (output (expand-file-name (concat base-name "." ext) out-dir))
  20001. (time (current-time))
  20002. (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
  20003. (save-window-excursion
  20004. (pcase process
  20005. ((pred functionp) (funcall process (shell-quote-argument source)))
  20006. ((pred consp)
  20007. (let ((log-buf (and log-buf (get-buffer-create log-buf)))
  20008. (spec (append spec
  20009. `((?b . ,(shell-quote-argument base-name))
  20010. (?f . ,(shell-quote-argument source))
  20011. (?F . ,(shell-quote-argument full-name))
  20012. (?o . ,(shell-quote-argument out-dir))
  20013. (?O . ,(shell-quote-argument output))))))
  20014. (dolist (command process)
  20015. (shell-command (format-spec command spec) log-buf))
  20016. (when log-buf (with-current-buffer log-buf (compilation-mode)))))
  20017. (_ (error "No valid command to process %S%s" source err-msg))))
  20018. ;; Check for process failure. Output file is expected to be
  20019. ;; located in the same directory as SOURCE.
  20020. (unless (org-file-newer-than-p output time)
  20021. (error (format "File %S wasn't produced%s" output err-msg)))
  20022. output))
  20023. ;;; Indentation
  20024. (defvar org-element-greater-elements)
  20025. (defun org--get-expected-indentation (element contentsp)
  20026. "Expected indentation column for current line, according to ELEMENT.
  20027. ELEMENT is an element containing point. CONTENTSP is non-nil
  20028. when indentation is to be computed according to contents of
  20029. ELEMENT."
  20030. (let ((type (org-element-type element))
  20031. (start (org-element-property :begin element))
  20032. (post-affiliated (org-element-property :post-affiliated element)))
  20033. (org-with-wide-buffer
  20034. (cond
  20035. (contentsp
  20036. (cl-case type
  20037. ((diary-sexp footnote-definition) 0)
  20038. ((headline inlinetask nil)
  20039. (if (not org-adapt-indentation) 0
  20040. (let ((level (org-current-level)))
  20041. (if level (1+ level) 0))))
  20042. ((item plain-list) (org-list-item-body-column post-affiliated))
  20043. (t
  20044. (goto-char start)
  20045. (org-get-indentation))))
  20046. ((memq type '(headline inlinetask nil))
  20047. (if (org-match-line "[ \t]*$")
  20048. (org--get-expected-indentation element t)
  20049. 0))
  20050. ((memq type '(diary-sexp footnote-definition)) 0)
  20051. ;; First paragraph of a footnote definition or an item.
  20052. ;; Indent like parent.
  20053. ((< (line-beginning-position) start)
  20054. (org--get-expected-indentation
  20055. (org-element-property :parent element) t))
  20056. ;; At first line: indent according to previous sibling, if any,
  20057. ;; ignoring footnote definitions and inline tasks, or parent's
  20058. ;; contents.
  20059. ((= (line-beginning-position) start)
  20060. (catch 'exit
  20061. (while t
  20062. (if (= (point-min) start) (throw 'exit 0)
  20063. (goto-char (1- start))
  20064. (let* ((previous (org-element-at-point))
  20065. (parent previous))
  20066. (while (and parent (<= (org-element-property :end parent) start))
  20067. (setq previous parent
  20068. parent (org-element-property :parent parent)))
  20069. (cond
  20070. ((not previous) (throw 'exit 0))
  20071. ((> (org-element-property :end previous) start)
  20072. (throw 'exit (org--get-expected-indentation previous t)))
  20073. ((memq (org-element-type previous)
  20074. '(footnote-definition inlinetask))
  20075. (setq start (org-element-property :begin previous)))
  20076. (t (goto-char (org-element-property :begin previous))
  20077. (throw 'exit
  20078. (if (bolp) (org-get-indentation)
  20079. ;; At first paragraph in an item or
  20080. ;; a footnote definition.
  20081. (org--get-expected-indentation
  20082. (org-element-property :parent previous) t))))))))))
  20083. ;; Otherwise, move to the first non-blank line above.
  20084. (t
  20085. (beginning-of-line)
  20086. (let ((pos (point)))
  20087. (skip-chars-backward " \r\t\n")
  20088. (cond
  20089. ;; Two blank lines end a footnote definition or a plain
  20090. ;; list. When we indent an empty line after them, the
  20091. ;; containing list or footnote definition is over, so it
  20092. ;; qualifies as a previous sibling. Therefore, we indent
  20093. ;; like its first line.
  20094. ((and (memq type '(footnote-definition plain-list))
  20095. (> (count-lines (point) pos) 2))
  20096. (goto-char start)
  20097. (org-get-indentation))
  20098. ;; Line above is the first one of a paragraph at the
  20099. ;; beginning of an item or a footnote definition. Indent
  20100. ;; like parent.
  20101. ((< (line-beginning-position) start)
  20102. (org--get-expected-indentation
  20103. (org-element-property :parent element) t))
  20104. ;; Line above is the beginning of an element, i.e., point
  20105. ;; was originally on the blank lines between element's start
  20106. ;; and contents.
  20107. ((= (line-beginning-position) post-affiliated)
  20108. (org--get-expected-indentation element t))
  20109. ;; POS is after contents in a greater element. Indent like
  20110. ;; the beginning of the element.
  20111. ((and (memq type org-element-greater-elements)
  20112. (let ((cend (org-element-property :contents-end element)))
  20113. (and cend (<= cend pos))))
  20114. ;; As a special case, if point is at the end of a footnote
  20115. ;; definition or an item, indent like the very last element
  20116. ;; within. If that last element is an item, indent like
  20117. ;; its contents.
  20118. (if (memq type '(footnote-definition item plain-list))
  20119. (let ((last (org-element-at-point)))
  20120. (goto-char pos)
  20121. (org--get-expected-indentation
  20122. last (eq (org-element-type last) 'item)))
  20123. (goto-char start)
  20124. (org-get-indentation)))
  20125. ;; In any other case, indent like the current line.
  20126. (t (org-get-indentation)))))))))
  20127. (defun org--align-node-property ()
  20128. "Align node property at point.
  20129. Alignment is done according to `org-property-format', which see."
  20130. (when (save-excursion
  20131. (beginning-of-line)
  20132. (looking-at org-property-re))
  20133. (replace-match
  20134. (concat (match-string 4)
  20135. (org-trim
  20136. (format org-property-format (match-string 1) (match-string 3))))
  20137. t t)))
  20138. (defun org-indent-line ()
  20139. "Indent line depending on context.
  20140. Indentation is done according to the following rules:
  20141. - Footnote definitions, diary sexps, headlines and inline tasks
  20142. have to start at column 0.
  20143. - On the very first line of an element, consider, in order, the
  20144. next rules until one matches:
  20145. 1. If there's a sibling element before, ignoring footnote
  20146. definitions and inline tasks, indent like its first line.
  20147. 2. If element has a parent, indent like its contents. More
  20148. precisely, if parent is an item, indent after the
  20149. description part, if any, or the bullet (see
  20150. `org-list-description-max-indent'). Else, indent like
  20151. parent's first line.
  20152. 3. Otherwise, indent relatively to current level, if
  20153. `org-adapt-indentation' is non-nil, or to left margin.
  20154. - On a blank line at the end of an element, indent according to
  20155. the type of the element. More precisely
  20156. 1. If element is a plain list, an item, or a footnote
  20157. definition, indent like the very last element within.
  20158. 2. If element is a paragraph, indent like its last non blank
  20159. line.
  20160. 3. Otherwise, indent like its very first line.
  20161. - In the code part of a source block, use language major mode
  20162. to indent current line if `org-src-tab-acts-natively' is
  20163. non-nil. If it is nil, do nothing.
  20164. - Otherwise, indent like the first non-blank line above.
  20165. The function doesn't indent an item as it could break the whole
  20166. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  20167. `\\[org-shiftmetaright]'.
  20168. Also align node properties according to `org-property-format'."
  20169. (interactive)
  20170. (cond
  20171. (orgstruct-is-++
  20172. (let ((indent-line-function
  20173. (cl-cadadr (assq 'indent-line-function org-fb-vars))))
  20174. (indent-according-to-mode)))
  20175. ((org-at-heading-p) 'noindent)
  20176. (t
  20177. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  20178. (type (org-element-type element)))
  20179. (cond ((and (memq type '(plain-list item))
  20180. (= (line-beginning-position)
  20181. (org-element-property :post-affiliated element)))
  20182. 'noindent)
  20183. ((and (eq type 'latex-environment)
  20184. (>= (point) (org-element-property :post-affiliated element))
  20185. (< (point) (org-with-wide-buffer
  20186. (goto-char (org-element-property :end element))
  20187. (skip-chars-backward " \r\t\n")
  20188. (line-beginning-position 2))))
  20189. 'noindent)
  20190. ((and (eq type 'src-block)
  20191. org-src-tab-acts-natively
  20192. (> (line-beginning-position)
  20193. (org-element-property :post-affiliated element))
  20194. (< (line-beginning-position)
  20195. (org-with-wide-buffer
  20196. (goto-char (org-element-property :end element))
  20197. (skip-chars-backward " \r\t\n")
  20198. (line-beginning-position))))
  20199. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  20200. (t
  20201. (let ((column (org--get-expected-indentation element nil)))
  20202. ;; Preserve current column.
  20203. (if (<= (current-column) (current-indentation))
  20204. (indent-line-to column)
  20205. (save-excursion (indent-line-to column))))
  20206. ;; Align node property. Also preserve current column.
  20207. (when (eq type 'node-property)
  20208. (let ((column (current-column)))
  20209. (org--align-node-property)
  20210. (org-move-to-column column)))))))))
  20211. (defun org-indent-region (start end)
  20212. "Indent each non-blank line in the region.
  20213. Called from a program, START and END specify the region to
  20214. indent. The function will not indent contents of example blocks,
  20215. verse blocks and export blocks as leading white spaces are
  20216. assumed to be significant there."
  20217. (interactive "r")
  20218. (save-excursion
  20219. (goto-char start)
  20220. (skip-chars-forward " \r\t\n")
  20221. (unless (eobp) (beginning-of-line))
  20222. (let ((indent-to
  20223. (lambda (ind pos)
  20224. ;; Set IND as indentation for all lines between point and
  20225. ;; POS. Blank lines are ignored. Leave point after POS
  20226. ;; once done.
  20227. (let ((limit (copy-marker pos)))
  20228. (while (< (point) limit)
  20229. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  20230. (forward-line))
  20231. (set-marker limit nil))))
  20232. (end (copy-marker end)))
  20233. (while (< (point) end)
  20234. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  20235. (let* ((element (org-element-at-point))
  20236. (type (org-element-type element))
  20237. (element-end (copy-marker (org-element-property :end element)))
  20238. (ind (org--get-expected-indentation element nil)))
  20239. (cond
  20240. ;; Element indented as a single block. Example blocks
  20241. ;; preserving indentation are a special case since the
  20242. ;; "contents" must not be indented whereas the block
  20243. ;; boundaries can.
  20244. ((or (memq type '(export-block latex-environment))
  20245. (and (eq type 'example-block)
  20246. (not
  20247. (or org-src-preserve-indentation
  20248. (org-element-property :preserve-indent element)))))
  20249. (let ((offset (- ind (org-get-indentation))))
  20250. (unless (zerop offset)
  20251. (indent-rigidly (org-element-property :begin element)
  20252. (org-element-property :end element)
  20253. offset)))
  20254. (goto-char element-end))
  20255. ;; Elements indented line wise. Be sure to exclude
  20256. ;; example blocks (preserving indentation) and source
  20257. ;; blocks from this category as they are treated
  20258. ;; specially later.
  20259. ((or (memq type '(paragraph table table-row))
  20260. (not (or (org-element-property :contents-begin element)
  20261. (memq type '(example-block src-block)))))
  20262. (when (eq type 'node-property)
  20263. (org--align-node-property)
  20264. (beginning-of-line))
  20265. (funcall indent-to ind (min element-end end)))
  20266. ;; Elements consisting of three parts: before the
  20267. ;; contents, the contents, and after the contents. The
  20268. ;; contents are treated specially, according to the
  20269. ;; element type, or not indented at all. Other parts are
  20270. ;; indented as a single block.
  20271. (t
  20272. (let* ((post (copy-marker
  20273. (org-element-property :post-affiliated element)))
  20274. (cbeg
  20275. (copy-marker
  20276. (cond
  20277. ((not (org-element-property :contents-begin element))
  20278. ;; Fake contents for source blocks.
  20279. (org-with-wide-buffer
  20280. (goto-char post)
  20281. (line-beginning-position 2)))
  20282. ((memq type '(footnote-definition item plain-list))
  20283. ;; Contents in these elements could start on
  20284. ;; the same line as the beginning of the
  20285. ;; element. Make sure we start indenting
  20286. ;; from the second line.
  20287. (org-with-wide-buffer
  20288. (goto-char post)
  20289. (end-of-line)
  20290. (skip-chars-forward " \r\t\n")
  20291. (if (eobp) (point) (line-beginning-position))))
  20292. (t (org-element-property :contents-begin element)))))
  20293. (cend (copy-marker
  20294. (or (org-element-property :contents-end element)
  20295. ;; Fake contents for source blocks.
  20296. (org-with-wide-buffer
  20297. (goto-char element-end)
  20298. (skip-chars-backward " \r\t\n")
  20299. (line-beginning-position)))
  20300. t)))
  20301. ;; Do not change items indentation individually as it
  20302. ;; might break the list as a whole. On the other
  20303. ;; hand, when at a plain list, indent it as a whole.
  20304. (cond ((eq type 'plain-list)
  20305. (let ((offset (- ind (org-get-indentation))))
  20306. (unless (zerop offset)
  20307. (indent-rigidly (org-element-property :begin element)
  20308. (org-element-property :end element)
  20309. offset))
  20310. (goto-char cbeg)))
  20311. ((eq type 'item) (goto-char cbeg))
  20312. (t (funcall indent-to ind (min cbeg end))))
  20313. (when (< (point) end)
  20314. (cl-case type
  20315. ((example-block verse-block))
  20316. (src-block
  20317. ;; In a source block, indent source code
  20318. ;; according to language major mode, but only if
  20319. ;; `org-src-tab-acts-natively' is non-nil.
  20320. (when (and (< (point) end) org-src-tab-acts-natively)
  20321. (ignore-errors
  20322. (org-babel-do-in-edit-buffer
  20323. (indent-region (point-min) (point-max))))))
  20324. (t (org-indent-region (point) (min cend end))))
  20325. (goto-char (min cend end))
  20326. (when (< (point) end)
  20327. (funcall indent-to ind (min element-end end))))
  20328. (set-marker post nil)
  20329. (set-marker cbeg nil)
  20330. (set-marker cend nil))))
  20331. (set-marker element-end nil))))
  20332. (set-marker end nil))))
  20333. (defun org-indent-drawer ()
  20334. "Indent the drawer at point."
  20335. (interactive)
  20336. (unless (save-excursion
  20337. (beginning-of-line)
  20338. (looking-at-p org-drawer-regexp))
  20339. (user-error "Not at a drawer"))
  20340. (let ((element (org-element-at-point)))
  20341. (unless (memq (org-element-type element) '(drawer property-drawer))
  20342. (user-error "Not at a drawer"))
  20343. (org-with-wide-buffer
  20344. (org-indent-region (org-element-property :begin element)
  20345. (org-element-property :end element))))
  20346. (message "Drawer at point indented"))
  20347. (defun org-indent-block ()
  20348. "Indent the block at point."
  20349. (interactive)
  20350. (unless (save-excursion
  20351. (beginning-of-line)
  20352. (let ((case-fold-search t))
  20353. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  20354. (user-error "Not at a block"))
  20355. (let ((element (org-element-at-point)))
  20356. (unless (memq (org-element-type element)
  20357. '(comment-block center-block dynamic-block example-block
  20358. export-block quote-block special-block
  20359. src-block verse-block))
  20360. (user-error "Not at a block"))
  20361. (org-with-wide-buffer
  20362. (org-indent-region (org-element-property :begin element)
  20363. (org-element-property :end element))))
  20364. (message "Block at point indented"))
  20365. ;;; Filling
  20366. ;; We use our own fill-paragraph and auto-fill functions.
  20367. ;; `org-fill-paragraph' relies on adaptive filling and context
  20368. ;; checking. Appropriate `fill-prefix' is computed with
  20369. ;; `org-adaptive-fill-function'.
  20370. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  20371. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  20372. ;; `org-adaptive-fill-function' value. Internally,
  20373. ;; `org-comment-line-break-function' breaks the line.
  20374. ;; `org-setup-filling' installs filling and auto-filling related
  20375. ;; variables during `org-mode' initialization.
  20376. (defvar org-element-paragraph-separate) ; org-element.el
  20377. (defun org-setup-filling ()
  20378. (require 'org-element)
  20379. ;; Prevent auto-fill from inserting unwanted new items.
  20380. (when (boundp 'fill-nobreak-predicate)
  20381. (setq-local
  20382. fill-nobreak-predicate
  20383. (org-uniquify
  20384. (append fill-nobreak-predicate
  20385. '(org-fill-line-break-nobreak-p
  20386. org-fill-n-macro-as-item-nobreak-p
  20387. org-fill-paragraph-with-timestamp-nobreak-p)))))
  20388. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  20389. (setq-local paragraph-start paragraph-ending)
  20390. (setq-local paragraph-separate paragraph-ending))
  20391. (setq-local fill-paragraph-function 'org-fill-paragraph)
  20392. (setq-local auto-fill-inhibit-regexp nil)
  20393. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  20394. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  20395. (setq-local comment-line-break-function 'org-comment-line-break-function))
  20396. (defun org-fill-line-break-nobreak-p ()
  20397. "Non-nil when a new line at point would create an Org line break."
  20398. (save-excursion
  20399. (skip-chars-backward "[ \t]")
  20400. (skip-chars-backward "\\\\")
  20401. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  20402. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  20403. "Non-nil when a new line at point would split a timestamp."
  20404. (and (org-at-timestamp-p 'lax)
  20405. (not (looking-at org-ts-regexp-both))))
  20406. (defun org-fill-n-macro-as-item-nobreak-p ()
  20407. "Non-nil when a new line at point would create a new list."
  20408. ;; During export, a "n" macro followed by a dot or a closing
  20409. ;; parenthesis can end up being parsed as a new list item.
  20410. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  20411. (declare-function message-in-body-p "message" ())
  20412. (defvar orgtbl-line-start-regexp) ; From org-table.el
  20413. (defun org-adaptive-fill-function ()
  20414. "Compute a fill prefix for the current line.
  20415. Return fill prefix, as a string, or nil if current line isn't
  20416. meant to be filled. For convenience, if `adaptive-fill-regexp'
  20417. matches in paragraphs or comments, use it."
  20418. (catch 'exit
  20419. (when (derived-mode-p 'message-mode)
  20420. (save-excursion
  20421. (beginning-of-line)
  20422. (cond ((not (message-in-body-p)) (throw 'exit nil))
  20423. ((looking-at-p org-table-line-regexp) (throw 'exit nil))
  20424. ((looking-at message-cite-prefix-regexp)
  20425. (throw 'exit (match-string-no-properties 0)))
  20426. ((looking-at org-outline-regexp)
  20427. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  20428. (org-with-wide-buffer
  20429. (unless (org-at-heading-p)
  20430. (let* ((p (line-beginning-position))
  20431. (element (save-excursion
  20432. (beginning-of-line)
  20433. (org-element-at-point)))
  20434. (type (org-element-type element))
  20435. (post-affiliated (org-element-property :post-affiliated element)))
  20436. (unless (< p post-affiliated)
  20437. (cl-case type
  20438. (comment
  20439. (save-excursion
  20440. (beginning-of-line)
  20441. (looking-at "[ \t]*")
  20442. (concat (match-string 0) "# ")))
  20443. (footnote-definition "")
  20444. ((item plain-list)
  20445. (make-string (org-list-item-body-column post-affiliated) ?\s))
  20446. (paragraph
  20447. ;; Fill prefix is usually the same as the current line,
  20448. ;; unless the paragraph is at the beginning of an item.
  20449. (let ((parent (org-element-property :parent element)))
  20450. (save-excursion
  20451. (beginning-of-line)
  20452. (cond ((eq (org-element-type parent) 'item)
  20453. (make-string (org-list-item-body-column
  20454. (org-element-property :begin parent))
  20455. ?\s))
  20456. ((and adaptive-fill-regexp
  20457. ;; Locally disable
  20458. ;; `adaptive-fill-function' to let
  20459. ;; `fill-context-prefix' handle
  20460. ;; `adaptive-fill-regexp' variable.
  20461. (let (adaptive-fill-function)
  20462. (fill-context-prefix
  20463. post-affiliated
  20464. (org-element-property :end element)))))
  20465. ((looking-at "[ \t]+") (match-string 0))
  20466. (t "")))))
  20467. (comment-block
  20468. ;; Only fill contents if P is within block boundaries.
  20469. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  20470. (forward-line)
  20471. (point)))
  20472. (cend (save-excursion
  20473. (goto-char (org-element-property :end element))
  20474. (skip-chars-backward " \r\t\n")
  20475. (line-beginning-position))))
  20476. (when (and (>= p cbeg) (< p cend))
  20477. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  20478. (match-string 0)
  20479. "")))))))))))
  20480. (declare-function message-goto-body "message" ())
  20481. (defvar message-cite-prefix-regexp) ; From message.el
  20482. (defun org-fill-element (&optional justify)
  20483. "Fill element at point, when applicable.
  20484. This function only applies to comment blocks, comments, example
  20485. blocks and paragraphs. Also, as a special case, re-align table
  20486. when point is at one.
  20487. If JUSTIFY is non-nil (interactively, with prefix argument),
  20488. justify as well. If `sentence-end-double-space' is non-nil, then
  20489. period followed by one space does not end a sentence, so don't
  20490. break a line there. The variable `fill-column' controls the
  20491. width for filling.
  20492. For convenience, when point is at a plain list, an item or
  20493. a footnote definition, try to fill the first paragraph within."
  20494. (with-syntax-table org-mode-transpose-word-syntax-table
  20495. ;; Move to end of line in order to get the first paragraph within
  20496. ;; a plain list or a footnote definition.
  20497. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  20498. ;; First check if point is in a blank line at the beginning of
  20499. ;; the buffer. In that case, ignore filling.
  20500. (cl-case (org-element-type element)
  20501. ;; Use major mode filling function is src blocks.
  20502. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  20503. ;; Align Org tables, leave table.el tables as-is.
  20504. (table-row (org-table-align) t)
  20505. (table
  20506. (when (eq (org-element-property :type element) 'org)
  20507. (save-excursion
  20508. (goto-char (org-element-property :post-affiliated element))
  20509. (org-table-align)))
  20510. t)
  20511. (paragraph
  20512. ;; Paragraphs may contain `line-break' type objects.
  20513. (let ((beg (max (point-min)
  20514. (org-element-property :contents-begin element)))
  20515. (end (min (point-max)
  20516. (org-element-property :contents-end element))))
  20517. ;; Do nothing if point is at an affiliated keyword.
  20518. (if (< (line-end-position) beg) t
  20519. (when (derived-mode-p 'message-mode)
  20520. ;; In `message-mode', do not fill following citation
  20521. ;; in current paragraph nor text before message body.
  20522. (let ((body-start (save-excursion (message-goto-body))))
  20523. (when body-start (setq beg (max body-start beg))))
  20524. (when (save-excursion
  20525. (re-search-forward
  20526. (concat "^" message-cite-prefix-regexp) end t))
  20527. (setq end (match-beginning 0))))
  20528. ;; Fill paragraph, taking line breaks into account.
  20529. (save-excursion
  20530. (goto-char beg)
  20531. (let ((cuts (list beg)))
  20532. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  20533. (when (eq 'line-break
  20534. (org-element-type
  20535. (save-excursion (backward-char)
  20536. (org-element-context))))
  20537. (push (point) cuts)))
  20538. (dolist (c (delq end cuts))
  20539. (fill-region-as-paragraph c end justify)
  20540. (setq end c))))
  20541. t)))
  20542. ;; Contents of `comment-block' type elements should be
  20543. ;; filled as plain text, but only if point is within block
  20544. ;; markers.
  20545. (comment-block
  20546. (let* ((case-fold-search t)
  20547. (beg (save-excursion
  20548. (goto-char (org-element-property :begin element))
  20549. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  20550. (forward-line)
  20551. (point)))
  20552. (end (save-excursion
  20553. (goto-char (org-element-property :end element))
  20554. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  20555. (line-beginning-position))))
  20556. (if (or (< (point) beg) (> (point) end)) t
  20557. (fill-region-as-paragraph
  20558. (save-excursion (end-of-line)
  20559. (re-search-backward "^[ \t]*$" beg 'move)
  20560. (line-beginning-position))
  20561. (save-excursion (beginning-of-line)
  20562. (re-search-forward "^[ \t]*$" end 'move)
  20563. (line-beginning-position))
  20564. justify))))
  20565. ;; Fill comments.
  20566. (comment
  20567. (let ((begin (org-element-property :post-affiliated element))
  20568. (end (org-element-property :end element)))
  20569. (when (and (>= (point) begin) (<= (point) end))
  20570. (let ((begin (save-excursion
  20571. (end-of-line)
  20572. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  20573. (progn (forward-line) (point))
  20574. begin)))
  20575. (end (save-excursion
  20576. (end-of-line)
  20577. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  20578. (1- (line-beginning-position))
  20579. (skip-chars-backward " \r\t\n")
  20580. (line-end-position)))))
  20581. ;; Do not fill comments when at a blank line.
  20582. (when (> end begin)
  20583. (let ((fill-prefix
  20584. (save-excursion
  20585. (beginning-of-line)
  20586. (looking-at "[ \t]*#")
  20587. (let ((comment-prefix (match-string 0)))
  20588. (goto-char (match-end 0))
  20589. (if (looking-at adaptive-fill-regexp)
  20590. (concat comment-prefix (match-string 0))
  20591. (concat comment-prefix " "))))))
  20592. (save-excursion
  20593. (fill-region-as-paragraph begin end justify))))))
  20594. t))
  20595. ;; Ignore every other element.
  20596. (otherwise t)))))
  20597. (defun org-fill-paragraph (&optional justify region)
  20598. "Fill element at point, when applicable.
  20599. This function only applies to comment blocks, comments, example
  20600. blocks and paragraphs. Also, as a special case, re-align table
  20601. when point is at one.
  20602. For convenience, when point is at a plain list, an item or
  20603. a footnote definition, try to fill the first paragraph within.
  20604. If JUSTIFY is non-nil (interactively, with prefix argument),
  20605. justify as well. If `sentence-end-double-space' is non-nil, then
  20606. period followed by one space does not end a sentence, so don't
  20607. break a line there. The variable `fill-column' controls the
  20608. width for filling.
  20609. The REGION argument is non-nil if called interactively; in that
  20610. case, if Transient Mark mode is enabled and the mark is active,
  20611. fill each of the elements in the active region, instead of just
  20612. filling the current element."
  20613. (interactive (progn
  20614. (barf-if-buffer-read-only)
  20615. (list (if current-prefix-arg 'full) t)))
  20616. (cond
  20617. ((and (derived-mode-p 'message-mode)
  20618. (or (not (message-in-body-p))
  20619. (save-excursion (move-beginning-of-line 1)
  20620. (looking-at message-cite-prefix-regexp))))
  20621. ;; First ensure filling is correct in message-mode.
  20622. (let ((fill-paragraph-function
  20623. (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
  20624. (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
  20625. (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
  20626. (paragraph-separate
  20627. (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
  20628. (fill-paragraph nil)))
  20629. ((and region transient-mark-mode mark-active
  20630. (not (eq (region-beginning) (region-end))))
  20631. (let ((origin (point-marker))
  20632. (start (region-beginning)))
  20633. (unwind-protect
  20634. (progn
  20635. (goto-char (region-end))
  20636. (while (> (point) start)
  20637. (org-backward-paragraph)
  20638. (org-fill-element justify)))
  20639. (goto-char origin)
  20640. (set-marker origin nil))))
  20641. (t (org-fill-element justify))))
  20642. (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
  20643. (defun org-auto-fill-function ()
  20644. "Auto-fill function."
  20645. ;; Check if auto-filling is meaningful.
  20646. (let ((fc (current-fill-column)))
  20647. (when (and fc (> (current-column) fc))
  20648. (let* ((fill-prefix (org-adaptive-fill-function))
  20649. ;; Enforce empty fill prefix, if required. Otherwise, it
  20650. ;; will be computed again.
  20651. (adaptive-fill-mode (not (equal fill-prefix ""))))
  20652. (when fill-prefix (do-auto-fill))))))
  20653. (defun org-comment-line-break-function (&optional soft)
  20654. "Break line at point and indent, continuing comment if within one.
  20655. The inserted newline is marked hard if variable
  20656. `use-hard-newlines' is true, unless optional argument SOFT is
  20657. non-nil."
  20658. (if soft (insert-and-inherit ?\n) (newline 1))
  20659. (save-excursion (forward-char -1) (delete-horizontal-space))
  20660. (delete-horizontal-space)
  20661. (indent-to-left-margin)
  20662. (insert-before-markers-and-inherit fill-prefix))
  20663. ;;; Fixed Width Areas
  20664. (defun org-toggle-fixed-width ()
  20665. "Toggle fixed-width markup.
  20666. Add or remove fixed-width markup on current line, whenever it
  20667. makes sense. Return an error otherwise.
  20668. If a region is active and if it contains only fixed-width areas
  20669. or blank lines, remove all fixed-width markup in it. If the
  20670. region contains anything else, convert all non-fixed-width lines
  20671. to fixed-width ones.
  20672. Blank lines at the end of the region are ignored unless the
  20673. region only contains such lines."
  20674. (interactive)
  20675. (if (not (org-region-active-p))
  20676. ;; No region:
  20677. ;;
  20678. ;; Remove fixed width marker only in a fixed-with element.
  20679. ;;
  20680. ;; Add fixed width maker in paragraphs, in blank lines after
  20681. ;; elements or at the beginning of a headline or an inlinetask,
  20682. ;; and before any one-line elements (e.g., a clock).
  20683. (progn
  20684. (beginning-of-line)
  20685. (let* ((element (org-element-at-point))
  20686. (type (org-element-type element)))
  20687. (cond
  20688. ((and (eq type 'fixed-width)
  20689. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  20690. (replace-match
  20691. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  20692. ((and (memq type '(babel-call clock comment diary-sexp headline
  20693. horizontal-rule keyword paragraph
  20694. planning))
  20695. (<= (org-element-property :post-affiliated element) (point)))
  20696. (skip-chars-forward " \t")
  20697. (insert ": "))
  20698. ((and (looking-at-p "[ \t]*$")
  20699. (or (eq type 'inlinetask)
  20700. (save-excursion
  20701. (skip-chars-forward " \r\t\n")
  20702. (<= (org-element-property :end element) (point)))))
  20703. (delete-region (point) (line-end-position))
  20704. (org-indent-line)
  20705. (insert ": "))
  20706. (t (user-error "Cannot insert a fixed-width line here")))))
  20707. ;; Region active.
  20708. (let* ((begin (save-excursion
  20709. (goto-char (region-beginning))
  20710. (line-beginning-position)))
  20711. (end (copy-marker
  20712. (save-excursion
  20713. (goto-char (region-end))
  20714. (unless (eolp) (beginning-of-line))
  20715. (if (save-excursion (re-search-backward "\\S-" begin t))
  20716. (progn (skip-chars-backward " \r\t\n") (point))
  20717. (point)))))
  20718. (all-fixed-width-p
  20719. (catch 'not-all-p
  20720. (save-excursion
  20721. (goto-char begin)
  20722. (skip-chars-forward " \r\t\n")
  20723. (when (eobp) (throw 'not-all-p nil))
  20724. (while (< (point) end)
  20725. (let ((element (org-element-at-point)))
  20726. (if (eq (org-element-type element) 'fixed-width)
  20727. (goto-char (org-element-property :end element))
  20728. (throw 'not-all-p nil))))
  20729. t))))
  20730. (if all-fixed-width-p
  20731. (save-excursion
  20732. (goto-char begin)
  20733. (while (< (point) end)
  20734. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  20735. (replace-match
  20736. "" nil nil nil
  20737. (if (= (line-end-position) (match-end 0)) 0 1)))
  20738. (forward-line)))
  20739. (let ((min-ind (point-max)))
  20740. ;; Find minimum indentation across all lines.
  20741. (save-excursion
  20742. (goto-char begin)
  20743. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  20744. (setq min-ind 0)
  20745. (catch 'zerop
  20746. (while (< (point) end)
  20747. (unless (looking-at-p "[ \t]*$")
  20748. (let ((ind (org-get-indentation)))
  20749. (setq min-ind (min min-ind ind))
  20750. (when (zerop ind) (throw 'zerop t))))
  20751. (forward-line)))))
  20752. ;; Loop over all lines and add fixed-width markup everywhere
  20753. ;; but in fixed-width lines.
  20754. (save-excursion
  20755. (goto-char begin)
  20756. (while (< (point) end)
  20757. (cond
  20758. ((org-at-heading-p)
  20759. (insert ": ")
  20760. (forward-line)
  20761. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  20762. (insert ":")
  20763. (forward-line)))
  20764. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  20765. (let* ((element (org-element-at-point))
  20766. (element-end (org-element-property :end element)))
  20767. (if (eq (org-element-type element) 'fixed-width)
  20768. (progn (goto-char element-end)
  20769. (skip-chars-backward " \r\t\n")
  20770. (forward-line))
  20771. (let ((limit (min end element-end)))
  20772. (while (< (point) limit)
  20773. (org-move-to-column min-ind t)
  20774. (insert ": ")
  20775. (forward-line))))))
  20776. (t
  20777. (org-move-to-column min-ind t)
  20778. (insert ": ")
  20779. (forward-line)))))))
  20780. (set-marker end nil))))
  20781. ;;; Comments
  20782. ;; Org comments syntax is quite complex. It requires the entire line
  20783. ;; to be just a comment. Also, even with the right syntax at the
  20784. ;; beginning of line, some elements (e.g., verse-block or
  20785. ;; example-block) don't accept comments. Usual Emacs comment commands
  20786. ;; cannot cope with those requirements. Therefore, Org replaces them.
  20787. ;; Org still relies on `comment-dwim', but cannot trust
  20788. ;; `comment-only-p'. So, `comment-region-function' and
  20789. ;; `uncomment-region-function' both point
  20790. ;; to`org-comment-or-uncomment-region'. Eventually,
  20791. ;; `org-insert-comment' takes care of insertion of comments at the
  20792. ;; beginning of line.
  20793. ;; `org-setup-comments-handling' install comments related variables
  20794. ;; during `org-mode' initialization.
  20795. (defun org-setup-comments-handling ()
  20796. (interactive)
  20797. (setq-local comment-use-syntax nil)
  20798. (setq-local comment-start "# ")
  20799. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  20800. (setq-local comment-insert-comment-function 'org-insert-comment)
  20801. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  20802. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  20803. (defun org-insert-comment ()
  20804. "Insert an empty comment above current line.
  20805. If the line is empty, insert comment at its beginning. When
  20806. point is within a source block, comment according to the related
  20807. major mode."
  20808. (if (let ((element (org-element-at-point)))
  20809. (and (eq (org-element-type element) 'src-block)
  20810. (< (save-excursion
  20811. (goto-char (org-element-property :post-affiliated element))
  20812. (line-end-position))
  20813. (point))
  20814. (> (save-excursion
  20815. (goto-char (org-element-property :end element))
  20816. (skip-chars-backward " \r\t\n")
  20817. (line-beginning-position))
  20818. (point))))
  20819. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  20820. (beginning-of-line)
  20821. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  20822. (open-line 1))
  20823. (org-indent-line)
  20824. (insert "# ")))
  20825. (defvar comment-empty-lines) ; From newcomment.el.
  20826. (defun org-comment-or-uncomment-region (beg end &rest _)
  20827. "Comment or uncomment each non-blank line in the region.
  20828. Uncomment each non-blank line between BEG and END if it only
  20829. contains commented lines. Otherwise, comment them. If region is
  20830. strictly within a source block, use appropriate comment syntax."
  20831. (if (let ((element (org-element-at-point)))
  20832. (and (eq (org-element-type element) 'src-block)
  20833. (< (save-excursion
  20834. (goto-char (org-element-property :post-affiliated element))
  20835. (line-end-position))
  20836. beg)
  20837. (>= (save-excursion
  20838. (goto-char (org-element-property :end element))
  20839. (skip-chars-backward " \r\t\n")
  20840. (line-beginning-position))
  20841. end)))
  20842. ;; Translate region boundaries for the Org buffer to the source
  20843. ;; buffer.
  20844. (let ((offset (- end beg)))
  20845. (save-excursion
  20846. (goto-char beg)
  20847. (org-babel-do-in-edit-buffer
  20848. (comment-or-uncomment-region (point) (+ offset (point))))))
  20849. (save-restriction
  20850. ;; Restrict region
  20851. (narrow-to-region (save-excursion (goto-char beg)
  20852. (skip-chars-forward " \r\t\n" end)
  20853. (line-beginning-position))
  20854. (save-excursion (goto-char end)
  20855. (skip-chars-backward " \r\t\n" beg)
  20856. (line-end-position)))
  20857. (let ((uncommentp
  20858. ;; UNCOMMENTP is non-nil when every non blank line between
  20859. ;; BEG and END is a comment.
  20860. (save-excursion
  20861. (goto-char (point-min))
  20862. (while (and (not (eobp))
  20863. (let ((element (org-element-at-point)))
  20864. (and (eq (org-element-type element) 'comment)
  20865. (goto-char (min (point-max)
  20866. (org-element-property
  20867. :end element)))))))
  20868. (eobp))))
  20869. (if uncommentp
  20870. ;; Only blank lines and comments in region: uncomment it.
  20871. (save-excursion
  20872. (goto-char (point-min))
  20873. (while (not (eobp))
  20874. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  20875. (replace-match "" nil nil nil 1))
  20876. (forward-line)))
  20877. ;; Comment each line in region.
  20878. (let ((min-indent (point-max)))
  20879. ;; First find the minimum indentation across all lines.
  20880. (save-excursion
  20881. (goto-char (point-min))
  20882. (while (and (not (eobp)) (not (zerop min-indent)))
  20883. (unless (looking-at "[ \t]*$")
  20884. (setq min-indent (min min-indent (current-indentation))))
  20885. (forward-line)))
  20886. ;; Then loop over all lines.
  20887. (save-excursion
  20888. (goto-char (point-min))
  20889. (while (not (eobp))
  20890. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  20891. ;; Don't get fooled by invisible text (e.g. link path)
  20892. ;; when moving to column MIN-INDENT.
  20893. (let ((buffer-invisibility-spec nil))
  20894. (org-move-to-column min-indent t))
  20895. (insert comment-start))
  20896. (forward-line)))))))))
  20897. (defun org-comment-dwim (_arg)
  20898. "Call `comment-dwim' within a source edit buffer if needed."
  20899. (interactive "*P")
  20900. (if (org-in-src-block-p)
  20901. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  20902. (call-interactively 'comment-dwim)))
  20903. ;;; Timestamps API
  20904. ;; This section contains tools to operate on timestamp objects, as
  20905. ;; returned by, e.g. `org-element-context'.
  20906. (defun org-timestamp--to-internal-time (timestamp &optional end)
  20907. "Encode TIMESTAMP object into Emacs internal time.
  20908. Use end of date range or time range when END is non-nil."
  20909. (apply #'encode-time
  20910. (cons 0
  20911. (mapcar
  20912. (lambda (prop) (or (org-element-property prop timestamp) 0))
  20913. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  20914. '(:minute-start :hour-start :day-start :month-start
  20915. :year-start))))))
  20916. (defun org-timestamp-has-time-p (timestamp)
  20917. "Non-nil when TIMESTAMP has a time specified."
  20918. (org-element-property :hour-start timestamp))
  20919. (defun org-timestamp-format (timestamp format &optional end utc)
  20920. "Format a TIMESTAMP object into a string.
  20921. FORMAT is a format specifier to be passed to
  20922. `format-time-string'.
  20923. When optional argument END is non-nil, use end of date-range or
  20924. time-range, if possible.
  20925. When optional argument UTC is non-nil, time will be expressed as
  20926. Universal Time."
  20927. (format-time-string
  20928. format (org-timestamp--to-internal-time timestamp end)
  20929. (and utc t)))
  20930. (defun org-timestamp-split-range (timestamp &optional end)
  20931. "Extract a TIMESTAMP object from a date or time range.
  20932. END, when non-nil, means extract the end of the range.
  20933. Otherwise, extract its start.
  20934. Return a new timestamp object."
  20935. (let ((type (org-element-property :type timestamp)))
  20936. (if (memq type '(active inactive diary)) timestamp
  20937. (let ((split-ts (org-element-copy timestamp)))
  20938. ;; Set new type.
  20939. (org-element-put-property
  20940. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  20941. ;; Copy start properties over end properties if END is
  20942. ;; non-nil. Otherwise, copy end properties over `start' ones.
  20943. (let ((p-alist '((:minute-start . :minute-end)
  20944. (:hour-start . :hour-end)
  20945. (:day-start . :day-end)
  20946. (:month-start . :month-end)
  20947. (:year-start . :year-end))))
  20948. (dolist (p-cell p-alist)
  20949. (org-element-put-property
  20950. split-ts
  20951. (funcall (if end #'car #'cdr) p-cell)
  20952. (org-element-property
  20953. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  20954. ;; Eventually refresh `:raw-value'.
  20955. (org-element-put-property split-ts :raw-value nil)
  20956. (org-element-put-property
  20957. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  20958. (defun org-timestamp-translate (timestamp &optional boundary)
  20959. "Translate TIMESTAMP object to custom format.
  20960. Format string is defined in `org-time-stamp-custom-formats',
  20961. which see.
  20962. When optional argument BOUNDARY is non-nil, it is either the
  20963. symbol `start' or `end'. In this case, only translate the
  20964. starting or ending part of TIMESTAMP if it is a date or time
  20965. range. Otherwise, translate both parts.
  20966. Return timestamp as-is if `org-display-custom-times' is nil or if
  20967. it has a `diary' type."
  20968. (let ((type (org-element-property :type timestamp)))
  20969. (if (or (not org-display-custom-times) (eq type 'diary))
  20970. (org-element-interpret-data timestamp)
  20971. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  20972. org-time-stamp-custom-formats)))
  20973. (if (and (not boundary) (memq type '(active-range inactive-range)))
  20974. (concat (org-timestamp-format timestamp fmt)
  20975. "--"
  20976. (org-timestamp-format timestamp fmt t))
  20977. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  20978. ;;; Other stuff.
  20979. (defvar reftex-docstruct-symbol)
  20980. (defvar org--rds)
  20981. (defun org-reftex-citation ()
  20982. "Use reftex-citation to insert a citation into the buffer.
  20983. This looks for a line like
  20984. #+BIBLIOGRAPHY: foo plain option:-d
  20985. and derives from it that foo.bib is the bibliography file relevant
  20986. for this document. It then installs the necessary environment for RefTeX
  20987. to work in this buffer and calls `reftex-citation' to insert a citation
  20988. into the buffer.
  20989. Export of such citations to both LaTeX and HTML is handled by the contributed
  20990. package ox-bibtex by Taru Karttunen."
  20991. (interactive)
  20992. (let ((reftex-docstruct-symbol 'org--rds)
  20993. org--rds bib)
  20994. (org-with-wide-buffer
  20995. (let ((case-fold-search t)
  20996. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  20997. (if (not (save-excursion
  20998. (or (re-search-forward re nil t)
  20999. (re-search-backward re nil t))))
  21000. (user-error "No bibliography defined in file")
  21001. (setq bib (concat (match-string 1) ".bib")
  21002. org--rds (list (list 'bib bib))))))
  21003. (call-interactively 'reftex-citation)))
  21004. ;;;; Functions extending outline functionality
  21005. (defun org-beginning-of-line (&optional n)
  21006. "Go to the beginning of the current visible line.
  21007. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21008. tags on the first attempt, and only move to after the tags when
  21009. the cursor is already beyond the end of the headline.
  21010. With argument N not nil or 1, move forward N - 1 lines first."
  21011. (interactive "^p")
  21012. (let ((origin (point))
  21013. (special (pcase org-special-ctrl-a/e
  21014. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  21015. deactivate-mark)
  21016. ;; First move to a visible line.
  21017. (if (bound-and-true-p visual-line-mode)
  21018. (beginning-of-visual-line n)
  21019. (move-beginning-of-line n)
  21020. ;; `move-beginning-of-line' may leave point after invisible
  21021. ;; characters if line starts with such of these (e.g., with
  21022. ;; a link at column 0). Really move to the beginning of the
  21023. ;; current visible line.
  21024. (beginning-of-line))
  21025. (cond
  21026. ;; No special behavior. Point is already at the beginning of
  21027. ;; a line, logical or visual.
  21028. ((not special))
  21029. ;; `beginning-of-visual-line' left point before logical beginning
  21030. ;; of line: point is at the beginning of a visual line. Bail
  21031. ;; out.
  21032. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  21033. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  21034. ;; At a headline, special position is before the title, but
  21035. ;; after any TODO keyword or priority cookie.
  21036. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21037. (line-end-position)))
  21038. (bol (point)))
  21039. (if (eq special 'reversed)
  21040. (when (and (= origin bol) (eq last-command this-command))
  21041. (goto-char refpos))
  21042. (when (or (> origin refpos) (= origin bol))
  21043. (goto-char refpos)))))
  21044. ((and (looking-at org-list-full-item-re)
  21045. (memq (org-element-type (save-match-data (org-element-at-point)))
  21046. '(item plain-list)))
  21047. ;; Set special position at first white space character after
  21048. ;; bullet, and check-box, if any.
  21049. (let ((after-bullet
  21050. (let ((box (match-end 3)))
  21051. (cond ((not box) (match-end 1))
  21052. ((eq (char-after box) ?\s) (1+ box))
  21053. (t box)))))
  21054. (if (eq special 'reversed)
  21055. (when (and (= (point) origin) (eq last-command this-command))
  21056. (goto-char after-bullet))
  21057. (when (or (> origin after-bullet) (= (point) origin))
  21058. (goto-char after-bullet)))))
  21059. ;; No special context. Point is already at beginning of line.
  21060. (t nil))))
  21061. (defun org-end-of-line (&optional n)
  21062. "Go to the end of the line, but before ellipsis, if any.
  21063. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21064. tags on the first attempt, and only move to after the tags when
  21065. the cursor is already beyond the end of the headline.
  21066. With argument N not nil or 1, move forward N - 1 lines first."
  21067. (interactive "^p")
  21068. (let ((origin (point))
  21069. (special (pcase org-special-ctrl-a/e
  21070. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  21071. deactivate-mark)
  21072. ;; First move to a visible line.
  21073. (if (bound-and-true-p visual-line-mode)
  21074. (beginning-of-visual-line n)
  21075. (move-beginning-of-line n))
  21076. (cond
  21077. ;; At a headline, with tags.
  21078. ((and special
  21079. (save-excursion
  21080. (beginning-of-line)
  21081. (let ((case-fold-search nil))
  21082. (looking-at org-complex-heading-regexp)))
  21083. (match-end 5))
  21084. (let ((tags (save-excursion
  21085. (goto-char (match-beginning 5))
  21086. (skip-chars-backward " \t")
  21087. (point)))
  21088. (visual-end (and (bound-and-true-p visual-line-mode)
  21089. (save-excursion
  21090. (end-of-visual-line)
  21091. (point)))))
  21092. ;; If `end-of-visual-line' brings us before end of line or
  21093. ;; even tags, i.e., the headline spans over multiple visual
  21094. ;; lines, move there.
  21095. (cond ((and visual-end
  21096. (< visual-end tags)
  21097. (<= origin visual-end))
  21098. (goto-char visual-end))
  21099. ((eq special 'reversed)
  21100. (if (and (= origin (line-end-position))
  21101. (eq this-command last-command))
  21102. (goto-char tags)
  21103. (end-of-line)))
  21104. (t
  21105. (if (or (< origin tags) (= origin (line-end-position)))
  21106. (goto-char tags)
  21107. (end-of-line))))))
  21108. ((bound-and-true-p visual-line-mode)
  21109. (let ((bol (line-beginning-position)))
  21110. (end-of-visual-line)
  21111. ;; If `end-of-visual-line' gets us past the ellipsis at the
  21112. ;; end of a line, backtrack and use `end-of-line' instead.
  21113. (when (/= bol (line-beginning-position))
  21114. (goto-char bol)
  21115. (end-of-line))))
  21116. (t (end-of-line)))))
  21117. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21118. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21119. (defun org-backward-sentence (&optional _arg)
  21120. "Go to beginning of sentence, or beginning of table field.
  21121. This will call `backward-sentence' or `org-table-beginning-of-field',
  21122. depending on context."
  21123. (interactive)
  21124. (let* ((element (org-element-at-point))
  21125. (contents-begin (org-element-property :contents-begin element))
  21126. (table (org-element-lineage element '(table) t)))
  21127. (if (and table
  21128. (> (point) contents-begin)
  21129. (<= (point) (org-element-property :contents-end table)))
  21130. (call-interactively #'org-table-beginning-of-field)
  21131. (save-restriction
  21132. (when (and contents-begin
  21133. (< (point-min) contents-begin)
  21134. (> (point) contents-begin))
  21135. (narrow-to-region contents-begin
  21136. (org-element-property :contents-end element)))
  21137. (call-interactively #'backward-sentence)))))
  21138. (defun org-forward-sentence (&optional _arg)
  21139. "Go to end of sentence, or end of table field.
  21140. This will call `forward-sentence' or `org-table-end-of-field',
  21141. depending on context."
  21142. (interactive)
  21143. (if (and (org-at-heading-p)
  21144. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  21145. (save-restriction
  21146. (narrow-to-region (line-beginning-position) (line-end-position))
  21147. (call-interactively #'forward-sentence))
  21148. (let* ((element (org-element-at-point))
  21149. (contents-end (org-element-property :contents-end element))
  21150. (table (org-element-lineage element '(table) t)))
  21151. (if (and table
  21152. (>= (point) (org-element-property :contents-begin table))
  21153. (< (point) contents-end))
  21154. (call-interactively #'org-table-end-of-field)
  21155. (save-restriction
  21156. (when (and contents-end
  21157. (> (point-max) contents-end)
  21158. ;; Skip blank lines between elements.
  21159. (< (org-element-property :end element)
  21160. (save-excursion (goto-char contents-end)
  21161. (skip-chars-forward " \r\t\n"))))
  21162. (narrow-to-region (org-element-property :contents-begin element)
  21163. contents-end))
  21164. ;; End of heading is considered as the end of a sentence.
  21165. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  21166. (call-interactively #'forward-sentence)))))))
  21167. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  21168. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  21169. (defun org-kill-line (&optional _arg)
  21170. "Kill line, to tags or end of line."
  21171. (interactive)
  21172. (cond
  21173. ((or (not org-special-ctrl-k)
  21174. (bolp)
  21175. (not (org-at-heading-p)))
  21176. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  21177. org-ctrl-k-protect-subtree
  21178. (or (eq org-ctrl-k-protect-subtree 'error)
  21179. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  21180. (user-error "C-k aborted as it would kill a hidden subtree"))
  21181. (call-interactively
  21182. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  21183. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  21184. (kill-region (point) (match-beginning 1))
  21185. (org-set-tags nil t))
  21186. (t (kill-region (point) (point-at-eol)))))
  21187. (define-key org-mode-map "\C-k" 'org-kill-line)
  21188. (defun org-yank (&optional arg)
  21189. "Yank. If the kill is a subtree, treat it specially.
  21190. This command will look at the current kill and check if is a single
  21191. subtree, or a series of subtrees[1]. If it passes the test, and if the
  21192. cursor is at the beginning of a line or after the stars of a currently
  21193. empty headline, then the yank is handled specially. How exactly depends
  21194. on the value of the following variables.
  21195. `org-yank-folded-subtrees'
  21196. By default, this variable is non-nil, which results in
  21197. subtree(s) being folded after insertion, except if doing so
  21198. would swallow text after the yanked text.
  21199. `org-yank-adjusted-subtrees'
  21200. When non-nil (the default value is nil), the subtree will be
  21201. promoted or demoted in order to fit into the local outline tree
  21202. structure, which means that the level will be adjusted so that it
  21203. becomes the smaller one of the two *visible* surrounding headings.
  21204. Any prefix to this command will cause `yank' to be called directly with
  21205. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  21206. will just
  21207. plainly yank the text as it is.
  21208. \[1] The test checks if the first non-white line is a heading
  21209. and if there are no other headings with fewer stars."
  21210. (interactive "P")
  21211. (org-yank-generic 'yank arg))
  21212. (defun org-yank-generic (command arg)
  21213. "Perform some yank-like command.
  21214. This function implements the behavior described in the `org-yank'
  21215. documentation. However, it has been generalized to work for any
  21216. interactive command with similar behavior."
  21217. ;; pretend to be command COMMAND
  21218. (setq this-command command)
  21219. (if arg
  21220. (call-interactively command)
  21221. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  21222. (and (org-kill-is-subtree-p)
  21223. (or (bolp)
  21224. (and (looking-at "[ \t]*$")
  21225. (string-match
  21226. "\\`\\*+\\'"
  21227. (buffer-substring (point-at-bol) (point)))))))
  21228. swallowp)
  21229. (cond
  21230. ((and subtreep org-yank-folded-subtrees)
  21231. (let ((beg (point))
  21232. end)
  21233. (if (and subtreep org-yank-adjusted-subtrees)
  21234. (org-paste-subtree nil nil 'for-yank)
  21235. (call-interactively command))
  21236. (setq end (point))
  21237. (goto-char beg)
  21238. (when (and (bolp) subtreep
  21239. (not (setq swallowp
  21240. (org-yank-folding-would-swallow-text beg end))))
  21241. (org-with-limited-levels
  21242. (or (looking-at org-outline-regexp)
  21243. (re-search-forward org-outline-regexp-bol end t))
  21244. (while (and (< (point) end) (looking-at org-outline-regexp))
  21245. (outline-hide-subtree)
  21246. (org-cycle-show-empty-lines 'folded)
  21247. (condition-case nil
  21248. (outline-forward-same-level 1)
  21249. (error (goto-char end))))))
  21250. (when swallowp
  21251. (message
  21252. "Inserted text not folded because that would swallow text"))
  21253. (goto-char end)
  21254. (skip-chars-forward " \t\n\r")
  21255. (beginning-of-line 1)
  21256. (push-mark beg 'nomsg)))
  21257. ((and subtreep org-yank-adjusted-subtrees)
  21258. (let ((beg (point-at-bol)))
  21259. (org-paste-subtree nil nil 'for-yank)
  21260. (push-mark beg 'nomsg)))
  21261. (t
  21262. (call-interactively command))))))
  21263. (defun org-yank-folding-would-swallow-text (beg end)
  21264. "Would hide-subtree at BEG swallow any text after END?"
  21265. (let (level)
  21266. (org-with-limited-levels
  21267. (save-excursion
  21268. (goto-char beg)
  21269. (when (or (looking-at org-outline-regexp)
  21270. (re-search-forward org-outline-regexp-bol end t))
  21271. (setq level (org-outline-level)))
  21272. (goto-char end)
  21273. (skip-chars-forward " \t\r\n\v\f")
  21274. (not (or (eobp)
  21275. (and (bolp) (looking-at-p org-outline-regexp)
  21276. (<= (org-outline-level) level))))))))
  21277. (define-key org-mode-map "\C-y" 'org-yank)
  21278. (defun org-back-to-heading (&optional invisible-ok)
  21279. "Call `outline-back-to-heading', but provide a better error message."
  21280. (condition-case nil
  21281. (outline-back-to-heading invisible-ok)
  21282. (error (error "Before first headline at position %d in buffer %s"
  21283. (point) (current-buffer)))))
  21284. (defun org-before-first-heading-p ()
  21285. "Before first heading?"
  21286. (save-excursion
  21287. (end-of-line)
  21288. (null (re-search-backward org-outline-regexp-bol nil t))))
  21289. (defun org-at-heading-p (&optional ignored)
  21290. (outline-on-heading-p t))
  21291. (defun org-in-commented-heading-p (&optional no-inheritance)
  21292. "Non-nil if point is under a commented heading.
  21293. This function also checks ancestors of the current headline,
  21294. unless optional argument NO-INHERITANCE is non-nil."
  21295. (cond
  21296. ((org-before-first-heading-p) nil)
  21297. ((let ((headline (nth 4 (org-heading-components))))
  21298. (and headline
  21299. (let ((case-fold-search nil))
  21300. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  21301. headline)))))
  21302. (no-inheritance nil)
  21303. (t
  21304. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  21305. (defun org-at-comment-p nil
  21306. "Is cursor in a commented line?"
  21307. (save-excursion
  21308. (save-match-data
  21309. (beginning-of-line)
  21310. (looking-at "^[ \t]*# "))))
  21311. (defun org-at-drawer-p nil
  21312. "Is cursor at a drawer keyword?"
  21313. (save-excursion
  21314. (move-beginning-of-line 1)
  21315. (looking-at org-drawer-regexp)))
  21316. (defun org-at-block-p nil
  21317. "Is cursor at a block keyword?"
  21318. (save-excursion
  21319. (move-beginning-of-line 1)
  21320. (looking-at org-block-regexp)))
  21321. (defun org-point-at-end-of-empty-headline ()
  21322. "If point is at the end of an empty headline, return t, else nil.
  21323. If the heading only contains a TODO keyword, it is still still considered
  21324. empty."
  21325. (let ((case-fold-search nil))
  21326. (and (looking-at "[ \t]*$")
  21327. org-todo-line-regexp
  21328. (save-excursion
  21329. (beginning-of-line)
  21330. (looking-at org-todo-line-regexp)
  21331. (string= (match-string 3) "")))))
  21332. (defun org-at-heading-or-item-p ()
  21333. (or (org-at-heading-p) (org-at-item-p)))
  21334. (defun org-at-target-p ()
  21335. (or (org-in-regexp org-radio-target-regexp)
  21336. (org-in-regexp org-target-regexp)))
  21337. ;; Compatibility alias with Org versions < 7.8.03
  21338. (defalias 'org-on-target-p 'org-at-target-p)
  21339. (defun org-up-heading-all (arg)
  21340. "Move to the heading line of which the present line is a subheading.
  21341. This function considers both visible and invisible heading lines.
  21342. With argument, move up ARG levels."
  21343. (outline-up-heading arg t))
  21344. (defun org-up-heading-safe ()
  21345. "Move to the heading line of which the present line is a subheading.
  21346. This version will not throw an error. It will return the level of the
  21347. headline found, or nil if no higher level is found.
  21348. Also, this function will be a lot faster than `outline-up-heading',
  21349. because it relies on stars being the outline starters. This can really
  21350. make a significant difference in outlines with very many siblings."
  21351. (when (ignore-errors (org-back-to-heading t))
  21352. (let ((level-up (1- (funcall outline-level))))
  21353. (and (> level-up 0)
  21354. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  21355. (funcall outline-level)))))
  21356. (defun org-first-sibling-p ()
  21357. "Is this heading the first child of its parents?"
  21358. (interactive)
  21359. (let ((re org-outline-regexp-bol)
  21360. level l)
  21361. (unless (org-at-heading-p t)
  21362. (user-error "Not at a heading"))
  21363. (setq level (funcall outline-level))
  21364. (save-excursion
  21365. (if (not (re-search-backward re nil t))
  21366. t
  21367. (setq l (funcall outline-level))
  21368. (< l level)))))
  21369. (defun org-goto-sibling (&optional previous)
  21370. "Goto the next sibling, even if it is invisible.
  21371. When PREVIOUS is set, go to the previous sibling instead. Returns t
  21372. when a sibling was found. When none is found, return nil and don't
  21373. move point."
  21374. (let ((fun (if previous 're-search-backward 're-search-forward))
  21375. (pos (point))
  21376. (re org-outline-regexp-bol)
  21377. level l)
  21378. (when (ignore-errors (org-back-to-heading t))
  21379. (setq level (funcall outline-level))
  21380. (catch 'exit
  21381. (or previous (forward-char 1))
  21382. (while (funcall fun re nil t)
  21383. (setq l (funcall outline-level))
  21384. (when (< l level) (goto-char pos) (throw 'exit nil))
  21385. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  21386. (goto-char pos)
  21387. nil))))
  21388. (defun org-show-siblings ()
  21389. "Show all siblings of the current headline."
  21390. (save-excursion
  21391. (while (org-goto-sibling) (org-flag-heading nil)))
  21392. (save-excursion
  21393. (while (org-goto-sibling 'previous)
  21394. (org-flag-heading nil))))
  21395. (defun org-goto-first-child ()
  21396. "Goto the first child, even if it is invisible.
  21397. Return t when a child was found. Otherwise don't move point and
  21398. return nil."
  21399. (let (level (pos (point)) (re org-outline-regexp-bol))
  21400. (when (ignore-errors (org-back-to-heading t))
  21401. (setq level (outline-level))
  21402. (forward-char 1)
  21403. (if (and (re-search-forward re nil t) (> (outline-level) level))
  21404. (progn (goto-char (match-beginning 0)) t)
  21405. (goto-char pos) nil))))
  21406. (defun org-show-hidden-entry ()
  21407. "Show an entry where even the heading is hidden."
  21408. (save-excursion
  21409. (org-show-entry)))
  21410. (defun org-flag-heading (flag &optional entry)
  21411. "Flag the current heading. FLAG non-nil means make invisible.
  21412. When ENTRY is non-nil, show the entire entry."
  21413. (save-excursion
  21414. (org-back-to-heading t)
  21415. ;; Check if we should show the entire entry
  21416. (if entry
  21417. (progn
  21418. (org-show-entry)
  21419. (save-excursion
  21420. (and (outline-next-heading)
  21421. (org-flag-heading nil))))
  21422. (outline-flag-region (max (point-min) (1- (point)))
  21423. (save-excursion (outline-end-of-heading) (point))
  21424. flag))))
  21425. (defun org-get-next-sibling ()
  21426. "Move to next heading of the same level, and return point.
  21427. If there is no such heading, return nil.
  21428. This is like outline-next-sibling, but invisible headings are ok."
  21429. (let ((level (funcall outline-level)))
  21430. (outline-next-heading)
  21431. (while (and (not (eobp)) (> (funcall outline-level) level))
  21432. (outline-next-heading))
  21433. (unless (or (eobp) (< (funcall outline-level) level))
  21434. (point))))
  21435. (defun org-get-last-sibling ()
  21436. "Move to previous heading of the same level, and return point.
  21437. If there is no such heading, return nil."
  21438. (let ((opoint (point))
  21439. (level (funcall outline-level)))
  21440. (outline-previous-heading)
  21441. (when (and (/= (point) opoint) (outline-on-heading-p t))
  21442. (while (and (> (funcall outline-level) level)
  21443. (not (bobp)))
  21444. (outline-previous-heading))
  21445. (unless (< (funcall outline-level) level)
  21446. (point)))))
  21447. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  21448. "Goto to the end of a subtree."
  21449. ;; This contains an exact copy of the original function, but it uses
  21450. ;; `org-back-to-heading', to make it work also in invisible
  21451. ;; trees. And is uses an invisible-ok argument.
  21452. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  21453. ;; Furthermore, when used inside Org, finding the end of a large subtree
  21454. ;; with many children and grandchildren etc, this can be much faster
  21455. ;; than the outline version.
  21456. (org-back-to-heading invisible-ok)
  21457. (let ((first t)
  21458. (level (funcall outline-level)))
  21459. (if (and (derived-mode-p 'org-mode) (< level 1000))
  21460. ;; A true heading (not a plain list item), in Org
  21461. ;; This means we can easily find the end by looking
  21462. ;; only for the right number of stars. Using a regexp to do
  21463. ;; this is so much faster than using a Lisp loop.
  21464. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  21465. (forward-char 1)
  21466. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  21467. ;; something else, do it the slow way
  21468. (while (and (not (eobp))
  21469. (or first (> (funcall outline-level) level)))
  21470. (setq first nil)
  21471. (outline-next-heading)))
  21472. (unless to-heading
  21473. (when (memq (preceding-char) '(?\n ?\^M))
  21474. ;; Go to end of line before heading
  21475. (forward-char -1)
  21476. (when (memq (preceding-char) '(?\n ?\^M))
  21477. ;; leave blank line before heading
  21478. (forward-char -1)))))
  21479. (point))
  21480. (defun org-end-of-meta-data (&optional full)
  21481. "Skip planning line and properties drawer in current entry.
  21482. When optional argument FULL is non-nil, also skip empty lines,
  21483. clocking lines and regular drawers at the beginning of the
  21484. entry."
  21485. (org-back-to-heading t)
  21486. (forward-line)
  21487. (when (looking-at-p org-planning-line-re) (forward-line))
  21488. (when (looking-at org-property-drawer-re)
  21489. (goto-char (match-end 0))
  21490. (forward-line))
  21491. (when (and full (not (org-at-heading-p)))
  21492. (catch 'exit
  21493. (let ((end (save-excursion (outline-next-heading) (point)))
  21494. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  21495. (while (not (eobp))
  21496. (cond ((looking-at-p org-drawer-regexp)
  21497. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  21498. (forward-line)
  21499. (throw 'exit t)))
  21500. ((looking-at-p re) (forward-line))
  21501. (t (throw 'exit t))))))))
  21502. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  21503. "Move forward to the ARG'th subheading at same level as this one.
  21504. Stop at the first and last subheadings of a superior heading.
  21505. Normally this only looks at visible headings, but when INVISIBLE-OK is
  21506. non-nil it will also look at invisible ones."
  21507. (interactive "p")
  21508. (let ((backward? (and arg (< arg 0))))
  21509. (if (org-before-first-heading-p)
  21510. (if backward? (goto-char (point-min)) (outline-next-heading))
  21511. (org-back-to-heading invisible-ok)
  21512. (unless backward? (end-of-line)) ;do not match current headline
  21513. (let ((level (- (match-end 0) (match-beginning 0) 1))
  21514. (f (if backward? #'re-search-backward #'re-search-forward))
  21515. (count (if arg (abs arg) 1))
  21516. (result (point)))
  21517. (while (and (> count 0)
  21518. (funcall f org-outline-regexp-bol nil 'move))
  21519. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  21520. (cond ((< l level) (setq count 0))
  21521. ((and (= l level)
  21522. (or invisible-ok
  21523. (not (org-invisible-p
  21524. (line-beginning-position)))))
  21525. (cl-decf count)
  21526. (when (= l level) (setq result (point)))))))
  21527. (goto-char result))
  21528. (beginning-of-line))))
  21529. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  21530. "Move backward to the ARG'th subheading at same level as this one.
  21531. Stop at the first and last subheadings of a superior heading."
  21532. (interactive "p")
  21533. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  21534. (defun org-next-visible-heading (arg)
  21535. "Move to the next visible heading.
  21536. This function wraps `outline-next-visible-heading' with
  21537. `org-with-limited-levels' in order to skip over inline tasks and
  21538. respect customization of `org-odd-levels-only'."
  21539. (interactive "p")
  21540. (org-with-limited-levels
  21541. (outline-next-visible-heading arg)))
  21542. (defun org-previous-visible-heading (arg)
  21543. "Move to the previous visible heading.
  21544. This function wraps `outline-previous-visible-heading' with
  21545. `org-with-limited-levels' in order to skip over inline tasks and
  21546. respect customization of `org-odd-levels-only'."
  21547. (interactive "p")
  21548. (org-with-limited-levels
  21549. (outline-previous-visible-heading arg)))
  21550. (defun org-next-block (arg &optional backward block-regexp)
  21551. "Jump to the next block.
  21552. With a prefix argument ARG, jump forward ARG many blocks.
  21553. When BACKWARD is non-nil, jump to the previous block.
  21554. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  21555. Match data is set according to this regexp when the function
  21556. returns.
  21557. Return point at beginning of the opening line of found block.
  21558. Throw an error if no block is found."
  21559. (interactive "p")
  21560. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  21561. (case-fold-search t)
  21562. (search-fn (if backward #'re-search-backward #'re-search-forward))
  21563. (count (or arg 1))
  21564. (origin (point))
  21565. last-element)
  21566. (if backward (beginning-of-line) (end-of-line))
  21567. (while (and (> count 0) (funcall search-fn re nil t))
  21568. (let ((element (save-excursion
  21569. (goto-char (match-beginning 0))
  21570. (save-match-data (org-element-at-point)))))
  21571. (when (and (memq (org-element-type element)
  21572. '(center-block comment-block dynamic-block
  21573. example-block export-block quote-block
  21574. special-block src-block verse-block))
  21575. (<= (match-beginning 0)
  21576. (org-element-property :post-affiliated element)))
  21577. (setq last-element element)
  21578. (cl-decf count))))
  21579. (if (= count 0)
  21580. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  21581. (save-match-data (org-show-context)))
  21582. (goto-char origin)
  21583. (user-error "No %s code blocks" (if backward "previous" "further")))))
  21584. (defun org-previous-block (arg &optional block-regexp)
  21585. "Jump to the previous block.
  21586. With a prefix argument ARG, jump backward ARG many source blocks.
  21587. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  21588. (interactive "p")
  21589. (org-next-block arg t block-regexp))
  21590. (defun org-forward-paragraph ()
  21591. "Move forward to beginning of next paragraph or equivalent.
  21592. The function moves point to the beginning of the next visible
  21593. structural element, which can be a paragraph, a table, a list
  21594. item, etc. It also provides some special moves for convenience:
  21595. - On an affiliated keyword, jump to the beginning of the
  21596. relative element.
  21597. - On an item or a footnote definition, move to the second
  21598. element inside, if any.
  21599. - On a table or a property drawer, jump after it.
  21600. - On a verse or source block, stop after blank lines."
  21601. (interactive)
  21602. (unless (eobp)
  21603. (let* ((deactivate-mark nil)
  21604. (element (org-element-at-point))
  21605. (type (org-element-type element))
  21606. (post-affiliated (org-element-property :post-affiliated element))
  21607. (contents-begin (org-element-property :contents-begin element))
  21608. (contents-end (org-element-property :contents-end element))
  21609. (end (let ((end (org-element-property :end element)) (parent element))
  21610. (while (and (setq parent (org-element-property :parent parent))
  21611. (= (org-element-property :contents-end parent) end))
  21612. (setq end (org-element-property :end parent)))
  21613. end)))
  21614. (cond ((not element)
  21615. (skip-chars-forward " \r\t\n")
  21616. (or (eobp) (beginning-of-line)))
  21617. ;; On affiliated keywords, move to element's beginning.
  21618. ((< (point) post-affiliated)
  21619. (goto-char post-affiliated))
  21620. ;; At a table row, move to the end of the table. Similarly,
  21621. ;; at a node property, move to the end of the property
  21622. ;; drawer.
  21623. ((memq type '(node-property table-row))
  21624. (goto-char (org-element-property
  21625. :end (org-element-property :parent element))))
  21626. ((memq type '(property-drawer table)) (goto-char end))
  21627. ;; Consider blank lines as separators in verse and source
  21628. ;; blocks to ease editing.
  21629. ((memq type '(src-block verse-block))
  21630. (when (eq type 'src-block)
  21631. (setq contents-end
  21632. (save-excursion (goto-char end)
  21633. (skip-chars-backward " \r\t\n")
  21634. (line-beginning-position))))
  21635. (beginning-of-line)
  21636. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  21637. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  21638. (goto-char end)
  21639. (skip-chars-forward " \r\t\n")
  21640. (if (= (point) contents-end) (goto-char end)
  21641. (beginning-of-line))))
  21642. ;; With no contents, just skip element.
  21643. ((not contents-begin) (goto-char end))
  21644. ;; If contents are invisible, skip the element altogether.
  21645. ((org-invisible-p (line-end-position))
  21646. (cl-case type
  21647. (headline
  21648. (org-with-limited-levels (outline-next-visible-heading 1)))
  21649. ;; At a plain list, make sure we move to the next item
  21650. ;; instead of skipping the whole list.
  21651. (plain-list (forward-char)
  21652. (org-forward-paragraph))
  21653. (otherwise (goto-char end))))
  21654. ((>= (point) contents-end) (goto-char end))
  21655. ((>= (point) contents-begin)
  21656. ;; This can only happen on paragraphs and plain lists.
  21657. (cl-case type
  21658. (paragraph (goto-char end))
  21659. ;; At a plain list, try to move to second element in
  21660. ;; first item, if possible.
  21661. (plain-list (end-of-line)
  21662. (org-forward-paragraph))))
  21663. ;; When contents start on the middle of a line (e.g. in
  21664. ;; items and footnote definitions), try to reach first
  21665. ;; element starting after current line.
  21666. ((> (line-end-position) contents-begin)
  21667. (end-of-line)
  21668. (org-forward-paragraph))
  21669. (t (goto-char contents-begin))))))
  21670. (defun org-backward-paragraph ()
  21671. "Move backward to start of previous paragraph or equivalent.
  21672. The function moves point to the beginning of the current
  21673. structural element, which can be a paragraph, a table, a list
  21674. item, etc., or to the beginning of the previous visible one if
  21675. point is already there. It also provides some special moves for
  21676. convenience:
  21677. - On an affiliated keyword, jump to the first one.
  21678. - On a table or a property drawer, move to its beginning.
  21679. - On comment, example, export, src and verse blocks, stop
  21680. before blank lines."
  21681. (interactive)
  21682. (unless (bobp)
  21683. (let* ((deactivate-mark nil)
  21684. (element (org-element-at-point))
  21685. (type (org-element-type element))
  21686. (contents-end (org-element-property :contents-end element))
  21687. (post-affiliated (org-element-property :post-affiliated element))
  21688. (begin (org-element-property :begin element))
  21689. (special? ;blocks handled specially
  21690. (memq type '(comment-block example-block export-block src-block
  21691. verse-block)))
  21692. (contents-begin
  21693. (if special?
  21694. ;; These types have no proper contents. Fake line
  21695. ;; below the block opening line as contents beginning.
  21696. (save-excursion (goto-char begin) (line-beginning-position 2))
  21697. (org-element-property :contents-begin element))))
  21698. (cond
  21699. ((not element) (goto-char (point-min)))
  21700. ((= (point) begin)
  21701. (backward-char)
  21702. (org-backward-paragraph))
  21703. ((<= (point) post-affiliated) (goto-char begin))
  21704. ;; Special behavior: on a table or a property drawer, move to
  21705. ;; its beginning.
  21706. ((memq type '(node-property table-row))
  21707. (goto-char (org-element-property
  21708. :post-affiliated (org-element-property :parent element))))
  21709. (special?
  21710. (if (<= (point) contents-begin) (goto-char post-affiliated)
  21711. ;; Inside a verse block, see blank lines as paragraph
  21712. ;; separators.
  21713. (let ((origin (point)))
  21714. (skip-chars-backward " \r\t\n" contents-begin)
  21715. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  21716. (skip-chars-forward " \r\t\n" origin)
  21717. (if (= (point) origin) (goto-char contents-begin)
  21718. (beginning-of-line))))))
  21719. ((eq type 'paragraph) (goto-char contents-begin)
  21720. ;; When at first paragraph in an item or a footnote definition,
  21721. ;; move directly to beginning of line.
  21722. (let ((parent-contents
  21723. (org-element-property
  21724. :contents-begin (org-element-property :parent element))))
  21725. (when (and parent-contents (= parent-contents contents-begin))
  21726. (beginning-of-line))))
  21727. ;; At the end of a greater element, move to the beginning of
  21728. ;; the last element within.
  21729. ((and contents-end (>= (point) contents-end))
  21730. (goto-char (1- contents-end))
  21731. (org-backward-paragraph))
  21732. (t (goto-char (or post-affiliated begin))))
  21733. ;; Ensure we never leave point invisible.
  21734. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  21735. (defun org-forward-element ()
  21736. "Move forward by one element.
  21737. Move to the next element at the same level, when possible."
  21738. (interactive)
  21739. (cond ((eobp) (user-error "Cannot move further down"))
  21740. ((org-with-limited-levels (org-at-heading-p))
  21741. (let ((origin (point)))
  21742. (goto-char (org-end-of-subtree nil t))
  21743. (unless (org-with-limited-levels (org-at-heading-p))
  21744. (goto-char origin)
  21745. (user-error "Cannot move further down"))))
  21746. (t
  21747. (let* ((elem (org-element-at-point))
  21748. (end (org-element-property :end elem))
  21749. (parent (org-element-property :parent elem)))
  21750. (cond ((and parent (= (org-element-property :contents-end parent) end))
  21751. (goto-char (org-element-property :end parent)))
  21752. ((integer-or-marker-p end) (goto-char end))
  21753. (t (message "No element at point")))))))
  21754. (defun org-backward-element ()
  21755. "Move backward by one element.
  21756. Move to the previous element at the same level, when possible."
  21757. (interactive)
  21758. (cond ((bobp) (user-error "Cannot move further up"))
  21759. ((org-with-limited-levels (org-at-heading-p))
  21760. ;; At a headline, move to the previous one, if any, or stay
  21761. ;; here.
  21762. (let ((origin (point)))
  21763. (org-with-limited-levels (org-backward-heading-same-level 1))
  21764. ;; When current headline has no sibling above, move to its
  21765. ;; parent.
  21766. (when (= (point) origin)
  21767. (or (org-with-limited-levels (org-up-heading-safe))
  21768. (progn (goto-char origin)
  21769. (user-error "Cannot move further up"))))))
  21770. (t
  21771. (let* ((elem (org-element-at-point))
  21772. (beg (org-element-property :begin elem)))
  21773. (cond
  21774. ;; Move to beginning of current element if point isn't
  21775. ;; there already.
  21776. ((null beg) (message "No element at point"))
  21777. ((/= (point) beg) (goto-char beg))
  21778. (t (goto-char beg)
  21779. (skip-chars-backward " \r\t\n")
  21780. (unless (bobp)
  21781. (let ((prev (org-element-at-point)))
  21782. (goto-char (org-element-property :begin prev))
  21783. (while (and (setq prev (org-element-property :parent prev))
  21784. (<= (org-element-property :end prev) beg))
  21785. (goto-char (org-element-property :begin prev)))))))))))
  21786. (defun org-up-element ()
  21787. "Move to upper element."
  21788. (interactive)
  21789. (if (org-with-limited-levels (org-at-heading-p))
  21790. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  21791. (let* ((elem (org-element-at-point))
  21792. (parent (org-element-property :parent elem)))
  21793. (if parent (goto-char (org-element-property :begin parent))
  21794. (if (org-with-limited-levels (org-before-first-heading-p))
  21795. (user-error "No surrounding element")
  21796. (org-with-limited-levels (org-back-to-heading)))))))
  21797. (defun org-down-element ()
  21798. "Move to inner element."
  21799. (interactive)
  21800. (let ((element (org-element-at-point)))
  21801. (cond
  21802. ((memq (org-element-type element) '(plain-list table))
  21803. (goto-char (org-element-property :contents-begin element))
  21804. (forward-char))
  21805. ((memq (org-element-type element) org-element-greater-elements)
  21806. ;; If contents are hidden, first disclose them.
  21807. (when (org-invisible-p (line-end-position)) (org-cycle))
  21808. (goto-char (or (org-element-property :contents-begin element)
  21809. (user-error "No content for this element"))))
  21810. (t (user-error "No inner element")))))
  21811. (defun org-drag-element-backward ()
  21812. "Move backward element at point."
  21813. (interactive)
  21814. (let ((elem (or (org-element-at-point)
  21815. (user-error "No element at point"))))
  21816. (if (eq (org-element-type elem) 'headline)
  21817. ;; Preserve point when moving a whole tree, even if point was
  21818. ;; on blank lines below the headline.
  21819. (let ((offset (skip-chars-backward " \t\n")))
  21820. (unwind-protect (org-move-subtree-up)
  21821. (forward-char (- offset))))
  21822. (let ((prev-elem
  21823. (save-excursion
  21824. (goto-char (org-element-property :begin elem))
  21825. (skip-chars-backward " \r\t\n")
  21826. (unless (bobp)
  21827. (let* ((beg (org-element-property :begin elem))
  21828. (prev (org-element-at-point))
  21829. (up prev))
  21830. (while (and (setq up (org-element-property :parent up))
  21831. (<= (org-element-property :end up) beg))
  21832. (setq prev up))
  21833. prev)))))
  21834. ;; Error out if no previous element or previous element is
  21835. ;; a parent of the current one.
  21836. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  21837. (user-error "Cannot drag element backward")
  21838. (let ((pos (point)))
  21839. (org-element-swap-A-B prev-elem elem)
  21840. (goto-char (+ (org-element-property :begin prev-elem)
  21841. (- pos (org-element-property :begin elem))))))))))
  21842. (defun org-drag-element-forward ()
  21843. "Move forward element at point."
  21844. (interactive)
  21845. (let* ((pos (point))
  21846. (elem (or (org-element-at-point)
  21847. (user-error "No element at point"))))
  21848. (when (= (point-max) (org-element-property :end elem))
  21849. (user-error "Cannot drag element forward"))
  21850. (goto-char (org-element-property :end elem))
  21851. (let ((next-elem (org-element-at-point)))
  21852. (when (or (org-element-nested-p elem next-elem)
  21853. (and (eq (org-element-type next-elem) 'headline)
  21854. (not (eq (org-element-type elem) 'headline))))
  21855. (goto-char pos)
  21856. (user-error "Cannot drag element forward"))
  21857. ;; Compute new position of point: it's shifted by NEXT-ELEM
  21858. ;; body's length (without final blanks) and by the length of
  21859. ;; blanks between ELEM and NEXT-ELEM.
  21860. (let ((size-next (- (save-excursion
  21861. (goto-char (org-element-property :end next-elem))
  21862. (skip-chars-backward " \r\t\n")
  21863. (forward-line)
  21864. ;; Small correction if buffer doesn't end
  21865. ;; with a newline character.
  21866. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  21867. (org-element-property :begin next-elem)))
  21868. (size-blank (- (org-element-property :end elem)
  21869. (save-excursion
  21870. (goto-char (org-element-property :end elem))
  21871. (skip-chars-backward " \r\t\n")
  21872. (forward-line)
  21873. (point)))))
  21874. (org-element-swap-A-B elem next-elem)
  21875. (goto-char (+ pos size-next size-blank))))))
  21876. (defun org-drag-line-forward (arg)
  21877. "Drag the line at point ARG lines forward."
  21878. (interactive "p")
  21879. (dotimes (_ (abs arg))
  21880. (let ((c (current-column)))
  21881. (if (< 0 arg)
  21882. (progn
  21883. (beginning-of-line 2)
  21884. (transpose-lines 1)
  21885. (beginning-of-line 0))
  21886. (transpose-lines 1)
  21887. (beginning-of-line -1))
  21888. (org-move-to-column c))))
  21889. (defun org-drag-line-backward (arg)
  21890. "Drag the line at point ARG lines backward."
  21891. (interactive "p")
  21892. (org-drag-line-forward (- arg)))
  21893. (defun org-mark-element ()
  21894. "Put point at beginning of this element, mark at end.
  21895. Interactively, if this command is repeated or (in Transient Mark
  21896. mode) if the mark is active, it marks the next element after the
  21897. ones already marked."
  21898. (interactive)
  21899. (let (deactivate-mark)
  21900. (if (and (called-interactively-p 'any)
  21901. (or (and (eq last-command this-command) (mark t))
  21902. (and transient-mark-mode mark-active)))
  21903. (set-mark
  21904. (save-excursion
  21905. (goto-char (mark))
  21906. (goto-char (org-element-property :end (org-element-at-point)))))
  21907. (let ((element (org-element-at-point)))
  21908. (end-of-line)
  21909. (push-mark (org-element-property :end element) t t)
  21910. (goto-char (org-element-property :begin element))))))
  21911. (defun org-narrow-to-element ()
  21912. "Narrow buffer to current element."
  21913. (interactive)
  21914. (let ((elem (org-element-at-point)))
  21915. (cond
  21916. ((eq (car elem) 'headline)
  21917. (narrow-to-region
  21918. (org-element-property :begin elem)
  21919. (org-element-property :end elem)))
  21920. ((memq (car elem) org-element-greater-elements)
  21921. (narrow-to-region
  21922. (org-element-property :contents-begin elem)
  21923. (org-element-property :contents-end elem)))
  21924. (t
  21925. (narrow-to-region
  21926. (org-element-property :begin elem)
  21927. (org-element-property :end elem))))))
  21928. (defun org-transpose-element ()
  21929. "Transpose current and previous elements, keeping blank lines between.
  21930. Point is moved after both elements."
  21931. (interactive)
  21932. (org-skip-whitespace)
  21933. (let ((end (org-element-property :end (org-element-at-point))))
  21934. (org-drag-element-backward)
  21935. (goto-char end)))
  21936. (defun org-unindent-buffer ()
  21937. "Un-indent the visible part of the buffer.
  21938. Relative indentation (between items, inside blocks, etc.) isn't
  21939. modified."
  21940. (interactive)
  21941. (unless (eq major-mode 'org-mode)
  21942. (user-error "Cannot un-indent a buffer not in Org mode"))
  21943. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  21944. (unindent-tree
  21945. (lambda (contents)
  21946. (dolist (element (reverse contents))
  21947. (if (memq (org-element-type element) '(headline section))
  21948. (funcall unindent-tree (org-element-contents element))
  21949. (save-excursion
  21950. (save-restriction
  21951. (narrow-to-region
  21952. (org-element-property :begin element)
  21953. (org-element-property :end element))
  21954. (org-do-remove-indentation))))))))
  21955. (funcall unindent-tree (org-element-contents parse-tree))))
  21956. (defun org-show-children (&optional level)
  21957. "Show all direct subheadings of this heading.
  21958. Prefix arg LEVEL is how many levels below the current level
  21959. should be shown. Default is enough to cause the following
  21960. heading to appear."
  21961. (interactive "p")
  21962. ;; If `orgstruct-mode' is active, use the slower version.
  21963. (if orgstruct-mode (call-interactively #'outline-show-children)
  21964. (save-excursion
  21965. (org-back-to-heading t)
  21966. (let* ((current-level (funcall outline-level))
  21967. (max-level (org-get-valid-level
  21968. current-level
  21969. (if level (prefix-numeric-value level) 1)))
  21970. (end (save-excursion (org-end-of-subtree t t)))
  21971. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  21972. (past-first-child nil)
  21973. ;; Make sure to skip inlinetasks.
  21974. (re (format regexp-fmt
  21975. current-level
  21976. (cond
  21977. ((not (featurep 'org-inlinetask)) "")
  21978. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  21979. 3))
  21980. (t (1- org-inlinetask-min-level))))))
  21981. ;; Display parent heading.
  21982. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  21983. (forward-line)
  21984. ;; Display children. First child may be deeper than expected
  21985. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  21986. ;; MAX-LEVEL accordingly.
  21987. (while (re-search-forward re end t)
  21988. (unless past-first-child
  21989. (setq re (format regexp-fmt
  21990. current-level
  21991. (max (funcall outline-level) max-level)))
  21992. (setq past-first-child t))
  21993. (outline-flag-region
  21994. (line-end-position 0) (line-end-position) nil))))))
  21995. (defun org-show-subtree ()
  21996. "Show everything after this heading at deeper levels."
  21997. (interactive)
  21998. (outline-flag-region
  21999. (point)
  22000. (save-excursion
  22001. (org-end-of-subtree t t))
  22002. nil))
  22003. (defun org-show-entry ()
  22004. "Show the body directly following this heading.
  22005. Show the heading too, if it is currently invisible."
  22006. (interactive)
  22007. (save-excursion
  22008. (ignore-errors
  22009. (org-back-to-heading t)
  22010. (outline-flag-region
  22011. (max (point-min) (1- (point)))
  22012. (save-excursion
  22013. (if (re-search-forward
  22014. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22015. (match-beginning 1)
  22016. (point-max)))
  22017. nil)
  22018. (org-cycle-hide-drawers 'children))))
  22019. (defun org-make-options-regexp (kwds &optional extra)
  22020. "Make a regular expression for keyword lines.
  22021. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22022. when non-nil, is a regexp matching keywords names."
  22023. (concat "^[ \t]*#\\+\\("
  22024. (regexp-opt kwds)
  22025. (and extra (concat (and kwds "\\|") extra))
  22026. "\\):[ \t]*\\(.*\\)"))
  22027. ;;;; Finish up
  22028. (provide 'org)
  22029. (run-hooks 'org-load-hook)
  22030. ;;; org.el ends here