org.el 875 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140
  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-2019 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: https://orgmode.org
  9. ;; Version: 9.3
  10. ;;
  11. ;; This file is part of GNU Emacs.
  12. ;;
  13. ;; GNU Emacs is free software: you can redistribute it and/or modify
  14. ;; it under the terms of the GNU General Public License as published by
  15. ;; the Free Software Foundation, either version 3 of the License, or
  16. ;; (at your option) any later version.
  17. ;; GNU Emacs is distributed in the hope that it will be useful,
  18. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. ;; GNU General Public License for more details.
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  23. ;;
  24. ;;; Commentary:
  25. ;;
  26. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  27. ;; project planning with a fast and effective plain-text system.
  28. ;;
  29. ;; Org mode develops organizational tasks around NOTES files that
  30. ;; contain information about projects as plain text. Org mode is
  31. ;; implemented on top of outline-mode, which makes it possible to keep
  32. ;; the content of large files well structured. Visibility cycling and
  33. ;; structure editing help to work with the tree. Tables are easily
  34. ;; created with a built-in table editor. Org mode supports ToDo
  35. ;; items, deadlines, time stamps, and scheduling. It dynamically
  36. ;; compiles entries into an agenda that utilizes and smoothly
  37. ;; integrates much of the Emacs calendar and diary. Plain text
  38. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  39. ;; entries, and any files related to the projects. For printing and
  40. ;; sharing of notes, an Org file can be exported as a structured ASCII
  41. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  42. ;; file. It can also serve as a publishing tool for a set of linked
  43. ;; webpages.
  44. ;;
  45. ;; Installation and Activation
  46. ;; ---------------------------
  47. ;; See the corresponding sections in the manual at
  48. ;;
  49. ;; https://orgmode.org/org.html#Installation
  50. ;;
  51. ;; Documentation
  52. ;; -------------
  53. ;; The documentation of Org mode can be found in the TeXInfo file. The
  54. ;; distribution also contains a PDF version of it. At the homepage of
  55. ;; Org mode, you can read the same text online as HTML. There is also an
  56. ;; excellent reference card made by Philip Rooke. This card can be found
  57. ;; in the doc/ directory.
  58. ;;
  59. ;; A list of recent changes can be found at
  60. ;; https://orgmode.org/Changes.html
  61. ;;
  62. ;;; Code:
  63. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  64. (defvar-local org-table-formula-constants-local nil
  65. "Local version of `org-table-formula-constants'.")
  66. (defvar org-inlinetask-min-level)
  67. ;;;; Require other packages
  68. (require 'cl-lib)
  69. (eval-when-compile (require 'gnus-sum))
  70. (require 'calendar)
  71. (require 'find-func)
  72. (require 'format-spec)
  73. (or (eq this-command 'eval-buffer)
  74. (condition-case nil
  75. (load (concat (file-name-directory load-file-name)
  76. "org-loaddefs.el")
  77. nil t t t)
  78. (error
  79. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  80. (sit-for 3)
  81. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  82. (sit-for 3))))
  83. (eval-and-compile (require 'org-macs))
  84. (require 'org-compat)
  85. (require 'org-keys)
  86. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  87. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  88. (defvar org-outline-regexp "\\*+ "
  89. "Regexp to match Org headlines.")
  90. (defvar org-outline-regexp-bol "^\\*+ "
  91. "Regexp to match Org headlines.
  92. This is similar to `org-outline-regexp' but additionally makes
  93. sure that we are at the beginning of the line.")
  94. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  95. "Matches a headline, putting stars and text into groups.
  96. Stars are put in group 1 and the trimmed body in group 2.")
  97. (declare-function calendar-check-holidays "holidays" (date))
  98. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  99. (declare-function cdlatex-math-symbol "ext:cdlatex")
  100. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  101. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  102. (declare-function org-add-archive-files "org-archive" (files))
  103. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  104. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  105. (declare-function org-agenda-redo "org-agenda" (&optional all))
  106. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  107. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  108. (declare-function org-archive-subtree-default "org-archive" ())
  109. (declare-function org-archive-to-archive-sibling "org-archive" ())
  110. (declare-function org-attach "org-attach" ())
  111. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  112. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  113. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  114. (declare-function org-clock-cancel "org-clock" ())
  115. (declare-function org-clock-display "org-clock" (&optional arg))
  116. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  117. (declare-function org-clock-goto "org-clock" (&optional select))
  118. (declare-function org-clock-in "org-clock" (&optional select start-time))
  119. (declare-function org-clock-in-last "org-clock" (&optional arg))
  120. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  121. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  122. (declare-function org-clock-report "org-clock" (&optional arg))
  123. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  124. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  125. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  126. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  127. (declare-function org-clock-update-time-maybe "org-clock" ())
  128. (declare-function org-clocking-buffer "org-clock" ())
  129. (declare-function org-clocktable-shift "org-clock" (dir n))
  130. (declare-function org-columns-insert-dblock "org-colview" ())
  131. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  132. (declare-function org-element-at-point "org-element" ())
  133. (declare-function org-element-cache-refresh "org-element" (pos))
  134. (declare-function org-element-cache-reset "org-element" (&optional all))
  135. (declare-function org-element-contents "org-element" (element))
  136. (declare-function org-element-context "org-element" (&optional element))
  137. (declare-function org-element-copy "org-element" (datum))
  138. (declare-function org-element-create "org-element" (type &optional props &rest children))
  139. (declare-function org-element-interpret-data "org-element" (data))
  140. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  141. (declare-function org-element-link-parser "org-element" ())
  142. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  143. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  144. (declare-function org-element-property "org-element" (property element))
  145. (declare-function org-element-put-property "org-element" (element property value))
  146. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  147. (declare-function org-element-timestamp-parser "org-element" ())
  148. (declare-function org-element-type "org-element" (element))
  149. (declare-function org-element-update-syntax "org-element" ())
  150. (declare-function org-export-dispatch "ox" (&optional arg))
  151. (declare-function org-export-get-backend "ox" (name))
  152. (declare-function org-export-get-backend "ox" (name))
  153. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  154. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  155. (declare-function org-feed-goto-inbox "org-feed" (feed))
  156. (declare-function org-feed-update-all "org-feed" ())
  157. (declare-function org-goto "org-goto" (&optional alternative-interface))
  158. (declare-function org-goto "org-goto" (&optional alternative-interface))
  159. (declare-function org-id-find-id-file "org-id" (id))
  160. (declare-function org-id-get-create "org-id" (&optional force))
  161. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  162. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  163. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  164. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  165. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  166. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  167. (declare-function org-table--shrunk-field "org-table" ()) ;; For `org-table-with-shrunk-field'.
  168. (declare-function org-table-align "org-table" ())
  169. (declare-function org-table-begin "org-table" (&optional table-type))
  170. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  171. (declare-function org-table-blank-field "org-table" ())
  172. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  173. (declare-function org-table-copy-down "org-table" (N))
  174. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  175. (declare-function org-table-create-or-convert-from-region "org-table" (arg))
  176. (declare-function org-table-create-with-table.el "org-table" ())
  177. (declare-function org-table-cut-region "org-table" (beg end))
  178. (declare-function org-table-edit-field "org-table" (arg))
  179. (declare-function org-table-end "org-table" (&optional table-type))
  180. (declare-function org-table-end-of-field "org-table" (&optional n))
  181. (declare-function org-table-eval-formula "org-table" (&optional arg equation suppress-align suppress-const suppress-store suppress-analysis))
  182. (declare-function org-table-field-info "org-table" (arg))
  183. (declare-function org-table-insert-row "org-table" (&optional arg))
  184. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  185. (declare-function org-table-maybe-eval-formula "org-table" ())
  186. (declare-function org-table-maybe-recalculate-line "org-table" ())
  187. (declare-function org-table-move-cell-up "org-table" ())
  188. (declare-function org-table-move-cell-down "org-table" ())
  189. (declare-function org-table-move-cell-right "org-table" ())
  190. (declare-function org-table-move-cell-left "org-table" ())
  191. (declare-function org-table-next-row "org-table" ())
  192. (declare-function org-table-paste-rectangle "org-table" ())
  193. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  194. (declare-function org-table-rotate-recalc-marks "org-table" (&optional newchar))
  195. (declare-function org-table-shrink "org-table" (&optional begin end))
  196. (declare-function org-table-sort-lines "org-table" (&optional with-case sorting-type getkey-func compare-func interactive?))
  197. (declare-function org-table-sum "org-table" (&optional beg end nlast))
  198. (declare-function org-table-toggle-column-width "org-table" (&optional arg))
  199. (declare-function org-table-toggle-coordinate-overlays "org-table" ())
  200. (declare-function org-table-toggle-formula-debugger "org-table" ())
  201. (declare-function org-table-wrap-region "org-table" (arg))
  202. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  203. (declare-function org-timer "org-timer" (&optional restart no-insert))
  204. (declare-function org-timer-item "org-timer" (&optional arg))
  205. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  206. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  207. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  208. (declare-function org-timer-start "org-timer" (&optional offset))
  209. (declare-function org-timer-stop "org-timer" ())
  210. (declare-function org-timer-stop "org-timer" ())
  211. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  212. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  213. (declare-function orgtbl-mode "org-table" (&optional arg))
  214. (defvar ffap-url-regexp)
  215. (defvar org-element-paragraph-separate)
  216. (defvar org-indent-indentation-per-level)
  217. (defvar org-table-auto-blank-field)
  218. ;; load languages based on value of `org-babel-load-languages'
  219. (defvar org-babel-load-languages)
  220. ;;;###autoload
  221. (defun org-babel-do-load-languages (sym value)
  222. "Load the languages defined in `org-babel-load-languages'."
  223. (set-default sym value)
  224. (dolist (pair org-babel-load-languages)
  225. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  226. (if active
  227. (require (intern (concat "ob-" lang)))
  228. (fmakunbound
  229. (intern (concat "org-babel-execute:" lang)))
  230. (fmakunbound
  231. (intern (concat "org-babel-expand-body:" lang)))))))
  232. ;;;###autoload
  233. (defun org-babel-load-file (file &optional compile)
  234. "Load Emacs Lisp source code blocks in the Org FILE.
  235. This function exports the source code using `org-babel-tangle'
  236. and then loads the resulting file using `load-file'. With
  237. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  238. byte-compiled before it is loaded."
  239. (interactive "fFile to load: \nP")
  240. (let* ((tangled-file (concat (file-name-sans-extension file) ".el")))
  241. ;; Tangle only if the Org file is newer than the Elisp file.
  242. (unless (org-file-newer-than-p tangled-file (nth 5 (file-attributes file)))
  243. (org-babel-tangle-file file tangled-file "emacs-lisp"))
  244. (if compile
  245. (progn
  246. (byte-compile-file tangled-file 'load)
  247. (message "Compiled and loaded %s" tangled-file))
  248. (load-file tangled-file)
  249. (message "Loaded %s" tangled-file))))
  250. (defcustom org-babel-load-languages '((emacs-lisp . t))
  251. "Languages which can be evaluated in Org buffers.
  252. \\<org-mode-map>
  253. This list can be used to load support for any of the languages
  254. below. Each language will depend on a different set of system
  255. executables and/or Emacs modes.
  256. When a language is \"loaded\", code blocks in that language can
  257. be evaluated with `org-babel-execute-src-block', which is bound
  258. by default to \\[org-ctrl-c-ctrl-c].
  259. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  260. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  261. default, only Emacs Lisp is loaded, since it has no specific
  262. requirement."
  263. :group 'org-babel
  264. :set 'org-babel-do-load-languages
  265. :version "24.1"
  266. :type '(alist :tag "Babel Languages"
  267. :key-type
  268. (choice
  269. (const :tag "Awk" awk)
  270. (const :tag "C" C)
  271. (const :tag "R" R)
  272. (const :tag "Asymptote" asymptote)
  273. (const :tag "Calc" calc)
  274. (const :tag "Clojure" clojure)
  275. (const :tag "CSS" css)
  276. (const :tag "Ditaa" ditaa)
  277. (const :tag "Dot" dot)
  278. (const :tag "Ebnf2ps" ebnf2ps)
  279. (const :tag "Emacs Lisp" emacs-lisp)
  280. (const :tag "Forth" forth)
  281. (const :tag "Fortran" fortran)
  282. (const :tag "Gnuplot" gnuplot)
  283. (const :tag "Haskell" haskell)
  284. (const :tag "hledger" hledger)
  285. (const :tag "IO" io)
  286. (const :tag "J" J)
  287. (const :tag "Java" java)
  288. (const :tag "Javascript" js)
  289. (const :tag "LaTeX" latex)
  290. (const :tag "Ledger" ledger)
  291. (const :tag "Lilypond" lilypond)
  292. (const :tag "Lisp" lisp)
  293. (const :tag "Makefile" makefile)
  294. (const :tag "Maxima" maxima)
  295. (const :tag "Matlab" matlab)
  296. (const :tag "Mscgen" mscgen)
  297. (const :tag "Ocaml" ocaml)
  298. (const :tag "Octave" octave)
  299. (const :tag "Org" org)
  300. (const :tag "Perl" perl)
  301. (const :tag "Pico Lisp" picolisp)
  302. (const :tag "PlantUML" plantuml)
  303. (const :tag "Python" python)
  304. (const :tag "Ruby" ruby)
  305. (const :tag "Sass" sass)
  306. (const :tag "Scala" scala)
  307. (const :tag "Scheme" scheme)
  308. (const :tag "Screen" screen)
  309. (const :tag "Shell Script" shell)
  310. (const :tag "Shen" shen)
  311. (const :tag "Sql" sql)
  312. (const :tag "Sqlite" sqlite)
  313. (const :tag "Stan" stan)
  314. (const :tag "Vala" vala))
  315. :value-type (boolean :tag "Activate" :value t)))
  316. ;;;; Customization variables
  317. (defcustom org-clone-delete-id nil
  318. "Remove ID property of clones of a subtree.
  319. When non-nil, clones of a subtree don't inherit the ID property.
  320. Otherwise they inherit the ID property with a new unique
  321. identifier."
  322. :type 'boolean
  323. :version "24.1"
  324. :group 'org-id)
  325. ;;; Version
  326. (org-check-version)
  327. ;;;###autoload
  328. (defun org-version (&optional here full message)
  329. "Show the Org version.
  330. Interactively, or when MESSAGE is non-nil, show it in echo area.
  331. With prefix argument, or when HERE is non-nil, insert it at point.
  332. In non-interactive uses, a reduced version string is output unless
  333. FULL is given."
  334. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  335. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  336. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  337. (load-suffixes (list ".el"))
  338. (org-install-dir
  339. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  340. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  341. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  342. (let* ((load-suffixes save-load-suffixes)
  343. (release (org-release))
  344. (git-version (org-git-version))
  345. (version (format "Org mode version %s (%s @ %s)"
  346. release
  347. git-version
  348. (if org-install-dir
  349. (if (string= org-dir org-install-dir)
  350. org-install-dir
  351. (concat "mixed installation! "
  352. org-install-dir
  353. " and "
  354. org-dir))
  355. "org-loaddefs.el can not be found!")))
  356. (version1 (if full version release)))
  357. (when here (insert version1))
  358. (when message (message "%s" version1))
  359. version1)))
  360. (defconst org-version (org-version))
  361. ;;; Syntax Constants
  362. ;;;; Block
  363. (defconst org-block-regexp
  364. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  365. "Regular expression for hiding blocks.")
  366. (defconst org-dblock-start-re
  367. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  368. "Matches the start line of a dynamic block, with parameters.")
  369. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  370. "Matches the end of a dynamic block.")
  371. ;;;; Clock and Planning
  372. (defconst org-clock-string "CLOCK:"
  373. "String used as prefix for timestamps clocking work hours on an item.")
  374. (defvar org-closed-string "CLOSED:"
  375. "String used as the prefix for timestamps logging closing a TODO entry.")
  376. (defvar org-deadline-string "DEADLINE:"
  377. "String to mark deadline entries.
  378. \\<org-mode-map>
  379. A deadline is this string, followed by a time stamp. It must be
  380. a word, terminated by a colon. You can insert a schedule keyword
  381. and a timestamp with `\\[org-deadline]'.")
  382. (defvar org-scheduled-string "SCHEDULED:"
  383. "String to mark scheduled TODO entries.
  384. \\<org-mode-map>
  385. A schedule is this string, followed by a time stamp. It must be
  386. a word, terminated by a colon. You can insert a schedule keyword
  387. and a timestamp with `\\[org-schedule]'.")
  388. (defconst org-ds-keyword-length
  389. (+ 2
  390. (apply #'max
  391. (mapcar #'length
  392. (list org-deadline-string org-scheduled-string
  393. org-clock-string org-closed-string))))
  394. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  395. (defconst org-planning-line-re
  396. (concat "^[ \t]*"
  397. (regexp-opt
  398. (list org-closed-string org-deadline-string org-scheduled-string)
  399. t))
  400. "Matches a line with planning info.
  401. Matched keyword is in group 1.")
  402. (defconst org-clock-line-re
  403. (concat "^[ \t]*" org-clock-string)
  404. "Matches a line with clock info.")
  405. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  406. "Matches the DEADLINE keyword.")
  407. (defconst org-deadline-time-regexp
  408. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  409. "Matches the DEADLINE keyword together with a time stamp.")
  410. (defconst org-deadline-time-hour-regexp
  411. (concat "\\<" org-deadline-string
  412. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  413. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  414. (defconst org-deadline-line-regexp
  415. (concat "\\<\\(" org-deadline-string "\\).*")
  416. "Matches the DEADLINE keyword and the rest of the line.")
  417. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  418. "Matches the SCHEDULED keyword.")
  419. (defconst org-scheduled-time-regexp
  420. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  421. "Matches the SCHEDULED keyword together with a time stamp.")
  422. (defconst org-scheduled-time-hour-regexp
  423. (concat "\\<" org-scheduled-string
  424. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  425. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  426. (defconst org-closed-time-regexp
  427. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  428. "Matches the CLOSED keyword together with a time stamp.")
  429. (defconst org-keyword-time-regexp
  430. (concat "\\<"
  431. (regexp-opt
  432. (list org-scheduled-string org-deadline-string org-closed-string
  433. org-clock-string)
  434. t)
  435. " *[[<]\\([^]>]+\\)[]>]")
  436. "Matches any of the 4 keywords, together with the time stamp.")
  437. (defconst org-keyword-time-not-clock-regexp
  438. (concat
  439. "\\<"
  440. (regexp-opt
  441. (list org-scheduled-string org-deadline-string org-closed-string) t)
  442. " *[[<]\\([^]>]+\\)[]>]")
  443. "Matches any of the 3 keywords, together with the time stamp.")
  444. (defconst org-maybe-keyword-time-regexp
  445. (concat "\\(\\<"
  446. (regexp-opt
  447. (list org-scheduled-string org-deadline-string org-closed-string
  448. org-clock-string)
  449. t)
  450. "\\)?"
  451. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  452. "\\|"
  453. "<%%([^\r\n>]*>\\)")
  454. "Matches a timestamp, possibly preceded by a keyword.")
  455. (defconst org-all-time-keywords
  456. (mapcar (lambda (w) (substring w 0 -1))
  457. (list org-scheduled-string org-deadline-string
  458. org-clock-string org-closed-string))
  459. "List of time keywords.")
  460. ;;;; Drawer
  461. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  462. "Matches first or last line of a hidden block.
  463. Group 1 contains drawer's name or \"END\".")
  464. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  465. "Regular expression matching the first line of a property drawer.")
  466. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  467. "Regular expression matching the last line of a property drawer.")
  468. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  469. "Regular expression matching the first line of a clock drawer.")
  470. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  471. "Regular expression matching the last line of a clock drawer.")
  472. (defconst org-property-drawer-re
  473. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  474. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  475. "[ \t]*:END:[ \t]*$")
  476. "Matches an entire property drawer.")
  477. (defconst org-clock-drawer-re
  478. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  479. org-clock-drawer-end-re "\\)\n?")
  480. "Matches an entire clock drawer.")
  481. ;;;; Headline
  482. (defconst org-heading-keyword-regexp-format
  483. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  484. "Printf format for a regexp matching a headline with some keyword.
  485. This regexp will match the headline of any node which has the
  486. exact keyword that is put into the format. The keyword isn't in
  487. any group by default, but the stars and the body are.")
  488. (defconst org-heading-keyword-maybe-regexp-format
  489. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  490. "Printf format for a regexp matching a headline, possibly with some keyword.
  491. This regexp can match any headline with the specified keyword, or
  492. without a keyword. The keyword isn't in any group by default,
  493. but the stars and the body are.")
  494. (defconst org-archive-tag "ARCHIVE"
  495. "The tag that marks a subtree as archived.
  496. An archived subtree does not open during visibility cycling, and does
  497. not contribute to the agenda listings.")
  498. (defconst org-tag-re "[[:alnum:]_@#%]+"
  499. "Regexp matching a single tag.")
  500. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  501. "Regexp matching the tag group at the end of a line, with leading spaces.
  502. Tags are stored in match group 1. Match group 2 stores the tags
  503. without the enclosing colons.")
  504. (defconst org-tag-line-re
  505. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  506. "Regexp matching tags in a headline.
  507. Tags are stored in match group 1. Match group 2 stores the tags
  508. without the enclosing colons.")
  509. (eval-and-compile
  510. (defconst org-comment-string "COMMENT"
  511. "Entries starting with this keyword will never be exported.
  512. \\<org-mode-map>
  513. An entry can be toggled between COMMENT and normal with
  514. `\\[org-toggle-comment]'."))
  515. ;;;; LaTeX Environments and Fragments
  516. (defconst org-latex-regexps
  517. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  518. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  519. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  520. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  521. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  522. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  523. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  524. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  525. "Regular expressions for matching embedded LaTeX.")
  526. ;;;; Node Property
  527. (defconst org-effort-property "Effort"
  528. "The property that is being used to keep track of effort estimates.
  529. Effort estimates given in this property need to have the format H:MM.")
  530. ;;;; Table
  531. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  532. "Detect an org-type or table-type table.")
  533. (defconst org-table-line-regexp "^[ \t]*|"
  534. "Detect an org-type table line.")
  535. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  536. "Detect an org-type table line.")
  537. (defconst org-table-hline-regexp "^[ \t]*|-"
  538. "Detect an org-type table hline.")
  539. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  540. "Detect a table-type table hline.")
  541. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  542. "Detect the first line outside a table when searching from within it.
  543. This works for both table types.")
  544. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  545. "Detect a #+TBLFM line.")
  546. ;;;; Timestamp
  547. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  548. "Regular expression for fast time stamp matching.")
  549. (defconst org-ts-regexp-inactive
  550. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  551. "Regular expression for fast inactive time stamp matching.")
  552. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  553. "Regular expression for fast time stamp matching.")
  554. (defconst org-ts-regexp0
  555. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  556. "Regular expression matching time strings for analysis.
  557. This one does not require the space after the date, so it can be used
  558. on a string that terminates immediately after the date.")
  559. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  560. "Regular expression matching time strings for analysis.")
  561. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  562. "Regular expression matching time stamps, with groups.")
  563. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  564. "Regular expression matching time stamps (also [..]), with groups.")
  565. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  566. "Regular expression matching a time stamp range.")
  567. (defconst org-tr-regexp-both
  568. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  569. "Regular expression matching a time stamp range.")
  570. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  571. org-ts-regexp "\\)?")
  572. "Regular expression matching a time stamp or time stamp range.")
  573. (defconst org-tsr-regexp-both
  574. (concat org-ts-regexp-both "\\(--?-?"
  575. org-ts-regexp-both "\\)?")
  576. "Regular expression matching a time stamp or time stamp range.
  577. The time stamps may be either active or inactive.")
  578. (defconst org-repeat-re
  579. "[[<][0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^]>\n]*?\
  580. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  581. "Regular expression for specifying repeated events.
  582. After a match, group 1 contains the repeat expression.")
  583. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  584. "Formats for `format-time-string' which are used for time stamps.")
  585. ;;; The custom variables
  586. (defgroup org nil
  587. "Outline-based notes management and organizer."
  588. :tag "Org"
  589. :group 'outlines
  590. :group 'calendar)
  591. (defcustom org-mode-hook nil
  592. "Mode hook for Org mode, run after the mode was turned on."
  593. :group 'org
  594. :type 'hook)
  595. (defcustom org-load-hook nil
  596. "Hook that is run after org.el has been loaded."
  597. :group 'org
  598. :type 'hook)
  599. (defcustom org-log-buffer-setup-hook nil
  600. "Hook that is run after an Org log buffer is created."
  601. :group 'org
  602. :version "24.1"
  603. :type 'hook)
  604. (defvar org-modules) ; defined below
  605. (defvar org-modules-loaded nil
  606. "Have the modules been loaded already?")
  607. (defun org-load-modules-maybe (&optional force)
  608. "Load all extensions listed in `org-modules'."
  609. (when (or force (not org-modules-loaded))
  610. (dolist (ext org-modules)
  611. (condition-case nil (require ext)
  612. (error (message "Problems while trying to load feature `%s'" ext))))
  613. (setq org-modules-loaded t)))
  614. (defun org-set-modules (var value)
  615. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  616. (set var value)
  617. (when (featurep 'org)
  618. (org-load-modules-maybe 'force)
  619. (org-element-cache-reset 'all)))
  620. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail org-eww)
  621. "Modules that should always be loaded together with org.el.
  622. If a description starts with <C>, the file is not part of Emacs
  623. and loading it will require that you have downloaded and properly
  624. installed the Org mode distribution.
  625. You can also use this system to load external packages (i.e. neither Org
  626. core modules, nor modules from the CONTRIB directory). Just add symbols
  627. to the end of the list. If the package is called org-xyz.el, then you need
  628. to add the symbol `xyz', and the package must have a call to:
  629. (provide \\='org-xyz)
  630. For export specific modules, see also `org-export-backends'."
  631. :group 'org
  632. :set 'org-set-modules
  633. :version "26.1"
  634. :package-version '(Org . "9.2")
  635. :type
  636. '(set :greedy t
  637. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  638. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  639. (const :tag " crypt: Encryption of subtrees" org-crypt)
  640. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  641. (const :tag " docview: Links to doc-view buffers" org-docview)
  642. (const :tag " eww: Store link to url of eww" org-eww)
  643. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  644. (const :tag " habit: Track your consistency with habits" org-habit)
  645. (const :tag " id: Global IDs for identifying entries" org-id)
  646. (const :tag " info: Links to Info nodes" org-info)
  647. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  648. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  649. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  650. (const :tag " mouse: Additional mouse support" org-mouse)
  651. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  652. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  653. (const :tag " tempo: Fast completion for structures" org-tempo)
  654. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  655. (const :tag " eshell: Support for links to working directories in eshell" org-eshell)
  656. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  657. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  658. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  659. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  660. (const :tag "C collector: Collect properties into tables" org-collector)
  661. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  662. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  663. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  664. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  665. (const :tag "C eval: Include command output as text" org-eval)
  666. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  667. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  668. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  669. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  670. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  671. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  672. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  673. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  674. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  675. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  676. (const :tag "C notify: Notifications for Org-mode" org-notify)
  677. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  678. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  679. (const :tag "C registry: A registry for Org links" org-registry)
  680. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  681. (const :tag "C screenshot: Take and manage screenshots in Org-mode files" org-screenshot)
  682. (const :tag "C secretary: Team management with Org" org-secretary)
  683. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  684. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  685. (const :tag "C track: Keep up with Org mode development" org-track)
  686. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  687. (const :tag "C vm: Links to VM folders/messages" org-vm)
  688. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  689. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  690. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  691. (defvar org-export-registered-backends) ; From ox.el.
  692. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  693. (declare-function org-export-backend-name "ox" (backend) t)
  694. (defcustom org-export-backends '(ascii html icalendar latex odt)
  695. "List of export back-ends that should be always available.
  696. If a description starts with <C>, the file is not part of Emacs
  697. and loading it will require that you have downloaded and properly
  698. installed the Org mode distribution.
  699. Unlike to `org-modules', libraries in this list will not be
  700. loaded along with Org, but only once the export framework is
  701. needed.
  702. This variable needs to be set before org.el is loaded. If you
  703. need to make a change while Emacs is running, use the customize
  704. interface or run the following code, where VAL stands for the new
  705. value of the variable, after updating it:
  706. (progn
  707. (setq org-export-registered-backends
  708. (cl-remove-if-not
  709. (lambda (backend)
  710. (let ((name (org-export-backend-name backend)))
  711. (or (memq name val)
  712. (catch \\='parentp
  713. (dolist (b val)
  714. (and (org-export-derived-backend-p b name)
  715. (throw \\='parentp t)))))))
  716. org-export-registered-backends))
  717. (let ((new-list (mapcar #\\='org-export-backend-name
  718. org-export-registered-backends)))
  719. (dolist (backend val)
  720. (cond
  721. ((not (load (format \"ox-%s\" backend) t t))
  722. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  723. backend))
  724. ((not (memq backend new-list)) (push backend new-list))))
  725. (set-default \\='org-export-backends new-list)))
  726. Adding a back-end to this list will also pull the back-end it
  727. depends on, if any."
  728. :group 'org
  729. :group 'org-export
  730. :version "26.1"
  731. :package-version '(Org . "9.0")
  732. :initialize 'custom-initialize-set
  733. :set (lambda (var val)
  734. (if (not (featurep 'ox)) (set-default var val)
  735. ;; Any back-end not required anymore (not present in VAL and not
  736. ;; a parent of any back-end in the new value) is removed from the
  737. ;; list of registered back-ends.
  738. (setq org-export-registered-backends
  739. (cl-remove-if-not
  740. (lambda (backend)
  741. (let ((name (org-export-backend-name backend)))
  742. (or (memq name val)
  743. (catch 'parentp
  744. (dolist (b val)
  745. (and (org-export-derived-backend-p b name)
  746. (throw 'parentp t)))))))
  747. org-export-registered-backends))
  748. ;; Now build NEW-LIST of both new back-ends and required
  749. ;; parents.
  750. (let ((new-list (mapcar #'org-export-backend-name
  751. org-export-registered-backends)))
  752. (dolist (backend val)
  753. (cond
  754. ((not (load (format "ox-%s" backend) t t))
  755. (message "Problems while trying to load export back-end `%s'"
  756. backend))
  757. ((not (memq backend new-list)) (push backend new-list))))
  758. ;; Set VAR to that list with fixed dependencies.
  759. (set-default var new-list))))
  760. :type '(set :greedy t
  761. (const :tag " ascii Export buffer to ASCII format" ascii)
  762. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  763. (const :tag " html Export buffer to HTML format" html)
  764. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  765. (const :tag " latex Export buffer to LaTeX format" latex)
  766. (const :tag " man Export buffer to MAN format" man)
  767. (const :tag " md Export buffer to Markdown format" md)
  768. (const :tag " odt Export buffer to ODT format" odt)
  769. (const :tag " org Export buffer to Org format" org)
  770. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  771. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  772. (const :tag "C deck Export buffer to deck.js presentations" deck)
  773. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  774. (const :tag "C groff Export buffer to Groff format" groff)
  775. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  776. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  777. (const :tag "C s5 Export buffer to s5 presentations" s5)
  778. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  779. (eval-after-load 'ox
  780. '(dolist (backend org-export-backends)
  781. (condition-case nil (require (intern (format "ox-%s" backend)))
  782. (error (message "Problems while trying to load export back-end `%s'"
  783. backend)))))
  784. (defcustom org-support-shift-select nil
  785. "Non-nil means make shift-cursor commands select text when possible.
  786. \\<org-mode-map>\
  787. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  788. start selecting a region, or enlarge regions started in this way.
  789. In Org mode, in special contexts, these same keys are used for
  790. other purposes, important enough to compete with shift selection.
  791. Org tries to balance these needs by supporting `shift-select-mode'
  792. outside these special contexts, under control of this variable.
  793. The default of this variable is nil, to avoid confusing behavior. Shifted
  794. cursor keys will then execute Org commands in the following contexts:
  795. - on a headline, changing TODO state (left/right) and priority (up/down)
  796. - on a time stamp, changing the time
  797. - in a plain list item, changing the bullet type
  798. - in a property definition line, switching between allowed values
  799. - in the BEGIN line of a clock table (changing the time block).
  800. Outside these contexts, the commands will throw an error.
  801. When this variable is t and the cursor is not in a special
  802. context, Org mode will support shift-selection for making and
  803. enlarging regions. To make this more effective, the bullet
  804. cycling will no longer happen anywhere in an item line, but only
  805. if the cursor is exactly on the bullet.
  806. If you set this variable to the symbol `always', then the keys
  807. will not be special in headlines, property lines, and item lines,
  808. to make shift selection work there as well. If this is what you
  809. want, you can use the following alternative commands:
  810. `\\[org-todo]' and `\\[org-priority]' \
  811. to change TODO state and priority,
  812. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  813. can be used to switch TODO sets,
  814. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  815. and properties can be edited by hand or in column view.
  816. However, when the cursor is on a timestamp, shift-cursor commands
  817. will still edit the time stamp - this is just too good to give up."
  818. :group 'org
  819. :type '(choice
  820. (const :tag "Never" nil)
  821. (const :tag "When outside special context" t)
  822. (const :tag "Everywhere except timestamps" always)))
  823. (defcustom org-loop-over-headlines-in-active-region nil
  824. "Shall some commands act upon headlines in the active region?
  825. When set to t, some commands will be performed in all headlines
  826. within the active region.
  827. When set to `start-level', some commands will be performed in all
  828. headlines within the active region, provided that these headlines
  829. are of the same level than the first one.
  830. When set to a string, those commands will be performed on the
  831. matching headlines within the active region. Such string must be
  832. a tags/property/todo match as it is used in the agenda tags view.
  833. The list of commands is: `org-schedule', `org-deadline',
  834. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  835. `org-archive-to-archive-sibling'. The archiving commands skip
  836. already archived entries."
  837. :type '(choice (const :tag "Don't loop" nil)
  838. (const :tag "All headlines in active region" t)
  839. (const :tag "In active region, headlines at the same level than the first one" start-level)
  840. (string :tag "Tags/Property/Todo matcher"))
  841. :version "24.1"
  842. :group 'org-todo
  843. :group 'org-archive)
  844. (defcustom org-startup-folded t
  845. "Non-nil means entering Org mode will switch to OVERVIEW.
  846. This can also be configured on a per-file basis by adding one of
  847. the following lines anywhere in the buffer:
  848. #+STARTUP: fold (or `overview', this is equivalent)
  849. #+STARTUP: nofold (or `showall', this is equivalent)
  850. #+STARTUP: content
  851. #+STARTUP: showeverything
  852. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  853. to ignore this option when Org opens agenda files for the first
  854. time."
  855. :group 'org-startup
  856. :type '(choice
  857. (const :tag "nofold: show all" nil)
  858. (const :tag "fold: overview" t)
  859. (const :tag "content: all headlines" content)
  860. (const :tag "show everything, even drawers" showeverything)))
  861. (defcustom org-startup-truncated t
  862. "Non-nil means entering Org mode will set `truncate-lines'.
  863. This is useful since some lines containing links can be very long and
  864. uninteresting. Also tables look terrible when wrapped.
  865. The variable `org-startup-truncated' allows to configure
  866. truncation for Org mode different to the other modes that use the
  867. variable `truncate-lines' and as a shortcut instead of putting
  868. the variable `truncate-lines' into the `org-mode-hook'. If one
  869. wants to configure truncation for Org mode not statically but
  870. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  871. the variable `truncate-lines' has to be used because in such a
  872. case it is too late to set the variable `org-startup-truncated'."
  873. :group 'org-startup
  874. :type 'boolean)
  875. (defcustom org-startup-indented nil
  876. "Non-nil means turn on `org-indent-mode' on startup.
  877. This can also be configured on a per-file basis by adding one of
  878. the following lines anywhere in the buffer:
  879. #+STARTUP: indent
  880. #+STARTUP: noindent"
  881. :group 'org-structure
  882. :type '(choice
  883. (const :tag "Not" nil)
  884. (const :tag "Globally (slow on startup in large files)" t)))
  885. (defcustom org-use-sub-superscripts t
  886. "Non-nil means interpret \"_\" and \"^\" for display.
  887. If you want to control how Org exports those characters, see
  888. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  889. used to be an alias for `org-export-with-sub-superscripts' in
  890. Org <8.0, it is not anymore.
  891. When this option is turned on, you can use TeX-like syntax for
  892. sub- and superscripts within the buffer. Several characters after
  893. \"_\" or \"^\" will be considered as a single item - so grouping
  894. with {} is normally not needed. For example, the following things
  895. will be parsed as single sub- or superscripts:
  896. 10^24 or 10^tau several digits will be considered 1 item.
  897. 10^-12 or 10^-tau a leading sign with digits or a word
  898. x^2-y^3 will be read as x^2 - y^3, because items are
  899. terminated by almost any nonword/nondigit char.
  900. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  901. Still, ambiguity is possible. So when in doubt, use {} to enclose
  902. the sub/superscript. If you set this variable to the symbol `{}',
  903. the braces are *required* in order to trigger interpretations as
  904. sub/superscript. This can be helpful in documents that need \"_\"
  905. frequently in plain text."
  906. :group 'org-startup
  907. :version "24.4"
  908. :package-version '(Org . "8.0")
  909. :type '(choice
  910. (const :tag "Always interpret" t)
  911. (const :tag "Only with braces" {})
  912. (const :tag "Never interpret" nil)))
  913. (defcustom org-startup-with-beamer-mode nil
  914. "Non-nil means turn on `org-beamer-mode' on startup.
  915. This can also be configured on a per-file basis by adding one of
  916. the following lines anywhere in the buffer:
  917. #+STARTUP: beamer"
  918. :group 'org-startup
  919. :version "24.1"
  920. :type 'boolean)
  921. (defcustom org-startup-align-all-tables nil
  922. "Non-nil means align all tables when visiting a file.
  923. This can also be configured on a per-file basis by adding one of
  924. the following lines anywhere in the buffer:
  925. #+STARTUP: align
  926. #+STARTUP: noalign"
  927. :group 'org-startup
  928. :type 'boolean)
  929. (defcustom org-startup-shrink-all-tables nil
  930. "Non-nil means shrink all table columns with a width cookie.
  931. This can also be configured on a per-file basis by adding one of
  932. the following lines anywhere in the buffer:
  933. #+STARTUP: shrink"
  934. :group 'org-startup
  935. :type 'boolean
  936. :version "27.1"
  937. :package-version '(Org . "9.2")
  938. :safe #'booleanp)
  939. (defcustom org-startup-with-inline-images nil
  940. "Non-nil means show inline images when loading a new Org file.
  941. This can also be configured on a per-file basis by adding one of
  942. the following lines anywhere in the buffer:
  943. #+STARTUP: inlineimages
  944. #+STARTUP: noinlineimages"
  945. :group 'org-startup
  946. :version "24.1"
  947. :type 'boolean)
  948. (defcustom org-startup-with-latex-preview nil
  949. "Non-nil means preview LaTeX fragments when loading a new Org file.
  950. This can also be configured on a per-file basis by adding one of
  951. the following lines anywhere in the buffer:
  952. #+STARTUP: latexpreview
  953. #+STARTUP: nolatexpreview"
  954. :group 'org-startup
  955. :version "24.4"
  956. :package-version '(Org . "8.0")
  957. :type 'boolean)
  958. (defcustom org-insert-mode-line-in-empty-file nil
  959. "Non-nil means insert the first line setting Org mode in empty files.
  960. When the function `org-mode' is called interactively in an empty file, this
  961. normally means that the file name does not automatically trigger Org mode.
  962. To ensure that the file will always be in Org mode in the future, a
  963. line enforcing Org mode will be inserted into the buffer, if this option
  964. has been set."
  965. :group 'org-startup
  966. :type 'boolean)
  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-bookmark-names-plist
  1082. '(:last-capture "org-capture-last-stored"
  1083. :last-refile "org-refile-last-stored"
  1084. :last-capture-marker "org-capture-last-stored-marker")
  1085. "Names for bookmarks automatically set by some Org commands.
  1086. This can provide strings as names for a number of bookmarks Org sets
  1087. automatically. The following keys are currently implemented:
  1088. :last-capture
  1089. :last-capture-marker
  1090. :last-refile
  1091. When a key does not show up in the property list, the corresponding bookmark
  1092. is not set."
  1093. :group 'org-structure
  1094. :type 'plist)
  1095. (defgroup org-cycle nil
  1096. "Options concerning visibility cycling in Org mode."
  1097. :tag "Org Cycle"
  1098. :group 'org-structure)
  1099. (defcustom org-cycle-skip-children-state-if-no-children t
  1100. "Non-nil means skip CHILDREN state in entries that don't have any."
  1101. :group 'org-cycle
  1102. :type 'boolean)
  1103. (defcustom org-cycle-max-level nil
  1104. "Maximum level which should still be subject to visibility cycling.
  1105. Levels higher than this will, for cycling, be treated as text, not a headline.
  1106. When `org-odd-levels-only' is set, a value of N in this variable actually
  1107. means 2N-1 stars as the limiting headline.
  1108. When nil, cycle all levels.
  1109. Note that the limiting level of cycling is also influenced by
  1110. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1111. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1112. than its value."
  1113. :group 'org-cycle
  1114. :type '(choice
  1115. (const :tag "No limit" nil)
  1116. (integer :tag "Maximum level")))
  1117. (defcustom org-hide-block-startup nil
  1118. "Non-nil means entering Org mode will fold all blocks.
  1119. This can also be set in on a per-file basis with
  1120. #+STARTUP: hideblocks
  1121. #+STARTUP: showblocks"
  1122. :group 'org-startup
  1123. :group 'org-cycle
  1124. :type 'boolean)
  1125. (defcustom org-cycle-global-at-bob nil
  1126. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1127. This makes it possible to do global cycling without having to use `S-TAB'
  1128. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1129. line of the buffer
  1130. must not be a headline -- it may be empty or some other text.
  1131. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1132. sure the cursor stays at the beginning of the buffer.
  1133. When this option is nil, don't do anything special at the beginning of
  1134. the buffer."
  1135. :group 'org-cycle
  1136. :type 'boolean)
  1137. (defcustom org-cycle-level-after-item/entry-creation t
  1138. "Non-nil means cycle entry level or item indentation in new empty entries.
  1139. When the cursor is at the end of an empty headline, i.e., with only stars
  1140. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1141. and then all possible ancestor states, before returning to the original state.
  1142. This makes data entry extremely fast: M-RET to create a new headline,
  1143. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1144. When the cursor is at the end of an empty plain list item, one TAB will
  1145. make it a subitem, two or more tabs will back up to make this an item
  1146. higher up in the item hierarchy."
  1147. :group 'org-cycle
  1148. :type 'boolean)
  1149. (defcustom org-cycle-emulate-tab t
  1150. "Where should `org-cycle' emulate TAB.
  1151. nil Never
  1152. white Only in completely white lines
  1153. whitestart Only at the beginning of lines, before the first non-white char
  1154. t Everywhere except in headlines
  1155. exc-hl-bol Everywhere except at the start of a headline
  1156. If TAB is used in a place where it does not emulate TAB, the current subtree
  1157. visibility is cycled."
  1158. :group 'org-cycle
  1159. :type '(choice (const :tag "Never" nil)
  1160. (const :tag "Only in completely white lines" white)
  1161. (const :tag "Before first char in a line" whitestart)
  1162. (const :tag "Everywhere except in headlines" t)
  1163. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1164. (defcustom org-cycle-separator-lines 2
  1165. "Number of empty lines needed to keep an empty line between collapsed trees.
  1166. If you leave an empty line between the end of a subtree and the following
  1167. headline, this empty line is hidden when the subtree is folded.
  1168. Org mode will leave (exactly) one empty line visible if the number of
  1169. empty lines is equal or larger to the number given in this variable.
  1170. So the default 2 means at least 2 empty lines after the end of a subtree
  1171. are needed to produce free space between a collapsed subtree and the
  1172. following headline.
  1173. If the number is negative, and the number of empty lines is at least -N,
  1174. all empty lines are shown.
  1175. Special case: when 0, never leave empty lines in collapsed view."
  1176. :group 'org-cycle
  1177. :type 'integer)
  1178. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1179. (defcustom org-pre-cycle-hook nil
  1180. "Hook that is run before visibility cycling is happening.
  1181. The function(s) in this hook must accept a single argument which indicates
  1182. the new state that will be set right after running this hook. The
  1183. argument is a symbol. Before a global state change, it can have the values
  1184. `overview', `content', or `all'. Before a local state change, it can have
  1185. the values `folded', `children', or `subtree'."
  1186. :group 'org-cycle
  1187. :type 'hook)
  1188. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1189. org-cycle-show-empty-lines
  1190. org-optimize-window-after-visibility-change)
  1191. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1192. The function(s) in this hook must accept a single argument which indicates
  1193. the new state that was set by the most recent `org-cycle' command. The
  1194. argument is a symbol. After a global state change, it can have the values
  1195. `overview', `contents', or `all'. After a local state change, it can have
  1196. the values `folded', `children', or `subtree'."
  1197. :group 'org-cycle
  1198. :type 'hook
  1199. :version "26.1"
  1200. :package-version '(Org . "8.3"))
  1201. (defgroup org-edit-structure nil
  1202. "Options concerning structure editing in Org mode."
  1203. :tag "Org Edit Structure"
  1204. :group 'org-structure)
  1205. (defcustom org-odd-levels-only nil
  1206. "Non-nil means skip even levels and only use odd levels for the outline.
  1207. This has the effect that two stars are being added/taken away in
  1208. promotion/demotion commands. It also influences how levels are
  1209. handled by the exporters.
  1210. Changing it requires restart of `font-lock-mode' to become effective
  1211. for fontification also in regions already fontified.
  1212. You may also set this on a per-file basis by adding one of the following
  1213. lines to the buffer:
  1214. #+STARTUP: odd
  1215. #+STARTUP: oddeven"
  1216. :group 'org-edit-structure
  1217. :group 'org-appearance
  1218. :type 'boolean)
  1219. (defcustom org-adapt-indentation t
  1220. "Non-nil means adapt indentation to outline node level.
  1221. When this variable is set, Org assumes that you write outlines by
  1222. indenting text in each node to align with the headline (after the
  1223. stars). The following issues are influenced by this variable:
  1224. - The indentation is increased by one space in a demotion
  1225. command, and decreased by one in a promotion command. However,
  1226. in the latter case, if shifting some line in the entry body
  1227. would alter document structure (e.g., insert a new headline),
  1228. indentation is not changed at all.
  1229. - Property drawers and planning information is inserted indented
  1230. when this variable is set. When nil, they will not be indented.
  1231. - TAB indents a line relative to current level. The lines below
  1232. a headline will be indented when this variable is set.
  1233. Note that this is all about true indentation, by adding and
  1234. removing space characters. See also \"org-indent.el\" which does
  1235. level-dependent indentation in a virtual way, i.e. at display
  1236. time in Emacs."
  1237. :group 'org-edit-structure
  1238. :type 'boolean
  1239. :safe #'booleanp)
  1240. (defcustom org-special-ctrl-a/e nil
  1241. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1242. When t, `C-a' will bring back the cursor to the beginning of the
  1243. headline text, i.e. after the stars and after a possible TODO
  1244. keyword. In an item, this will be the position after bullet and
  1245. check-box, if any. When the cursor is already at that position,
  1246. another `C-a' will bring it to the beginning of the line.
  1247. `C-e' will jump to the end of the headline, ignoring the presence
  1248. of tags in the headline. A second `C-e' will then jump to the
  1249. true end of the line, after any tags. This also means that, when
  1250. this variable is non-nil, `C-e' also will never jump beyond the
  1251. end of the heading of a folded section, i.e. not after the
  1252. ellipses.
  1253. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1254. normally, going to the true line boundary first. Only a directly
  1255. following, identical keypress will bring the cursor to the
  1256. special positions.
  1257. This may also be a cons cell where the behavior for `C-a' and
  1258. `C-e' is set separately."
  1259. :group 'org-edit-structure
  1260. :type '(choice
  1261. (const :tag "off" nil)
  1262. (const :tag "on: after stars/bullet and before tags first" t)
  1263. (const :tag "reversed: true line boundary first" reversed)
  1264. (cons :tag "Set C-a and C-e separately"
  1265. (choice :tag "Special C-a"
  1266. (const :tag "off" nil)
  1267. (const :tag "on: after stars/bullet first" t)
  1268. (const :tag "reversed: before stars/bullet first" reversed))
  1269. (choice :tag "Special C-e"
  1270. (const :tag "off" nil)
  1271. (const :tag "on: before tags first" t)
  1272. (const :tag "reversed: after tags first" reversed)))))
  1273. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1274. (defcustom org-special-ctrl-k nil
  1275. "Non-nil means `C-k' will behave specially in headlines.
  1276. When nil, `C-k' will call the default `kill-line' command.
  1277. When t, the following will happen while the cursor is in the headline:
  1278. - When the cursor is at the beginning of a headline, kill the entire
  1279. line and possible the folded subtree below the line.
  1280. - When in the middle of the headline text, kill the headline up to the tags.
  1281. - When after the headline text, kill the tags."
  1282. :group 'org-edit-structure
  1283. :type 'boolean)
  1284. (defcustom org-ctrl-k-protect-subtree nil
  1285. "Non-nil means, do not delete a hidden subtree with C-k.
  1286. When set to the symbol `error', simply throw an error when C-k is
  1287. used to kill (part-of) a headline that has hidden text behind it.
  1288. Any other non-nil value will result in a query to the user, if it is
  1289. OK to kill that hidden subtree. When nil, kill without remorse."
  1290. :group 'org-edit-structure
  1291. :version "24.1"
  1292. :type '(choice
  1293. (const :tag "Do not protect hidden subtrees" nil)
  1294. (const :tag "Protect hidden subtrees with a security query" t)
  1295. (const :tag "Never kill a hidden subtree with C-k" error)))
  1296. (defcustom org-special-ctrl-o t
  1297. "Non-nil means, make `C-o' insert a row in tables."
  1298. :group 'org-edit-structure
  1299. :type 'boolean)
  1300. (defcustom org-catch-invisible-edits nil
  1301. "Check if in invisible region before inserting or deleting a character.
  1302. Valid values are:
  1303. nil Do not check, so just do invisible edits.
  1304. error Throw an error and do nothing.
  1305. show Make point visible, and do the requested edit.
  1306. show-and-error Make point visible, then throw an error and abort the edit.
  1307. smart Make point visible, and do insertion/deletion if it is
  1308. adjacent to visible text and the change feels predictable.
  1309. Never delete a previously invisible character or add in the
  1310. middle or right after an invisible region. Basically, this
  1311. allows insertion and backward-delete right before ellipses.
  1312. FIXME: maybe in this case we should not even show?"
  1313. :group 'org-edit-structure
  1314. :version "24.1"
  1315. :type '(choice
  1316. (const :tag "Do not check" nil)
  1317. (const :tag "Throw error when trying to edit" error)
  1318. (const :tag "Unhide, but do not do the edit" show-and-error)
  1319. (const :tag "Show invisible part and do the edit" show)
  1320. (const :tag "Be smart and do the right thing" smart)))
  1321. (defcustom org-yank-folded-subtrees t
  1322. "Non-nil means when yanking subtrees, fold them.
  1323. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1324. it starts with a heading and all other headings in it are either children
  1325. or siblings, then fold all the subtrees. However, do this only if no
  1326. text after the yank would be swallowed into a folded tree by this action."
  1327. :group 'org-edit-structure
  1328. :type 'boolean)
  1329. (defcustom org-yank-adjusted-subtrees nil
  1330. "Non-nil means when yanking subtrees, adjust the level.
  1331. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1332. this function for details."
  1333. :group 'org-edit-structure
  1334. :type 'boolean)
  1335. (defcustom org-M-RET-may-split-line '((default . t))
  1336. "Non-nil means M-RET will split the line at the cursor position.
  1337. When nil, it will go to the end of the line before making a
  1338. new line.
  1339. You may also set this option in a different way for different
  1340. contexts. Valid contexts are:
  1341. headline when creating a new headline
  1342. item when creating a new item
  1343. table in a table field
  1344. default the value to be used for all contexts not explicitly
  1345. customized"
  1346. :group 'org-structure
  1347. :group 'org-table
  1348. :type '(choice
  1349. (const :tag "Always" t)
  1350. (const :tag "Never" nil)
  1351. (repeat :greedy t :tag "Individual contexts"
  1352. (cons
  1353. (choice :tag "Context"
  1354. (const headline)
  1355. (const item)
  1356. (const table)
  1357. (const default))
  1358. (boolean)))))
  1359. (defcustom org-insert-heading-respect-content nil
  1360. "Non-nil means insert new headings after the current subtree.
  1361. \\<org-mode-map>
  1362. When nil, the new heading is created directly after the current line.
  1363. The commands `\\[org-insert-heading-respect-content]' and \
  1364. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1365. for the duration of the command."
  1366. :group 'org-structure
  1367. :type 'boolean)
  1368. (defcustom org-blank-before-new-entry '((heading . auto)
  1369. (plain-list-item . auto))
  1370. "Should `org-insert-heading' leave a blank line before new heading/item?
  1371. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1372. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1373. which case Org will look at the surrounding headings/items and try to
  1374. make an intelligent decision whether to insert a blank line or not."
  1375. :group 'org-edit-structure
  1376. :type '(list
  1377. (cons (const heading)
  1378. (choice (const :tag "Never" nil)
  1379. (const :tag "Always" t)
  1380. (const :tag "Auto" auto)))
  1381. (cons (const plain-list-item)
  1382. (choice (const :tag "Never" nil)
  1383. (const :tag "Always" t)
  1384. (const :tag "Auto" auto)))))
  1385. (defcustom org-insert-heading-hook nil
  1386. "Hook being run after inserting a new heading."
  1387. :group 'org-edit-structure
  1388. :type 'hook)
  1389. (defcustom org-enable-fixed-width-editor t
  1390. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1391. This currently only means they are never auto-wrapped.
  1392. When nil, such lines will be treated like ordinary lines."
  1393. :group 'org-edit-structure
  1394. :type 'boolean)
  1395. (defgroup org-sparse-trees nil
  1396. "Options concerning sparse trees in Org mode."
  1397. :tag "Org Sparse Trees"
  1398. :group 'org-structure)
  1399. (defcustom org-highlight-sparse-tree-matches t
  1400. "Non-nil means highlight all matches that define a sparse tree.
  1401. The highlights will automatically disappear the next time the buffer is
  1402. changed by an edit command."
  1403. :group 'org-sparse-trees
  1404. :type 'boolean)
  1405. (defcustom org-remove-highlights-with-change t
  1406. "Non-nil means any change to the buffer will remove temporary highlights.
  1407. \\<org-mode-map>\
  1408. Such highlights are created by `org-occur' and `org-clock-display'.
  1409. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1410. to get rid of the highlights.
  1411. The highlights created by `org-toggle-latex-fragment' always need
  1412. `\\[org-toggle-latex-fragment]' to be removed."
  1413. :group 'org-sparse-trees
  1414. :group 'org-time
  1415. :type 'boolean)
  1416. (defcustom org-occur-case-fold-search t
  1417. "Non-nil means `org-occur' should be case-insensitive.
  1418. If set to `smart' the search will be case-insensitive only if it
  1419. doesn't specify any upper case character."
  1420. :group 'org-sparse-trees
  1421. :version "26.1"
  1422. :type '(choice
  1423. (const :tag "Case-sensitive" nil)
  1424. (const :tag "Case-insensitive" t)
  1425. (const :tag "Case-insensitive for lower case searches only" smart)))
  1426. (defcustom org-occur-hook '(org-first-headline-recenter)
  1427. "Hook that is run after `org-occur' has constructed a sparse tree.
  1428. This can be used to recenter the window to show as much of the structure
  1429. as possible."
  1430. :group 'org-sparse-trees
  1431. :type 'hook)
  1432. (defgroup org-table nil
  1433. "Options concerning tables in Org mode."
  1434. :tag "Org Table"
  1435. :group 'org)
  1436. (defcustom org-self-insert-cluster-for-undo nil
  1437. "Non-nil means cluster self-insert commands for undo when possible.
  1438. If this is set, then, like in the Emacs command loop, 20 consecutive
  1439. characters will be undone together.
  1440. This is configurable, because there is some impact on typing performance."
  1441. :group 'org-table
  1442. :type 'boolean)
  1443. (defcustom org-table-tab-recognizes-table.el t
  1444. "Non-nil means TAB will automatically notice a table.el table.
  1445. When it sees such a table, it moves point into it and - if necessary -
  1446. calls `table-recognize-table'."
  1447. :group 'org-table-editing
  1448. :type 'boolean)
  1449. (defgroup org-link nil
  1450. "Options concerning links in Org mode."
  1451. :tag "Org Link"
  1452. :group 'org)
  1453. (defvar-local org-link-abbrev-alist-local nil
  1454. "Buffer-local version of `org-link-abbrev-alist', which see.
  1455. The value of this is taken from the #+LINK lines.")
  1456. (defcustom org-link-parameters
  1457. '(("doi" :follow org--open-doi-link)
  1458. ("elisp" :follow org--open-elisp-link)
  1459. ("file" :complete org-file-complete-link)
  1460. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1461. ("help" :follow org--open-help-link)
  1462. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1463. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1464. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1465. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1466. ("shell" :follow org--open-shell-link))
  1467. "An alist of properties that defines all the links in Org mode.
  1468. The key in each association is a string of the link type.
  1469. Subsequent optional elements make up a p-list of link properties.
  1470. :follow - A function that takes the link path as an argument.
  1471. :export - A function that takes the link path, description and
  1472. export-backend as arguments.
  1473. :store - A function responsible for storing the link. See the
  1474. function `org-store-link-functions'.
  1475. :complete - A function that inserts a link with completion. The
  1476. function takes one optional prefix arg.
  1477. :face - A face for the link, or a function that returns a face.
  1478. The function takes one argument which is the link path. The
  1479. default face is `org-link'.
  1480. :mouse-face - The mouse-face. The default is `highlight'.
  1481. :display - `full' will not fold the link in descriptive
  1482. display. Default is `org-link'.
  1483. :help-echo - A string or function that takes (window object position)
  1484. as arguments and returns a string.
  1485. :keymap - A keymap that is active on the link. The default is
  1486. `org-mouse-map'.
  1487. :htmlize-link - A function for the htmlize-link. Defaults
  1488. to (list :uri \"type:path\")
  1489. :activate-func - A function to run at the end of font-lock
  1490. activation. The function must accept (link-start link-end path bracketp)
  1491. as arguments."
  1492. :group 'org-link
  1493. :type '(alist :tag "Link display parameters"
  1494. :value-type plist)
  1495. :version "26.1"
  1496. :package-version '(Org . "9.1"))
  1497. (defun org-link-get-parameter (type key)
  1498. "Get TYPE link property for KEY.
  1499. TYPE is a string and KEY is a plist keyword."
  1500. (plist-get
  1501. (cdr (assoc type org-link-parameters))
  1502. key))
  1503. (defun org-link-set-parameters (type &rest parameters)
  1504. "Set link TYPE properties to PARAMETERS.
  1505. PARAMETERS should be :key val pairs."
  1506. (let ((data (assoc type org-link-parameters)))
  1507. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1508. (push (cons type parameters) org-link-parameters)
  1509. (org-make-link-regexps)
  1510. (org-element-update-syntax))))
  1511. (defun org-link-types ()
  1512. "Return a list of known link types."
  1513. (mapcar #'car org-link-parameters))
  1514. (defcustom org-link-abbrev-alist nil
  1515. "Alist of link abbreviations.
  1516. The car of each element is a string, to be replaced at the start of a link.
  1517. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1518. links in Org buffers can have an optional tag after a double colon, e.g.,
  1519. [[linkkey:tag][description]]
  1520. The `linkkey' must be a single word, starting with a letter, followed
  1521. by letters, numbers, `-' or `_'.
  1522. If REPLACE is a string, the tag will simply be appended to create the link.
  1523. If the string contains \"%s\", the tag will be inserted there. If the string
  1524. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1525. at that point (see the function `url-hexify-string'). If the string contains
  1526. the specifier \"%(my-function)\", then the custom function `my-function' will
  1527. be invoked: this function takes the tag as its only argument and must return
  1528. a string.
  1529. REPLACE may also be a function that will be called with the tag as the
  1530. only argument to create the link, which should be returned as a string.
  1531. See the manual for examples."
  1532. :group 'org-link
  1533. :type '(repeat
  1534. (cons
  1535. (string :tag "Protocol")
  1536. (choice
  1537. (string :tag "Format")
  1538. (function)))))
  1539. (defcustom org-descriptive-links t
  1540. "Non-nil means Org will display descriptive links.
  1541. E.g. [[https://orgmode.org][Org website]] will be displayed as
  1542. \"Org Website\", hiding the link itself and just displaying its
  1543. description. When set to nil, Org will display the full links
  1544. literally.
  1545. You can interactively set the value of this variable by calling
  1546. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1547. :group 'org-link
  1548. :type 'boolean)
  1549. (defcustom org-link-file-path-type 'adaptive
  1550. "How the path name in file links should be stored.
  1551. Valid values are:
  1552. relative Relative to the current directory, i.e. the directory of the file
  1553. into which the link is being inserted.
  1554. absolute Absolute path, if possible with ~ for home directory.
  1555. noabbrev Absolute path, no abbreviation of home directory.
  1556. adaptive Use relative path for files in the current directory and sub-
  1557. directories of it. For other files, use an absolute path."
  1558. :group 'org-link
  1559. :type '(choice
  1560. (const relative)
  1561. (const absolute)
  1562. (const noabbrev)
  1563. (const adaptive)))
  1564. (defvaralias 'org-activate-links 'org-highlight-links)
  1565. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1566. "Types of links that should be highlighted in Org files.
  1567. This is a list of symbols, each one of them leading to the
  1568. highlighting of a certain link type.
  1569. You can still open links that are not highlighted.
  1570. In principle, it does not hurt to turn on highlighting for all
  1571. link types. There may be a small gain when turning off unused
  1572. link types. The types are:
  1573. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1574. angle Links in angular brackets that may contain whitespace like
  1575. <bbdb:Carsten Dominik>.
  1576. plain Plain links in normal text, no whitespace, like http://google.com.
  1577. radio Text that is matched by a radio target, see manual for details.
  1578. tag Tag settings in a headline (link to tag search).
  1579. date Time stamps (link to calendar).
  1580. footnote Footnote labels.
  1581. If you set this variable during an Emacs session, use `org-mode-restart'
  1582. in the Org buffer so that the change takes effect."
  1583. :group 'org-link
  1584. :group 'org-appearance
  1585. :type '(set :greedy t
  1586. (const :tag "Double bracket links" bracket)
  1587. (const :tag "Angular bracket links" angle)
  1588. (const :tag "Plain text links" plain)
  1589. (const :tag "Radio target matches" radio)
  1590. (const :tag "Tags" tag)
  1591. (const :tag "Timestamps" date)
  1592. (const :tag "Footnotes" footnote)))
  1593. (defcustom org-make-link-description-function nil
  1594. "Function to use for generating link descriptions from links.
  1595. This function must take two parameters: the first one is the
  1596. link, the second one is the description generated by
  1597. `org-insert-link'. The function should return the description to
  1598. use."
  1599. :group 'org-link
  1600. :type '(choice (const nil) (function)))
  1601. (defgroup org-link-store nil
  1602. "Options concerning storing links in Org mode."
  1603. :tag "Org Store Link"
  1604. :group 'org-link)
  1605. (defcustom org-url-hexify-p t
  1606. "When non-nil, hexify URL when creating a link."
  1607. :type 'boolean
  1608. :version "24.3"
  1609. :group 'org-link-store)
  1610. (defcustom org-email-link-description-format "Email %c: %s"
  1611. "Format of the description part of a link to an email or usenet message.
  1612. The following %-escapes will be replaced by corresponding information:
  1613. %F full \"From\" field
  1614. %f name, taken from \"From\" field, address if no name
  1615. %T full \"To\" field
  1616. %t first name in \"To\" field, address if no name
  1617. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1618. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1619. %s subject
  1620. %d date
  1621. %m message-id.
  1622. You may use normal field width specification between the % and the letter.
  1623. This is for example useful to limit the length of the subject.
  1624. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1625. :group 'org-link-store
  1626. :package-version '(Org . 9.3)
  1627. :type 'string
  1628. :safe #'stringp)
  1629. (defcustom org-from-is-user-regexp
  1630. (let (r1 r2)
  1631. (when (and user-mail-address (not (string= user-mail-address "")))
  1632. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1633. (when (and user-full-name (not (string= user-full-name "")))
  1634. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1635. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1636. "Regexp matched against the \"From:\" header of an email or usenet message.
  1637. It should match if the message is from the user him/herself."
  1638. :group 'org-link-store
  1639. :type 'regexp)
  1640. (defcustom org-context-in-file-links t
  1641. "Non-nil means file links from `org-store-link' contain context.
  1642. \\<org-mode-map>
  1643. A search string will be added to the file name with :: as separator
  1644. and used to find the context when the link is activated by the command
  1645. `org-open-at-point'. When this option is t, the entire active region
  1646. will be placed in the search string of the file link. If set to a
  1647. positive integer, only the first n lines of context will be stored.
  1648. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1649. \\[org-store-link]')
  1650. negates this setting for the duration of the command."
  1651. :group 'org-link-store
  1652. :type '(choice boolean integer))
  1653. (defcustom org-keep-stored-link-after-insertion nil
  1654. "Non-nil means keep link in list for entire session.
  1655. \\<org-mode-map>
  1656. The command `org-store-link' adds a link pointing to the current
  1657. location to an internal list. These links accumulate during a session.
  1658. The command `org-insert-link' can be used to insert links into any
  1659. Org file (offering completion for all stored links).
  1660. When this option is nil, every link which has been inserted once using
  1661. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1662. unused
  1663. links more efficient."
  1664. :group 'org-link-store
  1665. :type 'boolean)
  1666. (defgroup org-link-follow nil
  1667. "Options concerning following links in Org mode."
  1668. :tag "Org Follow Link"
  1669. :group 'org-link)
  1670. (defcustom org-link-translation-function nil
  1671. "Function to translate links with different syntax to Org syntax.
  1672. This can be used to translate links created for example by the Planner
  1673. or emacs-wiki packages to Org syntax.
  1674. The function must accept two parameters, a TYPE containing the link
  1675. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1676. which is everything after the link protocol. It should return a cons
  1677. with possibly modified values of type and path.
  1678. Org contains a function for this, so if you set this variable to
  1679. `org-translate-link-from-planner', you should be able follow many
  1680. links created by planner."
  1681. :group 'org-link-follow
  1682. :type '(choice (const nil) (function)))
  1683. (defcustom org-mark-ring-length 4
  1684. "Number of different positions to be recorded in the ring.
  1685. Changing this requires a restart of Emacs to work correctly."
  1686. :group 'org-link-follow
  1687. :type 'integer)
  1688. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1689. "Non-nil means internal fuzzy links can only match headlines.
  1690. When nil, the a fuzzy link may point to a target or a named
  1691. construct in the document. When set to the special value
  1692. `query-to-create', offer to create a new headline when none
  1693. matched.
  1694. Spaces and statistics cookies are ignored during heading searches."
  1695. :group 'org-link-follow
  1696. :version "24.1"
  1697. :type '(choice
  1698. (const :tag "Use fuzzy text search" nil)
  1699. (const :tag "Match only exact headline" t)
  1700. (const :tag "Match exact headline or query to create it"
  1701. query-to-create))
  1702. :safe #'symbolp)
  1703. (defcustom org-link-frame-setup
  1704. '((vm . vm-visit-folder-other-frame)
  1705. (vm-imap . vm-visit-imap-folder-other-frame)
  1706. (gnus . org-gnus-no-new-news)
  1707. (file . find-file-other-window)
  1708. (wl . wl-other-frame))
  1709. "Setup the frame configuration for following links.
  1710. When following a link with Emacs, it may often be useful to display
  1711. this link in another window or frame. This variable can be used to
  1712. set this up for the different types of links.
  1713. For VM, use any of
  1714. `vm-visit-folder'
  1715. `vm-visit-folder-other-window'
  1716. `vm-visit-folder-other-frame'
  1717. For Gnus, use any of
  1718. `gnus'
  1719. `gnus-other-frame'
  1720. `org-gnus-no-new-news'
  1721. For FILE, use any of
  1722. `find-file'
  1723. `find-file-other-window'
  1724. `find-file-other-frame'
  1725. For Wanderlust use any of
  1726. `wl'
  1727. `wl-other-frame'
  1728. For the calendar, use the variable `calendar-setup'.
  1729. For BBDB, it is currently only possible to display the matches in
  1730. another window."
  1731. :group 'org-link-follow
  1732. :type '(list
  1733. (cons (const vm)
  1734. (choice
  1735. (const vm-visit-folder)
  1736. (const vm-visit-folder-other-window)
  1737. (const vm-visit-folder-other-frame)))
  1738. (cons (const vm-imap)
  1739. (choice
  1740. (const vm-visit-imap-folder)
  1741. (const vm-visit-imap-folder-other-window)
  1742. (const vm-visit-imap-folder-other-frame)))
  1743. (cons (const gnus)
  1744. (choice
  1745. (const gnus)
  1746. (const gnus-other-frame)
  1747. (const org-gnus-no-new-news)))
  1748. (cons (const file)
  1749. (choice
  1750. (const find-file)
  1751. (const find-file-other-window)
  1752. (const find-file-other-frame)))
  1753. (cons (const wl)
  1754. (choice
  1755. (const wl)
  1756. (const wl-other-frame)))))
  1757. (defcustom org-display-internal-link-with-indirect-buffer nil
  1758. "Non-nil means use indirect buffer to display infile links.
  1759. Activating internal links (from one location in a file to another location
  1760. in the same file) normally just jumps to the location. When the link is
  1761. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1762. is displayed in
  1763. another window. When this option is set, the other window actually displays
  1764. an indirect buffer clone of the current buffer, to avoid any visibility
  1765. changes to the current buffer."
  1766. :group 'org-link-follow
  1767. :type 'boolean)
  1768. (defcustom org-open-non-existing-files nil
  1769. "Non-nil means `org-open-file' will open non-existing files.
  1770. When nil, an error will be generated.
  1771. This variable applies only to external applications because they
  1772. might choke on non-existing files. If the link is to a file that
  1773. will be opened in Emacs, the variable is ignored."
  1774. :group 'org-link-follow
  1775. :type 'boolean)
  1776. (defcustom org-open-directory-means-index-dot-org nil
  1777. "Non-nil means a link to a directory really means to index.org.
  1778. When nil, following a directory link will run dired or open a finder/explorer
  1779. window on that directory."
  1780. :group 'org-link-follow
  1781. :type 'boolean)
  1782. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1783. "Non-nil means ask for confirmation before executing shell links.
  1784. Shell links can be dangerous: just think about a link
  1785. [[shell:rm -rf ~/*][Google Search]]
  1786. This link would show up in your Org document as \"Google Search\",
  1787. but really it would remove your entire home directory.
  1788. Therefore we advise against setting this variable to nil.
  1789. Just change it to `y-or-n-p' if you want to confirm with a
  1790. single keystroke rather than having to type \"yes\"."
  1791. :group 'org-link-follow
  1792. :type '(choice
  1793. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1794. (const :tag "with y-or-n (faster)" y-or-n-p)
  1795. (const :tag "no confirmation (dangerous)" nil)))
  1796. (put 'org-confirm-shell-link-function
  1797. 'safe-local-variable
  1798. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1799. (defcustom org-confirm-shell-link-not-regexp ""
  1800. "A regexp to skip confirmation for shell links."
  1801. :group 'org-link-follow
  1802. :version "24.1"
  1803. :type 'regexp)
  1804. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1805. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1806. Elisp links can be dangerous: just think about a link
  1807. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1808. This link would show up in your Org document as \"Google Search\",
  1809. but really it would remove your entire home directory.
  1810. Therefore we advise against setting this variable to nil.
  1811. Just change it to `y-or-n-p' if you want to confirm with a
  1812. single keystroke rather than having to type \"yes\"."
  1813. :group 'org-link-follow
  1814. :type '(choice
  1815. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1816. (const :tag "with y-or-n (faster)" y-or-n-p)
  1817. (const :tag "no confirmation (dangerous)" nil)))
  1818. (put 'org-confirm-shell-link-function
  1819. 'safe-local-variable
  1820. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1821. (defcustom org-confirm-elisp-link-not-regexp ""
  1822. "A regexp to skip confirmation for Elisp links."
  1823. :group 'org-link-follow
  1824. :version "24.1"
  1825. :type 'regexp)
  1826. (defconst org-file-apps-defaults-gnu
  1827. '((remote . emacs)
  1828. (system . mailcap)
  1829. (t . mailcap))
  1830. "Default file applications on a UNIX or GNU/Linux system.
  1831. See `org-file-apps'.")
  1832. (defconst org-file-apps-defaults-macosx
  1833. '((remote . emacs)
  1834. (system . "open %s")
  1835. ("ps.gz" . "gv %s")
  1836. ("eps.gz" . "gv %s")
  1837. ("dvi" . "xdvi %s")
  1838. ("fig" . "xfig %s")
  1839. (t . "open %s"))
  1840. "Default file applications on a macOS system.
  1841. The system \"open\" is known as a default, but we use X11 applications
  1842. for some files for which the OS does not have a good default.
  1843. See `org-file-apps'.")
  1844. (defconst org-file-apps-defaults-windowsnt
  1845. (list '(remote . emacs)
  1846. (cons 'system (lambda (file _path)
  1847. (with-no-warnings (w32-shell-execute "open" file))))
  1848. (cons t (lambda (file _path)
  1849. (with-no-warnings (w32-shell-execute "open" file)))))
  1850. "Default file applications on a Windows NT system.
  1851. The system \"open\" is used for most files.
  1852. See `org-file-apps'.")
  1853. (defcustom org-file-apps
  1854. '((auto-mode . emacs)
  1855. ("\\.mm\\'" . default)
  1856. ("\\.x?html?\\'" . default)
  1857. ("\\.pdf\\'" . default))
  1858. "External applications for opening `file:path' items in a document.
  1859. \\<org-mode-map>\
  1860. Org mode uses system defaults for different file types, but
  1861. you can use this variable to set the application for a given file
  1862. extension. The entries in this list are cons cells where the car identifies
  1863. files and the cdr the corresponding command.
  1864. Possible values for the file identifier are:
  1865. \"string\" A string as a file identifier can be interpreted in different
  1866. ways, depending on its contents:
  1867. - Alphanumeric characters only:
  1868. Match links with this file extension.
  1869. Example: (\"pdf\" . \"evince %s\")
  1870. to open PDFs with evince.
  1871. - Regular expression: Match links where the
  1872. filename matches the regexp. If you want to
  1873. use groups here, use shy groups.
  1874. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1875. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1876. to open *.html and *.xhtml with firefox.
  1877. - Regular expression which contains (non-shy) groups:
  1878. Match links where the whole link, including \"::\", and
  1879. anything after that, matches the regexp.
  1880. In a custom command string, %1, %2, etc. are replaced with
  1881. the parts of the link that were matched by the groups.
  1882. For backwards compatibility, if a command string is given
  1883. that does not use any of the group matches, this case is
  1884. handled identically to the second one (i.e. match against
  1885. file name only).
  1886. In a custom function, you can access the group matches with
  1887. (match-string n link).
  1888. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1889. \"evince -p %1 %s\")
  1890. to open [[file:document.pdf::5]] with evince at page 5.
  1891. `directory' Matches a directory
  1892. `remote' Matches a remote file, accessible through tramp or efs.
  1893. Remote files most likely should be visited through Emacs
  1894. because external applications cannot handle such paths.
  1895. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1896. so all files Emacs knows how to handle. Using this with
  1897. command `emacs' will open most files in Emacs. Beware that this
  1898. will also open html files inside Emacs, unless you add
  1899. (\"html\" . default) to the list as well.
  1900. `system' The system command to open files, like `open' on Windows
  1901. and macOS, and mailcap under GNU/Linux. This is the command
  1902. that will be selected if you call `org-open-at-point' with a
  1903. double prefix argument (`\\[universal-argument] \
  1904. \\[universal-argument] \\[org-open-at-point]').
  1905. t Default for files not matched by any of the other options.
  1906. Possible values for the command are:
  1907. `emacs' The file will be visited by the current Emacs process.
  1908. `default' Use the default application for this file type, which is the
  1909. association for t in the list, most likely in the system-specific
  1910. part. This can be used to overrule an unwanted setting in the
  1911. system-specific variable.
  1912. `system' Use the system command for opening files, like \"open\".
  1913. This command is specified by the entry whose car is `system'.
  1914. Most likely, the system-specific version of this variable
  1915. does define this command, but you can overrule/replace it
  1916. here.
  1917. `mailcap' Use command specified in the mailcaps.
  1918. string A command to be executed by a shell; %s will be replaced
  1919. by the path to the file.
  1920. function A Lisp function, which will be called with two arguments:
  1921. the file path and the original link string, without the
  1922. \"file:\" prefix.
  1923. For more examples, see the system specific constants
  1924. `org-file-apps-defaults-macosx'
  1925. `org-file-apps-defaults-windowsnt'
  1926. `org-file-apps-defaults-gnu'."
  1927. :group 'org-link-follow
  1928. :type '(repeat
  1929. (cons (choice :value ""
  1930. (string :tag "Extension")
  1931. (const :tag "System command to open files" system)
  1932. (const :tag "Default for unrecognized files" t)
  1933. (const :tag "Remote file" remote)
  1934. (const :tag "Links to a directory" directory)
  1935. (const :tag "Any files that have Emacs modes"
  1936. auto-mode))
  1937. (choice :value ""
  1938. (const :tag "Visit with Emacs" emacs)
  1939. (const :tag "Use default" default)
  1940. (const :tag "Use the system command" system)
  1941. (string :tag "Command")
  1942. (function :tag "Function")))))
  1943. (defcustom org-doi-server-url "http://dx.doi.org/"
  1944. "The URL of the DOI server."
  1945. :type 'string
  1946. :version "24.3"
  1947. :group 'org-link-follow)
  1948. (defgroup org-refile nil
  1949. "Options concerning refiling entries in Org mode."
  1950. :tag "Org Refile"
  1951. :group 'org)
  1952. (defcustom org-directory "~/org"
  1953. "Directory with Org files.
  1954. This is just a default location to look for Org files. There is no need
  1955. at all to put your files into this directory. It is used in the
  1956. following situations:
  1957. 1. When a capture template specifies a target file that is not an
  1958. absolute path. The path will then be interpreted relative to
  1959. `org-directory'
  1960. 2. When the value of variable `org-agenda-files' is a single file, any
  1961. relative paths in this file will be taken as relative to
  1962. `org-directory'."
  1963. :group 'org-refile
  1964. :group 'org-capture
  1965. :type 'directory)
  1966. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  1967. "Default target for storing notes.
  1968. Used as a fall back file for org-capture.el, for templates that
  1969. do not specify a target file."
  1970. :group 'org-refile
  1971. :group 'org-capture
  1972. :type 'file)
  1973. (defcustom org-reverse-note-order nil
  1974. "Non-nil means store new notes at the beginning of a file or entry.
  1975. When nil, new notes will be filed to the end of a file or entry.
  1976. This can also be a list with cons cells of regular expressions that
  1977. are matched against file names, and values."
  1978. :group 'org-capture
  1979. :group 'org-refile
  1980. :type '(choice
  1981. (const :tag "Reverse always" t)
  1982. (const :tag "Reverse never" nil)
  1983. (repeat :tag "By file name regexp"
  1984. (cons regexp boolean))))
  1985. (defcustom org-log-refile nil
  1986. "Information to record when a task is refiled.
  1987. Possible values are:
  1988. nil Don't add anything
  1989. time Add a time stamp to the task
  1990. note Prompt for a note and add it with template `org-log-note-headings'
  1991. This option can also be set with on a per-file-basis with
  1992. #+STARTUP: nologrefile
  1993. #+STARTUP: logrefile
  1994. #+STARTUP: lognoterefile
  1995. You can have local logging settings for a subtree by setting the LOGGING
  1996. property to one or more of these keywords.
  1997. When bulk-refiling from the agenda, the value `note' is forbidden and
  1998. will temporarily be changed to `time'."
  1999. :group 'org-refile
  2000. :group 'org-progress
  2001. :version "24.1"
  2002. :type '(choice
  2003. (const :tag "No logging" nil)
  2004. (const :tag "Record timestamp" time)
  2005. (const :tag "Record timestamp with note." note)))
  2006. (defcustom org-refile-targets nil
  2007. "Targets for refiling entries with `\\[org-refile]'.
  2008. This is a list of cons cells. Each cell contains:
  2009. - a specification of the files to be considered, either a list of files,
  2010. or a symbol whose function or variable value will be used to retrieve
  2011. a file name or a list of file names. If you use `org-agenda-files' for
  2012. that, all agenda files will be scanned for targets. Nil means consider
  2013. headings in the current buffer.
  2014. - A specification of how to find candidate refile targets. This may be
  2015. any of:
  2016. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2017. This tag has to be present in all target headlines, inheritance will
  2018. not be considered.
  2019. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2020. todo keyword.
  2021. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2022. headlines that are refiling targets.
  2023. - a cons cell (:level . N). Any headline of level N is considered a target.
  2024. Note that, when `org-odd-levels-only' is set, level corresponds to
  2025. order in hierarchy, not to the number of stars.
  2026. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2027. Note that, when `org-odd-levels-only' is set, level corresponds to
  2028. order in hierarchy, not to the number of stars.
  2029. Each element of this list generates a set of possible targets.
  2030. The union of these sets is presented (with completion) to
  2031. the user by `org-refile'.
  2032. You can set the variable `org-refile-target-verify-function' to a function
  2033. to verify each headline found by the simple criteria above.
  2034. When this variable is nil, all top-level headlines in the current buffer
  2035. are used, equivalent to the value `((nil . (:level . 1))'."
  2036. :group 'org-refile
  2037. :type '(repeat
  2038. (cons
  2039. (choice :value org-agenda-files
  2040. (const :tag "All agenda files" org-agenda-files)
  2041. (const :tag "Current buffer" nil)
  2042. (function) (variable) (file))
  2043. (choice :tag "Identify target headline by"
  2044. (cons :tag "Specific tag" (const :value :tag) (string))
  2045. (cons :tag "TODO keyword" (const :value :todo) (string))
  2046. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2047. (cons :tag "Level number" (const :value :level) (integer))
  2048. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2049. (defcustom org-refile-target-verify-function nil
  2050. "Function to verify if the headline at point should be a refile target.
  2051. The function will be called without arguments, with point at the
  2052. beginning of the headline. It should return t and leave point
  2053. where it is if the headline is a valid target for refiling.
  2054. If the target should not be selected, the function must return nil.
  2055. In addition to this, it may move point to a place from where the search
  2056. should be continued. For example, the function may decide that the entire
  2057. subtree of the current entry should be excluded and move point to the end
  2058. of the subtree."
  2059. :group 'org-refile
  2060. :type '(choice
  2061. (const nil)
  2062. (function)))
  2063. (defcustom org-refile-use-cache nil
  2064. "Non-nil means cache refile targets to speed up the process.
  2065. \\<org-mode-map>\
  2066. The cache for a particular file will be updated automatically when
  2067. the buffer has been killed, or when any of the marker used for flagging
  2068. refile targets no longer points at a live buffer.
  2069. If you have added new entries to a buffer that might themselves be targets,
  2070. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2071. if you find that easier, \
  2072. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2073. \\[org-refile]'."
  2074. :group 'org-refile
  2075. :version "24.1"
  2076. :type 'boolean)
  2077. (defcustom org-refile-use-outline-path nil
  2078. "Non-nil means provide refile targets as paths.
  2079. So a level 3 headline will be available as level1/level2/level3.
  2080. When the value is `file', also include the file name (without directory)
  2081. into the path. In this case, you can also stop the completion after
  2082. the file name, to get entries inserted as top level in the file.
  2083. When `full-file-path', include the full file path.
  2084. When `buffer-name', use the buffer name."
  2085. :group 'org-refile
  2086. :type '(choice
  2087. (const :tag "Not" nil)
  2088. (const :tag "Yes" t)
  2089. (const :tag "Start with file name" file)
  2090. (const :tag "Start with full file path" full-file-path)
  2091. (const :tag "Start with buffer name" buffer-name)))
  2092. (defcustom org-outline-path-complete-in-steps t
  2093. "Non-nil means complete the outline path in hierarchical steps.
  2094. When Org uses the refile interface to select an outline path (see
  2095. `org-refile-use-outline-path'), the completion of the path can be
  2096. done in a single go, or it can be done in steps down the headline
  2097. hierarchy. Going in steps is probably the best if you do not use
  2098. a special completion package like `ido' or `icicles'. However,
  2099. when using these packages, going in one step can be very fast,
  2100. while still showing the whole path to the entry."
  2101. :group 'org-refile
  2102. :type 'boolean)
  2103. (defcustom org-refile-allow-creating-parent-nodes nil
  2104. "Non-nil means allow the creation of new nodes as refile targets.
  2105. New nodes are then created by adding \"/new node name\" to the completion
  2106. of an existing node. When the value of this variable is `confirm',
  2107. new node creation must be confirmed by the user (recommended).
  2108. When nil, the completion must match an existing entry.
  2109. Note that, if the new heading is not seen by the criteria
  2110. listed in `org-refile-targets', multiple instances of the same
  2111. heading would be created by trying again to file under the new
  2112. heading."
  2113. :group 'org-refile
  2114. :type '(choice
  2115. (const :tag "Never" nil)
  2116. (const :tag "Always" t)
  2117. (const :tag "Prompt for confirmation" confirm)))
  2118. (defcustom org-refile-active-region-within-subtree nil
  2119. "Non-nil means also refile active region within a subtree.
  2120. By default `org-refile' doesn't allow refiling regions if they
  2121. don't contain a set of subtrees, but it might be convenient to
  2122. do so sometimes: in that case, the first line of the region is
  2123. converted to a headline before refiling."
  2124. :group 'org-refile
  2125. :version "24.1"
  2126. :type 'boolean)
  2127. (defgroup org-todo nil
  2128. "Options concerning TODO items in Org mode."
  2129. :tag "Org TODO"
  2130. :group 'org)
  2131. (defgroup org-progress nil
  2132. "Options concerning Progress logging in Org mode."
  2133. :tag "Org Progress"
  2134. :group 'org-time)
  2135. (defvar org-todo-interpretation-widgets
  2136. '((:tag "Sequence (cycling hits every state)" sequence)
  2137. (:tag "Type (cycling directly to DONE)" type))
  2138. "The available interpretation symbols for customizing `org-todo-keywords'.
  2139. Interested libraries should add to this list.")
  2140. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2141. "List of TODO entry keyword sequences and their interpretation.
  2142. \\<org-mode-map>This is a list of sequences.
  2143. Each sequence starts with a symbol, either `sequence' or `type',
  2144. indicating if the keywords should be interpreted as a sequence of
  2145. action steps, or as different types of TODO items. The first
  2146. keywords are states requiring action - these states will select a headline
  2147. for inclusion into the global TODO list Org produces. If one of the
  2148. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2149. signify that no further action is necessary. If \"|\" is not found,
  2150. the last keyword is treated as the only DONE state of the sequence.
  2151. The command `\\[org-todo]' cycles an entry through these states, and one
  2152. additional state where no keyword is present. For details about this
  2153. cycling, see the manual.
  2154. TODO keywords and interpretation can also be set on a per-file basis with
  2155. the special #+SEQ_TODO and #+TYP_TODO lines.
  2156. Each keyword can optionally specify a character for fast state selection
  2157. \(in combination with the variable `org-use-fast-todo-selection')
  2158. and specifiers for state change logging, using the same syntax that
  2159. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2160. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2161. indicates to record a time stamp each time this state is selected.
  2162. Each keyword may also specify if a timestamp or a note should be
  2163. recorded when entering or leaving the state, by adding additional
  2164. characters in the parenthesis after the keyword. This looks like this:
  2165. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2166. record only the time of the state change. With X and Y being either
  2167. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2168. Y when leaving the state if and only if the *target* state does not
  2169. define X. You may omit any of the fast-selection key or X or /Y,
  2170. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2171. For backward compatibility, this variable may also be just a list
  2172. of keywords. In this case the interpretation (sequence or type) will be
  2173. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2174. :group 'org-todo
  2175. :group 'org-keywords
  2176. :type '(choice
  2177. (repeat :tag "Old syntax, just keywords"
  2178. (string :tag "Keyword"))
  2179. (repeat :tag "New syntax"
  2180. (cons
  2181. (choice
  2182. :tag "Interpretation"
  2183. ;;Quick and dirty way to see
  2184. ;;`org-todo-interpretations'. This takes the
  2185. ;;place of item arguments
  2186. :convert-widget
  2187. (lambda (widget)
  2188. (widget-put widget
  2189. :args (mapcar
  2190. (lambda (x)
  2191. (widget-convert
  2192. (cons 'const x)))
  2193. org-todo-interpretation-widgets))
  2194. widget))
  2195. (repeat
  2196. (string :tag "Keyword"))))))
  2197. (defvar-local org-todo-keywords-1 nil
  2198. "All TODO and DONE keywords active in a buffer.")
  2199. (defvar org-todo-keywords-for-agenda nil)
  2200. (defvar org-done-keywords-for-agenda nil)
  2201. (defvar org-todo-keyword-alist-for-agenda nil)
  2202. (defvar org-tag-alist-for-agenda nil
  2203. "Alist of all tags from all agenda files.")
  2204. (defvar org-tag-groups-alist-for-agenda nil
  2205. "Alist of all groups tags from all current agenda files.")
  2206. (defvar-local org-tag-groups-alist nil)
  2207. (defvar org-agenda-contributing-files nil)
  2208. (defvar-local org-current-tag-alist nil
  2209. "Alist of all tag groups in current buffer.
  2210. This variable takes into consideration `org-tag-alist',
  2211. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2212. (defvar-local org-not-done-keywords nil)
  2213. (defvar-local org-done-keywords nil)
  2214. (defvar-local org-todo-heads nil)
  2215. (defvar-local org-todo-sets nil)
  2216. (defvar-local org-todo-log-states nil)
  2217. (defvar-local org-todo-kwd-alist nil)
  2218. (defvar-local org-todo-key-alist nil)
  2219. (defvar-local org-todo-key-trigger nil)
  2220. (defcustom org-todo-interpretation 'sequence
  2221. "Controls how TODO keywords are interpreted.
  2222. This variable is in principle obsolete and is only used for
  2223. backward compatibility, if the interpretation of todo keywords is
  2224. not given already in `org-todo-keywords'. See that variable for
  2225. more information."
  2226. :group 'org-todo
  2227. :group 'org-keywords
  2228. :type '(choice (const sequence)
  2229. (const type)))
  2230. (defcustom org-use-fast-todo-selection t
  2231. "\\<org-mode-map>\
  2232. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2233. This variable describes if and under what circumstances the cycling
  2234. mechanism for TODO keywords will be replaced by a single-key, direct
  2235. selection scheme.
  2236. When nil, fast selection is never used.
  2237. When the symbol `prefix', it will be used when `org-todo' is called
  2238. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2239. in an Org buffer, and
  2240. `\\[universal-argument] t' in an agenda buffer.
  2241. When t, fast selection is used by default. In this case, the prefix
  2242. argument forces cycling instead.
  2243. In all cases, the special interface is only used if access keys have
  2244. actually been assigned by the user, i.e. if keywords in the configuration
  2245. are followed by a letter in parenthesis, like TODO(t)."
  2246. :group 'org-todo
  2247. :type '(choice
  2248. (const :tag "Never" nil)
  2249. (const :tag "By default" t)
  2250. (const :tag "Only with C-u C-c C-t" prefix)))
  2251. (defcustom org-provide-todo-statistics t
  2252. "Non-nil means update todo statistics after insert and toggle.
  2253. ALL-HEADLINES means update todo statistics by including headlines
  2254. with no TODO keyword as well, counting them as not done.
  2255. A list of TODO keywords means the same, but skip keywords that are
  2256. not in this list.
  2257. When set to a list of two lists, the first list contains keywords
  2258. to consider as TODO keywords, the second list contains keywords
  2259. to consider as DONE keywords.
  2260. When this is set, todo statistics is updated in the parent of the
  2261. current entry each time a todo state is changed."
  2262. :group 'org-todo
  2263. :type '(choice
  2264. (const :tag "Yes, only for TODO entries" t)
  2265. (const :tag "Yes, including all entries" all-headlines)
  2266. (repeat :tag "Yes, for TODOs in this list"
  2267. (string :tag "TODO keyword"))
  2268. (list :tag "Yes, for TODOs and DONEs in these lists"
  2269. (repeat (string :tag "TODO keyword"))
  2270. (repeat (string :tag "DONE keyword")))
  2271. (other :tag "No TODO statistics" nil)))
  2272. (defcustom org-hierarchical-todo-statistics t
  2273. "Non-nil means TODO statistics covers just direct children.
  2274. When nil, all entries in the subtree are considered.
  2275. This has only an effect if `org-provide-todo-statistics' is set.
  2276. To set this to nil for only a single subtree, use a COOKIE_DATA
  2277. property and include the word \"recursive\" into the value."
  2278. :group 'org-todo
  2279. :type 'boolean)
  2280. (defcustom org-after-todo-state-change-hook nil
  2281. "Hook which is run after the state of a TODO item was changed.
  2282. The new state (a string with a TODO keyword, or nil) is available in the
  2283. Lisp variable `org-state'."
  2284. :group 'org-todo
  2285. :type 'hook)
  2286. (defvar org-blocker-hook nil
  2287. "Hook for functions that are allowed to block a state change.
  2288. Functions in this hook should not modify the buffer.
  2289. Each function gets as its single argument a property list,
  2290. see `org-trigger-hook' for more information about this list.
  2291. If any of the functions in this hook returns nil, the state change
  2292. is blocked.")
  2293. (defvar org-trigger-hook nil
  2294. "Hook for functions that are triggered by a state change.
  2295. Each function gets as its single argument a property list with at
  2296. least the following elements:
  2297. (:type type-of-change :position pos-at-entry-start
  2298. :from old-state :to new-state)
  2299. Depending on the type, more properties may be present.
  2300. This mechanism is currently implemented for:
  2301. TODO state changes
  2302. ------------------
  2303. :type todo-state-change
  2304. :from previous state (keyword as a string), or nil, or a symbol
  2305. `todo' or `done', to indicate the general type of state.
  2306. :to new state, like in :from")
  2307. (defcustom org-enforce-todo-dependencies nil
  2308. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2309. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2310. be blocked if any prior sibling is not yet done.
  2311. Finally, if the parent is blocked because of ordered siblings of its own,
  2312. the child will also be blocked."
  2313. :set (lambda (var val)
  2314. (set var val)
  2315. (if val
  2316. (add-hook 'org-blocker-hook
  2317. 'org-block-todo-from-children-or-siblings-or-parent)
  2318. (remove-hook 'org-blocker-hook
  2319. 'org-block-todo-from-children-or-siblings-or-parent)))
  2320. :group 'org-todo
  2321. :type 'boolean)
  2322. (defcustom org-enforce-todo-checkbox-dependencies nil
  2323. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2324. When this is nil, checkboxes have no influence on switching TODO states.
  2325. When non-nil, you first need to check off all check boxes before the TODO
  2326. entry can be switched to DONE.
  2327. This variable needs to be set before org.el is loaded, and you need to
  2328. restart Emacs after a change to make the change effective. The only way
  2329. to change it while Emacs is running is through the customize interface."
  2330. :set (lambda (var val)
  2331. (set var val)
  2332. (if val
  2333. (add-hook 'org-blocker-hook
  2334. 'org-block-todo-from-checkboxes)
  2335. (remove-hook 'org-blocker-hook
  2336. 'org-block-todo-from-checkboxes)))
  2337. :group 'org-todo
  2338. :type 'boolean)
  2339. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2340. "Non-nil means inserting a TODO heading is treated as state change.
  2341. So when the command `\\[org-insert-todo-heading]' is used, state change
  2342. logging will apply if appropriate. When nil, the new TODO item will
  2343. be inserted directly, and no logging will take place."
  2344. :group 'org-todo
  2345. :type 'boolean)
  2346. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2347. "Non-nil means switching TODO states with S-cursor counts as state change.
  2348. This is the default behavior. However, setting this to nil allows a
  2349. convenient way to select a TODO state and bypass any logging associated
  2350. with that."
  2351. :group 'org-todo
  2352. :type 'boolean)
  2353. (defcustom org-todo-state-tags-triggers nil
  2354. "Tag changes that should be triggered by TODO state changes.
  2355. This is a list. Each entry is
  2356. (state-change (tag . flag) .......)
  2357. State-change can be a string with a state, and empty string to indicate the
  2358. state that has no TODO keyword, or it can be one of the symbols `todo'
  2359. or `done', meaning any not-done or done state, respectively."
  2360. :group 'org-todo
  2361. :group 'org-tags
  2362. :type '(repeat
  2363. (cons (choice :tag "When changing to"
  2364. (const :tag "Not-done state" todo)
  2365. (const :tag "Done state" done)
  2366. (string :tag "State"))
  2367. (repeat
  2368. (cons :tag "Tag action"
  2369. (string :tag "Tag")
  2370. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2371. (defcustom org-log-done nil
  2372. "Information to record when a task moves to the DONE state.
  2373. Possible values are:
  2374. nil Don't add anything, just change the keyword
  2375. time Add a time stamp to the task
  2376. note Prompt for a note and add it with template `org-log-note-headings'
  2377. This option can also be set with on a per-file-basis with
  2378. #+STARTUP: nologdone
  2379. #+STARTUP: logdone
  2380. #+STARTUP: lognotedone
  2381. You can have local logging settings for a subtree by setting the LOGGING
  2382. property to one or more of these keywords."
  2383. :group 'org-todo
  2384. :group 'org-progress
  2385. :type '(choice
  2386. (const :tag "No logging" nil)
  2387. (const :tag "Record CLOSED timestamp" time)
  2388. (const :tag "Record CLOSED timestamp with note." note)))
  2389. ;; Normalize old uses of org-log-done.
  2390. (cond
  2391. ((eq org-log-done t) (setq org-log-done 'time))
  2392. ((and (listp org-log-done) (memq 'done org-log-done))
  2393. (setq org-log-done 'note)))
  2394. (defcustom org-log-reschedule nil
  2395. "Information to record when the scheduling date of a task is modified.
  2396. Possible values are:
  2397. nil Don't add anything, just change the date
  2398. time Add a time stamp to the task
  2399. note Prompt for a note and add it with template `org-log-note-headings'
  2400. This option can also be set with on a per-file-basis with
  2401. #+STARTUP: nologreschedule
  2402. #+STARTUP: logreschedule
  2403. #+STARTUP: lognotereschedule
  2404. You can have local logging settings for a subtree by setting the LOGGING
  2405. property to one or more of these keywords.
  2406. This variable has an effect when calling `org-schedule' or
  2407. `org-agenda-schedule' only."
  2408. :group 'org-todo
  2409. :group 'org-progress
  2410. :type '(choice
  2411. (const :tag "No logging" nil)
  2412. (const :tag "Record timestamp" time)
  2413. (const :tag "Record timestamp with note" note)))
  2414. (defcustom org-log-redeadline nil
  2415. "Information to record when the deadline date of a task is modified.
  2416. Possible values are:
  2417. nil Don't add anything, just change the date
  2418. time Add a time stamp to the task
  2419. note Prompt for a note and add it with template `org-log-note-headings'
  2420. This option can also be set with on a per-file-basis with
  2421. #+STARTUP: nologredeadline
  2422. #+STARTUP: logredeadline
  2423. #+STARTUP: lognoteredeadline
  2424. You can have local logging settings for a subtree by setting the LOGGING
  2425. property to one or more of these keywords.
  2426. This variable has an effect when calling `org-deadline' or
  2427. `org-agenda-deadline' only."
  2428. :group 'org-todo
  2429. :group 'org-progress
  2430. :type '(choice
  2431. (const :tag "No logging" nil)
  2432. (const :tag "Record timestamp" time)
  2433. (const :tag "Record timestamp with note." note)))
  2434. (defcustom org-log-note-clock-out nil
  2435. "Non-nil means record a note when clocking out of an item.
  2436. This can also be configured on a per-file basis by adding one of
  2437. the following lines anywhere in the buffer:
  2438. #+STARTUP: lognoteclock-out
  2439. #+STARTUP: nolognoteclock-out"
  2440. :group 'org-todo
  2441. :group 'org-progress
  2442. :type 'boolean)
  2443. (defcustom org-log-done-with-time t
  2444. "Non-nil means the CLOSED time stamp will contain date and time.
  2445. When nil, only the date will be recorded."
  2446. :group 'org-progress
  2447. :type 'boolean)
  2448. (defcustom org-log-note-headings
  2449. '((done . "CLOSING NOTE %t")
  2450. (state . "State %-12s from %-12S %t")
  2451. (note . "Note taken on %t")
  2452. (reschedule . "Rescheduled from %S on %t")
  2453. (delschedule . "Not scheduled, was %S on %t")
  2454. (redeadline . "New deadline from %S on %t")
  2455. (deldeadline . "Removed deadline, was %S on %t")
  2456. (refile . "Refiled on %t")
  2457. (clock-out . ""))
  2458. "Headings for notes added to entries.
  2459. The value is an alist, with the car being a symbol indicating the
  2460. note context, and the cdr is the heading to be used. The heading
  2461. may also be the empty string. The following placeholders can be
  2462. used:
  2463. %t a time stamp.
  2464. %T an active time stamp instead the default inactive one
  2465. %d a short-format time stamp.
  2466. %D an active short-format time stamp.
  2467. %s the new TODO state or time stamp (inactive), in double quotes.
  2468. %S the old TODO state or time stamp (inactive), in double quotes.
  2469. %u the user name.
  2470. %U full user name.
  2471. In fact, it is not a good idea to change the `state' entry,
  2472. because Agenda Log mode depends on the format of these entries."
  2473. :group 'org-todo
  2474. :group 'org-progress
  2475. :type '(list :greedy t
  2476. (cons (const :tag "Heading when closing an item" done) string)
  2477. (cons (const :tag
  2478. "Heading when changing todo state (todo sequence only)"
  2479. state) string)
  2480. (cons (const :tag "Heading when just taking a note" note) string)
  2481. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2482. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2483. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2484. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2485. (cons (const :tag "Heading when refiling" refile) string)
  2486. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2487. (unless (assq 'note org-log-note-headings)
  2488. (push '(note . "%t") org-log-note-headings))
  2489. (defcustom org-log-into-drawer nil
  2490. "Non-nil means insert state change notes and time stamps into a drawer.
  2491. When nil, state changes notes will be inserted after the headline and
  2492. any scheduling and clock lines, but not inside a drawer.
  2493. The value of this variable should be the name of the drawer to use.
  2494. LOGBOOK is proposed as the default drawer for this purpose, you can
  2495. also set this to a string to define the drawer of your choice.
  2496. A value of t is also allowed, representing \"LOGBOOK\".
  2497. A value of t or nil can also be set with on a per-file-basis with
  2498. #+STARTUP: logdrawer
  2499. #+STARTUP: nologdrawer
  2500. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2501. will be ignored.
  2502. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2503. a subtree.
  2504. Do not check directly this variable in a Lisp program. Call
  2505. function `org-log-into-drawer' instead."
  2506. :group 'org-todo
  2507. :group 'org-progress
  2508. :type '(choice
  2509. (const :tag "Not into a drawer" nil)
  2510. (const :tag "LOGBOOK" t)
  2511. (string :tag "Other")))
  2512. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2513. (defun org-log-into-drawer ()
  2514. "Name of the log drawer, as a string, or nil.
  2515. This is the value of `org-log-into-drawer'. However, if the
  2516. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2517. be used instead of the default value."
  2518. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2519. (cond ((equal p "nil") nil)
  2520. ((equal p "t") "LOGBOOK")
  2521. ((stringp p) p)
  2522. (p "LOGBOOK")
  2523. ((stringp org-log-into-drawer) org-log-into-drawer)
  2524. (org-log-into-drawer "LOGBOOK"))))
  2525. (defcustom org-log-state-notes-insert-after-drawers nil
  2526. "Non-nil means insert state change notes after any drawers in entry.
  2527. Only the drawers that *immediately* follow the headline and the
  2528. deadline/scheduled line are skipped.
  2529. When nil, insert notes right after the heading and perhaps the line
  2530. with deadline/scheduling if present.
  2531. This variable will have no effect if `org-log-into-drawer' is
  2532. set."
  2533. :group 'org-todo
  2534. :group 'org-progress
  2535. :type 'boolean)
  2536. (defcustom org-log-states-order-reversed t
  2537. "Non-nil means the latest state note will be directly after heading.
  2538. When nil, the state change notes will be ordered according to time.
  2539. This option can also be set with on a per-file-basis with
  2540. #+STARTUP: logstatesreversed
  2541. #+STARTUP: nologstatesreversed"
  2542. :group 'org-todo
  2543. :group 'org-progress
  2544. :type 'boolean)
  2545. (defcustom org-todo-repeat-to-state nil
  2546. "The TODO state to which a repeater should return the repeating task.
  2547. By default this is the first task of a TODO sequence or the
  2548. previous state of a TYPE_TODO set. But you can specify to use
  2549. the previous state in a TODO sequence or a string.
  2550. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2551. entry, which has precedence over this option."
  2552. :group 'org-todo
  2553. :version "24.1"
  2554. :type '(choice (const :tag "Use the previous TODO state" t)
  2555. (const :tag "Use the head of the TODO sequence" nil)
  2556. (string :tag "Use a specific TODO state")))
  2557. (defcustom org-log-repeat 'time
  2558. "Non-nil means record moving through the DONE state when triggering repeat.
  2559. An auto-repeating task is immediately switched back to TODO when
  2560. marked DONE. If you are not logging state changes (by adding \"@\"
  2561. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2562. record a closing note, there will be no record of the task moving
  2563. through DONE. This variable forces taking a note anyway.
  2564. nil Don't force a record
  2565. time Record a time stamp
  2566. note Prompt for a note and add it with template `org-log-note-headings'
  2567. This option can also be set with on a per-file-basis with
  2568. #+STARTUP: nologrepeat
  2569. #+STARTUP: logrepeat
  2570. #+STARTUP: lognoterepeat
  2571. You can have local logging settings for a subtree by setting the LOGGING
  2572. property to one or more of these keywords."
  2573. :group 'org-todo
  2574. :group 'org-progress
  2575. :type '(choice
  2576. (const :tag "Don't force a record" nil)
  2577. (const :tag "Force recording the DONE state" time)
  2578. (const :tag "Force recording a note with the DONE state" note)))
  2579. (defgroup org-priorities nil
  2580. "Priorities in Org mode."
  2581. :tag "Org Priorities"
  2582. :group 'org-todo)
  2583. (defcustom org-enable-priority-commands t
  2584. "Non-nil means priority commands are active.
  2585. When nil, these commands will be disabled, so that you never accidentally
  2586. set a priority."
  2587. :group 'org-priorities
  2588. :type 'boolean)
  2589. (defcustom org-highest-priority ?A
  2590. "The highest priority of TODO items. A character like ?A, ?B etc.
  2591. Must have a smaller ASCII number than `org-lowest-priority'."
  2592. :group 'org-priorities
  2593. :type 'character)
  2594. (defcustom org-lowest-priority ?C
  2595. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2596. Must have a larger ASCII number than `org-highest-priority'."
  2597. :group 'org-priorities
  2598. :type 'character)
  2599. (defcustom org-default-priority ?B
  2600. "The default priority of TODO items.
  2601. This is the priority an item gets if no explicit priority is given.
  2602. When starting to cycle on an empty priority the first step in the cycle
  2603. depends on `org-priority-start-cycle-with-default'. The resulting first
  2604. step priority must not exceed the range from `org-highest-priority' to
  2605. `org-lowest-priority' which means that `org-default-priority' has to be
  2606. in this range exclusive or inclusive the range boundaries. Else the
  2607. first step refuses to set the default and the second will fall back
  2608. to (depending on the command used) the highest or lowest priority."
  2609. :group 'org-priorities
  2610. :type 'character)
  2611. (defcustom org-priority-start-cycle-with-default t
  2612. "Non-nil means start with default priority when starting to cycle.
  2613. When this is nil, the first step in the cycle will be (depending on the
  2614. command used) one higher or lower than the default priority.
  2615. See also `org-default-priority'."
  2616. :group 'org-priorities
  2617. :type 'boolean)
  2618. (defcustom org-get-priority-function nil
  2619. "Function to extract the priority from a string.
  2620. The string is normally the headline. If this is nil Org computes the
  2621. priority from the priority cookie like [#A] in the headline. It returns
  2622. an integer, increasing by 1000 for each priority level.
  2623. The user can set a different function here, which should take a string
  2624. as an argument and return the numeric priority."
  2625. :group 'org-priorities
  2626. :version "24.1"
  2627. :type '(choice
  2628. (const nil)
  2629. (function)))
  2630. (defgroup org-time nil
  2631. "Options concerning time stamps and deadlines in Org mode."
  2632. :tag "Org Time"
  2633. :group 'org)
  2634. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2635. "Number of minutes to round time stamps to.
  2636. \\<org-mode-map>\
  2637. These are two values, the first applies when first creating a time stamp.
  2638. The second applies when changing it with the commands `S-up' and `S-down'.
  2639. When changing the time stamp, this means that it will change in steps
  2640. of N minutes, as given by the second value.
  2641. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2642. numbers should be factors of 60, so for example 5, 10, 15.
  2643. When this is larger than 1, you can still force an exact time stamp by using
  2644. a double prefix argument to a time stamp command like \
  2645. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2646. and by using a prefix arg to `S-up/down' to specify the exact number
  2647. of minutes to shift."
  2648. :group 'org-time
  2649. :get (lambda (var) ; Make sure both elements are there
  2650. (if (integerp (default-value var))
  2651. (list (default-value var) 5)
  2652. (default-value var)))
  2653. :type '(list
  2654. (integer :tag "when inserting times")
  2655. (integer :tag "when modifying times")))
  2656. ;; Normalize old customizations of this variable.
  2657. (when (integerp org-time-stamp-rounding-minutes)
  2658. (setq org-time-stamp-rounding-minutes
  2659. (list org-time-stamp-rounding-minutes
  2660. org-time-stamp-rounding-minutes)))
  2661. (defcustom org-display-custom-times nil
  2662. "Non-nil means overlay custom formats over all time stamps.
  2663. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2664. To turn this on on a per-file basis, insert anywhere in the file:
  2665. #+STARTUP: customtime"
  2666. :group 'org-time
  2667. :set 'set-default
  2668. :type 'sexp)
  2669. (make-variable-buffer-local 'org-display-custom-times)
  2670. (defcustom org-time-stamp-custom-formats
  2671. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2672. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2673. These are overlaid over the default ISO format if the variable
  2674. `org-display-custom-times' is set. Time like %H:%M should be at the
  2675. end of the second format. The custom formats are also honored by export
  2676. commands, if custom time display is turned on at the time of export."
  2677. :group 'org-time
  2678. :type 'sexp)
  2679. (defun org-time-stamp-format (&optional long inactive)
  2680. "Get the right format for a time string."
  2681. (let ((f (if long (cdr org-time-stamp-formats)
  2682. (car org-time-stamp-formats))))
  2683. (if inactive
  2684. (concat "[" (substring f 1 -1) "]")
  2685. f)))
  2686. (defcustom org-deadline-warning-days 14
  2687. "Number of days before expiration during which a deadline becomes active.
  2688. This variable governs the display in sparse trees and in the agenda.
  2689. When 0 or negative, it means use this number (the absolute value of it)
  2690. even if a deadline has a different individual lead time specified.
  2691. Custom commands can set this variable in the options section."
  2692. :group 'org-time
  2693. :group 'org-agenda-daily/weekly
  2694. :type 'integer)
  2695. (defcustom org-scheduled-delay-days 0
  2696. "Number of days before a scheduled item becomes active.
  2697. This variable governs the display in sparse trees and in the agenda.
  2698. The default value (i.e. 0) means: don't delay scheduled item.
  2699. When negative, it means use this number (the absolute value of it)
  2700. even if a scheduled item has a different individual delay time
  2701. specified.
  2702. Custom commands can set this variable in the options section."
  2703. :group 'org-time
  2704. :group 'org-agenda-daily/weekly
  2705. :version "24.4"
  2706. :package-version '(Org . "8.0")
  2707. :type 'integer)
  2708. (defcustom org-read-date-prefer-future t
  2709. "Non-nil means assume future for incomplete date input from user.
  2710. This affects the following situations:
  2711. 1. The user gives a month but not a year.
  2712. For example, if it is April and you enter \"feb 2\", this will be read
  2713. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2714. 2. The user gives a day, but no month.
  2715. For example, if today is the 15th, and you enter \"3\", Org will read
  2716. this as the third of *next* month. However, if you enter \"17\",
  2717. it will be considered as *this* month.
  2718. If you set this variable to the symbol `time', then also the following
  2719. will work:
  2720. 3. If the user gives a time.
  2721. If the time is before now, it will be interpreted as tomorrow.
  2722. Currently none of this works for ISO week specifications.
  2723. When this option is nil, the current day, month and year will always be
  2724. used as defaults.
  2725. See also `org-agenda-jump-prefer-future'."
  2726. :group 'org-time
  2727. :type '(choice
  2728. (const :tag "Never" nil)
  2729. (const :tag "Check month and day" t)
  2730. (const :tag "Check month, day, and time" time)))
  2731. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2732. "Should the agenda jump command prefer the future for incomplete dates?
  2733. The default is to do the same as configured in `org-read-date-prefer-future'.
  2734. But you can also set a deviating value here.
  2735. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2736. :group 'org-agenda
  2737. :group 'org-time
  2738. :version "24.1"
  2739. :type '(choice
  2740. (const :tag "Use org-read-date-prefer-future"
  2741. org-read-date-prefer-future)
  2742. (const :tag "Never" nil)
  2743. (const :tag "Always" t)))
  2744. (defcustom org-read-date-force-compatible-dates t
  2745. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2746. Depending on the system Emacs is running on, certain dates cannot
  2747. be represented with the type used internally to represent time.
  2748. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2749. correctly. Some systems allow for earlier dates, some for later,
  2750. some for both. One way to find out it to insert any date into an
  2751. Org buffer, putting the cursor on the year and hitting S-up and
  2752. S-down to test the range.
  2753. When this variable is set to t, the date/time prompt will not let
  2754. you specify dates outside the 1970-2037 range, so it is certain that
  2755. these dates will work in whatever version of Emacs you are
  2756. running, and also that you can move a file from one Emacs implementation
  2757. to another. WHenever Org is forcing the year for you, it will display
  2758. a message and beep.
  2759. When this variable is nil, Org will check if the date is
  2760. representable in the specific Emacs implementation you are using.
  2761. If not, it will force a year, usually the current year, and beep
  2762. to remind you. Currently this setting is not recommended because
  2763. the likelihood that you will open your Org files in an Emacs that
  2764. has limited date range is not negligible.
  2765. A workaround for this problem is to use diary sexp dates for time
  2766. stamps outside of this range."
  2767. :group 'org-time
  2768. :version "24.1"
  2769. :type 'boolean)
  2770. (defcustom org-read-date-display-live t
  2771. "Non-nil means display current interpretation of date prompt live.
  2772. This display will be in an overlay, in the minibuffer."
  2773. :group 'org-time
  2774. :type 'boolean)
  2775. (defcustom org-read-date-popup-calendar t
  2776. "Non-nil means pop up a calendar when prompting for a date.
  2777. In the calendar, the date can be selected with mouse-1. However, the
  2778. minibuffer will also be active, and you can simply enter the date as well.
  2779. When nil, only the minibuffer will be available."
  2780. :group 'org-time
  2781. :type 'boolean)
  2782. (defvaralias 'org-popup-calendar-for-date-prompt
  2783. 'org-read-date-popup-calendar)
  2784. (defcustom org-extend-today-until 0
  2785. "The hour when your day really ends. Must be an integer.
  2786. This has influence for the following applications:
  2787. - When switching the agenda to \"today\". It it is still earlier than
  2788. the time given here, the day recognized as TODAY is actually yesterday.
  2789. - When a date is read from the user and it is still before the time given
  2790. here, the current date and time will be assumed to be yesterday, 23:59.
  2791. Also, timestamps inserted in capture templates follow this rule.
  2792. IMPORTANT: This is a feature whose implementation is and likely will
  2793. remain incomplete. Really, it is only here because past midnight seems to
  2794. be the favorite working time of John Wiegley :-)"
  2795. :group 'org-time
  2796. :type 'integer)
  2797. (defcustom org-use-effective-time nil
  2798. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2799. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2800. \"effective time\" of any timestamps between midnight and 8am will be
  2801. 23:59 of the previous day."
  2802. :group 'org-time
  2803. :version "24.1"
  2804. :type 'boolean)
  2805. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2806. "When non-nil, use the last clock out time for `org-todo'.
  2807. Note that this option has precedence over the combined use of
  2808. `org-use-effective-time' and `org-extend-today-until'."
  2809. :group 'org-time
  2810. :version "24.4"
  2811. :package-version '(Org . "8.0")
  2812. :type 'boolean)
  2813. (defcustom org-edit-timestamp-down-means-later nil
  2814. "Non-nil means S-down will increase the time in a time stamp.
  2815. When nil, S-up will increase."
  2816. :group 'org-time
  2817. :type 'boolean)
  2818. (defcustom org-calendar-follow-timestamp-change t
  2819. "Non-nil means make the calendar window follow timestamp changes.
  2820. When a timestamp is modified and the calendar window is visible, it will be
  2821. moved to the new date."
  2822. :group 'org-time
  2823. :type 'boolean)
  2824. (defgroup org-tags nil
  2825. "Options concerning tags in Org mode."
  2826. :tag "Org Tags"
  2827. :group 'org)
  2828. (defcustom org-tag-alist nil
  2829. "Default tags available in Org files.
  2830. The value of this variable is an alist. Associations either:
  2831. (TAG)
  2832. (TAG . SELECT)
  2833. (SPECIAL)
  2834. where TAG is a tag as a string, SELECT is character, used to
  2835. select that tag through the fast tag selection interface, and
  2836. SPECIAL is one of the following keywords: `:startgroup',
  2837. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2838. `:newline'. These keywords are used to define a hierarchy of
  2839. tags. See manual for details.
  2840. When this variable is nil, Org mode bases tag input on what is
  2841. already in the buffer. The value can be overridden locally by
  2842. using a TAGS keyword, e.g.,
  2843. #+TAGS: tag1 tag2
  2844. See also `org-tag-persistent-alist' to sidestep this behavior."
  2845. :group 'org-tags
  2846. :type '(repeat
  2847. (choice
  2848. (cons :tag "Tag with key"
  2849. (string :tag "Tag name")
  2850. (character :tag "Access char"))
  2851. (list :tag "Tag" (string :tag "Tag name"))
  2852. (const :tag "Start radio group" (:startgroup))
  2853. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2854. (const :tag "Group tags delimiter" (:grouptags))
  2855. (const :tag "End radio group" (:endgroup))
  2856. (const :tag "End tag group, non distinct" (:endgrouptag))
  2857. (const :tag "New line" (:newline)))))
  2858. (defcustom org-tag-persistent-alist nil
  2859. "Tags always available in Org files.
  2860. The value of this variable is an alist. Associations either:
  2861. (TAG)
  2862. (TAG . SELECT)
  2863. (SPECIAL)
  2864. where TAG is a tag as a string, SELECT is a character, used to
  2865. select that tag through the fast tag selection interface, and
  2866. SPECIAL is one of the following keywords: `:startgroup',
  2867. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2868. `:newline'. These keywords are used to define a hierarchy of
  2869. tags. See manual for details.
  2870. Unlike to `org-tag-alist', tags defined in this variable do not
  2871. depend on a local TAGS keyword. Instead, to disable these tags
  2872. on a per-file basis, insert anywhere in the file:
  2873. #+STARTUP: noptag"
  2874. :group 'org-tags
  2875. :type '(repeat
  2876. (choice
  2877. (cons :tag "Tag with key"
  2878. (string :tag "Tag name")
  2879. (character :tag "Access char"))
  2880. (list :tag "Tag" (string :tag "Tag name"))
  2881. (const :tag "Start radio group" (:startgroup))
  2882. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2883. (const :tag "Group tags delimiter" (:grouptags))
  2884. (const :tag "End radio group" (:endgroup))
  2885. (const :tag "End tag group, non distinct" (:endgrouptag))
  2886. (const :tag "New line" (:newline)))))
  2887. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2888. "If non-nil, always offer completion for all tags of all agenda files.
  2889. Setting this variable locally allows for dynamic generation of tag
  2890. completions in capture buffers.
  2891. (add-hook \\='org-capture-mode-hook
  2892. (lambda ()
  2893. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2894. :group 'org-tags
  2895. :version "24.1"
  2896. :type 'boolean)
  2897. (defvar org-file-tags nil
  2898. "List of tags that can be inherited by all entries in the file.
  2899. The tags will be inherited if the variable `org-use-tag-inheritance'
  2900. says they should be.
  2901. This variable is populated from #+FILETAGS lines.")
  2902. (defcustom org-use-fast-tag-selection 'auto
  2903. "Non-nil means use fast tag selection scheme.
  2904. This is a special interface to select and deselect tags with single keys.
  2905. When nil, fast selection is never used.
  2906. When the symbol `auto', fast selection is used if and only if selection
  2907. characters for tags have been configured, either through the variable
  2908. `org-tag-alist' or through a #+TAGS line in the buffer.
  2909. When t, fast selection is always used and selection keys are assigned
  2910. automatically if necessary."
  2911. :group 'org-tags
  2912. :type '(choice
  2913. (const :tag "Always" t)
  2914. (const :tag "Never" nil)
  2915. (const :tag "When selection characters are configured" auto)))
  2916. (defcustom org-fast-tag-selection-single-key nil
  2917. "Non-nil means fast tag selection exits after first change.
  2918. When nil, you have to press RET to exit it.
  2919. During fast tag selection, you can toggle this flag with `C-c'.
  2920. This variable can also have the value `expert'. In this case, the window
  2921. displaying the tags menu is not even shown, until you press C-c again."
  2922. :group 'org-tags
  2923. :type '(choice
  2924. (const :tag "No" nil)
  2925. (const :tag "Yes" t)
  2926. (const :tag "Expert" expert)))
  2927. (defvar org-fast-tag-selection-include-todo nil
  2928. "Non-nil means fast tags selection interface will also offer TODO states.
  2929. This is an undocumented feature, you should not rely on it.")
  2930. (defcustom org-tags-column -77
  2931. "The column to which tags should be indented in a headline.
  2932. If this number is positive, it specifies the column. If it is negative,
  2933. it means that the tags should be flushright to that column. For example,
  2934. -80 works well for a normal 80 character screen.
  2935. When 0, place tags directly after headline text, with only one space in
  2936. between."
  2937. :group 'org-tags
  2938. :type 'integer)
  2939. (defcustom org-auto-align-tags t
  2940. "Non-nil keeps tags aligned when modifying headlines.
  2941. Some operations (i.e. demoting) change the length of a headline and
  2942. therefore shift the tags around. With this option turned on, after
  2943. each such operation the tags are again aligned to `org-tags-column'."
  2944. :group 'org-tags
  2945. :type 'boolean)
  2946. (defcustom org-use-tag-inheritance t
  2947. "Non-nil means tags in levels apply also for sublevels.
  2948. When nil, only the tags directly given in a specific line apply there.
  2949. This may also be a list of tags that should be inherited, or a regexp that
  2950. matches tags that should be inherited. Additional control is possible
  2951. with the variable `org-tags-exclude-from-inheritance' which gives an
  2952. explicit list of tags to be excluded from inheritance, even if the value of
  2953. `org-use-tag-inheritance' would select it for inheritance.
  2954. If this option is t, a match early-on in a tree can lead to a large
  2955. number of matches in the subtree when constructing the agenda or creating
  2956. a sparse tree. If you only want to see the first match in a tree during
  2957. a search, check out the variable `org-tags-match-list-sublevels'."
  2958. :group 'org-tags
  2959. :type '(choice
  2960. (const :tag "Not" nil)
  2961. (const :tag "Always" t)
  2962. (repeat :tag "Specific tags" (string :tag "Tag"))
  2963. (regexp :tag "Tags matched by regexp")))
  2964. (defcustom org-tags-exclude-from-inheritance nil
  2965. "List of tags that should never be inherited.
  2966. This is a way to exclude a few tags from inheritance. For way to do
  2967. the opposite, to actively allow inheritance for selected tags,
  2968. see the variable `org-use-tag-inheritance'."
  2969. :group 'org-tags
  2970. :type '(repeat (string :tag "Tag")))
  2971. (defun org-tag-inherit-p (tag)
  2972. "Check if TAG is one that should be inherited."
  2973. (cond
  2974. ((member tag org-tags-exclude-from-inheritance) nil)
  2975. ((eq org-use-tag-inheritance t) t)
  2976. ((not org-use-tag-inheritance) nil)
  2977. ((stringp org-use-tag-inheritance)
  2978. (string-match org-use-tag-inheritance tag))
  2979. ((listp org-use-tag-inheritance)
  2980. (member tag org-use-tag-inheritance))
  2981. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2982. (defcustom org-tags-match-list-sublevels t
  2983. "Non-nil means list also sublevels of headlines matching a search.
  2984. This variable applies to tags/property searches, and also to stuck
  2985. projects because this search is based on a tags match as well.
  2986. When set to the symbol `indented', sublevels are indented with
  2987. leading dots.
  2988. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2989. the sublevels of a headline matching a tag search often also match
  2990. the same search. Listing all of them can create very long lists.
  2991. Setting this variable to nil causes subtrees of a match to be skipped.
  2992. This variable is semi-obsolete and probably should always be true. It
  2993. is better to limit inheritance to certain tags using the variables
  2994. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2995. :group 'org-tags
  2996. :type '(choice
  2997. (const :tag "No, don't list them" nil)
  2998. (const :tag "Yes, do list them" t)
  2999. (const :tag "List them, indented with leading dots" indented)))
  3000. (defcustom org-tags-sort-function nil
  3001. "When set, tags are sorted using this function as a comparator."
  3002. :group 'org-tags
  3003. :type '(choice
  3004. (const :tag "No sorting" nil)
  3005. (const :tag "Alphabetical" org-string-collate-lessp)
  3006. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  3007. (function :tag "Custom function" nil)))
  3008. (defvar org-tags-history nil
  3009. "History of minibuffer reads for tags.")
  3010. (defvar org-last-tags-completion-table nil
  3011. "The last used completion table for tags.")
  3012. (defvar org-after-tags-change-hook nil
  3013. "Hook that is run after the tags in a line have changed.")
  3014. (defgroup org-properties nil
  3015. "Options concerning properties in Org mode."
  3016. :tag "Org Properties"
  3017. :group 'org)
  3018. (defcustom org-property-format "%-10s %s"
  3019. "How property key/value pairs should be formatted by `indent-line'.
  3020. When `indent-line' hits a property definition, it will format the line
  3021. according to this format, mainly to make sure that the values are
  3022. lined-up with respect to each other."
  3023. :group 'org-properties
  3024. :type 'string)
  3025. (defcustom org-properties-postprocess-alist nil
  3026. "Alist of properties and functions to adjust inserted values.
  3027. Elements of this alist must be of the form
  3028. ([string] [function])
  3029. where [string] must be a property name and [function] must be a
  3030. lambda expression: this lambda expression must take one argument,
  3031. the value to adjust, and return the new value as a string.
  3032. For example, this element will allow the property \"Remaining\"
  3033. to be updated wrt the relation between the \"Effort\" property
  3034. and the clock summary:
  3035. ((\"Remaining\" (lambda(value)
  3036. (let ((clocksum (org-clock-sum-current-item))
  3037. (effort (org-duration-to-minutes
  3038. (org-entry-get (point) \"Effort\"))))
  3039. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3040. :group 'org-properties
  3041. :version "24.1"
  3042. :type '(alist :key-type (string :tag "Property")
  3043. :value-type (function :tag "Function")))
  3044. (defcustom org-use-property-inheritance nil
  3045. "Non-nil means properties apply also for sublevels.
  3046. This setting is chiefly used during property searches. Turning it on can
  3047. cause significant overhead when doing a search, which is why it is not
  3048. on by default.
  3049. When nil, only the properties directly given in the current entry count.
  3050. When t, every property is inherited. The value may also be a list of
  3051. properties that should have inheritance, or a regular expression matching
  3052. properties that should be inherited.
  3053. However, note that some special properties use inheritance under special
  3054. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3055. and the properties ending in \"_ALL\" when they are used as descriptor
  3056. for valid values of a property.
  3057. Note for programmers:
  3058. When querying an entry with `org-entry-get', you can control if inheritance
  3059. should be used. By default, `org-entry-get' looks only at the local
  3060. properties. You can request inheritance by setting the inherit argument
  3061. to t (to force inheritance) or to `selective' (to respect the setting
  3062. in this variable)."
  3063. :group 'org-properties
  3064. :type '(choice
  3065. (const :tag "Not" nil)
  3066. (const :tag "Always" t)
  3067. (repeat :tag "Specific properties" (string :tag "Property"))
  3068. (regexp :tag "Properties matched by regexp")))
  3069. (defun org-property-inherit-p (property)
  3070. "Return a non-nil value if PROPERTY should be inherited."
  3071. (cond
  3072. ((eq org-use-property-inheritance t) t)
  3073. ((not org-use-property-inheritance) nil)
  3074. ((stringp org-use-property-inheritance)
  3075. (string-match org-use-property-inheritance property))
  3076. ((listp org-use-property-inheritance)
  3077. (member-ignore-case property org-use-property-inheritance))
  3078. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3079. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3080. "The default column format, if no other format has been defined.
  3081. This variable can be set on the per-file basis by inserting a line
  3082. #+COLUMNS: %25ITEM ....."
  3083. :group 'org-properties
  3084. :type 'string)
  3085. (defcustom org-columns-ellipses ".."
  3086. "The ellipses to be used when a field in column view is truncated.
  3087. When this is the empty string, as many characters as possible are shown,
  3088. but then there will be no visual indication that the field has been truncated.
  3089. When this is a string of length N, the last N characters of a truncated
  3090. field are replaced by this string. If the column is narrower than the
  3091. ellipses string, only part of the ellipses string will be shown."
  3092. :group 'org-properties
  3093. :type 'string)
  3094. (defconst org-global-properties-fixed
  3095. '(("VISIBILITY_ALL" . "folded children content all")
  3096. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3097. "List of property/value pairs that can be inherited by any entry.
  3098. These are fixed values, for the preset properties. The user variable
  3099. that can be used to add to this list is `org-global-properties'.
  3100. The entries in this list are cons cells where the car is a property
  3101. name and cdr is a string with the value. If the value represents
  3102. multiple items like an \"_ALL\" property, separate the items by
  3103. spaces.")
  3104. (defcustom org-global-properties nil
  3105. "List of property/value pairs that can be inherited by any entry.
  3106. This list will be combined with the constant `org-global-properties-fixed'.
  3107. The entries in this list are cons cells where the car is a property
  3108. name and cdr is a string with the value.
  3109. You can set buffer-local values for the same purpose in the variable
  3110. `org-file-properties' this by adding lines like
  3111. #+PROPERTY: NAME VALUE"
  3112. :group 'org-properties
  3113. :type '(repeat
  3114. (cons (string :tag "Property")
  3115. (string :tag "Value"))))
  3116. (defvar-local org-file-properties nil
  3117. "List of property/value pairs that can be inherited by any entry.
  3118. Valid for the current buffer.
  3119. This variable is populated from #+PROPERTY lines.")
  3120. (defgroup org-agenda nil
  3121. "Options concerning agenda views in Org mode."
  3122. :tag "Org Agenda"
  3123. :group 'org)
  3124. (defvar-local org-category nil
  3125. "Variable used by Org files to set a category for agenda display.
  3126. Such files should use a file variable to set it, for example
  3127. # -*- mode: org; org-category: \"ELisp\"
  3128. or contain a special line
  3129. #+CATEGORY: ELisp
  3130. If the file does not specify a category, then file's base name
  3131. is used instead.")
  3132. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3133. (defcustom org-agenda-files nil
  3134. "The files to be used for agenda display.
  3135. If an entry is a directory, all files in that directory that are matched
  3136. by `org-agenda-file-regexp' will be part of the file list.
  3137. If the value of the variable is not a list but a single file name, then
  3138. the list of agenda files is actually stored and maintained in that file,
  3139. one agenda file per line. In this file paths can be given relative to
  3140. `org-directory'. Tilde expansion and environment variable substitution
  3141. are also made.
  3142. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3143. and removed with `\\[org-remove-file]'."
  3144. :group 'org-agenda
  3145. :type '(choice
  3146. (repeat :tag "List of files and directories" file)
  3147. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3148. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3149. "Regular expression to match files for `org-agenda-files'.
  3150. If any element in the list in that variable contains a directory instead
  3151. of a normal file, all files in that directory that are matched by this
  3152. regular expression will be included."
  3153. :group 'org-agenda
  3154. :type 'regexp)
  3155. (defcustom org-agenda-text-search-extra-files nil
  3156. "List of extra files to be searched by text search commands.
  3157. These files will be searched in addition to the agenda files by the
  3158. commands `org-search-view' (`\\[org-agenda] s') \
  3159. and `org-occur-in-agenda-files'.
  3160. Note that these files will only be searched for text search commands,
  3161. not for the other agenda views like todo lists, tag searches or the weekly
  3162. agenda. This variable is intended to list notes and possibly archive files
  3163. that should also be searched by these two commands.
  3164. In fact, if the first element in the list is the symbol `agenda-archives',
  3165. then all archive files of all agenda files will be added to the search
  3166. scope."
  3167. :group 'org-agenda
  3168. :type '(set :greedy t
  3169. (const :tag "Agenda Archives" agenda-archives)
  3170. (repeat :inline t (file))))
  3171. (defvaralias 'org-agenda-multi-occur-extra-files
  3172. 'org-agenda-text-search-extra-files)
  3173. (defcustom org-agenda-skip-unavailable-files nil
  3174. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3175. A nil value means to remove them, after a query, from the list."
  3176. :group 'org-agenda
  3177. :type 'boolean)
  3178. (defcustom org-agenda-diary-file 'diary-file
  3179. "File to which to add new entries with the `i' key in agenda and calendar.
  3180. When this is the symbol `diary-file', the functionality in the Emacs
  3181. calendar will be used to add entries to the `diary-file'. But when this
  3182. points to a file, `org-agenda-diary-entry' will be used instead."
  3183. :group 'org-agenda
  3184. :type '(choice
  3185. (const :tag "The standard Emacs diary file" diary-file)
  3186. (file :tag "Special Org file diary entries")))
  3187. (defgroup org-latex nil
  3188. "Options for embedding LaTeX code into Org mode."
  3189. :tag "Org LaTeX"
  3190. :group 'org)
  3191. (defcustom org-format-latex-options
  3192. '(:foreground default :background default :scale 1.0
  3193. :html-foreground "Black" :html-background "Transparent"
  3194. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3195. "Options for creating images from LaTeX fragments.
  3196. This is a property list with the following properties:
  3197. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3198. `default' means use the foreground of the default face.
  3199. `auto' means use the foreground from the text face.
  3200. :background the background color, or \"Transparent\".
  3201. `default' means use the background of the default face.
  3202. `auto' means use the background from the text face.
  3203. :scale a scaling factor for the size of the images, to get more pixels
  3204. :html-foreground, :html-background, :html-scale
  3205. the same numbers for HTML export.
  3206. :matchers a list indicating which matchers should be used to
  3207. find LaTeX fragments. Valid members of this list are:
  3208. \"begin\" find environments
  3209. \"$1\" find single characters surrounded by $.$
  3210. \"$\" find math expressions surrounded by $...$
  3211. \"$$\" find math expressions surrounded by $$....$$
  3212. \"\\(\" find math expressions surrounded by \\(...\\)
  3213. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3214. :group 'org-latex
  3215. :type 'plist)
  3216. (defcustom org-format-latex-signal-error t
  3217. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3218. When nil, just push out a message."
  3219. :group 'org-latex
  3220. :version "24.1"
  3221. :type 'boolean)
  3222. (defcustom org-latex-to-mathml-jar-file nil
  3223. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3224. Use this to specify additional executable file say a jar file.
  3225. When using MathToWeb as the converter, specify the full-path to
  3226. your mathtoweb.jar file."
  3227. :group 'org-latex
  3228. :version "24.1"
  3229. :type '(choice
  3230. (const :tag "None" nil)
  3231. (file :tag "JAR file" :must-match t)))
  3232. (defcustom org-latex-to-mathml-convert-command nil
  3233. "Command to convert LaTeX fragments to MathML.
  3234. Replace format-specifiers in the command as noted below and use
  3235. `shell-command' to convert LaTeX to MathML.
  3236. %j: Executable file in fully expanded form as specified by
  3237. `org-latex-to-mathml-jar-file'.
  3238. %I: Input LaTeX file in fully expanded form.
  3239. %i: The latex fragment to be converted.
  3240. %o: Output MathML file.
  3241. This command is used by `org-create-math-formula'.
  3242. When using MathToWeb as the converter, set this option to
  3243. \"java -jar %j -unicode -force -df %o %I\".
  3244. When using LaTeXML set this option to
  3245. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3246. :group 'org-latex
  3247. :version "24.1"
  3248. :type '(choice
  3249. (const :tag "None" nil)
  3250. (string :tag "\nShell command")))
  3251. (defcustom org-preview-latex-default-process 'dvipng
  3252. "The default process to convert LaTeX fragments to image files.
  3253. All available processes and theirs documents can be found in
  3254. `org-preview-latex-process-alist', which see."
  3255. :group 'org-latex
  3256. :version "26.1"
  3257. :package-version '(Org . "9.0")
  3258. :type 'symbol)
  3259. (defcustom org-preview-latex-process-alist
  3260. '((dvipng
  3261. :programs ("latex" "dvipng")
  3262. :description "dvi > png"
  3263. :message "you need to install the programs: latex and dvipng."
  3264. :image-input-type "dvi"
  3265. :image-output-type "png"
  3266. :image-size-adjust (1.0 . 1.0)
  3267. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3268. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3269. (dvisvgm
  3270. :programs ("latex" "dvisvgm")
  3271. :description "dvi > svg"
  3272. :message "you need to install the programs: latex and dvisvgm."
  3273. :use-xcolor t
  3274. :image-input-type "dvi"
  3275. :image-output-type "svg"
  3276. :image-size-adjust (1.7 . 1.5)
  3277. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3278. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3279. (imagemagick
  3280. :programs ("latex" "convert")
  3281. :description "pdf > png"
  3282. :message "you need to install the programs: latex and imagemagick."
  3283. :use-xcolor t
  3284. :image-input-type "pdf"
  3285. :image-output-type "png"
  3286. :image-size-adjust (1.0 . 1.0)
  3287. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3288. :image-converter
  3289. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3290. "Definitions of external processes for LaTeX previewing.
  3291. Org mode can use some external commands to generate TeX snippet's images for
  3292. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3293. `org-create-formula-image' how to call them.
  3294. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3295. PROPERTIES accepts the following attributes:
  3296. :programs list of strings, required programs.
  3297. :description string, describe the process.
  3298. :message string, message it when required programs cannot be found.
  3299. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3300. :image-output-type string, output file type of image converter (e.g., \"png\").
  3301. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3302. deal with background and foreground color of image.
  3303. Otherwise, dvipng style background and foreground color
  3304. format are generated. You may then refer to them in
  3305. command options with \"%F\" and \"%B\".
  3306. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3307. image size showed in buffer and the cdr element is for
  3308. HTML file. This option is only useful for process
  3309. developers, users should use variable
  3310. `org-format-latex-options' instead.
  3311. :post-clean list of strings, files matched are to be cleaned up once
  3312. the image is generated. When nil, the files with \".dvi\",
  3313. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3314. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3315. be cleaned up.
  3316. :latex-header list of strings, the LaTeX header of the snippet file.
  3317. When nil, the fallback value is used instead, which is
  3318. controlled by `org-format-latex-header',
  3319. `org-latex-default-packages-alist' and
  3320. `org-latex-packages-alist', which see.
  3321. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3322. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3323. replaced with values defined below.
  3324. :image-converter list of image converter commands strings. Each of them is
  3325. given to the shell and supports any of the following
  3326. place-holders defined below.
  3327. Place-holders used by `:image-converter' and `:latex-compiler':
  3328. %f input file name
  3329. %b base name of input file
  3330. %o base directory of input file
  3331. %O absolute output file name
  3332. Place-holders only used by `:image-converter':
  3333. %F foreground of image
  3334. %B background of image
  3335. %D dpi, which is used to adjust image size by some processing commands.
  3336. %S the image size scale ratio, which is used to adjust image size by some
  3337. processing commands."
  3338. :group 'org-latex
  3339. :version "26.1"
  3340. :package-version '(Org . "9.0")
  3341. :type '(alist :tag "LaTeX to image backends"
  3342. :value-type (plist)))
  3343. (defcustom org-preview-latex-image-directory "ltximg/"
  3344. "Path to store latex preview images.
  3345. A relative path here creates many directories relative to the
  3346. processed Org files paths. An absolute path puts all preview
  3347. images at the same place."
  3348. :group 'org-latex
  3349. :version "26.1"
  3350. :package-version '(Org . "9.0")
  3351. :type 'string)
  3352. (defun org-format-latex-mathml-available-p ()
  3353. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3354. (save-match-data
  3355. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3356. org-latex-to-mathml-convert-command)
  3357. (let ((executable (car (split-string
  3358. org-latex-to-mathml-convert-command))))
  3359. (when (executable-find executable)
  3360. (if (string-match
  3361. "%j" org-latex-to-mathml-convert-command)
  3362. (file-readable-p org-latex-to-mathml-jar-file)
  3363. t))))))
  3364. (defcustom org-format-latex-header "\\documentclass{article}
  3365. \\usepackage[usenames]{color}
  3366. \[PACKAGES]
  3367. \[DEFAULT-PACKAGES]
  3368. \\pagestyle{empty} % do not remove
  3369. % The settings below are copied from fullpage.sty
  3370. \\setlength{\\textwidth}{\\paperwidth}
  3371. \\addtolength{\\textwidth}{-3cm}
  3372. \\setlength{\\oddsidemargin}{1.5cm}
  3373. \\addtolength{\\oddsidemargin}{-2.54cm}
  3374. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3375. \\setlength{\\textheight}{\\paperheight}
  3376. \\addtolength{\\textheight}{-\\headheight}
  3377. \\addtolength{\\textheight}{-\\headsep}
  3378. \\addtolength{\\textheight}{-\\footskip}
  3379. \\addtolength{\\textheight}{-3cm}
  3380. \\setlength{\\topmargin}{1.5cm}
  3381. \\addtolength{\\topmargin}{-2.54cm}"
  3382. "The document header used for processing LaTeX fragments.
  3383. It is imperative that this header make sure that no page number
  3384. appears on the page. The package defined in the variables
  3385. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3386. will either replace the placeholder \"[PACKAGES]\" in this
  3387. header, or they will be appended."
  3388. :group 'org-latex
  3389. :type 'string)
  3390. (defun org-set-packages-alist (var val)
  3391. "Set the packages alist and make sure it has 3 elements per entry."
  3392. (set var (mapcar (lambda (x)
  3393. (if (and (consp x) (= (length x) 2))
  3394. (list (car x) (nth 1 x) t)
  3395. x))
  3396. val)))
  3397. (defun org-get-packages-alist (var)
  3398. "Get the packages alist and make sure it has 3 elements per entry."
  3399. (mapcar (lambda (x)
  3400. (if (and (consp x) (= (length x) 2))
  3401. (list (car x) (nth 1 x) t)
  3402. x))
  3403. (default-value var)))
  3404. (defcustom org-latex-default-packages-alist
  3405. '(("AUTO" "inputenc" t ("pdflatex"))
  3406. ("T1" "fontenc" t ("pdflatex"))
  3407. ("" "graphicx" t)
  3408. ("" "grffile" t)
  3409. ("" "longtable" nil)
  3410. ("" "wrapfig" nil)
  3411. ("" "rotating" nil)
  3412. ("normalem" "ulem" t)
  3413. ("" "amsmath" t)
  3414. ("" "textcomp" t)
  3415. ("" "amssymb" t)
  3416. ("" "capt-of" nil)
  3417. ("" "hyperref" nil))
  3418. "Alist of default packages to be inserted in the header.
  3419. Change this only if one of the packages here causes an
  3420. incompatibility with another package you are using.
  3421. The packages in this list are needed by one part or another of
  3422. Org mode to function properly:
  3423. - inputenc, fontenc: for basic font and character selection
  3424. - graphicx: for including images
  3425. - grffile: allow periods and spaces in graphics file names
  3426. - longtable: For multipage tables
  3427. - wrapfig: for figure placement
  3428. - rotating: for sideways figures and tables
  3429. - ulem: for underline and strike-through
  3430. - amsmath: for subscript and superscript and math environments
  3431. - textcomp, amssymb: for various symbols used
  3432. for interpreting the entities in `org-entities'. You can skip
  3433. some of these packages if you don't use any of their symbols.
  3434. - capt-of: for captions outside of floats
  3435. - hyperref: for cross references
  3436. Therefore you should not modify this variable unless you know
  3437. what you are doing. The one reason to change it anyway is that
  3438. you might be loading some other package that conflicts with one
  3439. of the default packages. Each element is either a cell or
  3440. a string.
  3441. A cell is of the format
  3442. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3443. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3444. when compiling LaTeX snippets into images for inclusion into
  3445. non-LaTeX output.
  3446. COMPILERS is a list of compilers that should include the package,
  3447. see `org-latex-compiler'. If the document compiler is not in the
  3448. list, and the list is non-nil, the package will not be inserted
  3449. in the final document.
  3450. A string will be inserted as-is in the header of the document."
  3451. :group 'org-latex
  3452. :group 'org-export-latex
  3453. :set 'org-set-packages-alist
  3454. :get 'org-get-packages-alist
  3455. :version "26.1"
  3456. :package-version '(Org . "8.3")
  3457. :type '(repeat
  3458. (choice
  3459. (list :tag "options/package pair"
  3460. (string :tag "options")
  3461. (string :tag "package")
  3462. (boolean :tag "Snippet")
  3463. (choice
  3464. (const :tag "For all compilers" nil)
  3465. (repeat :tag "Allowed compiler" string)))
  3466. (string :tag "A line of LaTeX"))))
  3467. (defcustom org-latex-packages-alist nil
  3468. "Alist of packages to be inserted in every LaTeX header.
  3469. These will be inserted after `org-latex-default-packages-alist'.
  3470. Each element is either a cell or a string.
  3471. A cell is of the format:
  3472. (\"options\" \"package\" SNIPPET-FLAG)
  3473. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3474. needed when turning LaTeX snippets into images for inclusion into
  3475. non-LaTeX output.
  3476. COMPILERS is a list of compilers that should include the package,
  3477. see `org-latex-compiler'. If the document compiler is not in the
  3478. list, and the list is non-nil, the package will not be inserted
  3479. in the final document.
  3480. A string will be inserted as-is in the header of the document.
  3481. Make sure that you only list packages here which:
  3482. - you want in every file;
  3483. - do not conflict with the setup in `org-format-latex-header';
  3484. - do not conflict with the default packages in
  3485. `org-latex-default-packages-alist'."
  3486. :group 'org-latex
  3487. :group 'org-export-latex
  3488. :set 'org-set-packages-alist
  3489. :get 'org-get-packages-alist
  3490. :type '(repeat
  3491. (choice
  3492. (list :tag "options/package pair"
  3493. (string :tag "options")
  3494. (string :tag "package")
  3495. (boolean :tag "Snippet"))
  3496. (string :tag "A line of LaTeX"))))
  3497. (defgroup org-appearance nil
  3498. "Settings for Org mode appearance."
  3499. :tag "Org Appearance"
  3500. :group 'org)
  3501. (defcustom org-level-color-stars-only nil
  3502. "Non-nil means fontify only the stars in each headline.
  3503. When nil, the entire headline is fontified.
  3504. Changing it requires restart of `font-lock-mode' to become effective
  3505. also in regions already fontified."
  3506. :group 'org-appearance
  3507. :type 'boolean)
  3508. (defcustom org-hide-leading-stars nil
  3509. "Non-nil means hide the first N-1 stars in a headline.
  3510. This works by using the face `org-hide' for these stars. This
  3511. face is white for a light background, and black for a dark
  3512. background. You may have to customize the face `org-hide' to
  3513. make this work.
  3514. Changing it requires restart of `font-lock-mode' to become effective
  3515. also in regions already fontified.
  3516. You may also set this on a per-file basis by adding one of the following
  3517. lines to the buffer:
  3518. #+STARTUP: hidestars
  3519. #+STARTUP: showstars"
  3520. :group 'org-appearance
  3521. :type 'boolean)
  3522. (defcustom org-hidden-keywords nil
  3523. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3524. For example, a value \\='(title) for this list makes the document's title
  3525. appear in the buffer without the initial \"#+TITLE:\" part."
  3526. :group 'org-appearance
  3527. :version "24.1"
  3528. :type '(set (const :tag "#+AUTHOR" author)
  3529. (const :tag "#+DATE" date)
  3530. (const :tag "#+EMAIL" email)
  3531. (const :tag "#+TITLE" title)))
  3532. (defcustom org-custom-properties nil
  3533. "List of properties (as strings) with a special meaning.
  3534. The default use of these custom properties is to let the user
  3535. hide them with `org-toggle-custom-properties-visibility'."
  3536. :group 'org-properties
  3537. :group 'org-appearance
  3538. :version "24.3"
  3539. :type '(repeat (string :tag "Property Name")))
  3540. (defcustom org-fontify-done-headline nil
  3541. "Non-nil means change the face of a headline if it is marked DONE.
  3542. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3543. When this is non-nil, the headline after the keyword is set to the
  3544. `org-headline-done' as an additional indication."
  3545. :group 'org-appearance
  3546. :type 'boolean)
  3547. (defcustom org-fontify-emphasized-text t
  3548. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3549. Changing this variable requires a restart of Emacs to take effect."
  3550. :group 'org-appearance
  3551. :type 'boolean)
  3552. (defcustom org-fontify-whole-heading-line nil
  3553. "Non-nil means fontify the whole line for headings.
  3554. This is useful when setting a background color for the
  3555. org-level-* faces."
  3556. :group 'org-appearance
  3557. :type 'boolean)
  3558. (defcustom org-highlight-latex-and-related nil
  3559. "Non-nil means highlight LaTeX related syntax in the buffer.
  3560. When non nil, the value should be a list containing any of the
  3561. following symbols:
  3562. `latex' Highlight LaTeX snippets and environments.
  3563. `script' Highlight subscript and superscript.
  3564. `entities' Highlight entities."
  3565. :group 'org-appearance
  3566. :version "24.4"
  3567. :package-version '(Org . "8.0")
  3568. :type '(choice
  3569. (const :tag "No highlighting" nil)
  3570. (set :greedy t :tag "Highlight"
  3571. (const :tag "LaTeX snippets and environments" latex)
  3572. (const :tag "Subscript and superscript" script)
  3573. (const :tag "Entities" entities))))
  3574. (defcustom org-hide-emphasis-markers nil
  3575. "Non-nil mean font-lock should hide the emphasis marker characters."
  3576. :group 'org-appearance
  3577. :type 'boolean
  3578. :safe #'booleanp)
  3579. (defcustom org-hide-macro-markers nil
  3580. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3581. :group 'org-appearance
  3582. :type 'boolean)
  3583. (defcustom org-pretty-entities nil
  3584. "Non-nil means show entities as UTF8 characters.
  3585. When nil, the \\name form remains in the buffer."
  3586. :group 'org-appearance
  3587. :version "24.1"
  3588. :type 'boolean)
  3589. (defcustom org-pretty-entities-include-sub-superscripts t
  3590. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3591. :group 'org-appearance
  3592. :version "24.1"
  3593. :type 'boolean)
  3594. (defvar org-emph-re nil
  3595. "Regular expression for matching emphasis.
  3596. After a match, the match groups contain these elements:
  3597. 0 The match of the full regular expression, including the characters
  3598. before and after the proper match
  3599. 1 The character before the proper match, or empty at beginning of line
  3600. 2 The proper match, including the leading and trailing markers
  3601. 3 The leading marker like * or /, indicating the type of highlighting
  3602. 4 The text between the emphasis markers, not including the markers
  3603. 5 The character after the match, empty at the end of a line")
  3604. (defvar org-verbatim-re nil
  3605. "Regular expression for matching verbatim text.")
  3606. (defvar org-emphasis-regexp-components) ; defined just below
  3607. (defvar org-emphasis-alist) ; defined just below
  3608. (defun org-set-emph-re (var val)
  3609. "Set variable and compute the emphasis regular expression."
  3610. (set var val)
  3611. (when (and (boundp 'org-emphasis-alist)
  3612. (boundp 'org-emphasis-regexp-components)
  3613. org-emphasis-alist org-emphasis-regexp-components)
  3614. (pcase-let*
  3615. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3616. (body (if (<= nl 0) body
  3617. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3618. (template
  3619. (format (concat "\\([%s]\\|^\\)" ;before markers
  3620. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3621. "\\([%s]\\|$\\)") ;after markers
  3622. pre border border body border post)))
  3623. (setq org-emph-re (format template "*/_+"))
  3624. (setq org-verbatim-re (format template "=~")))))
  3625. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3626. ;; set this option proved cumbersome. See this message/thread:
  3627. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3628. (defvar org-emphasis-regexp-components
  3629. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3630. "Components used to build the regular expression for emphasis.
  3631. This is a list with five entries. Terminology: In an emphasis string
  3632. like \" *strong word* \", we call the initial space PREMATCH, the final
  3633. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3634. and \"trong wor\" is the body. The different components in this variable
  3635. specify what is allowed/forbidden in each part:
  3636. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3637. post Chars allowed as postmatch. End of line will be allowed too.
  3638. border The chars *forbidden* as border characters.
  3639. body-regexp A regexp like \".\" to match a body character. Don't use
  3640. non-shy groups here, and don't allow newline here.
  3641. newline The maximum number of newlines allowed in an emphasis exp.
  3642. You need to reload Org or to restart Emacs after setting this.")
  3643. (defcustom org-emphasis-alist
  3644. '(("*" bold)
  3645. ("/" italic)
  3646. ("_" underline)
  3647. ("=" org-verbatim verbatim)
  3648. ("~" org-code verbatim)
  3649. ("+" (:strike-through t)))
  3650. "Alist of characters and faces to emphasize text.
  3651. Text starting and ending with a special character will be emphasized,
  3652. for example *bold*, _underlined_ and /italic/. This variable sets the
  3653. marker characters and the face to be used by font-lock for highlighting
  3654. in Org buffers.
  3655. You need to reload Org or to restart Emacs after customizing this."
  3656. :group 'org-appearance
  3657. :set 'org-set-emph-re
  3658. :version "24.4"
  3659. :package-version '(Org . "8.0")
  3660. :type '(repeat
  3661. (list
  3662. (string :tag "Marker character")
  3663. (choice
  3664. (face :tag "Font-lock-face")
  3665. (plist :tag "Face property list"))
  3666. (option (const verbatim)))))
  3667. (defvar org-protecting-blocks '("src" "example" "export")
  3668. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3669. This is needed for font-lock setup.")
  3670. ;;; Functions and variables from their packages
  3671. ;; Declared here to avoid compiler warnings
  3672. (defvar mark-active)
  3673. ;; Various packages
  3674. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3675. (declare-function calendar-forward-day "cal-move" (arg))
  3676. (declare-function calendar-goto-date "cal-move" (date))
  3677. (declare-function calendar-goto-today "cal-move" ())
  3678. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3679. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3680. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3681. (declare-function cdlatex-tab "ext:cdlatex" ())
  3682. (declare-function dired-get-filename
  3683. "dired"
  3684. (&optional localp no-error-if-not-filep))
  3685. (declare-function iswitchb-read-buffer
  3686. "iswitchb"
  3687. (prompt &optional
  3688. default require-match _predicate start matches-set))
  3689. (declare-function org-agenda-change-all-lines
  3690. "org-agenda"
  3691. (newhead hdmarker &optional fixface just-this))
  3692. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3693. "org-agenda"
  3694. (&optional end))
  3695. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3696. (declare-function org-agenda-format-item
  3697. "org-agenda"
  3698. (extra txt &optional level category tags dotime
  3699. remove-re habitp))
  3700. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3701. (declare-function org-agenda-save-markers-for-cut-and-paste
  3702. "org-agenda"
  3703. (beg end))
  3704. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3705. (declare-function org-agenda-skip "org-agenda" ())
  3706. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3707. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3708. (declare-function org-indent-mode "org-indent" (&optional arg))
  3709. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3710. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3711. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3712. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3713. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3714. (declare-function parse-time-string "parse-time" (string))
  3715. (defvar align-mode-rules-list)
  3716. (defvar calc-embedded-close-formula)
  3717. (defvar calc-embedded-open-formula)
  3718. (defvar calc-embedded-open-mode)
  3719. (defvar font-lock-unfontify-region-function)
  3720. (defvar iswitchb-temp-buflist)
  3721. (defvar org-agenda-tags-todo-honor-ignore-options)
  3722. (defvar remember-data-file)
  3723. (defvar texmathp-why)
  3724. ;;;###autoload
  3725. (defun turn-on-orgtbl ()
  3726. "Unconditionally turn on `orgtbl-mode'."
  3727. (require 'org-table)
  3728. (orgtbl-mode 1))
  3729. (defun org-at-table-p (&optional table-type)
  3730. "Non-nil if the cursor is inside an Org table.
  3731. If TABLE-TYPE is non-nil, also check for table.el-type tables."
  3732. (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
  3733. (or (not (derived-mode-p 'org-mode))
  3734. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3735. (and e (or table-type
  3736. (eq 'org (org-element-property :type e))))))))
  3737. (defun org-at-table.el-p ()
  3738. "Non-nil when point is at a table.el table."
  3739. (and (org-match-line "[ \t]*[|+]")
  3740. (let ((element (org-element-at-point)))
  3741. (and (eq (org-element-type element) 'table)
  3742. (eq (org-element-property :type element) 'table.el)))))
  3743. (defun org-at-table-hline-p ()
  3744. "Non-nil when point is inside a hline in a table.
  3745. Assume point is already in a table."
  3746. (org-match-line org-table-hline-regexp))
  3747. (defun org-table-map-tables (function &optional quietly)
  3748. "Apply FUNCTION to the start of all tables in the buffer."
  3749. (org-with-wide-buffer
  3750. (goto-char (point-min))
  3751. (while (re-search-forward org-table-any-line-regexp nil t)
  3752. (unless quietly
  3753. (message "Mapping tables: %d%%"
  3754. (floor (* 100.0 (point)) (buffer-size))))
  3755. (beginning-of-line 1)
  3756. (when (and (looking-at org-table-line-regexp)
  3757. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3758. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3759. (save-excursion (funcall function))
  3760. (or (looking-at org-table-line-regexp)
  3761. (forward-char 1)))
  3762. (re-search-forward org-table-any-border-regexp nil 1)))
  3763. (unless quietly (message "Mapping tables: done")))
  3764. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3765. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3766. (declare-function org-resolve-clocks "org-clock"
  3767. (&optional also-non-dangling-p prompt last-valid))
  3768. (defun org-at-TBLFM-p (&optional pos)
  3769. "Non-nil when point (or POS) is in #+TBLFM line."
  3770. (save-excursion
  3771. (goto-char (or pos (point)))
  3772. (beginning-of-line)
  3773. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3774. (eq (org-element-type (org-element-at-point)) 'table))))
  3775. (defvar org-clock-start-time)
  3776. (defvar org-clock-marker (make-marker)
  3777. "Marker recording the last clock-in.")
  3778. (defvar org-clock-hd-marker (make-marker)
  3779. "Marker recording the last clock-in, but the headline position.")
  3780. (defvar org-clock-heading ""
  3781. "The heading of the current clock entry.")
  3782. (defun org-clock-is-active ()
  3783. "Return the buffer where the clock is currently running.
  3784. Return nil if no clock is running."
  3785. (marker-buffer org-clock-marker))
  3786. (defun org-check-running-clock ()
  3787. "Check if the current buffer contains the running clock.
  3788. If yes, offer to stop it and to save the buffer with the changes."
  3789. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3790. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3791. (buffer-name))))
  3792. (org-clock-out)
  3793. (when (y-or-n-p "Save changed buffer?")
  3794. (save-buffer))))
  3795. (defun org-clocktable-try-shift (dir n)
  3796. "Check if this line starts a clock table, if yes, shift the time block."
  3797. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3798. (org-clocktable-shift dir n)))
  3799. ;;;###autoload
  3800. (defun org-clock-persistence-insinuate ()
  3801. "Set up hooks for clock persistence."
  3802. (require 'org-clock)
  3803. (add-hook 'org-mode-hook 'org-clock-load)
  3804. (add-hook 'kill-emacs-hook 'org-clock-save))
  3805. (defgroup org-archive nil
  3806. "Options concerning archiving in Org mode."
  3807. :tag "Org Archive"
  3808. :group 'org-structure)
  3809. (defcustom org-archive-location "%s_archive::"
  3810. "The location where subtrees should be archived.
  3811. The value of this variable is a string, consisting of two parts,
  3812. separated by a double-colon. The first part is a filename and
  3813. the second part is a headline.
  3814. When the filename is omitted, archiving happens in the same file.
  3815. %s in the filename will be replaced by the current file
  3816. name (without the directory part). Archiving to a different file
  3817. is useful to keep archived entries from contributing to the
  3818. Org Agenda.
  3819. The archived entries will be filed as subtrees of the specified
  3820. headline. When the headline is omitted, the subtrees are simply
  3821. filed away at the end of the file, as top-level entries. Also in
  3822. the heading you can use %s to represent the file name, this can be
  3823. useful when using the same archive for a number of different files.
  3824. Here are a few examples:
  3825. \"%s_archive::\"
  3826. If the current file is Projects.org, archive in file
  3827. Projects.org_archive, as top-level trees. This is the default.
  3828. \"::* Archived Tasks\"
  3829. Archive in the current file, under the top-level headline
  3830. \"* Archived Tasks\".
  3831. \"~/org/archive.org::\"
  3832. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3833. \"~/org/archive.org::* From %s\"
  3834. Archive in file ~/org/archive.org (absolute path), under headlines
  3835. \"From FILENAME\" where file name is the current file name.
  3836. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3837. The \"datetree/\" string is special, signifying to archive
  3838. items to the datetree. Items are placed in either the CLOSED
  3839. date of the item, or the current date if there is no CLOSED date.
  3840. The heading will be a subentry to the current date. There doesn't
  3841. need to be a heading, but there always needs to be a slash after
  3842. datetree. For example, to store archived items directly in the
  3843. datetree, use \"~/org/datetree.org::datetree/\".
  3844. \"basement::** Finished Tasks\"
  3845. Archive in file ./basement (relative path), as level 3 trees
  3846. below the level 2 heading \"** Finished Tasks\".
  3847. You may set this option on a per-file basis by adding to the buffer a
  3848. line like
  3849. #+ARCHIVE: basement::** Finished Tasks
  3850. You may also define it locally for a subtree by setting an ARCHIVE property
  3851. in the entry. If such a property is found in an entry, or anywhere up
  3852. the hierarchy, it will be used."
  3853. :group 'org-archive
  3854. :type 'string)
  3855. (defcustom org-agenda-skip-archived-trees t
  3856. "Non-nil means the agenda will skip any items located in archived trees.
  3857. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3858. variable is no longer recommended, you should leave it at the value t.
  3859. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3860. :group 'org-archive
  3861. :group 'org-agenda-skip
  3862. :type 'boolean)
  3863. (defcustom org-columns-skip-archived-trees t
  3864. "Non-nil means ignore archived trees when creating column view."
  3865. :group 'org-archive
  3866. :group 'org-properties
  3867. :type 'boolean)
  3868. (defcustom org-cycle-open-archived-trees nil
  3869. "Non-nil means `org-cycle' will open archived trees.
  3870. An archived tree is a tree marked with the tag ARCHIVE.
  3871. When nil, archived trees will stay folded. You can still open them with
  3872. normal outline commands like `show-all', but not with the cycling commands."
  3873. :group 'org-archive
  3874. :group 'org-cycle
  3875. :type 'boolean)
  3876. (defcustom org-sparse-tree-open-archived-trees nil
  3877. "Non-nil means sparse tree construction shows matches in archived trees.
  3878. When nil, matches in these trees are highlighted, but the trees are kept in
  3879. collapsed state."
  3880. :group 'org-archive
  3881. :group 'org-sparse-trees
  3882. :type 'boolean)
  3883. (defcustom org-sparse-tree-default-date-type nil
  3884. "The default date type when building a sparse tree.
  3885. When this is nil, a date is a scheduled or a deadline timestamp.
  3886. Otherwise, these types are allowed:
  3887. all: all timestamps
  3888. active: only active timestamps (<...>)
  3889. inactive: only inactive timestamps ([...])
  3890. scheduled: only scheduled timestamps
  3891. deadline: only deadline timestamps"
  3892. :type '(choice (const :tag "Scheduled or deadline" nil)
  3893. (const :tag "All timestamps" all)
  3894. (const :tag "Only active timestamps" active)
  3895. (const :tag "Only inactive timestamps" inactive)
  3896. (const :tag "Only scheduled timestamps" scheduled)
  3897. (const :tag "Only deadline timestamps" deadline)
  3898. (const :tag "Only closed timestamps" closed))
  3899. :version "26.1"
  3900. :package-version '(Org . "8.3")
  3901. :group 'org-sparse-trees)
  3902. (defun org-cycle-hide-archived-subtrees (state)
  3903. "Re-hide all archived subtrees after a visibility state change.
  3904. STATE should be one of the symbols listed in the docstring of
  3905. `org-cycle-hook'."
  3906. (when (and (not org-cycle-open-archived-trees)
  3907. (not (memq state '(overview folded))))
  3908. (save-excursion
  3909. (let* ((globalp (memq state '(contents all)))
  3910. (beg (if globalp (point-min) (point)))
  3911. (end (if globalp (point-max) (org-end-of-subtree t))))
  3912. (org-hide-archived-subtrees beg end)
  3913. (goto-char beg)
  3914. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3915. (message "%s" (substitute-command-keys
  3916. "Subtree is archived and stays closed. Use \
  3917. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3918. (defun org-force-cycle-archived ()
  3919. "Cycle subtree even if it is archived."
  3920. (interactive)
  3921. (setq this-command 'org-cycle)
  3922. (let ((org-cycle-open-archived-trees t))
  3923. (call-interactively 'org-cycle)))
  3924. (defun org-hide-archived-subtrees (beg end)
  3925. "Re-hide all archived subtrees after a visibility state change."
  3926. (org-with-wide-buffer
  3927. (let ((case-fold-search nil)
  3928. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3929. (goto-char beg)
  3930. ;; Include headline point is currently on.
  3931. (beginning-of-line)
  3932. (while (and (< (point) end) (re-search-forward re end t))
  3933. (when (member org-archive-tag (org-get-tags nil t))
  3934. (org-flag-subtree t)
  3935. (org-end-of-subtree t))))))
  3936. (defun org-flag-subtree (flag)
  3937. (save-excursion
  3938. (org-back-to-heading t)
  3939. (org-flag-region (line-end-position)
  3940. (progn (org-end-of-subtree t) (point))
  3941. flag
  3942. 'outline)))
  3943. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3944. ;; Declare Column View Code
  3945. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3946. (declare-function org-columns-compute "org-colview" (property))
  3947. ;; Declare ID code
  3948. (declare-function org-id-store-link "org-id")
  3949. (declare-function org-id-locations-load "org-id")
  3950. (declare-function org-id-locations-save "org-id")
  3951. (defvar org-id-track-globally)
  3952. ;;; Variables for pre-computed regular expressions, all buffer local
  3953. (defvar-local org-todo-regexp nil
  3954. "Matches any of the TODO state keywords.
  3955. Since TODO keywords are case-sensitive, `case-fold-search' is
  3956. expected to be bound to nil when matching against this regexp.")
  3957. (defvar-local org-not-done-regexp nil
  3958. "Matches any of the TODO state keywords except the last one.
  3959. Since TODO keywords are case-sensitive, `case-fold-search' is
  3960. expected to be bound to nil when matching against this regexp.")
  3961. (defvar-local org-not-done-heading-regexp nil
  3962. "Matches a TODO headline that is not done.
  3963. Since TODO keywords are case-sensitive, `case-fold-search' is
  3964. expected to be bound to nil when matching against this regexp.")
  3965. (defvar-local org-todo-line-regexp nil
  3966. "Matches a headline and puts TODO state into group 2 if present.
  3967. Since TODO keywords are case-sensitive, `case-fold-search' is
  3968. expected to be bound to nil when matching against this regexp.")
  3969. (defvar-local org-complex-heading-regexp nil
  3970. "Matches a headline and puts everything into groups:
  3971. group 1: Stars
  3972. group 2: The TODO keyword, maybe
  3973. group 3: Priority cookie
  3974. group 4: True headline
  3975. group 5: Tags
  3976. Since TODO keywords are case-sensitive, `case-fold-search' is
  3977. expected to be bound to nil when matching against this regexp.")
  3978. (defvar-local org-complex-heading-regexp-format nil
  3979. "Printf format to make regexp to match an exact headline.
  3980. This regexp will match the headline of any node which has the
  3981. exact headline text that is put into the format, but may have any
  3982. TODO state, priority and tags.")
  3983. (defvar-local org-todo-line-tags-regexp nil
  3984. "Matches a headline and puts TODO state into group 2 if present.
  3985. Also put tags into group 4 if tags are present.")
  3986. (defconst org-plain-time-of-day-regexp
  3987. (concat
  3988. "\\(\\<[012]?[0-9]"
  3989. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3990. "\\(--?"
  3991. "\\(\\<[012]?[0-9]"
  3992. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3993. "\\)?")
  3994. "Regular expression to match a plain time or time range.
  3995. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3996. groups carry important information:
  3997. 0 the full match
  3998. 1 the first time, range or not
  3999. 8 the second time, if it is a range.")
  4000. (defconst org-plain-time-extension-regexp
  4001. (concat
  4002. "\\(\\<[012]?[0-9]"
  4003. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4004. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4005. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4006. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4007. groups carry important information:
  4008. 0 the full match
  4009. 7 hours of duration
  4010. 9 minutes of duration")
  4011. (defconst org-stamp-time-of-day-regexp
  4012. (concat
  4013. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4014. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4015. "\\(--?"
  4016. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4017. "Regular expression to match a timestamp time or time range.
  4018. After a match, the following groups carry important information:
  4019. 0 the full match
  4020. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4021. 2 the first time, range or not
  4022. 4 the second time, if it is a range.")
  4023. (defconst org-startup-options
  4024. '(("fold" org-startup-folded t)
  4025. ("overview" org-startup-folded t)
  4026. ("nofold" org-startup-folded nil)
  4027. ("showall" org-startup-folded nil)
  4028. ("showeverything" org-startup-folded showeverything)
  4029. ("content" org-startup-folded content)
  4030. ("indent" org-startup-indented t)
  4031. ("noindent" org-startup-indented nil)
  4032. ("hidestars" org-hide-leading-stars t)
  4033. ("showstars" org-hide-leading-stars nil)
  4034. ("odd" org-odd-levels-only t)
  4035. ("oddeven" org-odd-levels-only nil)
  4036. ("align" org-startup-align-all-tables t)
  4037. ("noalign" org-startup-align-all-tables nil)
  4038. ("shrink" org-startup-shrink-all-tables t)
  4039. ("inlineimages" org-startup-with-inline-images t)
  4040. ("noinlineimages" org-startup-with-inline-images nil)
  4041. ("latexpreview" org-startup-with-latex-preview t)
  4042. ("nolatexpreview" org-startup-with-latex-preview nil)
  4043. ("customtime" org-display-custom-times t)
  4044. ("logdone" org-log-done time)
  4045. ("lognotedone" org-log-done note)
  4046. ("nologdone" org-log-done nil)
  4047. ("lognoteclock-out" org-log-note-clock-out t)
  4048. ("nolognoteclock-out" org-log-note-clock-out nil)
  4049. ("logrepeat" org-log-repeat state)
  4050. ("lognoterepeat" org-log-repeat note)
  4051. ("logdrawer" org-log-into-drawer t)
  4052. ("nologdrawer" org-log-into-drawer nil)
  4053. ("logstatesreversed" org-log-states-order-reversed t)
  4054. ("nologstatesreversed" org-log-states-order-reversed nil)
  4055. ("nologrepeat" org-log-repeat nil)
  4056. ("logreschedule" org-log-reschedule time)
  4057. ("lognotereschedule" org-log-reschedule note)
  4058. ("nologreschedule" org-log-reschedule nil)
  4059. ("logredeadline" org-log-redeadline time)
  4060. ("lognoteredeadline" org-log-redeadline note)
  4061. ("nologredeadline" org-log-redeadline nil)
  4062. ("logrefile" org-log-refile time)
  4063. ("lognoterefile" org-log-refile note)
  4064. ("nologrefile" org-log-refile nil)
  4065. ("fninline" org-footnote-define-inline t)
  4066. ("nofninline" org-footnote-define-inline nil)
  4067. ("fnlocal" org-footnote-section nil)
  4068. ("fnauto" org-footnote-auto-label t)
  4069. ("fnprompt" org-footnote-auto-label nil)
  4070. ("fnconfirm" org-footnote-auto-label confirm)
  4071. ("fnplain" org-footnote-auto-label plain)
  4072. ("fnadjust" org-footnote-auto-adjust t)
  4073. ("nofnadjust" org-footnote-auto-adjust nil)
  4074. ("constcgs" constants-unit-system cgs)
  4075. ("constSI" constants-unit-system SI)
  4076. ("noptag" org-tag-persistent-alist nil)
  4077. ("hideblocks" org-hide-block-startup t)
  4078. ("nohideblocks" org-hide-block-startup nil)
  4079. ("beamer" org-startup-with-beamer-mode t)
  4080. ("entitiespretty" org-pretty-entities t)
  4081. ("entitiesplain" org-pretty-entities nil))
  4082. "Variable associated with STARTUP options for Org.
  4083. Each element is a list of three items: the startup options (as written
  4084. in the #+STARTUP line), the corresponding variable, and the value to set
  4085. this variable to if the option is found. An optional forth element PUSH
  4086. means to push this value onto the list in the variable.")
  4087. (defcustom org-group-tags t
  4088. "When non-nil (the default), use group tags.
  4089. This can be turned on/off through `org-toggle-tags-groups'."
  4090. :group 'org-tags
  4091. :group 'org-startup
  4092. :type 'boolean)
  4093. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4094. (defun org-toggle-tags-groups ()
  4095. "Toggle support for group tags.
  4096. Support for group tags is controlled by the option
  4097. `org-group-tags', which is non-nil by default."
  4098. (interactive)
  4099. (setq org-group-tags (not org-group-tags))
  4100. (cond ((and (derived-mode-p 'org-agenda-mode)
  4101. org-group-tags)
  4102. (org-agenda-redo))
  4103. ((derived-mode-p 'org-mode)
  4104. (let ((org-inhibit-startup t)) (org-mode))))
  4105. (message "Groups tags support has been turned %s"
  4106. (if org-group-tags "on" "off")))
  4107. (defun org--tag-add-to-alist (alist1 alist2)
  4108. "Merge tags from ALIST1 into ALIST2.
  4109. Duplicates tags outside a group are removed. Keywords and order
  4110. are preserved.
  4111. The function assumes ALIST1 and ALIST2 are proper tag alists.
  4112. See `org-tag-alist' for their structure."
  4113. (cond
  4114. ((null alist2) alist1)
  4115. ((null alist1) alist2)
  4116. (t
  4117. (let ((to-add nil)
  4118. (group-flag nil))
  4119. (dolist (tag-pair alist1)
  4120. (pcase tag-pair
  4121. (`(,(or :startgrouptag :startgroup))
  4122. (setq group-flag t)
  4123. (push tag-pair to-add))
  4124. (`(,(or :endgrouptag :endgroup))
  4125. (setq group-flag nil)
  4126. (push tag-pair to-add))
  4127. (`(,(or :grouptags :newline))
  4128. (push tag-pair to-add))
  4129. (`(,tag . ,_)
  4130. ;; Remove duplicates from ALIST1, unless they are in
  4131. ;; a group. Indeed, it makes sense to have a tag appear in
  4132. ;; multiple groups.
  4133. (when (or group-flag (not (assoc tag alist2)))
  4134. (push tag-pair to-add)))
  4135. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  4136. ;; Preserve order of ALIST1.
  4137. (append (nreverse to-add) alist2)))))
  4138. (defun org-set-regexps-and-options (&optional tags-only)
  4139. "Precompute regular expressions used in the current buffer.
  4140. When optional argument TAGS-ONLY is non-nil, only compute tags
  4141. related expressions."
  4142. (when (derived-mode-p 'org-mode)
  4143. (let ((alist (org--setup-collect-keywords
  4144. (org-make-options-regexp
  4145. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4146. (and (not tags-only)
  4147. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4148. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4149. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4150. ;; Startup options. Get this early since it does change
  4151. ;; behavior for other options (e.g., tags).
  4152. (let ((startup (cdr (assq 'startup alist))))
  4153. (dolist (option startup)
  4154. (let ((entry (assoc-string option org-startup-options t)))
  4155. (when entry
  4156. (let ((var (nth 1 entry))
  4157. (val (nth 2 entry)))
  4158. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4159. (unless (listp (symbol-value var))
  4160. (set (make-local-variable var) nil))
  4161. (add-to-list var val)))))))
  4162. (setq-local org-file-tags
  4163. (mapcar #'org-add-prop-inherited
  4164. (cdr (assq 'filetags alist))))
  4165. (setq org-current-tag-alist
  4166. (org--tag-add-to-alist
  4167. org-tag-persistent-alist
  4168. (let ((tags (cdr (assq 'tags alist))))
  4169. (if tags (org-tag-string-to-alist tags)
  4170. org-tag-alist))))
  4171. (setq org-tag-groups-alist
  4172. (org-tag-alist-to-groups org-current-tag-alist))
  4173. (unless tags-only
  4174. ;; File properties.
  4175. (setq-local org-file-properties (cdr (assq 'property alist)))
  4176. ;; Archive location.
  4177. (let ((archive (cdr (assq 'archive alist))))
  4178. (when archive (setq-local org-archive-location archive)))
  4179. ;; Category.
  4180. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4181. (when cat
  4182. (setq-local org-category (intern cat))
  4183. (setq-local org-file-properties
  4184. (org--update-property-plist
  4185. "CATEGORY" cat org-file-properties))))
  4186. ;; Columns.
  4187. (let ((column (cdr (assq 'columns alist))))
  4188. (when column (setq-local org-columns-default-format column)))
  4189. ;; Constants.
  4190. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4191. ;; Link abbreviations.
  4192. (let ((links (cdr (assq 'link alist))))
  4193. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4194. ;; Priorities.
  4195. (let ((priorities (cdr (assq 'priorities alist))))
  4196. (when priorities
  4197. (setq-local org-highest-priority (nth 0 priorities))
  4198. (setq-local org-lowest-priority (nth 1 priorities))
  4199. (setq-local org-default-priority (nth 2 priorities))))
  4200. ;; Scripts.
  4201. (let ((scripts (assq 'scripts alist)))
  4202. (when scripts
  4203. (setq-local org-use-sub-superscripts (cdr scripts))))
  4204. ;; TODO keywords.
  4205. (setq-local org-todo-kwd-alist nil)
  4206. (setq-local org-todo-key-alist nil)
  4207. (setq-local org-todo-key-trigger nil)
  4208. (setq-local org-todo-keywords-1 nil)
  4209. (setq-local org-done-keywords nil)
  4210. (setq-local org-todo-heads nil)
  4211. (setq-local org-todo-sets nil)
  4212. (setq-local org-todo-log-states nil)
  4213. (let ((todo-sequences
  4214. (or (nreverse (cdr (assq 'todo alist)))
  4215. (let ((d (default-value 'org-todo-keywords)))
  4216. (if (not (stringp (car d))) d
  4217. ;; XXX: Backward compatibility code.
  4218. (list (cons org-todo-interpretation d)))))))
  4219. (dolist (sequence todo-sequences)
  4220. (let* ((sequence (or (run-hook-with-args-until-success
  4221. 'org-todo-setup-filter-hook sequence)
  4222. sequence))
  4223. (sequence-type (car sequence))
  4224. (keywords (cdr sequence))
  4225. (sep (member "|" keywords))
  4226. names alist)
  4227. (dolist (k (remove "|" keywords))
  4228. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4229. k)
  4230. (error "Invalid TODO keyword %s" k))
  4231. (let ((name (match-string 1 k))
  4232. (key (match-string 2 k))
  4233. (log (org-extract-log-state-settings k)))
  4234. (push name names)
  4235. (push (cons name (and key (string-to-char key))) alist)
  4236. (when log (push log org-todo-log-states))))
  4237. (let* ((names (nreverse names))
  4238. (done (if sep (org-remove-keyword-keys (cdr sep))
  4239. (last names)))
  4240. (head (car names))
  4241. (tail (list sequence-type head (car done) (org-last done))))
  4242. (add-to-list 'org-todo-heads head 'append)
  4243. (push names org-todo-sets)
  4244. (setq org-done-keywords (append org-done-keywords done nil))
  4245. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4246. (setq org-todo-key-alist
  4247. (append org-todo-key-alist
  4248. (and alist
  4249. (append '((:startgroup))
  4250. (nreverse alist)
  4251. '((:endgroup))))))
  4252. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4253. (setq org-todo-sets (nreverse org-todo-sets)
  4254. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4255. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4256. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4257. ;; Compute the regular expressions and other local variables.
  4258. ;; Using `org-outline-regexp-bol' would complicate them much,
  4259. ;; because of the fixed white space at the end of that string.
  4260. (unless org-done-keywords
  4261. (setq org-done-keywords
  4262. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4263. (setq org-not-done-keywords
  4264. (org-delete-all org-done-keywords
  4265. (copy-sequence org-todo-keywords-1))
  4266. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4267. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4268. org-not-done-heading-regexp
  4269. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4270. org-todo-line-regexp
  4271. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4272. org-complex-heading-regexp
  4273. (concat "^\\(\\*+\\)"
  4274. "\\(?: +" org-todo-regexp "\\)?"
  4275. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4276. "\\(?: +\\(.*?\\)\\)??"
  4277. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4278. "[ \t]*$")
  4279. org-complex-heading-regexp-format
  4280. (concat "^\\(\\*+\\)"
  4281. "\\(?: +" org-todo-regexp "\\)?"
  4282. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4283. "\\(?: +"
  4284. ;; Stats cookies can be stuck to body.
  4285. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4286. "\\(%s\\)"
  4287. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4288. "\\)"
  4289. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4290. "[ \t]*$")
  4291. org-todo-line-tags-regexp
  4292. (concat "^\\(\\*+\\)"
  4293. "\\(?: +" org-todo-regexp "\\)?"
  4294. "\\(?: +\\(.*?\\)\\)??"
  4295. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4296. "[ \t]*$"))
  4297. (org-compute-latex-and-related-regexp)))))
  4298. (defun org--setup-collect-keywords (regexp &optional files alist)
  4299. "Return setup keywords values as an alist.
  4300. REGEXP matches a subset of setup keywords. FILES is a list of
  4301. file names already visited. It is used to avoid circular setup
  4302. files. ALIST, when non-nil, is the alist computed so far.
  4303. Return value contains the following keys: `archive', `category',
  4304. `columns', `constants', `filetags', `link', `priorities',
  4305. `property', `scripts', `startup', `tags' and `todo'."
  4306. (org-with-wide-buffer
  4307. (goto-char (point-min))
  4308. (let ((case-fold-search t))
  4309. (while (re-search-forward regexp nil t)
  4310. (let ((element (org-element-at-point)))
  4311. (when (eq (org-element-type element) 'keyword)
  4312. (let ((key (org-element-property :key element))
  4313. (value (org-element-property :value element)))
  4314. (cond
  4315. ((equal key "ARCHIVE")
  4316. (when (org-string-nw-p value)
  4317. (push (cons 'archive value) alist)))
  4318. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4319. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4320. ((equal key "CONSTANTS")
  4321. (let* ((constants (assq 'constants alist))
  4322. (store (cdr constants)))
  4323. (dolist (pair (split-string value))
  4324. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4325. pair)
  4326. (let* ((name (match-string 1 pair))
  4327. (value (match-string 2 pair))
  4328. (old (assoc name store)))
  4329. (if old (setcdr old value)
  4330. (push (cons name value) store)))))
  4331. (if constants (setcdr constants store)
  4332. (push (cons 'constants store) alist))))
  4333. ((equal key "FILETAGS")
  4334. (when (org-string-nw-p value)
  4335. (let ((old (assq 'filetags alist))
  4336. (new (apply #'nconc
  4337. (mapcar (lambda (x) (org-split-string x ":"))
  4338. (split-string value)))))
  4339. (if old (setcdr old (append new (cdr old)))
  4340. (push (cons 'filetags new) alist)))))
  4341. ((equal key "LINK")
  4342. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4343. (let ((links (assq 'link alist))
  4344. (pair (cons (match-string-no-properties 1 value)
  4345. (match-string-no-properties 2 value))))
  4346. (if links (push pair (cdr links))
  4347. (push (list 'link pair) alist)))))
  4348. ((equal key "OPTIONS")
  4349. (when (and (org-string-nw-p value)
  4350. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4351. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4352. ((equal key "PRIORITIES")
  4353. (push (cons 'priorities
  4354. (let ((prio (split-string value)))
  4355. (if (< (length prio) 3) '(?A ?C ?B)
  4356. (mapcar #'string-to-char prio))))
  4357. alist))
  4358. ((equal key "PROPERTY")
  4359. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4360. (let* ((property (assq 'property alist))
  4361. (value (org--update-property-plist
  4362. (match-string-no-properties 1 value)
  4363. (match-string-no-properties 2 value)
  4364. (cdr property))))
  4365. (if property (setcdr property value)
  4366. (push (cons 'property value) alist)))))
  4367. ((equal key "STARTUP")
  4368. (let ((startup (assq 'startup alist)))
  4369. (if startup
  4370. (setcdr startup
  4371. (append (cdr startup) (split-string value)))
  4372. (push (cons 'startup (split-string value)) alist))))
  4373. ((equal key "TAGS")
  4374. (let ((tag-cell (assq 'tags alist)))
  4375. (if tag-cell
  4376. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4377. (push (cons 'tags value) alist))))
  4378. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4379. (let ((todo (assq 'todo alist))
  4380. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4381. (split-string value))))
  4382. (if todo (push value (cdr todo))
  4383. (push (list 'todo value) alist))))
  4384. ((equal key "SETUPFILE")
  4385. (unless buffer-read-only ; Do not check in Gnus messages.
  4386. (let ((f (and (org-string-nw-p value)
  4387. (expand-file-name (org-strip-quotes value)))))
  4388. (when (and f (file-readable-p f) (not (member f files)))
  4389. (with-temp-buffer
  4390. (setq default-directory (file-name-directory f))
  4391. (insert-file-contents f)
  4392. (setq alist
  4393. ;; Fake Org mode to benefit from cache
  4394. ;; without recurring needlessly.
  4395. (let ((major-mode 'org-mode))
  4396. (org--setup-collect-keywords
  4397. regexp (cons f files) alist)))))))))))))))
  4398. alist)
  4399. (defun org-tag-string-to-alist (s)
  4400. "Return tag alist associated to string S.
  4401. S is a value for TAGS keyword or produced with
  4402. `org-tag-alist-to-string'. Return value is an alist suitable for
  4403. `org-tag-alist' or `org-tag-persistent-alist'."
  4404. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4405. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  4406. "\\(?:(\\(.\\))\\)?\\'"))
  4407. alist group-flag)
  4408. (dolist (tokens lines (cdr (nreverse alist)))
  4409. (push '(:newline) alist)
  4410. (while tokens
  4411. (let ((token (pop tokens)))
  4412. (pcase token
  4413. ("{"
  4414. (push '(:startgroup) alist)
  4415. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4416. ("}"
  4417. (push '(:endgroup) alist)
  4418. (setq group-flag nil))
  4419. ("["
  4420. (push '(:startgrouptag) alist)
  4421. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4422. ("]"
  4423. (push '(:endgrouptag) alist)
  4424. (setq group-flag nil))
  4425. (":"
  4426. (push '(:grouptags) alist))
  4427. ((guard (string-match tag-re token))
  4428. (let ((tag (match-string 1 token))
  4429. (key (and (match-beginning 2)
  4430. (string-to-char (match-string 2 token)))))
  4431. ;; Push all tags in groups, no matter if they already
  4432. ;; appear somewhere else in the list.
  4433. (when (or group-flag (not (assoc tag alist)))
  4434. (push (cons tag key) alist))))))))))
  4435. (defun org-tag-alist-to-string (alist &optional skip-key)
  4436. "Return tag string associated to ALIST.
  4437. ALIST is an alist, as defined in `org-tag-alist' or
  4438. `org-tag-persistent-alist', or produced with
  4439. `org-tag-string-to-alist'.
  4440. Return value is a string suitable as a value for \"TAGS\"
  4441. keyword.
  4442. When optional argument SKIP-KEY is non-nil, skip selection keys
  4443. next to tags."
  4444. (mapconcat (lambda (token)
  4445. (pcase token
  4446. (`(:startgroup) "{")
  4447. (`(:endgroup) "}")
  4448. (`(:startgrouptag) "[")
  4449. (`(:endgrouptag) "]")
  4450. (`(:grouptags) ":")
  4451. (`(:newline) "\\n")
  4452. ((and
  4453. (guard (not skip-key))
  4454. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4455. (format "%s(%c)" tag key))
  4456. (`(,(and tag (pred stringp)) . ,_) tag)
  4457. (_ (user-error "Invalid tag token: %S" token))))
  4458. alist
  4459. " "))
  4460. (defun org-tag-alist-to-groups (alist)
  4461. "Return group alist from tag ALIST.
  4462. ALIST is an alist, as defined in `org-tag-alist' or
  4463. `org-tag-persistent-alist', or produced with
  4464. `org-tag-string-to-alist'. Return value is an alist following
  4465. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4466. a string, summarizing TAGS, as a list of strings."
  4467. (let (groups group-status current-group)
  4468. (dolist (token alist (nreverse groups))
  4469. (pcase token
  4470. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4471. (`(,(or :endgroup :endgrouptag))
  4472. (when (eq group-status 'append)
  4473. (push (nreverse current-group) groups))
  4474. (setq group-status nil current-group nil))
  4475. (`(:grouptags) (setq group-status 'append))
  4476. ((and `(,tag . ,_) (guard group-status))
  4477. (if (eq group-status 'append) (push tag current-group)
  4478. (setq current-group (list tag))))
  4479. (_ nil)))))
  4480. (defvar org--file-cache (make-hash-table :test #'equal)
  4481. "Hash table to store contents of files referenced via a URL.
  4482. This is the cache of file URLs read using `org-file-contents'.")
  4483. (defun org-reset-file-cache ()
  4484. "Reset the cache of files downloaded by `org-file-contents'."
  4485. (clrhash org--file-cache))
  4486. (defun org-file-url-p (file)
  4487. "Non-nil if FILE is a URL."
  4488. (require 'ffap)
  4489. (string-match-p ffap-url-regexp file))
  4490. (defun org-file-contents (file &optional noerror nocache)
  4491. "Return the contents of FILE, as a string.
  4492. FILE can be a file name or URL.
  4493. If FILE is a URL, download the contents. If the URL contents are
  4494. already cached in the `org--file-cache' hash table, the download step
  4495. is skipped.
  4496. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4497. from file or URL.
  4498. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4499. is available. This option applies only if FILE is a URL."
  4500. (let* ((is-url (org-file-url-p file))
  4501. (cache (and is-url
  4502. (not nocache)
  4503. (gethash file org--file-cache))))
  4504. (cond
  4505. (cache)
  4506. (is-url
  4507. (with-current-buffer (url-retrieve-synchronously file)
  4508. (goto-char (point-min))
  4509. ;; Move point to after the url-retrieve header.
  4510. (search-forward "\n\n" nil :move)
  4511. ;; Search for the success code only in the url-retrieve header.
  4512. (if (save-excursion
  4513. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4514. ;; Update the cache `org--file-cache' and return contents.
  4515. (puthash file
  4516. (buffer-substring-no-properties (point) (point-max))
  4517. org--file-cache)
  4518. (funcall (if noerror #'message #'user-error)
  4519. "Unable to fetch file from %S"
  4520. file))))
  4521. (t
  4522. (with-temp-buffer
  4523. (condition-case nil
  4524. (progn
  4525. (insert-file-contents file)
  4526. (buffer-string))
  4527. (file-error
  4528. (funcall (if noerror #'message #'user-error)
  4529. "Unable to read file %S"
  4530. file))))))))
  4531. (defun org-extract-log-state-settings (x)
  4532. "Extract the log state setting from a TODO keyword string.
  4533. This will extract info from a string like \"WAIT(w@/!)\"."
  4534. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4535. (let ((kw (match-string 1 x))
  4536. (log1 (and (match-end 3) (match-string 3 x)))
  4537. (log2 (and (match-end 4) (match-string 4 x))))
  4538. (and (or log1 log2)
  4539. (list kw
  4540. (and log1 (if (equal log1 "!") 'time 'note))
  4541. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4542. (defun org-remove-keyword-keys (list)
  4543. "Remove a pair of parenthesis at the end of each string in LIST."
  4544. (mapcar (lambda (x)
  4545. (if (string-match "(.*)$" x)
  4546. (substring x 0 (match-beginning 0))
  4547. x))
  4548. list))
  4549. (defun org-assign-fast-keys (alist)
  4550. "Assign fast keys to a keyword-key alist.
  4551. Respect keys that are already there."
  4552. (let (new e (alt ?0))
  4553. (while (setq e (pop alist))
  4554. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4555. (cdr e)) ;; Key already assigned.
  4556. (push e new)
  4557. (let ((clist (string-to-list (downcase (car e))))
  4558. (used (append new alist)))
  4559. (when (= (car clist) ?@)
  4560. (pop clist))
  4561. (while (and clist (rassoc (car clist) used))
  4562. (pop clist))
  4563. (unless clist
  4564. (while (rassoc alt used)
  4565. (cl-incf alt)))
  4566. (push (cons (car e) (or (car clist) alt)) new))))
  4567. (nreverse new)))
  4568. ;;; Some variables used in various places
  4569. (defvar org-window-configuration nil
  4570. "Used in various places to store a window configuration.")
  4571. (defvar org-selected-window nil
  4572. "Used in various places to store a window configuration.")
  4573. (defvar org-finish-function nil
  4574. "Function to be called when `C-c C-c' is used.
  4575. This is for getting out of special buffers like capture.")
  4576. (defvar org-last-state)
  4577. ;; Defined somewhere in this file, but used before definition.
  4578. (defvar org-entities) ;; defined in org-entities.el
  4579. (defvar org-struct-menu)
  4580. (defvar org-org-menu)
  4581. (defvar org-tbl-menu)
  4582. ;;;; Define the Org mode
  4583. ;; We use a before-change function to check if a table might need
  4584. ;; an update.
  4585. (defvar org-table-may-need-update t
  4586. "Indicates that a table might need an update.
  4587. This variable is set by `org-before-change-function'.
  4588. `org-table-align' sets it back to nil.")
  4589. (defun org-before-change-function (_beg _end)
  4590. "Every change indicates that a table might need an update."
  4591. (setq org-table-may-need-update t))
  4592. (defvar org-mode-map)
  4593. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4594. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4595. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4596. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4597. (defvar org-table-buffer-is-an nil)
  4598. (defvar bidi-paragraph-direction)
  4599. (defvar buffer-face-mode-face)
  4600. (require 'outline)
  4601. ;; Other stuff we need.
  4602. (require 'time-date)
  4603. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4604. (require 'easymenu)
  4605. (autoload 'easy-menu-add "easymenu")
  4606. (require 'overlay)
  4607. ;; (require 'org-macs) moved higher up in the file before it is first used
  4608. (require 'org-entities)
  4609. ;; (require 'org-compat) moved higher up in the file before it is first used
  4610. (require 'org-faces)
  4611. (require 'org-list)
  4612. (require 'org-pcomplete)
  4613. (require 'org-src)
  4614. (require 'org-footnote)
  4615. (require 'org-macro)
  4616. ;; babel
  4617. (require 'ob)
  4618. ;;;###autoload
  4619. (define-derived-mode org-mode outline-mode "Org"
  4620. "Outline-based notes management and organizer, alias
  4621. \"Carsten's outline-mode for keeping track of everything.\"
  4622. Org mode develops organizational tasks around a NOTES file which
  4623. contains information about projects as plain text. Org mode is
  4624. implemented on top of Outline mode, which is ideal to keep the content
  4625. of large files well structured. It supports ToDo items, deadlines and
  4626. time stamps, which magically appear in the diary listing of the Emacs
  4627. calendar. Tables are easily created with a built-in table editor.
  4628. Plain text URL-like links connect to websites, emails (VM), Usenet
  4629. messages (Gnus), BBDB entries, and any files related to the project.
  4630. For printing and sharing of notes, an Org file (or a part of it)
  4631. can be exported as a structured ASCII or HTML file.
  4632. The following commands are available:
  4633. \\{org-mode-map}"
  4634. (org-load-modules-maybe)
  4635. (org-install-agenda-files-menu)
  4636. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4637. (add-to-invisibility-spec '(org-hide-block . t))
  4638. (add-to-invisibility-spec '(org-hide-drawer . t))
  4639. (setq-local outline-regexp org-outline-regexp)
  4640. (setq-local outline-level 'org-outline-level)
  4641. (setq bidi-paragraph-direction 'left-to-right)
  4642. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4643. (unless org-display-table
  4644. (setq org-display-table (make-display-table)))
  4645. (set-display-table-slot
  4646. org-display-table 4
  4647. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4648. org-ellipsis)))
  4649. (setq buffer-display-table org-display-table))
  4650. (org-set-regexps-and-options)
  4651. (org-set-font-lock-defaults)
  4652. (when (and org-tag-faces (not org-tags-special-faces-re))
  4653. ;; tag faces set outside customize.... force initialization.
  4654. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4655. ;; Calc embedded
  4656. (setq-local calc-embedded-open-mode "# ")
  4657. ;; Modify a few syntax entries
  4658. (modify-syntax-entry ?\" "\"")
  4659. (modify-syntax-entry ?\\ "_")
  4660. (modify-syntax-entry ?~ "_")
  4661. (modify-syntax-entry ?< "(>")
  4662. (modify-syntax-entry ?> ")<")
  4663. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4664. ;; Activate before-change-function
  4665. (setq-local org-table-may-need-update t)
  4666. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4667. ;; Check for running clock before killing a buffer
  4668. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4669. ;; Initialize macros templates.
  4670. (org-macro-initialize-templates)
  4671. ;; Initialize radio targets.
  4672. (org-update-radio-target-regexp)
  4673. ;; Indentation.
  4674. (setq-local indent-line-function 'org-indent-line)
  4675. (setq-local indent-region-function 'org-indent-region)
  4676. ;; Filling and auto-filling.
  4677. (org-setup-filling)
  4678. ;; Comments.
  4679. (org-setup-comments-handling)
  4680. ;; Initialize cache.
  4681. (org-element-cache-reset)
  4682. ;; Beginning/end of defun
  4683. (setq-local beginning-of-defun-function 'org-backward-element)
  4684. (setq-local end-of-defun-function
  4685. (lambda ()
  4686. (if (not (org-at-heading-p))
  4687. (org-forward-element)
  4688. (org-forward-element)
  4689. (forward-char -1))))
  4690. ;; Next error for sparse trees
  4691. (setq-local next-error-function 'org-occur-next-match)
  4692. ;; Make commit log messages from Org documents easier.
  4693. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4694. ;; Make sure dependence stuff works reliably, even for users who set it
  4695. ;; too late :-(
  4696. (if org-enforce-todo-dependencies
  4697. (add-hook 'org-blocker-hook
  4698. 'org-block-todo-from-children-or-siblings-or-parent)
  4699. (remove-hook 'org-blocker-hook
  4700. 'org-block-todo-from-children-or-siblings-or-parent))
  4701. (if org-enforce-todo-checkbox-dependencies
  4702. (add-hook 'org-blocker-hook
  4703. 'org-block-todo-from-checkboxes)
  4704. (remove-hook 'org-blocker-hook
  4705. 'org-block-todo-from-checkboxes))
  4706. ;; Align options lines
  4707. (setq-local
  4708. align-mode-rules-list
  4709. '((org-in-buffer-settings
  4710. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4711. (modes . '(org-mode)))))
  4712. ;; Make isearch reveal context
  4713. (setq-local outline-isearch-open-invisible-function
  4714. (lambda (&rest _) (org-show-context 'isearch)))
  4715. ;; Setup the pcomplete hooks
  4716. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4717. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4718. (setq-local pcomplete-default-completion-function 'ignore)
  4719. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4720. (setq-local pcomplete-termination-string "")
  4721. (setq-local buffer-face-mode-face 'org-default)
  4722. ;; If empty file that did not turn on Org mode automatically, make
  4723. ;; it to.
  4724. (when (and org-insert-mode-line-in-empty-file
  4725. (called-interactively-p 'any)
  4726. (= (point-min) (point-max)))
  4727. (insert "# -*- mode: org -*-\n\n"))
  4728. (unless org-inhibit-startup
  4729. (org-unmodified
  4730. (when org-startup-with-beamer-mode (org-beamer-mode))
  4731. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4732. (org-table-map-tables
  4733. (cond ((and org-startup-align-all-tables
  4734. org-startup-shrink-all-tables)
  4735. (lambda () (org-table-align) (org-table-shrink)))
  4736. (org-startup-align-all-tables #'org-table-align)
  4737. (t #'org-table-shrink))
  4738. t))
  4739. (when org-startup-with-inline-images (org-display-inline-images))
  4740. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4741. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4742. (when org-startup-truncated (setq truncate-lines t))
  4743. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4744. ;; Try to set `org-hide' face correctly.
  4745. (let ((foreground (org-find-invisible-foreground)))
  4746. (when foreground
  4747. (set-face-foreground 'org-hide foreground))))
  4748. ;; Update `customize-package-emacs-version-alist'
  4749. (add-to-list 'customize-package-emacs-version-alist
  4750. '(Org ("8.0" . "24.4")
  4751. ("8.1" . "24.4")
  4752. ("8.2" . "24.4")
  4753. ("8.2.7" . "24.4")
  4754. ("8.3" . "26.1")
  4755. ("9.0" . "26.1")
  4756. ("9.1" . "26.1")
  4757. ("9.2" . "27.1")))
  4758. (defvar org-mode-transpose-word-syntax-table
  4759. (let ((st (make-syntax-table text-mode-syntax-table)))
  4760. (dolist (c org-emphasis-alist st)
  4761. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4762. (when (fboundp 'abbrev-table-put)
  4763. (abbrev-table-put org-mode-abbrev-table
  4764. :parents (list text-mode-abbrev-table)))
  4765. (defun org-find-invisible-foreground ()
  4766. (let ((candidates (remove
  4767. "unspecified-bg"
  4768. (nconc
  4769. (list (face-background 'default)
  4770. (face-background 'org-default))
  4771. (mapcar
  4772. (lambda (alist)
  4773. (when (boundp alist)
  4774. (cdr (assq 'background-color (symbol-value alist)))))
  4775. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4776. (list (face-foreground 'org-hide))))))
  4777. (car (remove nil candidates))))
  4778. (defun org-current-time (&optional rounding-minutes past)
  4779. "Current time, possibly rounded to ROUNDING-MINUTES.
  4780. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4781. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4782. the rounding returns a past time."
  4783. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4784. (car org-time-stamp-rounding-minutes)))
  4785. (time (decode-time)) res)
  4786. (if (< r 1)
  4787. (current-time)
  4788. (setq res
  4789. (apply 'encode-time
  4790. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4791. (nthcdr 2 time))))
  4792. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4793. (seconds-to-time (- (float-time res) (* r 60)))
  4794. res))))
  4795. (defun org-today ()
  4796. "Return today date, considering `org-extend-today-until'."
  4797. (time-to-days
  4798. (time-subtract (current-time)
  4799. (list 0 (* 3600 org-extend-today-until) 0))))
  4800. ;;;; Font-Lock stuff, including the activators
  4801. (require 'font-lock)
  4802. (defconst org-non-link-chars "]\t\n\r<>")
  4803. (defvar org-link-types-re nil
  4804. "Matches a link that has a url-like prefix like \"http:\"")
  4805. (defvar org-link-re-with-space nil
  4806. "Matches a link with spaces, optional angular brackets around it.")
  4807. (defvar org-link-re-with-space2 nil
  4808. "Matches a link with spaces, optional angular brackets around it.")
  4809. (defvar org-link-re-with-space3 nil
  4810. "Matches a link with spaces, only for internal part in bracket links.")
  4811. (defvar org-angle-link-re nil
  4812. "Matches link with angular brackets, spaces are allowed.")
  4813. (defvar org-plain-link-re nil
  4814. "Matches plain link, without spaces.")
  4815. (defvar org-bracket-link-regexp nil
  4816. "Matches a link in double brackets.")
  4817. (defvar org-bracket-link-analytic-regexp nil
  4818. "Regular expression used to analyze links.
  4819. Here is what the match groups contain after a match:
  4820. 1: http:
  4821. 2: http
  4822. 3: path
  4823. 4: [desc]
  4824. 5: desc")
  4825. (defvar org-bracket-link-analytic-regexp++ nil
  4826. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4827. (defvar org-any-link-re nil
  4828. "Regular expression matching any link.")
  4829. (defconst org-match-sexp-depth 3
  4830. "Number of stacked braces for sub/superscript matching.")
  4831. (defun org-create-multibrace-regexp (left right n)
  4832. "Create a regular expression which will match a balanced sexp.
  4833. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4834. as single character strings.
  4835. The regexp returned will match the entire expression including the
  4836. delimiters. It will also define a single group which contains the
  4837. match except for the outermost delimiters. The maximum depth of
  4838. stacked delimiters is N. Escaping delimiters is not possible."
  4839. (let* ((nothing (concat "[^" left right "]*?"))
  4840. (or "\\|")
  4841. (re nothing)
  4842. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4843. (while (> n 1)
  4844. (setq n (1- n)
  4845. re (concat re or next)
  4846. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4847. (concat left "\\(" re "\\)" right)))
  4848. (defconst org-match-substring-regexp
  4849. (concat
  4850. "\\(\\S-\\)\\([_^]\\)\\("
  4851. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4852. "\\|"
  4853. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4854. "\\|"
  4855. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4856. "The regular expression matching a sub- or superscript.")
  4857. (defconst org-match-substring-with-braces-regexp
  4858. (concat
  4859. "\\(\\S-\\)\\([_^]\\)"
  4860. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4861. "The regular expression matching a sub- or superscript, forcing braces.")
  4862. (defun org-make-link-regexps ()
  4863. "Update the link regular expressions.
  4864. This should be called after the variable `org-link-parameters' has changed."
  4865. (let ((types-re (regexp-opt (org-link-types) t)))
  4866. (setq org-link-types-re
  4867. (concat "\\`" types-re ":")
  4868. org-link-re-with-space
  4869. (concat "<?" types-re ":"
  4870. "\\([^" org-non-link-chars " ]"
  4871. "[^" org-non-link-chars "]*"
  4872. "[^" org-non-link-chars " ]\\)>?")
  4873. org-link-re-with-space2
  4874. (concat "<?" types-re ":"
  4875. "\\([^" org-non-link-chars " ]"
  4876. "[^\t\n\r]*"
  4877. "[^" org-non-link-chars " ]\\)>?")
  4878. org-link-re-with-space3
  4879. (concat "<?" types-re ":"
  4880. "\\([^" org-non-link-chars " ]"
  4881. "[^\t\n\r]*\\)")
  4882. org-angle-link-re
  4883. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  4884. types-re)
  4885. org-plain-link-re
  4886. (concat
  4887. "\\<" types-re ":"
  4888. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  4889. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  4890. org-bracket-link-regexp
  4891. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  4892. org-bracket-link-analytic-regexp
  4893. (concat
  4894. "\\[\\["
  4895. "\\(" types-re ":\\)?"
  4896. "\\([^]]+\\)"
  4897. "\\]"
  4898. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4899. "\\]")
  4900. org-bracket-link-analytic-regexp++
  4901. (concat
  4902. "\\[\\["
  4903. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  4904. "\\([^]]+\\)"
  4905. "\\]"
  4906. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4907. "\\]")
  4908. org-any-link-re
  4909. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  4910. org-angle-link-re "\\)\\|\\("
  4911. org-plain-link-re "\\)"))))
  4912. (org-make-link-regexps)
  4913. (defvar org-emph-face nil)
  4914. (defun org-do-emphasis-faces (limit)
  4915. "Run through the buffer and emphasize strings."
  4916. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4917. (car org-emphasis-regexp-components))))
  4918. (catch :exit
  4919. (while (re-search-forward quick-re limit t)
  4920. (let* ((marker (match-string 2))
  4921. (verbatim? (member marker '("~" "="))))
  4922. (when (save-excursion
  4923. (goto-char (match-beginning 0))
  4924. (and
  4925. ;; Do not match table hlines.
  4926. (not (and (equal marker "+")
  4927. (org-match-line
  4928. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4929. ;; Do not match headline stars. Do not consider
  4930. ;; stars of a headline as closing marker for bold
  4931. ;; markup either.
  4932. (not (and (equal marker "*")
  4933. (save-excursion
  4934. (forward-char)
  4935. (skip-chars-backward "*")
  4936. (looking-at-p org-outline-regexp-bol))))
  4937. ;; Match full emphasis markup regexp.
  4938. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4939. ;; Do not span over paragraph boundaries.
  4940. (not (string-match-p org-element-paragraph-separate
  4941. (match-string 2)))
  4942. ;; Do not span over cells in table rows.
  4943. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4944. (string-match-p "|" (match-string 4))))))
  4945. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  4946. (font-lock-prepend-text-property
  4947. (match-beginning 2) (match-end 2) 'face face)
  4948. (when verbatim?
  4949. (org-remove-flyspell-overlays-in
  4950. (match-beginning 0) (match-end 0))
  4951. (remove-text-properties (match-beginning 2) (match-end 2)
  4952. '(display t invisible t intangible t)))
  4953. (add-text-properties (match-beginning 2) (match-end 2)
  4954. '(font-lock-multiline t org-emphasis t))
  4955. (when org-hide-emphasis-markers
  4956. (add-text-properties (match-end 4) (match-beginning 5)
  4957. '(invisible org-link))
  4958. (add-text-properties (match-beginning 3) (match-end 3)
  4959. '(invisible org-link)))
  4960. (throw :exit t))))))))
  4961. (defun org-emphasize (&optional char)
  4962. "Insert or change an emphasis, i.e. a font like bold or italic.
  4963. If there is an active region, change that region to a new emphasis.
  4964. If there is no region, just insert the marker characters and position
  4965. the cursor between them.
  4966. CHAR should be the marker character. If it is a space, it means to
  4967. remove the emphasis of the selected region.
  4968. If CHAR is not given (for example in an interactive call) it will be
  4969. prompted for."
  4970. (interactive)
  4971. (let ((erc org-emphasis-regexp-components)
  4972. (string "") beg end move s)
  4973. (if (org-region-active-p)
  4974. (setq beg (region-beginning)
  4975. end (region-end)
  4976. string (buffer-substring beg end))
  4977. (setq move t))
  4978. (unless char
  4979. (message "Emphasis marker or tag: [%s]"
  4980. (mapconcat #'car org-emphasis-alist ""))
  4981. (setq char (read-char-exclusive)))
  4982. (if (equal char ?\s)
  4983. (setq s ""
  4984. move nil)
  4985. (unless (assoc (char-to-string char) org-emphasis-alist)
  4986. (user-error "No such emphasis marker: \"%c\"" char))
  4987. (setq s (char-to-string char)))
  4988. (while (and (> (length string) 1)
  4989. (equal (substring string 0 1) (substring string -1))
  4990. (assoc (substring string 0 1) org-emphasis-alist))
  4991. (setq string (substring string 1 -1)))
  4992. (setq string (concat s string s))
  4993. (when beg (delete-region beg end))
  4994. (unless (or (bolp)
  4995. (string-match (concat "[" (nth 0 erc) "\n]")
  4996. (char-to-string (char-before (point)))))
  4997. (insert " "))
  4998. (unless (or (eobp)
  4999. (string-match (concat "[" (nth 1 erc) "\n]")
  5000. (char-to-string (char-after (point)))))
  5001. (insert " ") (backward-char 1))
  5002. (insert string)
  5003. (and move (backward-char 1))))
  5004. (defconst org-nonsticky-props
  5005. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5006. (defsubst org-rear-nonsticky-at (pos)
  5007. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5008. (defun org-activate-links (limit)
  5009. "Add link properties to links.
  5010. This includes angle, plain, and bracket links."
  5011. (catch :exit
  5012. (while (re-search-forward org-any-link-re limit t)
  5013. (let* ((start (match-beginning 0))
  5014. (end (match-end 0))
  5015. (style (cond ((eq ?< (char-after start)) 'angle)
  5016. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5017. (t 'plain))))
  5018. (when (and (memq style org-highlight-links)
  5019. ;; Do not confuse plain links with tags.
  5020. (not (and (eq style 'plain)
  5021. (let ((face (get-text-property
  5022. (max (1- start) (point-min)) 'face)))
  5023. (if (consp face) (memq 'org-tag face)
  5024. (eq 'org-tag face))))))
  5025. (let* ((link-object (save-excursion
  5026. (goto-char start)
  5027. (save-match-data (org-element-link-parser))))
  5028. (link (org-element-property :raw-link link-object))
  5029. (type (org-element-property :type link-object))
  5030. (path (org-element-property :path link-object))
  5031. (properties ;for link's visible part
  5032. (list
  5033. 'face (pcase (org-link-get-parameter type :face)
  5034. ((and (pred functionp) face) (funcall face path))
  5035. ((and (pred facep) face) face)
  5036. ((and (pred consp) face) face) ;anonymous
  5037. (_ 'org-link))
  5038. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5039. 'highlight)
  5040. 'keymap (or (org-link-get-parameter type :keymap)
  5041. org-mouse-map)
  5042. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5043. ((and (pred stringp) echo) echo)
  5044. ((and (pred functionp) echo) echo)
  5045. (_ (concat "LINK: " link)))
  5046. 'htmlize-link (pcase (org-link-get-parameter type
  5047. :htmlize-link)
  5048. ((and (pred functionp) f) (funcall f))
  5049. (_ `(:uri ,link)))
  5050. 'font-lock-multiline t)))
  5051. (org-remove-flyspell-overlays-in start end)
  5052. (org-rear-nonsticky-at end)
  5053. (if (not (eq 'bracket style))
  5054. (add-text-properties start end properties)
  5055. ;; Handle invisible parts in bracket links.
  5056. (remove-text-properties start end '(invisible nil))
  5057. (let ((hidden
  5058. (append `(invisible
  5059. ,(or (org-link-get-parameter type :display)
  5060. 'org-link))
  5061. properties))
  5062. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5063. (visible-end (or (match-end 4) (match-end 2))))
  5064. (add-text-properties start visible-start hidden)
  5065. (add-text-properties visible-start visible-end properties)
  5066. (add-text-properties visible-end end hidden)
  5067. (org-rear-nonsticky-at visible-start)
  5068. (org-rear-nonsticky-at visible-end)))
  5069. (let ((f (org-link-get-parameter type :activate-func)))
  5070. (when (functionp f)
  5071. (funcall f start end path (eq style 'bracket))))
  5072. (throw :exit t))))) ;signal success
  5073. nil))
  5074. (defun org-activate-code (limit)
  5075. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5076. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5077. (remove-text-properties (match-beginning 0) (match-end 0)
  5078. '(display t invisible t intangible t))
  5079. t))
  5080. (defcustom org-src-fontify-natively t
  5081. "When non-nil, fontify code in code blocks.
  5082. See also the `org-block' face."
  5083. :type 'boolean
  5084. :version "26.1"
  5085. :package-version '(Org . "8.3")
  5086. :group 'org-appearance
  5087. :group 'org-babel)
  5088. (defcustom org-allow-promoting-top-level-subtree nil
  5089. "When non-nil, allow promoting a top level subtree.
  5090. The leading star of the top level headline will be replaced
  5091. by a #."
  5092. :type 'boolean
  5093. :version "24.1"
  5094. :group 'org-appearance)
  5095. (defun org-fontify-meta-lines-and-blocks (limit)
  5096. (condition-case nil
  5097. (org-fontify-meta-lines-and-blocks-1 limit)
  5098. (error (message "Org mode fontification error in %S at %d"
  5099. (current-buffer)
  5100. (line-number-at-pos)))))
  5101. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5102. "Fontify #+ lines and blocks."
  5103. (let ((case-fold-search t))
  5104. (when (re-search-forward
  5105. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5106. limit t)
  5107. (let ((beg (match-beginning 0))
  5108. (block-start (match-end 0))
  5109. (block-end nil)
  5110. (lang (match-string 7))
  5111. (beg1 (line-beginning-position 2))
  5112. (dc1 (downcase (match-string 2)))
  5113. (dc3 (downcase (match-string 3)))
  5114. end end1 quoting block-type)
  5115. (cond
  5116. ((and (match-end 4) (equal dc3 "+begin"))
  5117. ;; Truly a block
  5118. (setq block-type (downcase (match-string 5))
  5119. quoting (member block-type org-protecting-blocks))
  5120. (when (re-search-forward
  5121. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5122. nil t) ;; on purpose, we look further than LIMIT
  5123. (setq end (min (point-max) (match-end 0))
  5124. end1 (min (point-max) (1- (match-beginning 0))))
  5125. (setq block-end (match-beginning 0))
  5126. (when quoting
  5127. (org-remove-flyspell-overlays-in beg1 end1)
  5128. (remove-text-properties beg end
  5129. '(display t invisible t intangible t)))
  5130. (add-text-properties
  5131. beg end '(font-lock-fontified t font-lock-multiline t))
  5132. (add-text-properties beg beg1 '(face org-meta-line))
  5133. (org-remove-flyspell-overlays-in beg beg1)
  5134. (add-text-properties ; For end_src
  5135. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5136. (org-remove-flyspell-overlays-in end1 end)
  5137. (cond
  5138. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5139. (org-src-font-lock-fontify-block lang block-start block-end)
  5140. (add-text-properties beg1 block-end '(src-block t)))
  5141. (quoting
  5142. (add-text-properties beg1 (min (point-max) (1+ end1))
  5143. (list 'face
  5144. (list :inherit
  5145. (let ((face-name
  5146. (intern (format "org-block-%s" lang))))
  5147. (append (and (facep face-name) (list face-name))
  5148. '(org-block))))))) ; end of source block
  5149. ((not org-fontify-quote-and-verse-blocks))
  5150. ((string= block-type "quote")
  5151. (add-face-text-property
  5152. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5153. ((string= block-type "verse")
  5154. (add-face-text-property
  5155. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5156. (add-text-properties beg beg1 '(face org-block-begin-line))
  5157. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5158. '(face org-block-end-line))
  5159. t))
  5160. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5161. (org-remove-flyspell-overlays-in
  5162. (match-beginning 0)
  5163. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5164. (add-text-properties
  5165. beg (match-end 3)
  5166. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5167. '(font-lock-fontified t invisible t)
  5168. '(font-lock-fontified t face org-document-info-keyword)))
  5169. (add-text-properties
  5170. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5171. (if (string-equal dc1 "+title:")
  5172. '(font-lock-fontified t face org-document-title)
  5173. '(font-lock-fontified t face org-document-info))))
  5174. ((string-prefix-p "+caption" dc1)
  5175. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5176. (remove-text-properties (match-beginning 0) (match-end 0)
  5177. '(display t invisible t intangible t))
  5178. ;; Handle short captions.
  5179. (save-excursion
  5180. (beginning-of-line)
  5181. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5182. (add-text-properties (line-beginning-position) (match-end 1)
  5183. '(font-lock-fontified t face org-meta-line))
  5184. (add-text-properties (match-end 0) (line-end-position)
  5185. '(font-lock-fontified t face org-block))
  5186. t)
  5187. ((member dc3 '(" " ""))
  5188. (org-remove-flyspell-overlays-in beg (match-end 0))
  5189. (add-text-properties
  5190. beg (match-end 0)
  5191. '(font-lock-fontified t face font-lock-comment-face)))
  5192. (t ;; just any other in-buffer setting, but not indented
  5193. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5194. (remove-text-properties (match-beginning 0) (match-end 0)
  5195. '(display t invisible t intangible t))
  5196. (add-text-properties beg (match-end 0)
  5197. '(font-lock-fontified t face org-meta-line))
  5198. t))))))
  5199. (defun org-fontify-drawers (limit)
  5200. "Fontify drawers."
  5201. (when (re-search-forward org-drawer-regexp limit t)
  5202. (add-text-properties
  5203. (match-beginning 0) (match-end 0)
  5204. '(font-lock-fontified t face org-special-keyword))
  5205. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5206. t))
  5207. (defun org-fontify-macros (limit)
  5208. "Fontify macros."
  5209. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  5210. (let ((begin (match-beginning 0))
  5211. (opening-end (match-beginning 1)))
  5212. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  5213. (match-string 1))
  5214. (let ((end (match-end 1))
  5215. (closing-start (match-beginning 1)))
  5216. (add-text-properties
  5217. begin end
  5218. '(font-lock-multiline t font-lock-fontified t face org-macro))
  5219. (org-remove-flyspell-overlays-in begin end)
  5220. (when org-hide-macro-markers
  5221. (add-text-properties begin opening-end '(invisible t))
  5222. (add-text-properties closing-start end '(invisible t)))
  5223. t)))))
  5224. (defun org-fontify-extend-region (beg end _old-len)
  5225. (let ((begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  5226. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  5227. (extend (lambda (r1 r2 dir)
  5228. (let ((re (replace-regexp-in-string "\\(begin\\|end\\)" r1
  5229. (replace-regexp-in-string "[][]" r2
  5230. (match-string-no-properties 0)))))
  5231. (re-search-forward (regexp-quote re) nil t dir)))))
  5232. (save-match-data
  5233. (save-excursion
  5234. (goto-char beg)
  5235. (back-to-indentation)
  5236. (cond ((looking-at end-re)
  5237. (cons (or (funcall extend "begin" "[" -1) beg) end))
  5238. ((looking-at begin-re)
  5239. (cons beg (or (funcall extend "end" "]" 1) end)))
  5240. (t (cons beg end)))))))
  5241. (defun org-activate-footnote-links (limit)
  5242. "Add text properties for footnotes."
  5243. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5244. (when fn
  5245. (let* ((beg (nth 1 fn))
  5246. (end (nth 2 fn))
  5247. (label (car fn))
  5248. (referencep (/= (line-beginning-position) beg)))
  5249. (when (and referencep (nth 3 fn))
  5250. (save-excursion
  5251. (goto-char beg)
  5252. (search-forward (or label "fn:"))
  5253. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5254. (add-text-properties beg end
  5255. (list 'mouse-face 'highlight
  5256. 'keymap org-mouse-map
  5257. 'help-echo
  5258. (if referencep "Footnote reference"
  5259. "Footnote definition")
  5260. 'font-lock-fontified t
  5261. 'font-lock-multiline t
  5262. 'face 'org-footnote))))))
  5263. (defun org-activate-dates (limit)
  5264. "Add text properties for dates."
  5265. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5266. (not (equal (char-before (match-beginning 0)) 91)))
  5267. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5268. (add-text-properties (match-beginning 0) (match-end 0)
  5269. (list 'mouse-face 'highlight
  5270. 'keymap org-mouse-map))
  5271. (org-rear-nonsticky-at (match-end 0))
  5272. (when org-display-custom-times
  5273. ;; If it's a date range, activate custom time for second date.
  5274. (when (match-end 3)
  5275. (org-display-custom-time (match-beginning 3) (match-end 3)))
  5276. (org-display-custom-time (match-beginning 1) (match-end 1)))
  5277. t))
  5278. (defvar-local org-target-link-regexp nil
  5279. "Regular expression matching radio targets in plain text.")
  5280. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5281. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5282. border border border))
  5283. "Regular expression matching a link target.")
  5284. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5285. "Regular expression matching a radio target.")
  5286. (defconst org-any-target-regexp
  5287. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5288. "Regular expression matching any target.")
  5289. (defun org-activate-target-links (limit)
  5290. "Add text properties for target matches."
  5291. (when org-target-link-regexp
  5292. (let ((case-fold-search t))
  5293. (when (re-search-forward org-target-link-regexp limit t)
  5294. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5295. (add-text-properties (match-beginning 1) (match-end 1)
  5296. (list 'mouse-face 'highlight
  5297. 'keymap org-mouse-map
  5298. 'help-echo "Radio target link"
  5299. 'org-linked-text t))
  5300. (org-rear-nonsticky-at (match-end 1))
  5301. t))))
  5302. (defun org-update-radio-target-regexp ()
  5303. "Find all radio targets in this file and update the regular expression.
  5304. Also refresh fontification if needed."
  5305. (interactive)
  5306. (let ((old-regexp org-target-link-regexp)
  5307. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5308. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5309. (targets
  5310. (org-with-wide-buffer
  5311. (goto-char (point-min))
  5312. (let (rtn)
  5313. (while (re-search-forward org-radio-target-regexp nil t)
  5314. ;; Make sure point is really within the object.
  5315. (backward-char)
  5316. (let ((obj (org-element-context)))
  5317. (when (eq (org-element-type obj) 'radio-target)
  5318. (cl-pushnew (org-element-property :value obj) rtn
  5319. :test #'equal))))
  5320. rtn))))
  5321. (setq org-target-link-regexp
  5322. (and targets
  5323. (concat before-re
  5324. (mapconcat
  5325. (lambda (x)
  5326. (replace-regexp-in-string
  5327. " +" "\\s-+" (regexp-quote x) t t))
  5328. targets
  5329. "\\|")
  5330. after-re)))
  5331. (unless (equal old-regexp org-target-link-regexp)
  5332. ;; Clean-up cache.
  5333. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5334. ((not org-target-link-regexp) old-regexp)
  5335. (t
  5336. (concat before-re
  5337. (mapconcat
  5338. (lambda (re)
  5339. (substring re (length before-re)
  5340. (- (length after-re))))
  5341. (list old-regexp org-target-link-regexp)
  5342. "\\|")
  5343. after-re)))))
  5344. (org-with-wide-buffer
  5345. (goto-char (point-min))
  5346. (while (re-search-forward regexp nil t)
  5347. (org-element-cache-refresh (match-beginning 1)))))
  5348. ;; Re fontify buffer.
  5349. (when (memq 'radio org-highlight-links)
  5350. (org-restart-font-lock)))))
  5351. (defvar org-latex-and-related-regexp nil
  5352. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5353. (defun org-compute-latex-and-related-regexp ()
  5354. "Compute regular expression for LaTeX, entities and sub/superscript.
  5355. Result depends on variable `org-highlight-latex-and-related'."
  5356. (let ((re-sub
  5357. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5358. ((eq org-use-sub-superscripts '{})
  5359. (list org-match-substring-with-braces-regexp))
  5360. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5361. (re-latex
  5362. (when (memq 'latex org-highlight-latex-and-related)
  5363. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5364. (delq nil
  5365. (mapcar (lambda (x)
  5366. (and (member (car x) matchers) (nth 1 x)))
  5367. org-latex-regexps)))))
  5368. (re-entities
  5369. (when (memq 'entities org-highlight-latex-and-related)
  5370. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  5371. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  5372. (setq-local org-latex-and-related-regexp
  5373. (mapconcat #'identity
  5374. (append re-latex re-entities re-sub)
  5375. "\\|"))))
  5376. (defun org-do-latex-and-related (_limit)
  5377. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5378. Stop at first highlighted object, if any. Return t if some
  5379. highlighting was done, nil otherwise."
  5380. (when (org-string-nw-p org-latex-and-related-regexp)
  5381. (catch 'found
  5382. (while (re-search-forward org-latex-and-related-regexp
  5383. nil t) ;; on purpose, we ignore LIMIT
  5384. (unless (cl-some (lambda (f) (memq f '(org-code org-verbatim underline
  5385. org-special-keyword)))
  5386. (save-excursion
  5387. (goto-char (1+ (match-beginning 0)))
  5388. (face-at-point nil t)))
  5389. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5390. '(?_ ?^))
  5391. 1
  5392. 0)))
  5393. (font-lock-prepend-text-property
  5394. (+ offset (match-beginning 0)) (match-end 0)
  5395. 'face 'org-latex-and-related)
  5396. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5397. '(font-lock-multiline t)))
  5398. (throw 'found t)))
  5399. nil)))
  5400. (defun org-restart-font-lock ()
  5401. "Restart `font-lock-mode', to force refontification."
  5402. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5403. (font-lock-mode -1)
  5404. (font-lock-mode 1)))
  5405. (defun org-activate-tags (limit)
  5406. (when (re-search-forward org-tag-line-re limit t)
  5407. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5408. (add-text-properties (match-beginning 1) (match-end 1)
  5409. (list 'mouse-face 'highlight
  5410. 'keymap org-mouse-map))
  5411. (org-rear-nonsticky-at (match-end 1))
  5412. t))
  5413. (defun org-outline-level ()
  5414. "Compute the outline level of the heading at point.
  5415. If this is called at a normal headline, the level is the number
  5416. of stars. Use `org-reduced-level' to remove the effect of
  5417. `org-odd-levels'. Unlike to `org-current-level', this function
  5418. takes into consideration inlinetasks."
  5419. (org-with-wide-buffer
  5420. (end-of-line)
  5421. (if (re-search-backward org-outline-regexp-bol nil t)
  5422. (1- (- (match-end 0) (match-beginning 0)))
  5423. 0)))
  5424. (defvar org-font-lock-keywords nil)
  5425. (defsubst org-re-property (property &optional literal allow-null value)
  5426. "Return a regexp matching a PROPERTY line.
  5427. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5428. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5429. non-nil, match properties even without a value.
  5430. Match group 3 is set to the value when it exists. If there is no
  5431. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5432. With optional argument VALUE, match only property lines with
  5433. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5434. unless LITERAL is non-nil."
  5435. (concat
  5436. "^\\(?4:[ \t]*\\)"
  5437. (format "\\(?1::\\(?2:%s\\):\\)"
  5438. (if literal property (regexp-quote property)))
  5439. (cond (value
  5440. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5441. (if literal value (regexp-quote value))))
  5442. (allow-null
  5443. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5444. (t
  5445. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5446. (defconst org-property-re
  5447. (org-re-property "\\S-+" 'literal t)
  5448. "Regular expression matching a property line.
  5449. There are four matching groups:
  5450. 1: :PROPKEY: including the leading and trailing colon,
  5451. 2: PROPKEY without the leading and trailing colon,
  5452. 3: PROPVAL without leading or trailing spaces,
  5453. 4: the indentation of the current line,
  5454. 5: trailing whitespace.")
  5455. (defvar org-font-lock-hook nil
  5456. "Functions to be called for special font lock stuff.")
  5457. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5458. (defvar org-font-lock-set-keywords-hook nil
  5459. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5460. This is called after `org-font-lock-extra-keywords' is defined, but before
  5461. it is installed to be used by font lock. This can be useful if something
  5462. needs to be inserted at a specific position in the font-lock sequence.")
  5463. (defun org-font-lock-hook (limit)
  5464. "Run `org-font-lock-hook' within LIMIT."
  5465. (run-hook-with-args 'org-font-lock-hook limit))
  5466. (defun org-set-font-lock-defaults ()
  5467. "Set font lock defaults for the current buffer."
  5468. (let* ((em org-fontify-emphasized-text)
  5469. (lk org-highlight-links)
  5470. (org-font-lock-extra-keywords
  5471. (list
  5472. ;; Call the hook
  5473. '(org-font-lock-hook)
  5474. ;; Headlines
  5475. `(,(if org-fontify-whole-heading-line
  5476. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5477. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5478. (1 (org-get-level-face 1))
  5479. (2 (org-get-level-face 2))
  5480. (3 (org-get-level-face 3)))
  5481. ;; Table lines
  5482. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5483. (1 'org-table t))
  5484. ;; Table internals
  5485. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5486. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5487. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5488. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5489. ;; Drawers
  5490. '(org-fontify-drawers)
  5491. ;; Properties
  5492. (list org-property-re
  5493. '(1 'org-special-keyword t)
  5494. '(3 'org-property-value t))
  5495. ;; Link related fontification.
  5496. '(org-activate-links)
  5497. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5498. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5499. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5500. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5501. ;; Targets.
  5502. (list org-any-target-regexp '(0 'org-target t))
  5503. ;; Diary sexps.
  5504. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5505. ;; Macro
  5506. '(org-fontify-macros)
  5507. ;; TODO keyword
  5508. (list (format org-heading-keyword-regexp-format
  5509. org-todo-regexp)
  5510. '(2 (org-get-todo-face 2) t))
  5511. ;; DONE
  5512. (if org-fontify-done-headline
  5513. (list (format org-heading-keyword-regexp-format
  5514. (concat
  5515. "\\(?:"
  5516. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5517. "\\)"))
  5518. '(2 'org-headline-done t))
  5519. nil)
  5520. ;; Priorities
  5521. '(org-font-lock-add-priority-faces)
  5522. ;; Tags
  5523. '(org-font-lock-add-tag-faces)
  5524. ;; Tags groups
  5525. (when (and org-group-tags org-tag-groups-alist)
  5526. (list (concat org-outline-regexp-bol ".+\\(:"
  5527. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5528. ":\\).*$")
  5529. '(1 'org-tag-group prepend)))
  5530. ;; Special keywords
  5531. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5532. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5533. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5534. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5535. ;; Emphasis
  5536. (when em '(org-do-emphasis-faces))
  5537. ;; Checkboxes
  5538. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5539. 1 'org-checkbox prepend)
  5540. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5541. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5542. (0 (org-get-checkbox-statistics-face) t)))
  5543. ;; Description list items
  5544. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5545. 1 'org-list-dt prepend)
  5546. ;; ARCHIVEd headings
  5547. (list (concat
  5548. org-outline-regexp-bol
  5549. "\\(.*:" org-archive-tag ":.*\\)")
  5550. '(1 'org-archived prepend))
  5551. ;; Specials
  5552. '(org-do-latex-and-related)
  5553. '(org-fontify-entities)
  5554. '(org-raise-scripts)
  5555. ;; Code
  5556. '(org-activate-code (1 'org-code t))
  5557. ;; COMMENT
  5558. (list (format
  5559. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5560. org-todo-regexp
  5561. org-comment-string)
  5562. '(9 'org-special-keyword t))
  5563. ;; Blocks and meta lines
  5564. '(org-fontify-meta-lines-and-blocks))))
  5565. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5566. (run-hooks 'org-font-lock-set-keywords-hook)
  5567. ;; Now set the full font-lock-keywords
  5568. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5569. (setq-local font-lock-defaults
  5570. '(org-font-lock-keywords t nil nil backward-paragraph))
  5571. (setq-local font-lock-extend-after-change-region-function
  5572. #'org-fontify-extend-region)
  5573. (kill-local-variable 'font-lock-keywords)
  5574. nil))
  5575. (defun org-toggle-pretty-entities ()
  5576. "Toggle the composition display of entities as UTF8 characters."
  5577. (interactive)
  5578. (setq-local org-pretty-entities (not org-pretty-entities))
  5579. (org-restart-font-lock)
  5580. (if org-pretty-entities
  5581. (message "Entities are now displayed as UTF8 characters")
  5582. (save-restriction
  5583. (widen)
  5584. (decompose-region (point-min) (point-max))
  5585. (message "Entities are now displayed as plain text"))))
  5586. (defvar-local org-custom-properties-overlays nil
  5587. "List of overlays used for custom properties.")
  5588. (defun org-toggle-custom-properties-visibility ()
  5589. "Display or hide properties in `org-custom-properties'."
  5590. (interactive)
  5591. (if org-custom-properties-overlays
  5592. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5593. (setq org-custom-properties-overlays nil))
  5594. (when org-custom-properties
  5595. (org-with-wide-buffer
  5596. (goto-char (point-min))
  5597. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5598. (while (re-search-forward regexp nil t)
  5599. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5600. (when (and end (< (point) end))
  5601. ;; Hide first custom property in current drawer.
  5602. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5603. (overlay-put o 'invisible t)
  5604. (overlay-put o 'org-custom-property t)
  5605. (push o org-custom-properties-overlays))
  5606. ;; Hide additional custom properties in the same drawer.
  5607. (while (re-search-forward regexp end t)
  5608. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5609. (overlay-put o 'invisible t)
  5610. (overlay-put o 'org-custom-property t)
  5611. (push o org-custom-properties-overlays)))))
  5612. ;; Each entry is limited to a single property drawer.
  5613. (outline-next-heading)))))))
  5614. (defun org-fontify-entities (limit)
  5615. "Find an entity to fontify."
  5616. (let (ee)
  5617. (when org-pretty-entities
  5618. (catch 'match
  5619. ;; "\_ "-family is left out on purpose. Only the first one,
  5620. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5621. ;; confusing when adding a second white space character.
  5622. (while (re-search-forward
  5623. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5624. limit t)
  5625. (when (and (not (org-at-comment-p))
  5626. (setq ee (org-entity-get (match-string 1)))
  5627. (= (length (nth 6 ee)) 1))
  5628. (let* ((end (if (equal (match-string 2) "{}")
  5629. (match-end 2)
  5630. (match-end 1))))
  5631. (add-text-properties
  5632. (match-beginning 0) end
  5633. (list 'font-lock-fontified t))
  5634. (compose-region (match-beginning 0) end
  5635. (nth 6 ee) nil)
  5636. (backward-char 1)
  5637. (throw 'match t))))
  5638. nil))))
  5639. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5640. "Fontify string S like in Org mode."
  5641. (with-temp-buffer
  5642. (insert s)
  5643. (let ((org-odd-levels-only odd-levels))
  5644. (org-mode)
  5645. (org-font-lock-ensure)
  5646. (buffer-string))))
  5647. (defvar org-m nil)
  5648. (defvar org-l nil)
  5649. (defvar org-f nil)
  5650. (defun org-get-level-face (n)
  5651. "Get the right face for match N in font-lock matching of headlines."
  5652. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5653. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5654. (if org-cycle-level-faces
  5655. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5656. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5657. (cond
  5658. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5659. ((eq n 2) org-f)
  5660. (t (unless org-level-color-stars-only org-f))))
  5661. (defun org-face-from-face-or-color (context inherit face-or-color)
  5662. "Create a face list that inherits INHERIT, but sets the foreground color.
  5663. When FACE-OR-COLOR is not a string, just return it."
  5664. (if (stringp face-or-color)
  5665. (list :inherit inherit
  5666. (cdr (assoc context org-faces-easy-properties))
  5667. face-or-color)
  5668. face-or-color))
  5669. (defun org-get-todo-face (kwd)
  5670. "Get the right face for a TODO keyword KWD.
  5671. If KWD is a number, get the corresponding match group."
  5672. (when (numberp kwd) (setq kwd (match-string kwd)))
  5673. (or (org-face-from-face-or-color
  5674. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5675. (and (member kwd org-done-keywords) 'org-done)
  5676. 'org-todo))
  5677. (defun org-get-priority-face (priority)
  5678. "Get the right face for PRIORITY.
  5679. PRIORITY is a character."
  5680. (or (org-face-from-face-or-color
  5681. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5682. 'org-priority))
  5683. (defun org-get-tag-face (tag)
  5684. "Get the right face for TAG.
  5685. If TAG is a number, get the corresponding match group."
  5686. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5687. (or (org-face-from-face-or-color
  5688. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5689. 'org-tag)))
  5690. (defun org-font-lock-add-priority-faces (limit)
  5691. "Add the special priority faces."
  5692. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5693. (add-text-properties
  5694. (match-beginning 1) (match-end 1)
  5695. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5696. 'font-lock-fontified t))))
  5697. (defun org-font-lock-add-tag-faces (limit)
  5698. "Add the special tag faces."
  5699. (when (and org-tag-faces org-tags-special-faces-re)
  5700. (while (re-search-forward org-tags-special-faces-re limit t)
  5701. (add-text-properties (match-beginning 1) (match-end 1)
  5702. (list 'face (org-get-tag-face 1)
  5703. 'font-lock-fontified t))
  5704. (backward-char 1))))
  5705. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5706. "Remove fontification and activation overlays from links."
  5707. (font-lock-default-unfontify-region beg end)
  5708. (let* ((buffer-undo-list t)
  5709. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5710. (inhibit-modification-hooks t)
  5711. deactivate-mark buffer-file-name buffer-file-truename)
  5712. (decompose-region beg end)
  5713. (remove-text-properties beg end
  5714. '(mouse-face t keymap t org-linked-text t
  5715. invisible t intangible t
  5716. org-emphasis t))
  5717. (org-remove-font-lock-display-properties beg end)))
  5718. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5719. ((raise 0.3) (height 0.7))
  5720. ((raise -0.5))
  5721. ((raise 0.5)))
  5722. "Display properties for showing superscripts and subscripts.")
  5723. (defun org-remove-font-lock-display-properties (beg end)
  5724. "Remove specific display properties that have been added by font lock.
  5725. The will remove the raise properties that are used to show superscripts
  5726. and subscripts."
  5727. (let (next prop)
  5728. (while (< beg end)
  5729. (setq next (next-single-property-change beg 'display nil end)
  5730. prop (get-text-property beg 'display))
  5731. (when (member prop org-script-display)
  5732. (put-text-property beg next 'display nil))
  5733. (setq beg next))))
  5734. (defun org-raise-scripts (limit)
  5735. "Add raise properties to sub/superscripts."
  5736. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5737. (re-search-forward
  5738. (if (eq org-use-sub-superscripts t)
  5739. org-match-substring-regexp
  5740. org-match-substring-with-braces-regexp)
  5741. limit t))
  5742. (let* ((pos (point)) table-p comment-p
  5743. (mpos (match-beginning 3))
  5744. (emph-p (get-text-property mpos 'org-emphasis))
  5745. (link-p (get-text-property mpos 'mouse-face))
  5746. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5747. (goto-char (point-at-bol))
  5748. (setq table-p (looking-at-p org-table-dataline-regexp)
  5749. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5750. (goto-char pos)
  5751. ;; Handle a_b^c
  5752. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5753. (unless (or comment-p emph-p link-p keyw-p)
  5754. (put-text-property (match-beginning 3) (match-end 0)
  5755. 'display
  5756. (if (equal (char-after (match-beginning 2)) ?^)
  5757. (nth (if table-p 3 1) org-script-display)
  5758. (nth (if table-p 2 0) org-script-display)))
  5759. (add-text-properties (match-beginning 2) (match-end 2)
  5760. (list 'invisible t))
  5761. (when (and (eq (char-after (match-beginning 3)) ?{)
  5762. (eq (char-before (match-end 3)) ?}))
  5763. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5764. (list 'invisible t))
  5765. (add-text-properties (1- (match-end 3)) (match-end 3)
  5766. (list 'invisible t))))
  5767. t)))
  5768. (defun org-remove-empty-overlays-at (pos)
  5769. "Remove outline overlays that do not contain non-white stuff."
  5770. (dolist (o (overlays-at pos))
  5771. (and (eq 'outline (overlay-get o 'invisible))
  5772. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5773. (overlay-end o))))
  5774. (delete-overlay o))))
  5775. (defun org-show-empty-lines-in-parent ()
  5776. "Move to the parent and re-show empty lines before visible headlines."
  5777. (save-excursion
  5778. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5779. (org-cycle-show-empty-lines context))))
  5780. (defun org-files-list ()
  5781. "Return `org-agenda-files' list, plus all open Org files.
  5782. This is useful for operations that need to scan all of a user's
  5783. open and agenda-wise Org files."
  5784. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5785. (dolist (buf (buffer-list))
  5786. (with-current-buffer buf
  5787. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5788. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5789. :test #'equal))))
  5790. files))
  5791. (defsubst org-entry-beginning-position ()
  5792. "Return the beginning position of the current entry."
  5793. (save-excursion (org-back-to-heading t) (point)))
  5794. (defsubst org-entry-end-position ()
  5795. "Return the end position of the current entry."
  5796. (save-excursion (outline-next-heading) (point)))
  5797. (defun org-subtree-end-visible-p ()
  5798. "Is the end of the current subtree visible?"
  5799. (pos-visible-in-window-p
  5800. (save-excursion (org-end-of-subtree t) (point))))
  5801. (defun org-first-headline-recenter ()
  5802. "Move cursor to the first headline and recenter the headline."
  5803. (let ((window (get-buffer-window)))
  5804. (when window
  5805. (goto-char (point-min))
  5806. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5807. (set-window-start window (line-beginning-position))))))
  5808. ;;; Visibility (headlines, blocks, drawers)
  5809. ;;;; Headlines visibility
  5810. (defun org-show-entry ()
  5811. "Show the body directly following this heading.
  5812. Show the heading too, if it is currently invisible."
  5813. (interactive)
  5814. (save-excursion
  5815. (ignore-errors
  5816. (org-back-to-heading t)
  5817. (org-flag-region
  5818. (line-end-position 0)
  5819. (save-excursion
  5820. (if (re-search-forward
  5821. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5822. (match-beginning 1)
  5823. (point-max)))
  5824. nil
  5825. 'outline))))
  5826. (defun org-show-children (&optional level)
  5827. "Show all direct subheadings of this heading.
  5828. Prefix arg LEVEL is how many levels below the current level
  5829. should be shown. Default is enough to cause the following
  5830. heading to appear."
  5831. (interactive "p")
  5832. (save-excursion
  5833. (org-back-to-heading t)
  5834. (let* ((current-level (funcall outline-level))
  5835. (max-level (org-get-valid-level
  5836. current-level
  5837. (if level (prefix-numeric-value level) 1)))
  5838. (end (save-excursion (org-end-of-subtree t t)))
  5839. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5840. (past-first-child nil)
  5841. ;; Make sure to skip inlinetasks.
  5842. (re (format regexp-fmt
  5843. current-level
  5844. (cond
  5845. ((not (featurep 'org-inlinetask)) "")
  5846. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5847. 3))
  5848. (t (1- org-inlinetask-min-level))))))
  5849. ;; Display parent heading.
  5850. (org-flag-heading nil)
  5851. (forward-line)
  5852. ;; Display children. First child may be deeper than expected
  5853. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5854. ;; MAX-LEVEL accordingly.
  5855. (while (re-search-forward re end t)
  5856. (unless past-first-child
  5857. (setq re (format regexp-fmt
  5858. current-level
  5859. (max (funcall outline-level) max-level)))
  5860. (setq past-first-child t))
  5861. (org-flag-heading nil)))))
  5862. (defun org-show-subtree ()
  5863. "Show everything after this heading at deeper levels."
  5864. (interactive)
  5865. (org-flag-region
  5866. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5867. ;;;; Blocks visibility
  5868. (defun org-hide-block-toggle-maybe ()
  5869. "Toggle visibility of block at point.
  5870. Unlike to `org-hide-block-toggle', this function does not throw
  5871. an error. Return a non-nil value when toggling is successful."
  5872. (interactive)
  5873. (ignore-errors (org-hide-block-toggle)))
  5874. (defun org-hide-block-toggle (&optional force)
  5875. "Toggle the visibility of the current block.
  5876. When optional argument FORCE is `off', make block visible. If it
  5877. is non-nil, hide it unconditionally. Throw an error when not at
  5878. a block. Return a non-nil value when toggling is successful."
  5879. (interactive)
  5880. (let ((element (org-element-at-point)))
  5881. (unless (memq (org-element-type element)
  5882. '(center-block comment-block dynamic-block example-block
  5883. export-block quote-block special-block
  5884. src-block verse-block))
  5885. (user-error "Not at a block"))
  5886. (let* ((post (org-element-property :post-affiliated element))
  5887. (start (save-excursion
  5888. (goto-char post)
  5889. (line-end-position)))
  5890. (end (save-excursion
  5891. (goto-char (org-element-property :end element))
  5892. (skip-chars-backward " \t\n")
  5893. (line-end-position))))
  5894. ;; Do nothing when not before or at the block opening line or at
  5895. ;; the block closing line.
  5896. (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
  5897. (cond ((eq force 'off)
  5898. (org-flag-region start end nil 'org-hide-block))
  5899. (force
  5900. (org-flag-region start end t 'org-hide-block))
  5901. ((eq (get-char-property start 'invisible) 'org-hide-block)
  5902. (org-flag-region start end nil 'org-hide-block))
  5903. (t
  5904. (org-flag-region start end t 'org-hide-block)))
  5905. ;; When the block is hidden away, make sure point is left in
  5906. ;; a visible part of the buffer.
  5907. (when (invisible-p (max (1- (point)) (point-min)))
  5908. (goto-char post))
  5909. ;; Signal success.
  5910. t))))
  5911. (defun org-hide-block-toggle-all ()
  5912. "Toggle the visibility of all blocks in the current buffer."
  5913. (org-block-map 'org-hide-block-toggle))
  5914. (defun org-hide-block-all ()
  5915. "Fold all blocks in the current buffer."
  5916. (interactive)
  5917. (org-show-all '(blocks))
  5918. (org-block-map 'org-hide-block-toggle-maybe))
  5919. ;;;; Drawers visibility
  5920. (defun org-cycle-hide-drawers (state &optional exceptions)
  5921. "Re-hide all drawers after a visibility state change.
  5922. STATE should be one of the symbols listed in the docstring of
  5923. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  5924. a list of strings specifying which drawers should not be hidden."
  5925. (when (and (derived-mode-p 'org-mode)
  5926. (not (memq state '(overview folded contents))))
  5927. (save-excursion
  5928. (let* ((globalp (eq state 'all))
  5929. (beg (if globalp (point-min) (point)))
  5930. (end (if globalp (point-max)
  5931. (if (eq state 'children)
  5932. (save-excursion (outline-next-heading) (point))
  5933. (org-end-of-subtree t)))))
  5934. (goto-char beg)
  5935. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  5936. (unless (member-ignore-case (match-string 1) exceptions)
  5937. (let ((drawer (org-element-at-point)))
  5938. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5939. (org-flag-drawer t drawer)
  5940. ;; Make sure to skip drawer entirely or we might flag
  5941. ;; it another time when matching its ending line with
  5942. ;; `org-drawer-regexp'.
  5943. (goto-char (org-element-property :end drawer))))))))))
  5944. (defun org-flag-drawer (flag &optional element)
  5945. "When FLAG is non-nil, hide the drawer we are at.
  5946. Otherwise make it visible. When optional argument ELEMENT is
  5947. a parsed drawer, as returned by `org-element-at-point', hide or
  5948. show that drawer instead."
  5949. (let ((drawer (or element
  5950. (and (save-excursion
  5951. (beginning-of-line)
  5952. (looking-at-p org-drawer-regexp))
  5953. (org-element-at-point)))))
  5954. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5955. (let ((post (org-element-property :post-affiliated drawer)))
  5956. (org-flag-region
  5957. (save-excursion (goto-char post) (line-end-position))
  5958. (save-excursion (goto-char (org-element-property :end drawer))
  5959. (skip-chars-backward " \t\n")
  5960. (line-end-position))
  5961. flag 'org-hide-drawer)
  5962. ;; When the drawer is hidden away, make sure point lies in
  5963. ;; a visible part of the buffer.
  5964. (when (invisible-p (max (1- (point)) (point-min)))
  5965. (goto-char post))))))
  5966. ;;;; Visibility cycling
  5967. (defvar-local org-cycle-global-status nil)
  5968. (put 'org-cycle-global-status 'org-state t)
  5969. (defvar-local org-cycle-subtree-status nil)
  5970. (put 'org-cycle-subtree-status 'org-state t)
  5971. (defun org-show-all (&optional types)
  5972. "Show all contents in the visible part of the buffer.
  5973. By default, the function expands headings, blocks and drawers.
  5974. When optional argument TYPE is a list of symbols among `blocks',
  5975. `drawers' and `headings', to only expand one specific type."
  5976. (dolist (type (or types '(blocks drawers headings)))
  5977. (org-flag-region (point-min) (point-max) nil
  5978. (pcase type
  5979. (`blocks 'org-hide-block)
  5980. (`drawers 'org-hide-drawer)
  5981. (`headings 'outline)
  5982. (_ (error "Invalid type: %S" type))))))
  5983. ;;;###autoload
  5984. (defun org-cycle (&optional arg)
  5985. "TAB-action and visibility cycling for Org mode.
  5986. This is the command invoked in Org mode by the `TAB' key. Its main
  5987. purpose is outline visibility cycling, but it also invokes other actions
  5988. in special contexts.
  5989. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5990. the entire
  5991. buffer through 3 states (global cycling)
  5992. 1. OVERVIEW: Show only top-level headlines.
  5993. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5994. 3. SHOW ALL: Show everything.
  5995. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5996. switch to the startup visibility,
  5997. determined by the variable `org-startup-folded', and by any VISIBILITY
  5998. properties in the buffer.
  5999. With a `\\[universal-argument] \\[universal-argument] \
  6000. \\[universal-argument]' prefix argument, show the entire buffer, including
  6001. any drawers.
  6002. When inside a table, re-align the table and move to the next field.
  6003. When point is at the beginning of a headline, rotate the subtree started
  6004. by this line through 3 different states (local cycling)
  6005. 1. FOLDED: Only the main headline is shown.
  6006. 2. CHILDREN: The main headline and the direct children are shown.
  6007. From this state, you can move to one of the children
  6008. and zoom in further.
  6009. 3. SUBTREE: Show the entire subtree, including body text.
  6010. If there is no subtree, switch directly from CHILDREN to FOLDED.
  6011. When point is at the beginning of an empty headline and the variable
  6012. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  6013. of the headline by demoting and promoting it to likely levels. This
  6014. speeds up creation document structure by pressing `TAB' once or several
  6015. times right after creating a new headline.
  6016. When there is a numeric prefix, go up to a heading with level ARG, do
  6017. a `show-subtree' and return to the previous cursor position. If ARG
  6018. is negative, go up that many levels.
  6019. When point is not at the beginning of a headline, execute the global
  6020. binding for `TAB', which is re-indenting the line. See the option
  6021. `org-cycle-emulate-tab' for details.
  6022. As a special case, if point is at the beginning of the buffer and there is
  6023. no headline in line 1, this function will act as if called with prefix arg
  6024. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  6025. prefix arg, but only
  6026. if the variable `org-cycle-global-at-bob' is t."
  6027. (interactive "P")
  6028. (org-load-modules-maybe)
  6029. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  6030. (and org-cycle-level-after-item/entry-creation
  6031. (or (org-cycle-level)
  6032. (org-cycle-item-indentation))))
  6033. (let* ((limit-level
  6034. (or org-cycle-max-level
  6035. (and (boundp 'org-inlinetask-min-level)
  6036. org-inlinetask-min-level
  6037. (1- org-inlinetask-min-level))))
  6038. (nstars (and limit-level
  6039. (if org-odd-levels-only
  6040. (and limit-level (1- (* limit-level 2)))
  6041. limit-level)))
  6042. (org-outline-regexp
  6043. (if (not (derived-mode-p 'org-mode))
  6044. outline-regexp
  6045. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  6046. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  6047. (not (looking-at org-outline-regexp))))
  6048. (org-cycle-hook
  6049. (if bob-special
  6050. (delq 'org-optimize-window-after-visibility-change
  6051. (copy-sequence org-cycle-hook))
  6052. org-cycle-hook))
  6053. (pos (point)))
  6054. (cond
  6055. ((equal arg '(16))
  6056. (setq last-command 'dummy)
  6057. (org-set-startup-visibility)
  6058. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  6059. ((equal arg '(64))
  6060. (org-show-all)
  6061. (org-unlogged-message "Entire buffer visible, including drawers"))
  6062. ((equal arg '(4)) (org-cycle-internal-global))
  6063. ;; Try hiding block at point.
  6064. ((org-hide-block-toggle-maybe))
  6065. ;; Try cdlatex TAB completion
  6066. ((org-try-cdlatex-tab))
  6067. ;; Table: enter it or move to the next field.
  6068. ((org-at-table-p 'any)
  6069. (if (org-at-table.el-p)
  6070. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6071. Use `\\[org-edit-special]' to edit table.el tables"))
  6072. (if arg (org-table-edit-field t)
  6073. (org-table-justify-field-maybe)
  6074. (call-interactively 'org-table-next-field))))
  6075. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  6076. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6077. (bob-special (org-cycle-internal-global))
  6078. ;; Drawers: delegate to `org-flag-drawer'.
  6079. ((save-excursion
  6080. (beginning-of-line 1)
  6081. (looking-at org-drawer-regexp))
  6082. (org-flag-drawer ; toggle block visibility
  6083. (not (get-char-property (match-end 0) 'invisible))))
  6084. ;; Show-subtree, ARG levels up from here.
  6085. ((integerp arg)
  6086. (save-excursion
  6087. (org-back-to-heading)
  6088. (outline-up-heading (if (< arg 0) (- arg)
  6089. (- (funcall outline-level) arg)))
  6090. (org-show-subtree)))
  6091. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6092. ((and (featurep 'org-inlinetask)
  6093. (org-inlinetask-at-task-p)
  6094. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6095. (org-inlinetask-toggle-visibility))
  6096. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6097. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6098. (save-excursion (move-beginning-of-line 1)
  6099. (looking-at org-outline-regexp)))
  6100. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6101. (org-cycle-internal-local))
  6102. ;; From there: TAB emulation and template completion.
  6103. (buffer-read-only (org-back-to-heading))
  6104. ((run-hook-with-args-until-success
  6105. 'org-tab-after-check-for-cycling-hook))
  6106. ((run-hook-with-args-until-success
  6107. 'org-tab-before-tab-emulation-hook))
  6108. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6109. (or (not (bolp))
  6110. (not (looking-at org-outline-regexp))))
  6111. (call-interactively (global-key-binding "\t")))
  6112. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6113. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6114. (or (and (eq org-cycle-emulate-tab 'white)
  6115. (= (match-end 0) (point-at-eol)))
  6116. (and (eq org-cycle-emulate-tab 'whitestart)
  6117. (>= (match-end 0) pos))))
  6118. t
  6119. (eq org-cycle-emulate-tab t))
  6120. (call-interactively (global-key-binding "\t")))
  6121. (t (save-excursion
  6122. (org-back-to-heading)
  6123. (org-cycle)))))))
  6124. (defun org-cycle-internal-global ()
  6125. "Do the global cycling action."
  6126. ;; Hack to avoid display of messages for .org attachments in Gnus
  6127. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6128. (cond
  6129. ((and (eq last-command this-command)
  6130. (eq org-cycle-global-status 'overview))
  6131. ;; We just created the overview - now do table of contents
  6132. ;; This can be slow in very large buffers, so indicate action
  6133. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6134. (unless ga (org-unlogged-message "CONTENTS..."))
  6135. (org-content)
  6136. (unless ga (org-unlogged-message "CONTENTS...done"))
  6137. (setq org-cycle-global-status 'contents)
  6138. (run-hook-with-args 'org-cycle-hook 'contents))
  6139. ((and (eq last-command this-command)
  6140. (eq org-cycle-global-status 'contents))
  6141. ;; We just showed the table of contents - now show everything
  6142. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6143. (org-show-all '(headings blocks))
  6144. (unless ga (org-unlogged-message "SHOW ALL"))
  6145. (setq org-cycle-global-status 'all)
  6146. (run-hook-with-args 'org-cycle-hook 'all))
  6147. (t
  6148. ;; Default action: go to overview
  6149. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6150. (org-overview)
  6151. (unless ga (org-unlogged-message "OVERVIEW"))
  6152. (setq org-cycle-global-status 'overview)
  6153. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6154. (defvar org-called-with-limited-levels nil
  6155. "Non-nil when `org-with-limited-levels' is currently active.")
  6156. (defun org-cycle-internal-local ()
  6157. "Do the local cycling action."
  6158. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6159. ;; First, determine end of headline (EOH), end of subtree or item
  6160. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6161. (save-excursion
  6162. (if (org-at-item-p)
  6163. (progn
  6164. (beginning-of-line)
  6165. (setq struct (org-list-struct))
  6166. (setq eoh (point-at-eol))
  6167. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6168. (setq has-children (org-list-has-child-p (point) struct)))
  6169. (org-back-to-heading)
  6170. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6171. (setq eos (save-excursion (org-end-of-subtree t t)
  6172. (when (bolp) (backward-char)) (point)))
  6173. (setq has-children
  6174. (or (save-excursion
  6175. (let ((level (funcall outline-level)))
  6176. (outline-next-heading)
  6177. (and (org-at-heading-p t)
  6178. (> (funcall outline-level) level))))
  6179. (save-excursion
  6180. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6181. ;; Determine end invisible part of buffer (EOL)
  6182. (beginning-of-line 2)
  6183. (while (and (not (eobp)) ;This is like `next-line'.
  6184. (get-char-property (1- (point)) 'invisible))
  6185. (goto-char (next-single-char-property-change (point) 'invisible))
  6186. (and (eolp) (beginning-of-line 2)))
  6187. (setq eol (point)))
  6188. ;; Find out what to do next and set `this-command'
  6189. (cond
  6190. ((= eos eoh)
  6191. ;; Nothing is hidden behind this heading
  6192. (unless (org-before-first-heading-p)
  6193. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6194. (org-unlogged-message "EMPTY ENTRY")
  6195. (setq org-cycle-subtree-status nil)
  6196. (save-excursion
  6197. (goto-char eos)
  6198. (outline-next-heading)
  6199. (when (org-invisible-p) (org-flag-heading nil))))
  6200. ((and (or (>= eol eos)
  6201. (not (string-match "\\S-" (buffer-substring eol eos))))
  6202. (or has-children
  6203. (not (setq children-skipped
  6204. org-cycle-skip-children-state-if-no-children))))
  6205. ;; Entire subtree is hidden in one line: children view
  6206. (unless (org-before-first-heading-p)
  6207. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6208. (if (org-at-item-p)
  6209. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6210. (org-show-entry)
  6211. (org-with-limited-levels (org-show-children))
  6212. (org-show-set-visibility 'canonical)
  6213. ;; Fold every list in subtree to top-level items.
  6214. (when (eq org-cycle-include-plain-lists 'integrate)
  6215. (save-excursion
  6216. (org-back-to-heading)
  6217. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6218. (beginning-of-line 1)
  6219. (let* ((struct (org-list-struct))
  6220. (prevs (org-list-prevs-alist struct))
  6221. (end (org-list-get-bottom-point struct)))
  6222. (dolist (e (org-list-get-all-items (point) struct prevs))
  6223. (org-list-set-item-visibility e struct 'folded))
  6224. (goto-char (if (< end eos) end eos)))))))
  6225. (org-unlogged-message "CHILDREN")
  6226. (save-excursion
  6227. (goto-char eos)
  6228. (outline-next-heading)
  6229. (when (org-invisible-p) (org-flag-heading nil)))
  6230. (setq org-cycle-subtree-status 'children)
  6231. (unless (org-before-first-heading-p)
  6232. (run-hook-with-args 'org-cycle-hook 'children)))
  6233. ((or children-skipped
  6234. (and (eq last-command this-command)
  6235. (eq org-cycle-subtree-status 'children)))
  6236. ;; We just showed the children, or no children are there,
  6237. ;; now show everything.
  6238. (unless (org-before-first-heading-p)
  6239. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6240. (org-flag-region eoh eos nil 'outline)
  6241. (org-unlogged-message
  6242. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6243. (setq org-cycle-subtree-status 'subtree)
  6244. (unless (org-before-first-heading-p)
  6245. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6246. (t
  6247. ;; Default action: hide the subtree.
  6248. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6249. (org-flag-region eoh eos t 'outline)
  6250. (org-unlogged-message "FOLDED")
  6251. (setq org-cycle-subtree-status 'folded)
  6252. (unless (org-before-first-heading-p)
  6253. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6254. ;;;###autoload
  6255. (defun org-global-cycle (&optional arg)
  6256. "Cycle the global visibility. For details see `org-cycle'.
  6257. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6258. With a numeric prefix, show all headlines up to that level."
  6259. (interactive "P")
  6260. (let ((org-cycle-include-plain-lists
  6261. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6262. (cond
  6263. ((integerp arg)
  6264. (org-show-all '(headings blocks))
  6265. (outline-hide-sublevels arg)
  6266. (setq org-cycle-global-status 'contents))
  6267. ((equal arg '(4))
  6268. (org-set-startup-visibility)
  6269. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6270. (t
  6271. (org-cycle '(4))))))
  6272. (defun org-set-startup-visibility ()
  6273. "Set the visibility required by startup options and properties."
  6274. (cond
  6275. ((eq org-startup-folded t)
  6276. (org-overview))
  6277. ((eq org-startup-folded 'content)
  6278. (org-content))
  6279. ((or (eq org-startup-folded 'showeverything)
  6280. (eq org-startup-folded nil))
  6281. (org-show-all)))
  6282. (unless (eq org-startup-folded 'showeverything)
  6283. (when org-hide-block-startup (org-hide-block-all))
  6284. (org-set-visibility-according-to-property)
  6285. (org-cycle-hide-archived-subtrees 'all)
  6286. (org-cycle-hide-drawers 'all)
  6287. (org-cycle-show-empty-lines t)))
  6288. (defun org-set-visibility-according-to-property ()
  6289. "Switch subtree visibilities according to :VISIBILITY: property."
  6290. (interactive)
  6291. (org-with-wide-buffer
  6292. (goto-char (point-min))
  6293. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6294. (if (not (org-at-property-p)) (outline-next-heading)
  6295. (let ((state (match-string 3)))
  6296. (save-excursion
  6297. (org-back-to-heading t)
  6298. (outline-hide-subtree)
  6299. (org-reveal)
  6300. (cond
  6301. ((equal state "folded")
  6302. (outline-hide-subtree))
  6303. ((equal state "children")
  6304. (org-show-hidden-entry)
  6305. (org-show-children))
  6306. ((equal state "content")
  6307. (save-excursion
  6308. (save-restriction
  6309. (org-narrow-to-subtree)
  6310. (org-content))))
  6311. ((member state '("all" "showall"))
  6312. (outline-show-subtree)))))))))
  6313. (defun org-overview ()
  6314. "Switch to overview mode, showing only top-level headlines.
  6315. This shows all headlines with a level equal or greater than the level
  6316. of the first headline in the buffer. This is important, because if the
  6317. first headline is not level one, then (hide-sublevels 1) gives confusing
  6318. results."
  6319. (interactive)
  6320. (save-excursion
  6321. (let ((level
  6322. (save-excursion
  6323. (goto-char (point-min))
  6324. (when (re-search-forward org-outline-regexp-bol nil t)
  6325. (goto-char (match-beginning 0))
  6326. (funcall outline-level)))))
  6327. (and level (outline-hide-sublevels level)))))
  6328. (defun org-content (&optional arg)
  6329. "Show all headlines in the buffer, like a table of contents.
  6330. With numerical argument N, show content up to level N."
  6331. (interactive "P")
  6332. (org-overview)
  6333. (save-excursion
  6334. ;; Visit all headings and show their offspring
  6335. (and (integerp arg) (org-overview))
  6336. (goto-char (point-max))
  6337. (catch 'exit
  6338. (while (and (progn (condition-case nil
  6339. (outline-previous-visible-heading 1)
  6340. (error (goto-char (point-min))))
  6341. t)
  6342. (looking-at org-outline-regexp))
  6343. (if (integerp arg)
  6344. (org-show-children (1- arg))
  6345. (outline-show-branches))
  6346. (when (bobp) (throw 'exit nil))))))
  6347. (defun org-optimize-window-after-visibility-change (state)
  6348. "Adjust the window after a change in outline visibility.
  6349. This function is the default value of the hook `org-cycle-hook'."
  6350. (when (get-buffer-window (current-buffer))
  6351. (cond
  6352. ((eq state 'content) nil)
  6353. ((eq state 'all) nil)
  6354. ((eq state 'folded) nil)
  6355. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6356. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6357. (defun org-clean-visibility-after-subtree-move ()
  6358. "Fix visibility issues after moving a subtree."
  6359. ;; First, find a reasonable region to look at:
  6360. ;; Start two siblings above, end three below
  6361. (let* ((beg (save-excursion
  6362. (and (org-get-last-sibling)
  6363. (org-get-last-sibling))
  6364. (point)))
  6365. (end (save-excursion
  6366. (and (org-get-next-sibling)
  6367. (org-get-next-sibling)
  6368. (org-get-next-sibling))
  6369. (if (org-at-heading-p)
  6370. (point-at-eol)
  6371. (point))))
  6372. (level (looking-at "\\*+"))
  6373. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6374. (save-excursion
  6375. (save-restriction
  6376. (narrow-to-region beg end)
  6377. (when re
  6378. ;; Properly fold already folded siblings
  6379. (goto-char (point-min))
  6380. (while (re-search-forward re nil t)
  6381. (when (and (not (org-invisible-p))
  6382. (org-invisible-p (line-end-position)))
  6383. (outline-hide-entry))))
  6384. (org-cycle-hide-drawers 'all)
  6385. (org-cycle-show-empty-lines 'overview)))))
  6386. (defun org-cycle-show-empty-lines (state)
  6387. "Show empty lines above all visible headlines.
  6388. The region to be covered depends on STATE when called through
  6389. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6390. entire buffer covered. Note that an empty line is only shown if there
  6391. are at least `org-cycle-separator-lines' empty lines before the headline."
  6392. (when (/= org-cycle-separator-lines 0)
  6393. (save-excursion
  6394. (let* ((n (abs org-cycle-separator-lines))
  6395. (re (cond
  6396. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6397. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6398. (t (let ((ns (number-to-string (- n 2))))
  6399. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6400. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6401. beg end)
  6402. (cond
  6403. ((memq state '(overview contents t))
  6404. (setq beg (point-min) end (point-max)))
  6405. ((memq state '(children folded))
  6406. (setq beg (point)
  6407. end (progn (org-end-of-subtree t t)
  6408. (line-beginning-position 2)))))
  6409. (when beg
  6410. (goto-char beg)
  6411. (while (re-search-forward re end t)
  6412. (unless (get-char-property (match-end 1) 'invisible)
  6413. (let ((e (match-end 1))
  6414. (b (if (>= org-cycle-separator-lines 0)
  6415. (match-beginning 1)
  6416. (save-excursion
  6417. (goto-char (match-beginning 0))
  6418. (skip-chars-backward " \t\n")
  6419. (line-end-position)))))
  6420. (org-flag-region b e nil 'outline))))))))
  6421. ;; Never hide empty lines at the end of the file.
  6422. (save-excursion
  6423. (goto-char (point-max))
  6424. (outline-previous-heading)
  6425. (outline-end-of-heading)
  6426. (when (and (looking-at "[ \t\n]+")
  6427. (= (match-end 0) (point-max)))
  6428. (org-flag-region (point) (match-end 0) nil 'outline))))
  6429. ;;;; Reveal point location
  6430. (defun org-show-context (&optional key)
  6431. "Make sure point and context are visible.
  6432. Optional argument KEY, when non-nil, is a symbol. See
  6433. `org-show-context-detail' for allowed values and how much is to
  6434. be shown."
  6435. (org-show-set-visibility
  6436. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  6437. ((cdr (assq key org-show-context-detail)))
  6438. (t (cdr (assq 'default org-show-context-detail))))))
  6439. (defun org-show-set-visibility (detail)
  6440. "Set visibility around point according to DETAIL.
  6441. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  6442. `tree', `canonical' or t. See `org-show-context-detail' for more
  6443. information."
  6444. ;; Show current heading and possibly its entry, following headline
  6445. ;; or all children.
  6446. (if (and (org-at-heading-p) (not (eq detail 'local)))
  6447. (org-flag-heading nil)
  6448. (org-show-entry)
  6449. ;; If point is hidden within a drawer or a block, make sure to
  6450. ;; expose it.
  6451. (dolist (o (overlays-at (point)))
  6452. (when (memq (overlay-get o 'invisible)
  6453. '(org-hide-block org-hide-drawer outline))
  6454. (delete-overlay o)))
  6455. (unless (org-before-first-heading-p)
  6456. (org-with-limited-levels
  6457. (cl-case detail
  6458. ((tree canonical t) (org-show-children))
  6459. ((nil minimal ancestors))
  6460. (t (save-excursion
  6461. (outline-next-heading)
  6462. (org-flag-heading nil)))))))
  6463. ;; Show all siblings.
  6464. (when (eq detail 'lineage) (org-show-siblings))
  6465. ;; Show ancestors, possibly with their children.
  6466. (when (memq detail '(ancestors lineage tree canonical t))
  6467. (save-excursion
  6468. (while (org-up-heading-safe)
  6469. (org-flag-heading nil)
  6470. (when (memq detail '(canonical t)) (org-show-entry))
  6471. (when (memq detail '(tree canonical t)) (org-show-children))))))
  6472. (defvar org-reveal-start-hook nil
  6473. "Hook run before revealing a location.")
  6474. (defun org-reveal (&optional siblings)
  6475. "Show current entry, hierarchy above it, and the following headline.
  6476. This can be used to show a consistent set of context around
  6477. locations exposed with `org-show-context'.
  6478. With optional argument SIBLINGS, on each level of the hierarchy all
  6479. siblings are shown. This repairs the tree structure to what it would
  6480. look like when opened with hierarchical calls to `org-cycle'.
  6481. With a \\[universal-argument] \\[universal-argument] prefix, \
  6482. go to the parent and show the entire tree."
  6483. (interactive "P")
  6484. (run-hooks 'org-reveal-start-hook)
  6485. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6486. ((equal siblings '(16))
  6487. (save-excursion
  6488. (when (org-up-heading-safe)
  6489. (org-show-subtree)
  6490. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6491. (t (org-show-set-visibility 'lineage))))
  6492. ;;; Indirect buffer display of subtrees
  6493. (defvar org-indirect-dedicated-frame nil
  6494. "This is the frame being used for indirect tree display.")
  6495. (defvar org-last-indirect-buffer nil)
  6496. (defun org-tree-to-indirect-buffer (&optional arg)
  6497. "Create indirect buffer and narrow it to current subtree.
  6498. With a numerical prefix ARG, go up to this level and then take that tree.
  6499. If ARG is negative, go up that many levels.
  6500. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6501. indirect buffer previously made with this command, to avoid proliferation of
  6502. indirect buffers. However, when you call the command with a \
  6503. `\\[universal-argument]' prefix, or
  6504. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6505. so that you can work with several indirect buffers at the same time. If
  6506. `org-indirect-buffer-display' is `dedicated-frame', the \
  6507. `\\[universal-argument]' prefix also
  6508. requests that a new frame be made for the new buffer, so that the dedicated
  6509. frame is not changed."
  6510. (interactive "P")
  6511. (let ((cbuf (current-buffer))
  6512. (cwin (selected-window))
  6513. (pos (point))
  6514. beg end level heading ibuf)
  6515. (save-excursion
  6516. (org-back-to-heading t)
  6517. (when (numberp arg)
  6518. (setq level (org-outline-level))
  6519. (when (< arg 0) (setq arg (+ level arg)))
  6520. (while (> (setq level (org-outline-level)) arg)
  6521. (org-up-heading-safe)))
  6522. (setq beg (point)
  6523. heading (org-get-heading 'no-tags))
  6524. (org-end-of-subtree t t)
  6525. (when (org-at-heading-p) (backward-char 1))
  6526. (setq end (point)))
  6527. (when (and (buffer-live-p org-last-indirect-buffer)
  6528. (not (eq org-indirect-buffer-display 'new-frame))
  6529. (not arg))
  6530. (kill-buffer org-last-indirect-buffer))
  6531. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6532. org-last-indirect-buffer ibuf)
  6533. (cond
  6534. ((or (eq org-indirect-buffer-display 'new-frame)
  6535. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6536. (select-frame (make-frame))
  6537. (delete-other-windows)
  6538. (pop-to-buffer-same-window ibuf)
  6539. (org-set-frame-title heading))
  6540. ((eq org-indirect-buffer-display 'dedicated-frame)
  6541. (raise-frame
  6542. (select-frame (or (and org-indirect-dedicated-frame
  6543. (frame-live-p org-indirect-dedicated-frame)
  6544. org-indirect-dedicated-frame)
  6545. (setq org-indirect-dedicated-frame (make-frame)))))
  6546. (delete-other-windows)
  6547. (pop-to-buffer-same-window ibuf)
  6548. (org-set-frame-title (concat "Indirect: " heading)))
  6549. ((eq org-indirect-buffer-display 'current-window)
  6550. (pop-to-buffer-same-window ibuf))
  6551. ((eq org-indirect-buffer-display 'other-window)
  6552. (pop-to-buffer ibuf))
  6553. (t (error "Invalid value")))
  6554. (narrow-to-region beg end)
  6555. (org-show-all '(headings blocks))
  6556. (goto-char pos)
  6557. (run-hook-with-args 'org-cycle-hook 'all)
  6558. (and (window-live-p cwin) (select-window cwin))))
  6559. (defun org-get-indirect-buffer (&optional buffer heading)
  6560. (setq buffer (or buffer (current-buffer)))
  6561. (let ((n 1) (base (buffer-name buffer)) bname)
  6562. (while (buffer-live-p
  6563. (get-buffer
  6564. (setq bname
  6565. (concat base "-"
  6566. (if heading (concat heading "-" (number-to-string n))
  6567. (number-to-string n))))))
  6568. (setq n (1+ n)))
  6569. (condition-case nil
  6570. (make-indirect-buffer buffer bname 'clone)
  6571. (error (make-indirect-buffer buffer bname)))))
  6572. (defun org-set-frame-title (title)
  6573. "Set the title of the current frame to the string TITLE."
  6574. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6575. ;;;; Structure editing
  6576. ;;; Inserting headlines
  6577. (defun org--line-empty-p (n)
  6578. "Is the Nth next line empty?
  6579. Counts the current line as N = 1 and the previous line as N = 0;
  6580. see `beginning-of-line'."
  6581. (save-excursion
  6582. (and (not (bobp))
  6583. (or (beginning-of-line n) t)
  6584. (save-match-data
  6585. (looking-at "[ \t]*$")))))
  6586. (defun org-previous-line-empty-p ()
  6587. "Is the previous line a blank line?
  6588. When NEXT is non-nil, check the next line instead."
  6589. (org--line-empty-p 0))
  6590. (defun org-next-line-empty-p ()
  6591. "Is the previous line a blank line?
  6592. When NEXT is non-nil, check the next line instead."
  6593. (org--line-empty-p 2))
  6594. (defun org--blank-before-heading-p (&optional parent)
  6595. "Non-nil when an empty line should precede a new heading here.
  6596. When optional argument PARENT is non-nil, consider parent
  6597. headline instead of current one."
  6598. (pcase (assq 'heading org-blank-before-new-entry)
  6599. (`(heading . auto)
  6600. (save-excursion
  6601. (org-with-limited-levels
  6602. (unless (and (org-before-first-heading-p)
  6603. (not (outline-next-heading)))
  6604. (org-back-to-heading t)
  6605. (when parent (org-up-heading-safe))
  6606. (cond ((not (bobp))
  6607. (org-previous-line-empty-p))
  6608. ((outline-next-heading)
  6609. (org-previous-line-empty-p))
  6610. ;; Ignore trailing spaces on last buffer line.
  6611. ((progn (skip-chars-backward " \t") (bolp))
  6612. (org-previous-line-empty-p))
  6613. (t nil))))))
  6614. (`(heading . ,value) value)
  6615. (_ nil)))
  6616. (defun org-insert-heading (&optional arg invisible-ok top)
  6617. "Insert a new heading or an item with the same depth at point.
  6618. If point is at the beginning of a heading, insert a new heading
  6619. or a new headline above the current one. When at the beginning
  6620. of a regular line of text, turn it into a heading.
  6621. If point is in the middle of a line, split it and create a new
  6622. headline with the text in the current line after point (see
  6623. `org-M-RET-may-split-line' on how to modify this behavior). As
  6624. a special case, on a headline, splitting can only happen on the
  6625. title itself. E.g., this excludes breaking stars or tags.
  6626. With a `\\[universal-argument]' prefix, set \
  6627. `org-insert-heading-respect-content' to
  6628. a non-nil value for the duration of the command. This forces the
  6629. insertion of a heading after the current subtree, independently
  6630. on the location of point.
  6631. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6632. insert the heading at the end of the tree
  6633. above the current heading. For example, if point is within a
  6634. 2nd-level heading, then it will insert a 2nd-level heading at
  6635. the end of the 1st-level parent subtree.
  6636. When INVISIBLE-OK is set, stop at invisible headlines when going
  6637. back. This is important for non-interactive uses of the
  6638. command.
  6639. When optional argument TOP is non-nil, insert a level 1 heading,
  6640. unconditionally."
  6641. (interactive "P")
  6642. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6643. (level (org-current-level))
  6644. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6645. (cond
  6646. ((or org-insert-heading-respect-content
  6647. (member arg '((4) (16)))
  6648. (and (not invisible-ok)
  6649. (invisible-p (max (1- (point)) (point-min)))))
  6650. ;; Position point at the location of insertion. Make sure we
  6651. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6652. (org-with-limited-levels
  6653. (if (not level) (outline-next-heading) ;before first headline
  6654. (org-back-to-heading invisible-ok)
  6655. (when (equal arg '(16)) (org-up-heading-safe))
  6656. (org-end-of-subtree)))
  6657. (unless (bolp) (insert "\n"))
  6658. (unless (and blank? (org-previous-line-empty-p))
  6659. (org-N-empty-lines-before-current (if blank? 1 0)))
  6660. (insert stars " ")
  6661. (when (eobp) (save-excursion (insert "\n")))
  6662. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6663. ;; is visible.
  6664. (unless invisible-ok
  6665. (pcase (get-char-property-and-overlay (point) 'invisible)
  6666. (`(outline . ,o)
  6667. (move-overlay o (overlay-start o) (line-end-position 0)))
  6668. (_ nil))))
  6669. ;; At a headline...
  6670. ((org-at-heading-p)
  6671. (cond ((bolp)
  6672. (when blank? (save-excursion (insert "\n")))
  6673. (save-excursion (insert stars " \n"))
  6674. (unless (and blank? (org-previous-line-empty-p))
  6675. (org-N-empty-lines-before-current (if blank? 1 0)))
  6676. (end-of-line))
  6677. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6678. (org-match-line org-complex-heading-regexp)
  6679. (org-pos-in-match-range (point) 4))
  6680. ;; Grab the text that should moved to the new headline.
  6681. ;; Preserve tags.
  6682. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6683. (if (looking-at "[ \t]*$") (replace-match "")
  6684. (org-align-tags))
  6685. (end-of-line)
  6686. (when blank? (insert "\n"))
  6687. (insert "\n" stars " ")
  6688. (when (org-string-nw-p split) (insert split))
  6689. (when (eobp) (save-excursion (insert "\n")))))
  6690. (t
  6691. (end-of-line)
  6692. (when blank? (insert "\n"))
  6693. (insert "\n" stars " ")
  6694. (when (eobp) (save-excursion (insert "\n"))))))
  6695. ;; On regular text, turn line into a headline or split, if
  6696. ;; appropriate.
  6697. ((bolp)
  6698. (insert stars " ")
  6699. (unless (and blank? (org-previous-line-empty-p))
  6700. (org-N-empty-lines-before-current (if blank? 1 0))))
  6701. (t
  6702. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6703. (end-of-line))
  6704. (insert "\n" stars " ")
  6705. (unless (and blank? (org-previous-line-empty-p))
  6706. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6707. (run-hooks 'org-insert-heading-hook))
  6708. (defun org-N-empty-lines-before-current (n)
  6709. "Make the number of empty lines before current exactly N.
  6710. So this will delete or add empty lines."
  6711. (let ((column (current-column)))
  6712. (beginning-of-line)
  6713. (unless (bobp)
  6714. (let ((start (save-excursion
  6715. (skip-chars-backward " \r\t\n")
  6716. (line-end-position))))
  6717. (delete-region start (line-end-position 0))))
  6718. (insert (make-string n ?\n))
  6719. (move-to-column column)))
  6720. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6721. "Return the heading of the current entry, without the stars.
  6722. When NO-TAGS is non-nil, don't include tags.
  6723. When NO-TODO is non-nil, don't include TODO keywords.
  6724. When NO-PRIORITY is non-nil, don't include priority cookie.
  6725. When NO-COMMENT is non-nil, don't include COMMENT string.
  6726. Return nil before first heading."
  6727. (unless (org-before-first-heading-p)
  6728. (save-excursion
  6729. (org-back-to-heading t)
  6730. (let ((case-fold-search nil))
  6731. (looking-at org-complex-heading-regexp)
  6732. (let ((todo (and (not no-todo) (match-string 2)))
  6733. (priority (and (not no-priority) (match-string 3)))
  6734. (headline (pcase (match-string 4)
  6735. (`nil "")
  6736. ((and (guard no-comment) h)
  6737. (replace-regexp-in-string
  6738. (eval-when-compile
  6739. (format "\\`%s[ \t]+" org-comment-string))
  6740. "" h))
  6741. (h h)))
  6742. (tags (and (not no-tags) (match-string 5))))
  6743. (mapconcat #'identity
  6744. (delq nil (list todo priority headline tags))
  6745. " "))))))
  6746. (defun org-heading-components ()
  6747. "Return the components of the current heading.
  6748. This is a list with the following elements:
  6749. - the level as an integer
  6750. - the reduced level, different if `org-odd-levels-only' is set.
  6751. - the TODO keyword, or nil
  6752. - the priority character, like ?A, or nil if no priority is given
  6753. - the headline text itself, or the tags string if no headline text
  6754. - the tags string, or nil."
  6755. (save-excursion
  6756. (org-back-to-heading t)
  6757. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6758. (list (length (match-string 1))
  6759. (org-reduced-level (length (match-string 1)))
  6760. (match-string-no-properties 2)
  6761. (and (match-end 3) (aref (match-string 3) 2))
  6762. (match-string-no-properties 4)
  6763. (match-string-no-properties 5)))))
  6764. (defun org-get-entry ()
  6765. "Get the entry text, after heading, entire subtree."
  6766. (save-excursion
  6767. (org-back-to-heading t)
  6768. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6769. (defun org-edit-headline (&optional heading)
  6770. "Edit the current headline.
  6771. Set it to HEADING when provided."
  6772. (interactive)
  6773. (org-with-wide-buffer
  6774. (org-back-to-heading t)
  6775. (let ((case-fold-search nil))
  6776. (when (looking-at org-complex-heading-regexp)
  6777. (let* ((old (match-string-no-properties 4))
  6778. (new (save-match-data
  6779. (org-trim (or heading (read-string "Edit: " old))))))
  6780. (unless (equal old new)
  6781. (if old (replace-match new t t nil 4)
  6782. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6783. (insert " " new))
  6784. (org-align-tags)
  6785. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6786. (defun org-insert-heading-after-current ()
  6787. "Insert a new heading with same level as current, after current subtree."
  6788. (interactive)
  6789. (org-back-to-heading)
  6790. (org-insert-heading)
  6791. (org-move-subtree-down)
  6792. (end-of-line 1))
  6793. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6794. "Insert heading with `org-insert-heading-respect-content' set to t."
  6795. (interactive)
  6796. (org-insert-heading '(4) invisible-ok))
  6797. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6798. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6799. (interactive)
  6800. (org-insert-todo-heading force-state '(4)))
  6801. (defun org-insert-todo-heading (arg &optional force-heading)
  6802. "Insert a new heading with the same level and TODO state as current heading.
  6803. If the heading has no TODO state, or if the state is DONE, use
  6804. the first state (TODO by default). Also with one prefix arg,
  6805. force first state. With two prefix args, force inserting at the
  6806. end of the parent subtree.
  6807. When called at a plain list item, insert a new item with an
  6808. unchecked check box."
  6809. (interactive "P")
  6810. (when (or force-heading (not (org-insert-item 'checkbox)))
  6811. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6812. force-heading))
  6813. (save-excursion
  6814. (org-forward-heading-same-level -1)
  6815. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6816. (let* ((new-mark-x
  6817. (if (or (equal arg '(4))
  6818. (not (match-beginning 2))
  6819. (member (match-string 2) org-done-keywords))
  6820. (car org-todo-keywords-1)
  6821. (match-string 2)))
  6822. (new-mark
  6823. (or
  6824. (run-hook-with-args-until-success
  6825. 'org-todo-get-default-hook new-mark-x nil)
  6826. new-mark-x)))
  6827. (beginning-of-line 1)
  6828. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6829. (if org-treat-insert-todo-heading-as-state-change
  6830. (org-todo new-mark)
  6831. (insert new-mark " "))))
  6832. (when org-provide-todo-statistics
  6833. (org-update-parent-todo-statistics))))
  6834. (defun org-insert-subheading (arg)
  6835. "Insert a new subheading and demote it.
  6836. Works for outline headings and for plain lists alike."
  6837. (interactive "P")
  6838. (org-insert-heading arg)
  6839. (cond
  6840. ((org-at-heading-p) (org-do-demote))
  6841. ((org-at-item-p) (org-indent-item))))
  6842. (defun org-insert-todo-subheading (arg)
  6843. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6844. Works for outline headings and for plain lists alike."
  6845. (interactive "P")
  6846. (org-insert-todo-heading arg)
  6847. (cond
  6848. ((org-at-heading-p) (org-do-demote))
  6849. ((org-at-item-p) (org-indent-item))))
  6850. ;;; Promotion and Demotion
  6851. (defvar org-after-demote-entry-hook nil
  6852. "Hook run after an entry has been demoted.
  6853. The cursor will be at the beginning of the entry.
  6854. When a subtree is being demoted, the hook will be called for each node.")
  6855. (defvar org-after-promote-entry-hook nil
  6856. "Hook run after an entry has been promoted.
  6857. The cursor will be at the beginning of the entry.
  6858. When a subtree is being promoted, the hook will be called for each node.")
  6859. (defun org-promote-subtree ()
  6860. "Promote the entire subtree.
  6861. See also `org-promote'."
  6862. (interactive)
  6863. (save-excursion
  6864. (org-with-limited-levels (org-map-tree 'org-promote)))
  6865. (org-fix-position-after-promote))
  6866. (defun org-demote-subtree ()
  6867. "Demote the entire subtree.
  6868. See `org-demote' and `org-promote'."
  6869. (interactive)
  6870. (save-excursion
  6871. (org-with-limited-levels (org-map-tree 'org-demote)))
  6872. (org-fix-position-after-promote))
  6873. (defun org-do-promote ()
  6874. "Promote the current heading higher up the tree.
  6875. If the region is active in `transient-mark-mode', promote all
  6876. headings in the region."
  6877. (interactive)
  6878. (save-excursion
  6879. (if (org-region-active-p)
  6880. (org-map-region 'org-promote (region-beginning) (region-end))
  6881. (org-promote)))
  6882. (org-fix-position-after-promote))
  6883. (defun org-do-demote ()
  6884. "Demote the current heading lower down the tree.
  6885. If the region is active in `transient-mark-mode', demote all
  6886. headings in the region."
  6887. (interactive)
  6888. (save-excursion
  6889. (if (org-region-active-p)
  6890. (org-map-region 'org-demote (region-beginning) (region-end))
  6891. (org-demote)))
  6892. (org-fix-position-after-promote))
  6893. (defun org-fix-position-after-promote ()
  6894. "Fix cursor position and indentation after demoting/promoting."
  6895. (let ((pos (point)))
  6896. (when (save-excursion
  6897. (beginning-of-line)
  6898. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6899. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6900. (cond ((eobp) (insert " "))
  6901. ((eolp) (insert " "))
  6902. ((equal (char-after) ?\s) (forward-char 1))))))
  6903. (defun org-current-level ()
  6904. "Return the level of the current entry, or nil if before the first headline.
  6905. The level is the number of stars at the beginning of the
  6906. headline. Use `org-reduced-level' to remove the effect of
  6907. `org-odd-levels'. Unlike to `org-outline-level', this function
  6908. ignores inlinetasks."
  6909. (let ((level (org-with-limited-levels (org-outline-level))))
  6910. (and (> level 0) level)))
  6911. (defun org-get-previous-line-level ()
  6912. "Return the outline depth of the last headline before the current line.
  6913. Returns 0 for the first headline in the buffer, and nil if before the
  6914. first headline."
  6915. (and (org-current-level)
  6916. (or (and (/= (line-beginning-position) (point-min))
  6917. (save-excursion (beginning-of-line 0) (org-current-level)))
  6918. 0)))
  6919. (defun org-reduced-level (l)
  6920. "Compute the effective level of a heading.
  6921. This takes into account the setting of `org-odd-levels-only'."
  6922. (cond
  6923. ((zerop l) 0)
  6924. (org-odd-levels-only (1+ (floor (/ l 2))))
  6925. (t l)))
  6926. (defun org-level-increment ()
  6927. "Return the number of stars that will be added or removed at a
  6928. time to headlines when structure editing, based on the value of
  6929. `org-odd-levels-only'."
  6930. (if org-odd-levels-only 2 1))
  6931. (defun org-get-valid-level (level &optional change)
  6932. "Rectify a level change under the influence of `org-odd-levels-only'.
  6933. LEVEL is a current level, CHANGE is by how much the level should
  6934. be modified. Even if CHANGE is nil, LEVEL may be returned
  6935. modified because even level numbers will become the next higher
  6936. odd number. Returns values greater than 0."
  6937. (if org-odd-levels-only
  6938. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6939. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6940. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6941. (max 1 (+ level (or change 0)))))
  6942. (defun org-promote ()
  6943. "Promote the current heading higher up the tree."
  6944. (org-with-wide-buffer
  6945. (org-back-to-heading t)
  6946. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6947. after-change-functions))
  6948. (level (save-match-data (funcall outline-level)))
  6949. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6950. (diff (abs (- level (length up-head) -1))))
  6951. (cond
  6952. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6953. (replace-match "# " nil t))
  6954. ((= level 1)
  6955. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6956. (t (replace-match up-head nil t)))
  6957. (unless (= level 1)
  6958. (when org-auto-align-tags (org-align-tags))
  6959. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6960. (run-hooks 'org-after-promote-entry-hook))))
  6961. (defun org-demote ()
  6962. "Demote the current heading lower down the tree."
  6963. (org-with-wide-buffer
  6964. (org-back-to-heading t)
  6965. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6966. after-change-functions))
  6967. (level (save-match-data (funcall outline-level)))
  6968. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6969. (diff (abs (- level (length down-head) -1))))
  6970. (replace-match down-head nil t)
  6971. (when org-auto-align-tags (org-align-tags))
  6972. (when org-adapt-indentation (org-fixup-indentation diff))
  6973. (run-hooks 'org-after-demote-entry-hook))))
  6974. (defun org-cycle-level ()
  6975. "Cycle the level of an empty headline through possible states.
  6976. This goes first to child, then to parent, level, then up the hierarchy.
  6977. After top level, it switches back to sibling level."
  6978. (interactive)
  6979. (let ((org-adapt-indentation nil))
  6980. (when (org-point-at-end-of-empty-headline)
  6981. (setq this-command 'org-cycle-level) ; Only needed for caching
  6982. (let ((cur-level (org-current-level))
  6983. (prev-level (org-get-previous-line-level)))
  6984. (cond
  6985. ;; If first headline in file, promote to top-level.
  6986. ((= prev-level 0)
  6987. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6988. do (org-do-promote)))
  6989. ;; If same level as prev, demote one.
  6990. ((= prev-level cur-level)
  6991. (org-do-demote))
  6992. ;; If parent is top-level, promote to top level if not already.
  6993. ((= prev-level 1)
  6994. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6995. do (org-do-promote)))
  6996. ;; If top-level, return to prev-level.
  6997. ((= cur-level 1)
  6998. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6999. do (org-do-demote)))
  7000. ;; If less than prev-level, promote one.
  7001. ((< cur-level prev-level)
  7002. (org-do-promote))
  7003. ;; If deeper than prev-level, promote until higher than
  7004. ;; prev-level.
  7005. ((> cur-level prev-level)
  7006. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7007. do (org-do-promote))))
  7008. t))))
  7009. (defun org-map-tree (fun)
  7010. "Call FUN for every heading underneath the current one."
  7011. (org-back-to-heading t)
  7012. (let ((level (funcall outline-level)))
  7013. (save-excursion
  7014. (funcall fun)
  7015. (while (and (progn
  7016. (outline-next-heading)
  7017. (> (funcall outline-level) level))
  7018. (not (eobp)))
  7019. (funcall fun)))))
  7020. (defun org-map-region (fun beg end)
  7021. "Call FUN for every heading between BEG and END."
  7022. (let ((org-ignore-region t))
  7023. (save-excursion
  7024. (setq end (copy-marker end))
  7025. (goto-char beg)
  7026. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7027. (< (point) end))
  7028. (funcall fun))
  7029. (while (and (progn
  7030. (outline-next-heading)
  7031. (< (point) end))
  7032. (not (eobp)))
  7033. (funcall fun)))))
  7034. (defun org-fixup-indentation (diff)
  7035. "Change the indentation in the current entry by DIFF.
  7036. DIFF is an integer. Indentation is done according to the
  7037. following rules:
  7038. - Planning information and property drawers are always indented
  7039. according to the new level of the headline;
  7040. - Footnote definitions and their contents are ignored;
  7041. - Inlinetasks' boundaries are not shifted;
  7042. - Empty lines are ignored;
  7043. - Other lines' indentation are shifted by DIFF columns, unless
  7044. it would introduce a structural change in the document, in
  7045. which case no shifting is done at all.
  7046. Assume point is at a heading or an inlinetask beginning."
  7047. (org-with-wide-buffer
  7048. (narrow-to-region (line-beginning-position)
  7049. (save-excursion
  7050. (if (org-with-limited-levels (org-at-heading-p))
  7051. (org-with-limited-levels (outline-next-heading))
  7052. (org-inlinetask-goto-end))
  7053. (point)))
  7054. (forward-line)
  7055. ;; Indent properly planning info and property drawer.
  7056. (when (looking-at-p org-planning-line-re)
  7057. (org-indent-line)
  7058. (forward-line))
  7059. (when (looking-at org-property-drawer-re)
  7060. (goto-char (match-end 0))
  7061. (forward-line)
  7062. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7063. (catch 'no-shift
  7064. (when (zerop diff) (throw 'no-shift nil))
  7065. ;; If DIFF is negative, first check if a shift is possible at all
  7066. ;; (e.g., it doesn't break structure). This can only happen if
  7067. ;; some contents are not properly indented.
  7068. (let ((case-fold-search t))
  7069. (when (< diff 0)
  7070. (let ((diff (- diff))
  7071. (forbidden-re (concat org-outline-regexp
  7072. "\\|"
  7073. (substring org-footnote-definition-re 1))))
  7074. (save-excursion
  7075. (while (not (eobp))
  7076. (cond
  7077. ((looking-at-p "[ \t]*$") (forward-line))
  7078. ((and (looking-at-p org-footnote-definition-re)
  7079. (let ((e (org-element-at-point)))
  7080. (and (eq (org-element-type e) 'footnote-definition)
  7081. (goto-char (org-element-property :end e))))))
  7082. ((looking-at-p org-outline-regexp) (forward-line))
  7083. ;; Give up if shifting would move before column 0 or
  7084. ;; if it would introduce a headline or a footnote
  7085. ;; definition.
  7086. (t
  7087. (skip-chars-forward " \t")
  7088. (let ((ind (current-column)))
  7089. (when (or (< ind diff)
  7090. (and (= ind diff) (looking-at-p forbidden-re)))
  7091. (throw 'no-shift nil)))
  7092. ;; Ignore contents of example blocks and source
  7093. ;; blocks if their indentation is meant to be
  7094. ;; preserved. Jump to block's closing line.
  7095. (beginning-of-line)
  7096. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7097. (let ((e (org-element-at-point)))
  7098. (and (memq (org-element-type e)
  7099. '(example-block src-block))
  7100. (or org-src-preserve-indentation
  7101. (org-element-property :preserve-indent e))
  7102. (goto-char (org-element-property :end e))
  7103. (progn (skip-chars-backward " \r\t\n")
  7104. (beginning-of-line)
  7105. t))))
  7106. (forward-line))))))))
  7107. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7108. ;; by DIFF. Also skip contents of source or example blocks
  7109. ;; when indentation is meant to be preserved.
  7110. (while (not (eobp))
  7111. (cond
  7112. ((and (looking-at-p org-footnote-definition-re)
  7113. (let ((e (org-element-at-point)))
  7114. (and (eq (org-element-type e) 'footnote-definition)
  7115. (goto-char (org-element-property :end e))))))
  7116. ((looking-at-p org-outline-regexp) (forward-line))
  7117. ((looking-at-p "[ \t]*$") (forward-line))
  7118. (t
  7119. (indent-line-to (+ (current-indentation) diff))
  7120. (beginning-of-line)
  7121. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7122. (let ((e (org-element-at-point)))
  7123. (and (memq (org-element-type e)
  7124. '(example-block src-block))
  7125. (or org-src-preserve-indentation
  7126. (org-element-property :preserve-indent e))
  7127. (goto-char (org-element-property :end e))
  7128. (progn (skip-chars-backward " \r\t\n")
  7129. (beginning-of-line)
  7130. t))))
  7131. (forward-line)))))))))
  7132. (defun org-convert-to-odd-levels ()
  7133. "Convert an Org file with all levels allowed to one with odd levels.
  7134. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7135. level 5 etc."
  7136. (interactive)
  7137. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7138. (let ((outline-level 'org-outline-level)
  7139. (org-odd-levels-only nil) n)
  7140. (save-excursion
  7141. (goto-char (point-min))
  7142. (while (re-search-forward "^\\*\\*+ " nil t)
  7143. (setq n (- (length (match-string 0)) 2))
  7144. (while (>= (setq n (1- n)) 0)
  7145. (org-demote))
  7146. (end-of-line 1))))))
  7147. (defun org-convert-to-oddeven-levels ()
  7148. "Convert an Org file with only odd levels to one with odd/even levels.
  7149. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7150. file contains a section with an even level, conversion would
  7151. destroy the structure of the file. An error is signaled in this
  7152. case."
  7153. (interactive)
  7154. (goto-char (point-min))
  7155. ;; First check if there are no even levels
  7156. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7157. (org-show-set-visibility 'canonical)
  7158. (error "Not all levels are odd in this file. Conversion not possible"))
  7159. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7160. (let ((outline-regexp org-outline-regexp)
  7161. (outline-level 'org-outline-level)
  7162. (org-odd-levels-only nil) n)
  7163. (save-excursion
  7164. (goto-char (point-min))
  7165. (while (re-search-forward "^\\*\\*+ " nil t)
  7166. (setq n (/ (1- (length (match-string 0))) 2))
  7167. (while (>= (setq n (1- n)) 0)
  7168. (org-promote))
  7169. (end-of-line 1))))))
  7170. (defun org-tr-level (n)
  7171. "Make N odd if required."
  7172. (if org-odd-levels-only (1+ (/ n 2)) n))
  7173. ;;; Vertical tree motion, cutting and pasting of subtrees
  7174. (defun org-move-subtree-up (&optional arg)
  7175. "Move the current subtree up past ARG headlines of the same level."
  7176. (interactive "p")
  7177. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7178. (defun org-move-subtree-down (&optional arg)
  7179. "Move the current subtree down past ARG headlines of the same level."
  7180. (interactive "p")
  7181. (setq arg (prefix-numeric-value arg))
  7182. (org-preserve-local-variables
  7183. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7184. 'org-get-last-sibling))
  7185. (ins-point (make-marker))
  7186. (cnt (abs arg))
  7187. (col (current-column))
  7188. beg end txt folded)
  7189. ;; Select the tree
  7190. (org-back-to-heading)
  7191. (setq beg (point))
  7192. (save-match-data
  7193. (save-excursion (outline-end-of-heading)
  7194. (setq folded (org-invisible-p)))
  7195. (progn (org-end-of-subtree nil t)
  7196. (unless (eobp) (backward-char))))
  7197. (outline-next-heading)
  7198. (setq end (point))
  7199. (goto-char beg)
  7200. ;; Find insertion point, with error handling
  7201. (while (> cnt 0)
  7202. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  7203. (goto-char beg)
  7204. (user-error "Cannot move past superior level or buffer limit"))
  7205. (setq cnt (1- cnt)))
  7206. (when (> arg 0)
  7207. ;; Moving forward - still need to move over subtree
  7208. (org-end-of-subtree t t)
  7209. (save-excursion
  7210. (org-back-over-empty-lines)
  7211. (or (bolp) (newline))))
  7212. (move-marker ins-point (point))
  7213. (setq txt (buffer-substring beg end))
  7214. (org-save-markers-in-region beg end)
  7215. (delete-region beg end)
  7216. (org-remove-empty-overlays-at beg)
  7217. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  7218. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  7219. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7220. (let ((bbb (point)))
  7221. (insert-before-markers txt)
  7222. (org-reinstall-markers-in-region bbb)
  7223. (move-marker ins-point bbb))
  7224. (or (bolp) (insert "\n"))
  7225. (goto-char ins-point)
  7226. (org-skip-whitespace)
  7227. (move-marker ins-point nil)
  7228. (if folded
  7229. (outline-hide-subtree)
  7230. (org-show-entry)
  7231. (org-show-children))
  7232. (org-clean-visibility-after-subtree-move)
  7233. ;; move back to the initial column we were at
  7234. (move-to-column col))))
  7235. (defvar org-subtree-clip ""
  7236. "Clipboard for cut and paste of subtrees.
  7237. This is actually only a copy of the kill, because we use the normal kill
  7238. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7239. (defvar org-subtree-clip-folded nil
  7240. "Was the last copied subtree folded?
  7241. This is used to fold the tree back after pasting.")
  7242. (defun org-cut-subtree (&optional n)
  7243. "Cut the current subtree into the clipboard.
  7244. With prefix arg N, cut this many sequential subtrees.
  7245. This is a short-hand for marking the subtree and then cutting it."
  7246. (interactive "p")
  7247. (org-copy-subtree n 'cut))
  7248. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7249. "Copy the current subtree into the clipboard.
  7250. With prefix arg N, copy this many sequential subtrees.
  7251. This is a short-hand for marking the subtree and then copying it.
  7252. If CUT is non-nil, actually cut the subtree.
  7253. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7254. of some markers in the region, even if CUT is non-nil. This is
  7255. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7256. (interactive "p")
  7257. (org-preserve-local-variables
  7258. (let (beg end folded (beg0 (point)))
  7259. (if (called-interactively-p 'any)
  7260. (org-back-to-heading nil) ; take what looks like a subtree
  7261. (org-back-to-heading t)) ; take what is really there
  7262. (setq beg (point))
  7263. (skip-chars-forward " \t\r\n")
  7264. (save-match-data
  7265. (if nosubtrees
  7266. (outline-next-heading)
  7267. (save-excursion (outline-end-of-heading)
  7268. (setq folded (org-invisible-p)))
  7269. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7270. (org-end-of-subtree t t)))
  7271. ;; Include the end of an inlinetask
  7272. (when (and (featurep 'org-inlinetask)
  7273. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7274. "END[ \t]*$")))
  7275. (end-of-line))
  7276. (setq end (point))
  7277. (goto-char beg0)
  7278. (when (> end beg)
  7279. (setq org-subtree-clip-folded folded)
  7280. (when (or cut force-store-markers)
  7281. (org-save-markers-in-region beg end))
  7282. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7283. (setq org-subtree-clip (current-kill 0))
  7284. (message "%s: Subtree(s) with %d characters"
  7285. (if cut "Cut" "Copied")
  7286. (length org-subtree-clip))))))
  7287. (defun org-paste-subtree (&optional level tree for-yank remove)
  7288. "Paste the clipboard as a subtree, with modification of headline level.
  7289. The entire subtree is promoted or demoted in order to match a new headline
  7290. level.
  7291. If the cursor is at the beginning of a headline, the same level as
  7292. that headline is used to paste the tree.
  7293. If not, the new level is derived from the *visible* headings
  7294. before and after the insertion point, and taken to be the inferior headline
  7295. level of the two. So if the previous visible heading is level 3 and the
  7296. next is level 4 (or vice versa), level 4 will be used for insertion.
  7297. This makes sure that the subtree remains an independent subtree and does
  7298. not swallow low level entries.
  7299. You can also force a different level, either by using a numeric prefix
  7300. argument, or by inserting the heading marker by hand. For example, if the
  7301. cursor is after \"*****\", then the tree will be shifted to level 5.
  7302. If optional TREE is given, use this text instead of the kill ring.
  7303. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7304. move back over whitespace before inserting, and move point to the end of
  7305. the inserted text when done.
  7306. When REMOVE is non-nil, remove the subtree from the clipboard."
  7307. (interactive "P")
  7308. (setq tree (or tree (and kill-ring (current-kill 0))))
  7309. (unless (org-kill-is-subtree-p tree)
  7310. (user-error
  7311. (substitute-command-keys
  7312. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  7313. (org-with-limited-levels
  7314. (let* ((visp (not (org-invisible-p)))
  7315. (txt tree)
  7316. (old-level (if (string-match org-outline-regexp-bol txt)
  7317. (- (match-end 0) (match-beginning 0) 1)
  7318. -1))
  7319. (force-level
  7320. (cond
  7321. (level (prefix-numeric-value level))
  7322. ;; When point is after the stars in an otherwise empty
  7323. ;; headline, use the number of stars as the forced level.
  7324. ((and (org-match-line "^\\*+[ \t]*$")
  7325. (not (eq ?* (char-after))))
  7326. (org-outline-level))
  7327. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  7328. (previous-level
  7329. (save-excursion
  7330. (org-previous-visible-heading 1)
  7331. (if (org-at-heading-p) (org-outline-level) 1)))
  7332. (next-level
  7333. (save-excursion
  7334. (if (org-at-heading-p) (org-outline-level)
  7335. (org-next-visible-heading 1)
  7336. (if (org-at-heading-p) (org-outline-level) 1))))
  7337. (new-level (or force-level (max previous-level next-level)))
  7338. (shift (if (or (= old-level -1)
  7339. (= new-level -1)
  7340. (= old-level new-level))
  7341. 0
  7342. (- new-level old-level)))
  7343. (delta (if (> shift 0) -1 1))
  7344. (func (if (> shift 0) #'org-demote #'org-promote))
  7345. (org-odd-levels-only nil)
  7346. beg end newend)
  7347. ;; Remove the forced level indicator.
  7348. (when (and force-level (not level))
  7349. (delete-region (line-beginning-position) (point)))
  7350. ;; Paste before the next visible heading or at end of buffer,
  7351. ;; unless point is at the beginning of a headline.
  7352. (unless (and (bolp) (org-at-heading-p))
  7353. (org-next-visible-heading 1)
  7354. (unless (bolp) (insert "\n")))
  7355. (setq beg (point))
  7356. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7357. (insert-before-markers txt)
  7358. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7359. (setq newend (point))
  7360. (org-reinstall-markers-in-region beg)
  7361. (setq end (point))
  7362. (goto-char beg)
  7363. (skip-chars-forward " \t\n\r")
  7364. (setq beg (point))
  7365. (when (and (org-invisible-p) visp)
  7366. (save-excursion (outline-show-heading)))
  7367. ;; Shift if necessary.
  7368. (unless (= shift 0)
  7369. (save-restriction
  7370. (narrow-to-region beg end)
  7371. (while (not (= shift 0))
  7372. (org-map-region func (point-min) (point-max))
  7373. (setq shift (+ delta shift)))
  7374. (goto-char (point-min))
  7375. (setq newend (point-max))))
  7376. (when (or for-yank (called-interactively-p 'interactive))
  7377. (message "Clipboard pasted as level %d subtree" new-level))
  7378. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7379. kill-ring
  7380. (equal org-subtree-clip (current-kill 0))
  7381. org-subtree-clip-folded)
  7382. ;; The tree was folded before it was killed/copied
  7383. (outline-hide-subtree))
  7384. (when for-yank (goto-char newend))
  7385. (when remove (pop kill-ring)))))
  7386. (defun org-kill-is-subtree-p (&optional txt)
  7387. "Check if the current kill is an outline subtree, or a set of trees.
  7388. Returns nil if kill does not start with a headline, or if the first
  7389. headline level is not the largest headline level in the tree.
  7390. So this will actually accept several entries of equal levels as well,
  7391. which is OK for `org-paste-subtree'.
  7392. If optional TXT is given, check this string instead of the current kill."
  7393. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7394. (re (org-get-limited-outline-regexp))
  7395. (^re (concat "^" re))
  7396. (start-level (and kill
  7397. (string-match
  7398. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7399. kill)
  7400. (- (match-end 2) (match-beginning 2) 1)))
  7401. (start (1+ (or (match-beginning 2) -1))))
  7402. (if (not start-level)
  7403. (progn
  7404. nil) ;; does not even start with a heading
  7405. (catch 'exit
  7406. (while (setq start (string-match ^re kill (1+ start)))
  7407. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7408. (throw 'exit nil)))
  7409. t))))
  7410. (defvar org-markers-to-move nil
  7411. "Markers that should be moved with a cut-and-paste operation.
  7412. Those markers are stored together with their positions relative to
  7413. the start of the region.")
  7414. (defun org-save-markers-in-region (beg end)
  7415. "Check markers in region.
  7416. If these markers are between BEG and END, record their position relative
  7417. to BEG, so that after moving the block of text, we can put the markers back
  7418. into place.
  7419. This function gets called just before an entry or tree gets cut from the
  7420. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7421. called immediately, to move the markers with the entries."
  7422. (setq org-markers-to-move nil)
  7423. (when (featurep 'org-clock)
  7424. (org-clock-save-markers-for-cut-and-paste beg end))
  7425. (when (featurep 'org-agenda)
  7426. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7427. (defun org-check-and-save-marker (marker beg end)
  7428. "Check if MARKER is between BEG and END.
  7429. If yes, remember the marker and the distance to BEG."
  7430. (when (and (marker-buffer marker)
  7431. (equal (marker-buffer marker) (current-buffer))
  7432. (>= marker beg) (< marker end))
  7433. (push (cons marker (- marker beg)) org-markers-to-move)))
  7434. (defun org-reinstall-markers-in-region (beg)
  7435. "Move all remembered markers to their position relative to BEG."
  7436. (dolist (x org-markers-to-move)
  7437. (move-marker (car x) (+ beg (cdr x))))
  7438. (setq org-markers-to-move nil))
  7439. (defun org-narrow-to-subtree ()
  7440. "Narrow buffer to the current subtree."
  7441. (interactive)
  7442. (save-excursion
  7443. (save-match-data
  7444. (org-with-limited-levels
  7445. (narrow-to-region
  7446. (progn (org-back-to-heading t) (point))
  7447. (progn (org-end-of-subtree t t)
  7448. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7449. (point)))))))
  7450. (defun org-toggle-narrow-to-subtree ()
  7451. "Narrow to the subtree at point or widen a narrowed buffer."
  7452. (interactive)
  7453. (if (buffer-narrowed-p)
  7454. (widen)
  7455. (org-narrow-to-subtree)))
  7456. (defun org-narrow-to-block ()
  7457. "Narrow buffer to the current block."
  7458. (interactive)
  7459. (let* ((case-fold-search t)
  7460. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7461. "^[ \t]*#\\+end_.*")))
  7462. (if blockp
  7463. (narrow-to-region (car blockp) (cdr blockp))
  7464. (user-error "Not in a block"))))
  7465. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7466. "Clone the task (subtree) at point N times.
  7467. The clones will be inserted as siblings.
  7468. In interactive use, the user will be prompted for the number of
  7469. clones to be produced. If the entry has a timestamp, the user
  7470. will also be prompted for a time shift, which may be a repeater
  7471. as used in time stamps, for example `+3d'. To disable this,
  7472. you can call the function with a universal prefix argument.
  7473. When a valid repeater is given and the entry contains any time
  7474. stamps, the clones will become a sequence in time, with time
  7475. stamps in the subtree shifted for each clone produced. If SHIFT
  7476. is nil or the empty string, time stamps will be left alone. The
  7477. ID property of the original subtree is removed.
  7478. In each clone, all the CLOCK entries will be removed. This
  7479. prevents Org from considering that the clocked times overlap.
  7480. If the original subtree did contain time stamps with a repeater,
  7481. the following will happen:
  7482. - the repeater will be removed in each clone
  7483. - an additional clone will be produced, with the current, unshifted
  7484. date(s) in the entry.
  7485. - the original entry will be placed *after* all the clones, with
  7486. repeater intact.
  7487. - the start days in the repeater in the original entry will be shifted
  7488. to past the last clone.
  7489. In this way you can spell out a number of instances of a repeating task,
  7490. and still retain the repeater to cover future instances of the task.
  7491. As described above, N+1 clones are produced when the original
  7492. subtree has a repeater. Setting N to 0, then, can be used to
  7493. remove the repeater from a subtree and create a shifted clone
  7494. with the original repeater."
  7495. (interactive "nNumber of clones to produce: ")
  7496. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7497. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7498. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7499. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7500. (shift
  7501. (or shift
  7502. (if (and (not (equal current-prefix-arg '(4)))
  7503. (save-excursion
  7504. (goto-char beg)
  7505. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7506. (read-from-minibuffer
  7507. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7508. ""))) ;No time shift
  7509. (doshift
  7510. (and (org-string-nw-p shift)
  7511. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7512. shift)
  7513. (user-error "Invalid shift specification %s" shift)))))
  7514. (goto-char end-of-tree)
  7515. (unless (bolp) (insert "\n"))
  7516. (let* ((end (point))
  7517. (template (buffer-substring beg end))
  7518. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7519. (shift-what (pcase (and doshift (match-string 2 shift))
  7520. (`nil nil)
  7521. ("d" 'day)
  7522. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7523. ("m" 'month)
  7524. ("y" 'year)
  7525. (_ (error "Unsupported time unit"))))
  7526. (nmin 1)
  7527. (nmax n)
  7528. (n-no-remove -1)
  7529. (idprop (org-entry-get nil "ID")))
  7530. (when (and doshift
  7531. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7532. template))
  7533. (delete-region beg end)
  7534. (setq end beg)
  7535. (setq nmin 0)
  7536. (setq nmax (1+ nmax))
  7537. (setq n-no-remove nmax))
  7538. (goto-char end)
  7539. (cl-loop for n from nmin to nmax do
  7540. (insert
  7541. ;; Prepare clone.
  7542. (with-temp-buffer
  7543. (insert template)
  7544. (org-mode)
  7545. (goto-char (point-min))
  7546. (org-show-subtree)
  7547. (and idprop (if org-clone-delete-id
  7548. (org-entry-delete nil "ID")
  7549. (org-id-get-create t)))
  7550. (unless (= n 0)
  7551. (while (re-search-forward org-clock-line-re nil t)
  7552. (delete-region (line-beginning-position)
  7553. (line-beginning-position 2)))
  7554. (goto-char (point-min))
  7555. (while (re-search-forward org-drawer-regexp nil t)
  7556. (org-remove-empty-drawer-at (point))))
  7557. (goto-char (point-min))
  7558. (when doshift
  7559. (while (re-search-forward org-ts-regexp-both nil t)
  7560. (org-timestamp-change (* n shift-n) shift-what))
  7561. (unless (= n n-no-remove)
  7562. (goto-char (point-min))
  7563. (while (re-search-forward org-ts-regexp nil t)
  7564. (save-excursion
  7565. (goto-char (match-beginning 0))
  7566. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7567. (delete-region (match-beginning 1) (match-end 1)))))))
  7568. (buffer-string)))))
  7569. (goto-char beg)))
  7570. ;;; Outline Sorting
  7571. (defun org-sort (&optional with-case)
  7572. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7573. Optional argument WITH-CASE means sort case-sensitively."
  7574. (interactive "P")
  7575. (org-call-with-arg
  7576. (cond ((org-at-table-p) #'org-table-sort-lines)
  7577. ((org-at-item-p) #'org-sort-list)
  7578. (t #'org-sort-entries))
  7579. with-case))
  7580. (defun org-sort-remove-invisible (s)
  7581. "Remove invisible part of links and emphasis markers from string S."
  7582. (remove-text-properties 0 (length s) org-rm-props s)
  7583. (replace-regexp-in-string
  7584. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7585. (replace-regexp-in-string
  7586. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7587. (org-link-display-format s)
  7588. t t) t t))
  7589. (defvar org-priority-regexp) ; defined later in the file
  7590. (defvar org-after-sorting-entries-or-items-hook nil
  7591. "Hook that is run after a bunch of entries or items have been sorted.
  7592. When children are sorted, the cursor is in the parent line when this
  7593. hook gets called. When a region or a plain list is sorted, the cursor
  7594. will be in the first entry of the sorted region/list.")
  7595. (defun org-sort-entries
  7596. (&optional with-case sorting-type getkey-func compare-func property
  7597. interactive?)
  7598. "Sort entries on a certain level of an outline tree.
  7599. If there is an active region, the entries in the region are sorted.
  7600. Else, if the cursor is before the first entry, sort the top-level items.
  7601. Else, the children of the entry at point are sorted.
  7602. Sorting can be alphabetically, numerically, by date/time as given by
  7603. a time stamp, by a property, by priority order, or by a custom function.
  7604. The command prompts for the sorting type unless it has been given to the
  7605. function through the SORTING-TYPE argument, which needs to be a character,
  7606. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7607. the precise meaning of each character:
  7608. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7609. c By creation time, which is assumed to be the first inactive time stamp
  7610. at the beginning of a line.
  7611. d By deadline date/time.
  7612. k By clocking time.
  7613. n Numerically, by converting the beginning of the entry/item to a number.
  7614. o By order of TODO keywords.
  7615. p By priority according to the cookie.
  7616. r By the value of a property.
  7617. s By scheduled date/time.
  7618. t By date/time, either the first active time stamp in the entry, or, if
  7619. none exist, by the first inactive one.
  7620. Capital letters will reverse the sort order.
  7621. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7622. called with point at the beginning of the record. It must return a
  7623. value that is compatible with COMPARE-FUNC, the function used to
  7624. compare entries.
  7625. Comparing entries ignores case by default. However, with an optional argument
  7626. WITH-CASE, the sorting considers case as well.
  7627. Sorting is done against the visible part of the headlines, it ignores hidden
  7628. links.
  7629. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7630. A non-nil value for INTERACTIVE? is used to signal that this
  7631. function is being called interactively."
  7632. (interactive (list current-prefix-arg nil nil nil nil t))
  7633. (let ((case-func (if with-case 'identity 'downcase))
  7634. start beg end stars re re2
  7635. txt what tmp)
  7636. ;; Find beginning and end of region to sort
  7637. (cond
  7638. ((org-region-active-p)
  7639. ;; we will sort the region
  7640. (setq end (region-end)
  7641. what "region")
  7642. (goto-char (region-beginning))
  7643. (unless (org-at-heading-p) (outline-next-heading))
  7644. (setq start (point)))
  7645. ((or (org-at-heading-p)
  7646. (ignore-errors (progn (org-back-to-heading) t)))
  7647. ;; we will sort the children of the current headline
  7648. (org-back-to-heading)
  7649. (setq start (point)
  7650. end (progn (org-end-of-subtree t t)
  7651. (or (bolp) (insert "\n"))
  7652. (when (>= (org-back-over-empty-lines) 1)
  7653. (forward-line 1))
  7654. (point))
  7655. what "children")
  7656. (goto-char start)
  7657. (outline-show-subtree)
  7658. (outline-next-heading))
  7659. (t
  7660. ;; we will sort the top-level entries in this file
  7661. (goto-char (point-min))
  7662. (or (org-at-heading-p) (outline-next-heading))
  7663. (setq start (point))
  7664. (goto-char (point-max))
  7665. (beginning-of-line 1)
  7666. (when (looking-at ".*?\\S-")
  7667. ;; File ends in a non-white line
  7668. (end-of-line 1)
  7669. (insert "\n"))
  7670. (setq end (point-max))
  7671. (setq what "top-level")
  7672. (goto-char start)
  7673. (org-show-all '(headings blocks))))
  7674. (setq beg (point))
  7675. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7676. (looking-at "\\(\\*+\\)")
  7677. (setq stars (match-string 1)
  7678. re (concat "^" (regexp-quote stars) " +")
  7679. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7680. txt (buffer-substring beg end))
  7681. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7682. (when (and (not (equal stars "*")) (string-match re2 txt))
  7683. (user-error "Region to sort contains a level above the first entry"))
  7684. (unless sorting-type
  7685. (message
  7686. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7687. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7688. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7689. what)
  7690. (setq sorting-type (read-char-exclusive)))
  7691. (unless getkey-func
  7692. (and (= (downcase sorting-type) ?f)
  7693. (setq getkey-func
  7694. (or (and interactive?
  7695. (org-read-function
  7696. "Function for extracting keys: "))
  7697. (error "Missing key extractor")))))
  7698. (and (= (downcase sorting-type) ?r)
  7699. (not property)
  7700. (setq property
  7701. (completing-read "Property: "
  7702. (mapcar #'list (org-buffer-property-keys t))
  7703. nil t)))
  7704. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7705. (message "Sorting entries...")
  7706. (save-restriction
  7707. (narrow-to-region start end)
  7708. (let ((restore-clock?
  7709. ;; The clock marker is lost when using `sort-subr'; mark
  7710. ;; the clock with temporary `:org-clock-marker-backup'
  7711. ;; text property.
  7712. (when (and (eq (org-clock-is-active) (current-buffer))
  7713. (<= start (marker-position org-clock-marker))
  7714. (>= end (marker-position org-clock-marker)))
  7715. (with-silent-modifications
  7716. (put-text-property (1- org-clock-marker) org-clock-marker
  7717. :org-clock-marker-backup t))
  7718. t))
  7719. (dcst (downcase sorting-type))
  7720. (case-fold-search nil)
  7721. (now (current-time)))
  7722. (org-preserve-local-variables
  7723. (sort-subr
  7724. (/= dcst sorting-type)
  7725. ;; This function moves to the beginning character of the
  7726. ;; "record" to be sorted.
  7727. (lambda nil
  7728. (if (re-search-forward re nil t)
  7729. (goto-char (match-beginning 0))
  7730. (goto-char (point-max))))
  7731. ;; This function moves to the last character of the "record" being
  7732. ;; sorted.
  7733. (lambda nil
  7734. (save-match-data
  7735. (condition-case nil
  7736. (outline-forward-same-level 1)
  7737. (error
  7738. (goto-char (point-max))))))
  7739. ;; This function returns the value that gets sorted against.
  7740. (lambda ()
  7741. (cond
  7742. ((= dcst ?n)
  7743. (string-to-number
  7744. (org-sort-remove-invisible (org-get-heading t t t t))))
  7745. ((= dcst ?a)
  7746. (funcall case-func
  7747. (org-sort-remove-invisible (org-get-heading t t t t))))
  7748. ((= dcst ?k)
  7749. (or (get-text-property (point) :org-clock-minutes) 0))
  7750. ((= dcst ?t)
  7751. (let ((end (save-excursion (outline-next-heading) (point))))
  7752. (if (or (re-search-forward org-ts-regexp end t)
  7753. (re-search-forward org-ts-regexp-both end t))
  7754. (org-time-string-to-seconds (match-string 0))
  7755. (float-time now))))
  7756. ((= dcst ?c)
  7757. (let ((end (save-excursion (outline-next-heading) (point))))
  7758. (if (re-search-forward
  7759. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7760. end t)
  7761. (org-time-string-to-seconds (match-string 0))
  7762. (float-time now))))
  7763. ((= dcst ?s)
  7764. (let ((end (save-excursion (outline-next-heading) (point))))
  7765. (if (re-search-forward org-scheduled-time-regexp end t)
  7766. (org-time-string-to-seconds (match-string 1))
  7767. (float-time now))))
  7768. ((= dcst ?d)
  7769. (let ((end (save-excursion (outline-next-heading) (point))))
  7770. (if (re-search-forward org-deadline-time-regexp end t)
  7771. (org-time-string-to-seconds (match-string 1))
  7772. (float-time now))))
  7773. ((= dcst ?p)
  7774. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7775. (string-to-char (match-string 2))
  7776. org-default-priority))
  7777. ((= dcst ?r)
  7778. (or (org-entry-get nil property) ""))
  7779. ((= dcst ?o)
  7780. (when (looking-at org-complex-heading-regexp)
  7781. (let* ((m (match-string 2))
  7782. (s (if (member m org-done-keywords) '- '+)))
  7783. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7784. ((= dcst ?f)
  7785. (if getkey-func
  7786. (progn
  7787. (setq tmp (funcall getkey-func))
  7788. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7789. tmp)
  7790. (error "Invalid key function `%s'" getkey-func)))
  7791. (t (error "Invalid sorting type `%c'" sorting-type))))
  7792. nil
  7793. (cond
  7794. ((= dcst ?a) 'org-string-collate-lessp)
  7795. ((= dcst ?f)
  7796. (or compare-func
  7797. (and interactive?
  7798. (org-read-function
  7799. (concat "Function for comparing keys "
  7800. "(empty for default `sort-subr' predicate): ")
  7801. 'allow-empty))))
  7802. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7803. (when restore-clock?
  7804. (move-marker org-clock-marker
  7805. (1+ (next-single-property-change
  7806. start :org-clock-marker-backup)))
  7807. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7808. '(:org-clock-marker-backup t)))))
  7809. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7810. (message "Sorting entries...done")))
  7811. (defun org-contextualize-keys (alist contexts)
  7812. "Return valid elements in ALIST depending on CONTEXTS.
  7813. `org-agenda-custom-commands' or `org-capture-templates' are the
  7814. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7815. or `org-capture-templates-contexts' are the associated contexts
  7816. definitions."
  7817. (let ((contexts
  7818. ;; normalize contexts
  7819. (mapcar
  7820. (lambda(c) (cond ((listp (cadr c))
  7821. (list (car c) (car c) (nth 1 c)))
  7822. ((string= "" (cadr c))
  7823. (list (car c) (car c) (nth 2 c)))
  7824. (t c)))
  7825. contexts))
  7826. (a alist) r s)
  7827. ;; loop over all commands or templates
  7828. (dolist (c a)
  7829. (let (vrules repl)
  7830. (cond
  7831. ((not (assoc (car c) contexts))
  7832. (push c r))
  7833. ((and (assoc (car c) contexts)
  7834. (setq vrules (org-contextualize-validate-key
  7835. (car c) contexts)))
  7836. (mapc (lambda (vr)
  7837. (unless (equal (car vr) (cadr vr))
  7838. (setq repl vr)))
  7839. vrules)
  7840. (if (not repl) (push c r)
  7841. (push (cadr repl) s)
  7842. (push
  7843. (cons (car c)
  7844. (cdr (or (assoc (cadr repl) alist)
  7845. (error "Undefined key `%s' as contextual replacement for `%s'"
  7846. (cadr repl) (car c)))))
  7847. r))))))
  7848. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7849. (delq
  7850. nil
  7851. (delete-dups
  7852. (mapcar (lambda (x)
  7853. (let ((tpl (car x)))
  7854. (unless (delq
  7855. nil
  7856. (mapcar (lambda (y)
  7857. (equal y tpl))
  7858. s))
  7859. x)))
  7860. (reverse r))))))
  7861. (defun org-contextualize-validate-key (key contexts)
  7862. "Check CONTEXTS for agenda or capture KEY."
  7863. (let (res)
  7864. (dolist (r contexts)
  7865. (dolist (rr (car (last r)))
  7866. (when
  7867. (and (equal key (car r))
  7868. (if (functionp rr) (funcall rr)
  7869. (or (and (eq (car rr) 'in-file)
  7870. (buffer-file-name)
  7871. (string-match (cdr rr) (buffer-file-name)))
  7872. (and (eq (car rr) 'in-mode)
  7873. (string-match (cdr rr) (symbol-name major-mode)))
  7874. (and (eq (car rr) 'in-buffer)
  7875. (string-match (cdr rr) (buffer-name)))
  7876. (when (and (eq (car rr) 'not-in-file)
  7877. (buffer-file-name))
  7878. (not (string-match (cdr rr) (buffer-file-name))))
  7879. (when (eq (car rr) 'not-in-mode)
  7880. (not (string-match (cdr rr) (symbol-name major-mode))))
  7881. (when (eq (car rr) 'not-in-buffer)
  7882. (not (string-match (cdr rr) (buffer-name)))))))
  7883. (push r res))))
  7884. (delete-dups (delq nil res))))
  7885. ;; Defined to provide a value for defcustom, since there is no
  7886. ;; string-collate-greaterp in Emacs.
  7887. (defun org-string-collate-greaterp (s1 s2)
  7888. "Return non-nil if S1 is greater than S2 in collation order."
  7889. (not (org-string-collate-lessp s1 s2)))
  7890. ;;;###autoload
  7891. (defun org-run-like-in-org-mode (cmd)
  7892. "Run a command, pretending that the current buffer is in Org mode.
  7893. This will temporarily bind local variables that are typically bound in
  7894. Org mode to the values they have in Org mode, and then interactively
  7895. call CMD."
  7896. (org-load-modules-maybe)
  7897. (let (binds)
  7898. (dolist (var (org-get-local-variables))
  7899. (when (or (not (boundp (car var)))
  7900. (eq (symbol-value (car var))
  7901. (default-value (car var))))
  7902. (push (list (car var) `(quote ,(cadr var))) binds)))
  7903. (eval `(let ,binds
  7904. (call-interactively (quote ,cmd))))))
  7905. (defun org-get-category (&optional pos force-refresh)
  7906. "Get the category applying to position POS."
  7907. (save-match-data
  7908. (when force-refresh (org-refresh-category-properties))
  7909. (let ((pos (or pos (point))))
  7910. (or (get-text-property pos 'org-category)
  7911. (progn (org-refresh-category-properties)
  7912. (get-text-property pos 'org-category))))))
  7913. ;;; Refresh properties
  7914. (defun org-refresh-properties (dprop tprop)
  7915. "Refresh buffer text properties.
  7916. DPROP is the drawer property and TPROP is either the
  7917. corresponding text property to set, or an alist with each element
  7918. being a text property (as a symbol) and a function to apply to
  7919. the value of the drawer property."
  7920. (let* ((case-fold-search t)
  7921. (inhibit-read-only t)
  7922. (inherit? (org-property-inherit-p dprop))
  7923. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7924. (global (and inherit? (org--property-global-value dprop nil))))
  7925. (with-silent-modifications
  7926. (org-with-point-at 1
  7927. ;; Set global values (e.g., values defined through
  7928. ;; "#+PROPERTY:" keywords) to the whole buffer.
  7929. (when global (put-text-property (point-min) (point-max) tprop global))
  7930. ;; Set local values.
  7931. (while (re-search-forward property-re nil t)
  7932. (when (org-at-property-p)
  7933. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7934. (outline-next-heading))))))
  7935. (defun org-refresh-property (tprop p &optional inherit)
  7936. "Refresh the buffer text property TPROP from the drawer property P.
  7937. The refresh happens only for the current headline, or the whole
  7938. sub-tree if optional argument INHERIT is non-nil."
  7939. (unless (org-before-first-heading-p)
  7940. (save-excursion
  7941. (org-back-to-heading t)
  7942. (let ((start (point))
  7943. (end (save-excursion
  7944. (if inherit (org-end-of-subtree t t)
  7945. (or (outline-next-heading) (point-max))))))
  7946. (if (symbolp tprop)
  7947. ;; TPROP is a text property symbol.
  7948. (put-text-property start end tprop p)
  7949. ;; TPROP is an alist with (property . function) elements.
  7950. (pcase-dolist (`(,prop . ,f) tprop)
  7951. (put-text-property start end prop (funcall f p))))))))
  7952. (defun org-refresh-category-properties ()
  7953. "Refresh category text properties in the buffer."
  7954. (let ((case-fold-search t)
  7955. (inhibit-read-only t)
  7956. (default-category
  7957. (cond ((null org-category)
  7958. (if buffer-file-name
  7959. (file-name-sans-extension
  7960. (file-name-nondirectory buffer-file-name))
  7961. "???"))
  7962. ((symbolp org-category) (symbol-name org-category))
  7963. (t org-category))))
  7964. (with-silent-modifications
  7965. (org-with-wide-buffer
  7966. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  7967. ;; This is the default category for the buffer. If none is
  7968. ;; found, fall-back to `org-category' or buffer file name.
  7969. (put-text-property
  7970. (point-min) (point-max)
  7971. 'org-category
  7972. (catch 'buffer-category
  7973. (goto-char (point-max))
  7974. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7975. (let ((element (org-element-at-point)))
  7976. (when (eq (org-element-type element) 'keyword)
  7977. (throw 'buffer-category
  7978. (org-element-property :value element)))))
  7979. default-category))
  7980. ;; Set sub-tree specific categories.
  7981. (goto-char (point-min))
  7982. (let ((regexp (org-re-property "CATEGORY")))
  7983. (while (re-search-forward regexp nil t)
  7984. (let ((value (match-string-no-properties 3)))
  7985. (when (org-at-property-p)
  7986. (put-text-property
  7987. (save-excursion (org-back-to-heading t) (point))
  7988. (save-excursion (org-end-of-subtree t t) (point))
  7989. 'org-category
  7990. value)))))))))
  7991. (defun org-refresh-stats-properties ()
  7992. "Refresh stats text properties in the buffer."
  7993. (with-silent-modifications
  7994. (org-with-point-at 1
  7995. (let ((regexp (concat org-outline-regexp-bol
  7996. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7997. (while (re-search-forward regexp nil t)
  7998. (let* ((numerator (string-to-number (match-string 1)))
  7999. (denominator (and (match-end 2)
  8000. (string-to-number (match-string 2))))
  8001. (stats (cond ((not denominator) numerator) ;percent
  8002. ((= denominator 0) 0)
  8003. (t (/ (* numerator 100) denominator)))))
  8004. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8005. 'org-stats stats)))))))
  8006. (defun org-refresh-effort-properties ()
  8007. "Refresh effort properties"
  8008. (org-refresh-properties
  8009. org-effort-property
  8010. '((effort . identity)
  8011. (effort-minutes . org-duration-to-minutes))))
  8012. ;;;; Link Stuff
  8013. ;;; Link abbreviations
  8014. (defun org-link-expand-abbrev (link)
  8015. "Apply replacements as defined in `org-link-abbrev-alist'."
  8016. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8017. (let* ((key (match-string 1 link))
  8018. (as (or (assoc key org-link-abbrev-alist-local)
  8019. (assoc key org-link-abbrev-alist)))
  8020. (tag (and (match-end 2) (match-string 3 link)))
  8021. rpl)
  8022. (if (not as)
  8023. link
  8024. (setq rpl (cdr as))
  8025. (cond
  8026. ((symbolp rpl) (funcall rpl tag))
  8027. ((string-match "%(\\([^)]+\\))" rpl)
  8028. (replace-match
  8029. (save-match-data
  8030. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8031. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8032. ((string-match "%h" rpl)
  8033. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8034. (t (concat rpl tag)))))
  8035. link))
  8036. ;;; Storing and inserting links
  8037. (defvar org-insert-link-history nil
  8038. "Minibuffer history for links inserted with `org-insert-link'.")
  8039. (defvar org-stored-links nil
  8040. "Contains the links stored with `org-store-link'.")
  8041. (defvar org-store-link-plist nil
  8042. "Plist with info about the most recently link created with `org-store-link'.")
  8043. (defun org-store-link-functions ()
  8044. "Return a list of functions that are called to create and store a link.
  8045. The functions are defined in the `:store' property of
  8046. `org-link-parameters'.
  8047. Each function is called in turn until one returns a non-nil
  8048. value. Each function should check if it is responsible for
  8049. creating this link (for example by looking at the major mode).
  8050. If not, it must exit and return nil. If yes, it should return
  8051. a non-nil value after calling `org-store-link-props' with a list
  8052. of properties and values. Special properties are:
  8053. :type The link prefix, like \"http\". This must be given.
  8054. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8055. This is obligatory as well.
  8056. :description Optional default description for the second pair
  8057. of brackets in an Org mode link. The user can still change
  8058. this when inserting this link into an Org mode buffer.
  8059. In addition to these, any additional properties can be specified
  8060. and then used in capture templates."
  8061. (cl-loop for link in org-link-parameters
  8062. with store-func
  8063. do (setq store-func (org-link-get-parameter (car link) :store))
  8064. if store-func
  8065. collect store-func))
  8066. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8067. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8068. ;;;###autoload
  8069. (defun org-store-link (arg &optional interactive?)
  8070. "Store a link to the current location.
  8071. \\<org-mode-map>
  8072. This link is added to `org-stored-links' and can later be inserted
  8073. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8074. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8075. A single
  8076. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8077. `org-gnus-prefer-web-links' for links to Usenet articles.
  8078. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8079. skipping storing functions that are not
  8080. part of Org core.
  8081. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8082. prefix ARG forces storing a link for each line in the
  8083. active region.
  8084. Assume the function is called interactively if INTERACTIVE? is
  8085. non-nil."
  8086. (interactive "P\np")
  8087. (org-load-modules-maybe)
  8088. (if (and (equal arg '(64)) (org-region-active-p))
  8089. (save-excursion
  8090. (let ((end (region-end)))
  8091. (goto-char (region-beginning))
  8092. (set-mark (point))
  8093. (while (< (point-at-eol) end)
  8094. (move-end-of-line 1) (activate-mark)
  8095. (let (current-prefix-arg)
  8096. (call-interactively 'org-store-link))
  8097. (move-beginning-of-line 2)
  8098. (set-mark (point)))))
  8099. (setq org-store-link-plist nil)
  8100. (let (link cpltxt desc description search txt custom-id agenda-link)
  8101. (cond
  8102. ;; Store a link using an external link type, if any function is
  8103. ;; available. If more than one can generate a link from current
  8104. ;; location, ask which one to use.
  8105. ((and (not (equal arg '(16)))
  8106. (let ((results-alist nil))
  8107. (dolist (f (org-store-link-functions))
  8108. (when (funcall f)
  8109. ;; XXX: return value is not link's plist, so we
  8110. ;; store the new value before it is modified. It
  8111. ;; would be cleaner to ask store link functions to
  8112. ;; return the plist instead.
  8113. (push (cons f (copy-sequence org-store-link-plist))
  8114. results-alist)))
  8115. (pcase results-alist
  8116. (`nil nil)
  8117. (`((,_ . ,_)) t) ;single choice: nothing to do
  8118. (`((,name . ,_) . ,_)
  8119. ;; Reinstate link plist associated to the chosen
  8120. ;; function.
  8121. (apply #'org-store-link-props
  8122. (cdr (assoc-string
  8123. (completing-read
  8124. "Which function for creating the link? "
  8125. (mapcar #'car results-alist)
  8126. nil t (symbol-name name))
  8127. results-alist)))
  8128. t))))
  8129. (setq link (plist-get org-store-link-plist :link))
  8130. (setq desc (or (plist-get org-store-link-plist :description)
  8131. link)))
  8132. ;; Store a link from a remote editing buffer.
  8133. ((org-src-edit-buffer-p)
  8134. (let ((coderef-format (org-src-coderef-format))
  8135. (format-link
  8136. (lambda (label)
  8137. (if org-src-source-file-name
  8138. (format "file:%s::(%s)" org-src-source-file-name label)
  8139. (format "(%s)" label)))))
  8140. (cond
  8141. ;; Code references do not exist in this type of buffer.
  8142. ;; Pretend we're linking from the source buffer directly.
  8143. ((not (memq (org-src-source-type) '(example-block src-block)))
  8144. (with-current-buffer (org-src-source-buffer)
  8145. (org-store-link arg interactive?))
  8146. (setq link nil))
  8147. ;; A code reference exists. Use it.
  8148. ((save-excursion
  8149. (beginning-of-line)
  8150. (re-search-forward (org-src-coderef-regexp coderef-format)
  8151. (line-end-position)
  8152. t))
  8153. (setq link (funcall format-link (match-string-no-properties 3))))
  8154. ;; No code reference. Create a new one then store the link
  8155. ;; to it, but only in the function is called interactively.
  8156. (interactive?
  8157. (end-of-line)
  8158. (let* ((label (read-string "Code line label: "))
  8159. (reference (format coderef-format label))
  8160. (gc (- 79 (length reference))))
  8161. (if (< (current-column) gc)
  8162. (org-move-to-column gc t)
  8163. (insert " "))
  8164. (insert reference)
  8165. (setq link (funcall format-link label))))
  8166. ;; No code reference, and non-interactive call. Don't know
  8167. ;; what to do. Give up.
  8168. (t (setq link nil)))))
  8169. ;; We are in the agenda, link to referenced location
  8170. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8171. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8172. (get-text-property (point) 'org-marker))))
  8173. (when m
  8174. (org-with-point-at m
  8175. (setq agenda-link (org-store-link nil interactive?))))))
  8176. ((eq major-mode 'calendar-mode)
  8177. (let ((cd (calendar-cursor-to-date)))
  8178. (setq link
  8179. (format-time-string
  8180. (car org-time-stamp-formats)
  8181. (apply 'encode-time
  8182. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8183. nil nil nil))))
  8184. (org-store-link-props :type "calendar" :date cd)))
  8185. ((eq major-mode 'help-mode)
  8186. (setq link (concat "help:" (save-excursion
  8187. (goto-char (point-min))
  8188. (looking-at "^[^ ]+")
  8189. (match-string 0))))
  8190. (org-store-link-props :type "help"))
  8191. ((eq major-mode 'w3-mode)
  8192. (setq cpltxt (if (and (buffer-name)
  8193. (not (string-match "Untitled" (buffer-name))))
  8194. (buffer-name)
  8195. (url-view-url t))
  8196. link (url-view-url t))
  8197. (org-store-link-props :type "w3" :url (url-view-url t)))
  8198. ((eq major-mode 'image-mode)
  8199. (setq cpltxt (concat "file:"
  8200. (abbreviate-file-name buffer-file-name))
  8201. link cpltxt)
  8202. (org-store-link-props :type "image" :file buffer-file-name))
  8203. ;; In dired, store a link to the file of the current line
  8204. ((derived-mode-p 'dired-mode)
  8205. (let ((file (dired-get-filename nil t)))
  8206. (setq file (if file
  8207. (abbreviate-file-name
  8208. (expand-file-name (dired-get-filename nil t)))
  8209. ;; otherwise, no file so use current directory.
  8210. default-directory))
  8211. (setq cpltxt (concat "file:" file)
  8212. link cpltxt)))
  8213. ((setq search (run-hook-with-args-until-success
  8214. 'org-create-file-search-functions))
  8215. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8216. "::" search))
  8217. (setq cpltxt (or description link)))
  8218. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8219. (org-with-limited-levels
  8220. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8221. (cond
  8222. ;; Store a link using the target at point
  8223. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8224. (setq cpltxt
  8225. (concat "file:"
  8226. (abbreviate-file-name
  8227. (buffer-file-name (buffer-base-buffer)))
  8228. "::" (match-string 1))
  8229. link cpltxt))
  8230. ((and (featurep 'org-id)
  8231. (or (eq org-id-link-to-org-use-id t)
  8232. (and interactive?
  8233. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8234. (and (eq org-id-link-to-org-use-id
  8235. 'create-if-interactive-and-no-custom-id)
  8236. (not custom-id))))
  8237. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8238. ;; Store a link using the ID at point
  8239. (setq link (condition-case nil
  8240. (prog1 (org-id-store-link)
  8241. (setq desc (or (plist-get org-store-link-plist
  8242. :description)
  8243. "")))
  8244. (error
  8245. ;; Probably before first headline, link only to file
  8246. (concat "file:"
  8247. (abbreviate-file-name
  8248. (buffer-file-name (buffer-base-buffer))))))))
  8249. (t
  8250. ;; Just link to current headline
  8251. (setq cpltxt (concat "file:"
  8252. (abbreviate-file-name
  8253. (buffer-file-name (buffer-base-buffer)))))
  8254. ;; Add a context search string
  8255. (when (org-xor org-context-in-file-links
  8256. (equal arg '(4)))
  8257. (let* ((element (org-element-at-point))
  8258. (name (org-element-property :name element)))
  8259. (setq txt (cond
  8260. ((org-at-heading-p) nil)
  8261. (name)
  8262. ((org-region-active-p)
  8263. (buffer-substring (region-beginning) (region-end)))))
  8264. (when (or (null txt) (string-match "\\S-" txt))
  8265. (setq cpltxt
  8266. (concat cpltxt "::"
  8267. (condition-case nil
  8268. (org-make-org-heading-search-string txt)
  8269. (error "")))
  8270. desc (or name
  8271. (nth 4 (ignore-errors (org-heading-components)))
  8272. "NONE")))))
  8273. (when (string-match "::\\'" cpltxt)
  8274. (setq cpltxt (substring cpltxt 0 -2)))
  8275. (setq link cpltxt)))))
  8276. ((buffer-file-name (buffer-base-buffer))
  8277. ;; Just link to this file here.
  8278. (setq cpltxt (concat "file:"
  8279. (abbreviate-file-name
  8280. (buffer-file-name (buffer-base-buffer)))))
  8281. ;; Add a context string.
  8282. (when (org-xor org-context-in-file-links
  8283. (equal arg '(4)))
  8284. (setq txt (if (org-region-active-p)
  8285. (buffer-substring (region-beginning) (region-end))
  8286. (buffer-substring (point-at-bol) (point-at-eol))))
  8287. ;; Only use search option if there is some text.
  8288. (when (string-match "\\S-" txt)
  8289. (setq cpltxt
  8290. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8291. desc "NONE")))
  8292. (setq link cpltxt))
  8293. (interactive?
  8294. (user-error "No method for storing a link from this buffer"))
  8295. (t (setq link nil)))
  8296. ;; We're done setting link and desc, clean up
  8297. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8298. (setq link (or link cpltxt)
  8299. desc (or desc cpltxt))
  8300. (cond ((not desc))
  8301. ((equal desc "NONE") (setq desc nil))
  8302. (t (setq desc
  8303. (replace-regexp-in-string
  8304. org-bracket-link-analytic-regexp
  8305. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8306. desc))))
  8307. ;; Return the link
  8308. (if (not (and interactive? link))
  8309. (or agenda-link (and link (org-make-link-string link desc)))
  8310. (push (list link desc) org-stored-links)
  8311. (message "Stored: %s" (or desc link))
  8312. (when custom-id
  8313. (setq link (concat "file:" (abbreviate-file-name
  8314. (buffer-file-name)) "::#" custom-id))
  8315. (push (list link desc) org-stored-links))
  8316. (car org-stored-links)))))
  8317. (defun org-store-link-props (&rest plist)
  8318. "Store link properties.
  8319. The properties are pre-processed by extracting names, addresses
  8320. and dates."
  8321. (let ((x (plist-get plist :from)))
  8322. (when x
  8323. (let ((adr (mail-extract-address-components x)))
  8324. (setq plist (plist-put plist :fromname (car adr)))
  8325. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8326. (let ((x (plist-get plist :to)))
  8327. (when x
  8328. (let ((adr (mail-extract-address-components x)))
  8329. (setq plist (plist-put plist :toname (car adr)))
  8330. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8331. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8332. (when x
  8333. (setq plist (plist-put plist :date-timestamp
  8334. (format-time-string
  8335. (org-time-stamp-format t) x)))
  8336. (setq plist (plist-put plist :date-timestamp-inactive
  8337. (format-time-string
  8338. (org-time-stamp-format t t) x)))))
  8339. (let ((from (plist-get plist :from))
  8340. (to (plist-get plist :to)))
  8341. (when (and from to org-from-is-user-regexp)
  8342. (setq plist
  8343. (plist-put plist :fromto
  8344. (if (string-match org-from-is-user-regexp from)
  8345. (concat "to %t")
  8346. (concat "from %f"))))))
  8347. (setq org-store-link-plist plist))
  8348. (defun org-add-link-props (&rest plist)
  8349. "Add these properties to the link property list."
  8350. (let (key value)
  8351. (while plist
  8352. (setq key (pop plist) value (pop plist))
  8353. (setq org-store-link-plist
  8354. (plist-put org-store-link-plist key value)))))
  8355. (defun org-email-link-description (&optional fmt)
  8356. "Return the description part of an email link.
  8357. This takes information from `org-store-link-plist' and formats it
  8358. according to FMT (default from `org-email-link-description-format')."
  8359. (setq fmt (or fmt org-email-link-description-format))
  8360. (let* ((p org-store-link-plist)
  8361. (to (plist-get p :toaddress))
  8362. (from (plist-get p :fromaddress))
  8363. (table
  8364. (list
  8365. (cons "%c" (plist-get p :fromto))
  8366. (cons "%F" (plist-get p :from))
  8367. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8368. (cons "%T" (plist-get p :to))
  8369. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8370. (cons "%s" (plist-get p :subject))
  8371. (cons "%d" (plist-get p :date))
  8372. (cons "%m" (plist-get p :message-id)))))
  8373. (when (string-match "%c" fmt)
  8374. ;; Check if the user wrote this message
  8375. (if (and org-from-is-user-regexp from to
  8376. (save-match-data (string-match org-from-is-user-regexp from)))
  8377. (setq fmt (replace-match "to %t" t t fmt))
  8378. (setq fmt (replace-match "from %f" t t fmt))))
  8379. (org-replace-escapes fmt table)))
  8380. (defun org-make-org-heading-search-string (&optional string)
  8381. "Make search string for the current headline or STRING."
  8382. (let ((s (or string
  8383. (and (derived-mode-p 'org-mode)
  8384. (save-excursion
  8385. (org-back-to-heading t)
  8386. (org-element-property :raw-value (org-element-at-point))))))
  8387. (lines org-context-in-file-links))
  8388. (unless string (setq s (concat "*" s))) ;Add * for headlines
  8389. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8390. (when (and string (integerp lines) (> lines 0))
  8391. (let ((slines (org-split-string s "\n")))
  8392. (when (< lines (length slines))
  8393. (setq s (mapconcat
  8394. 'identity
  8395. (reverse (nthcdr (- (length slines) lines)
  8396. (reverse slines))) "\n")))))
  8397. (mapconcat #'identity (split-string s) " ")))
  8398. (defconst org-link-escape-chars
  8399. ;;%20 %5B %5D %25
  8400. '(?\s ?\[ ?\] ?%)
  8401. "List of characters that should be escaped in a link when stored to Org.
  8402. This is the list that is used for internal purposes.")
  8403. (defun org-make-link-string (link &optional description)
  8404. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8405. (unless (org-string-nw-p link) (error "Empty link"))
  8406. (let ((uri (cond ((string-match org-link-types-re link)
  8407. (concat (match-string 1 link)
  8408. (org-link-escape (substring link (match-end 1)))))
  8409. ((or (file-name-absolute-p link)
  8410. (string-match-p "\\`\\.\\.?/" link))
  8411. (org-link-escape link))
  8412. ;; For readability, do not encode space characters
  8413. ;; in fuzzy links.
  8414. (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
  8415. (description
  8416. (and (org-string-nw-p description)
  8417. ;; Remove brackets from description, as they are fatal.
  8418. (replace-regexp-in-string
  8419. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8420. (org-trim description)))))
  8421. (format "[[%s]%s]"
  8422. uri
  8423. (if description (format "[%s]" description) ""))))
  8424. (defun org-link-escape (text &optional table merge)
  8425. "Return percent escaped representation of TEXT.
  8426. TEXT is a string with the text to escape.
  8427. Optional argument TABLE is a list with characters that should be
  8428. escaped. When nil, `org-link-escape-chars' is used.
  8429. If optional argument MERGE is set, merge TABLE into
  8430. `org-link-escape-chars'."
  8431. (let ((characters-to-encode
  8432. (cond ((null table) org-link-escape-chars)
  8433. (merge (append org-link-escape-chars table))
  8434. (t table))))
  8435. (mapconcat
  8436. (lambda (c)
  8437. (if (or (memq c characters-to-encode)
  8438. (and org-url-hexify-p (or (< c 32) (> c 126))))
  8439. (mapconcat (lambda (e) (format "%%%.2X" e))
  8440. (or (encode-coding-char c 'utf-8)
  8441. (error "Unable to percent escape character: %c" c))
  8442. "")
  8443. (char-to-string c)))
  8444. text "")))
  8445. (defun org-link-unescape (str)
  8446. "Unhex hexified Unicode parts in string STR.
  8447. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  8448. reciprocal of `org-link-escape', which see."
  8449. (if (org-string-nw-p str)
  8450. (replace-regexp-in-string
  8451. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  8452. str))
  8453. (defun org-link-unescape-compound (hex)
  8454. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  8455. Note: this function also decodes single byte encodings like
  8456. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  8457. (save-match-data
  8458. (let* ((bytes (cdr (split-string hex "%")))
  8459. (ret "")
  8460. (eat 0)
  8461. (sum 0))
  8462. (while bytes
  8463. (let* ((val (string-to-number (pop bytes) 16))
  8464. (shift-xor
  8465. (if (= 0 eat)
  8466. (cond
  8467. ((>= val 252) (cons 6 252))
  8468. ((>= val 248) (cons 5 248))
  8469. ((>= val 240) (cons 4 240))
  8470. ((>= val 224) (cons 3 224))
  8471. ((>= val 192) (cons 2 192))
  8472. (t (cons 0 0)))
  8473. (cons 6 128))))
  8474. (when (>= val 192) (setq eat (car shift-xor)))
  8475. (setq val (logxor val (cdr shift-xor)))
  8476. (setq sum (+ (lsh sum (car shift-xor)) val))
  8477. (when (> eat 0) (setq eat (- eat 1)))
  8478. (cond
  8479. ((= 0 eat) ;multi byte
  8480. (setq ret (concat ret (char-to-string sum)))
  8481. (setq sum 0))
  8482. ((not bytes) ; single byte(s)
  8483. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  8484. ret)))
  8485. (defun org-link-unescape-single-byte-sequence (hex)
  8486. "Unhexify hex-encoded single byte character sequences."
  8487. (mapconcat (lambda (byte)
  8488. (char-to-string (string-to-number byte 16)))
  8489. (cdr (split-string hex "%")) ""))
  8490. (defun org-fixup-message-id-for-http (s)
  8491. "Replace special characters in a message id, so it can be used in an http query."
  8492. (when (string-match "%" s)
  8493. (setq s (mapconcat (lambda (c)
  8494. (if (eq c ?%)
  8495. "%25"
  8496. (char-to-string c)))
  8497. s "")))
  8498. (while (string-match "<" s)
  8499. (setq s (replace-match "%3C" t t s)))
  8500. (while (string-match ">" s)
  8501. (setq s (replace-match "%3E" t t s)))
  8502. (while (string-match "@" s)
  8503. (setq s (replace-match "%40" t t s)))
  8504. s)
  8505. (defun org-link-prettify (link)
  8506. "Return a human-readable representation of LINK.
  8507. The car of LINK must be a raw link.
  8508. The cdr of LINK must be either a link description or nil."
  8509. (let ((desc (or (cadr link) "<no description>")))
  8510. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  8511. "<" (car link) ">")))
  8512. ;;;###autoload
  8513. (defun org-insert-link-global ()
  8514. "Insert a link like Org mode does.
  8515. This command can be called in any mode to insert a link in Org syntax."
  8516. (interactive)
  8517. (org-load-modules-maybe)
  8518. (org-run-like-in-org-mode 'org-insert-link))
  8519. (defun org-insert-all-links (arg &optional pre post)
  8520. "Insert all links in `org-stored-links'.
  8521. When a universal prefix, do not delete the links from `org-stored-links'.
  8522. When `ARG' is a number, insert the last N link(s).
  8523. `PRE' and `POST' are optional arguments to define a string to
  8524. prepend or to append."
  8525. (interactive "P")
  8526. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  8527. (links (copy-sequence org-stored-links))
  8528. (pr (or pre "- "))
  8529. (po (or post "\n"))
  8530. (cnt 1) l)
  8531. (if (null org-stored-links)
  8532. (message "No link to insert")
  8533. (while (and (or (listp arg) (>= arg cnt))
  8534. (setq l (if (listp arg)
  8535. (pop links)
  8536. (pop org-stored-links))))
  8537. (setq cnt (1+ cnt))
  8538. (insert pr)
  8539. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  8540. (insert po)))))
  8541. (defun org-insert-last-stored-link (arg)
  8542. "Insert the last link stored in `org-stored-links'."
  8543. (interactive "p")
  8544. (org-insert-all-links arg "" "\n"))
  8545. (defun org-link-fontify-links-to-this-file ()
  8546. "Fontify links to the current file in `org-stored-links'."
  8547. (let ((f (buffer-file-name)) a b)
  8548. (setq a (mapcar (lambda(l)
  8549. (let ((ll (car l)))
  8550. (when (and (string-match "^file:\\(.+\\)::" ll)
  8551. (equal f (expand-file-name (match-string 1 ll))))
  8552. ll)))
  8553. org-stored-links))
  8554. (when (featurep 'org-id)
  8555. (setq b (mapcar (lambda(l)
  8556. (let ((ll (car l)))
  8557. (when (and (string-match "^id:\\(.+\\)$" ll)
  8558. (equal f (expand-file-name
  8559. (or (org-id-find-id-file
  8560. (match-string 1 ll)) ""))))
  8561. ll)))
  8562. org-stored-links)))
  8563. (mapcar (lambda(l)
  8564. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  8565. (delq nil (append a b)))))
  8566. (defvar org--links-history nil)
  8567. (defun org-insert-link (&optional complete-file link-location default-description)
  8568. "Insert a link. At the prompt, enter the link.
  8569. Completion can be used to insert any of the link protocol prefixes in use.
  8570. The history can be used to select a link previously stored with
  8571. `org-store-link'. When the empty string is entered (i.e. if you just
  8572. press `RET' at the prompt), the link defaults to the most recently
  8573. stored link. As `SPC' triggers completion in the minibuffer, you need to
  8574. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  8575. You will also be prompted for a description, and if one is given, it will
  8576. be displayed in the buffer instead of the link.
  8577. If there is already a link at point, this command will allow you to edit
  8578. link and description parts.
  8579. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  8580. file name can be
  8581. selected using completion. The path to the file will be relative to the
  8582. current directory if the file is in the current directory or a subdirectory.
  8583. Otherwise, the link will be the absolute path as completed in the minibuffer
  8584. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  8585. option `org-link-file-path-type'.
  8586. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  8587. absolute path even if the file is in
  8588. the current directory or below.
  8589. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8590. prefix negates `org-keep-stored-link-after-insertion'.
  8591. If the LINK-LOCATION parameter is non-nil, this value will be used as
  8592. the link location instead of reading one interactively.
  8593. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  8594. be used as the default description. Otherwise, if
  8595. `org-make-link-description-function' is non-nil, this function
  8596. will be called with the link target, and the result will be the
  8597. default link description. When called non-interactivily, don't
  8598. allow to edit the default description."
  8599. (interactive "P")
  8600. (let* ((wcf (current-window-configuration))
  8601. (origbuf (current-buffer))
  8602. (region (when (org-region-active-p)
  8603. (buffer-substring (region-beginning) (region-end))))
  8604. (remove (and region (list (region-beginning) (region-end))))
  8605. (desc region)
  8606. (link link-location)
  8607. (abbrevs org-link-abbrev-alist-local)
  8608. entry all-prefixes auto-desc)
  8609. (cond
  8610. (link-location) ; specified by arg, just use it.
  8611. ((org-in-regexp org-bracket-link-regexp 1)
  8612. ;; We do have a link at point, and we are going to edit it.
  8613. (setq remove (list (match-beginning 0) (match-end 0)))
  8614. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  8615. (setq link (read-string "Link: "
  8616. (org-link-unescape
  8617. (match-string-no-properties 1)))))
  8618. ((or (org-in-regexp org-angle-link-re)
  8619. (org-in-regexp org-plain-link-re))
  8620. ;; Convert to bracket link
  8621. (setq remove (list (match-beginning 0) (match-end 0))
  8622. link (read-string "Link: "
  8623. (org-unbracket-string "<" ">" (match-string 0)))))
  8624. ((member complete-file '((4) (16)))
  8625. ;; Completing read for file names.
  8626. (setq link (org-file-complete-link complete-file)))
  8627. (t
  8628. ;; Read link, with completion for stored links.
  8629. (org-link-fontify-links-to-this-file)
  8630. (org-switch-to-buffer-other-window "*Org Links*")
  8631. (with-current-buffer "*Org Links*"
  8632. (erase-buffer)
  8633. (insert "Insert a link.
  8634. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  8635. (when org-stored-links
  8636. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  8637. (insert (mapconcat 'org-link-prettify
  8638. (reverse org-stored-links) "\n")))
  8639. (goto-char (point-min)))
  8640. (let ((cw (selected-window)))
  8641. (select-window (get-buffer-window "*Org Links*" 'visible))
  8642. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  8643. (unless (pos-visible-in-window-p (point-max))
  8644. (org-fit-window-to-buffer))
  8645. (and (window-live-p cw) (select-window cw)))
  8646. (setq all-prefixes (append (mapcar 'car abbrevs)
  8647. (mapcar 'car org-link-abbrev-alist)
  8648. (org-link-types)))
  8649. (unwind-protect
  8650. ;; Fake a link history, containing the stored links.
  8651. (let ((org--links-history
  8652. (append (mapcar #'car org-stored-links)
  8653. org-insert-link-history)))
  8654. (setq link
  8655. (org-completing-read
  8656. "Link: "
  8657. (append
  8658. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  8659. (mapcar #'car org-stored-links))
  8660. nil nil nil
  8661. 'org--links-history
  8662. (caar org-stored-links)))
  8663. (unless (org-string-nw-p link) (user-error "No link selected"))
  8664. (dolist (l org-stored-links)
  8665. (when (equal link (cadr l))
  8666. (setq link (car l))
  8667. (setq auto-desc t)))
  8668. (when (or (member link all-prefixes)
  8669. (and (equal ":" (substring link -1))
  8670. (member (substring link 0 -1) all-prefixes)
  8671. (setq link (substring link 0 -1))))
  8672. (setq link (with-current-buffer origbuf
  8673. (org-link-try-special-completion link)))))
  8674. (set-window-configuration wcf)
  8675. (kill-buffer "*Org Links*"))
  8676. (setq entry (assoc link org-stored-links))
  8677. (or entry (push link org-insert-link-history))
  8678. (setq desc (or desc (nth 1 entry)))))
  8679. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  8680. (not org-keep-stored-link-after-insertion))
  8681. (setq org-stored-links (delq (assoc link org-stored-links)
  8682. org-stored-links)))
  8683. (when (and (string-match org-plain-link-re link)
  8684. (not (string-match org-ts-regexp link)))
  8685. ;; URL-like link, normalize the use of angular brackets.
  8686. (setq link (org-unbracket-string "<" ">" link)))
  8687. ;; Check if we are linking to the current file with a search
  8688. ;; option If yes, simplify the link by using only the search
  8689. ;; option.
  8690. (when (and buffer-file-name
  8691. (let ((case-fold-search nil))
  8692. (string-match "\\`file:\\(.+?\\)::" link)))
  8693. (let ((path (match-string-no-properties 1 link))
  8694. (search (substring-no-properties link (match-end 0))))
  8695. (save-match-data
  8696. (when (equal (file-truename buffer-file-name) (file-truename path))
  8697. ;; We are linking to this same file, with a search option
  8698. (setq link search)))))
  8699. ;; Check if we can/should use a relative path. If yes, simplify
  8700. ;; the link.
  8701. (let ((case-fold-search nil))
  8702. (when (string-match "\\`\\(file\\|docview\\):" link)
  8703. (let* ((type (match-string-no-properties 0 link))
  8704. (path-start (match-end 0))
  8705. (search (and (string-match "::\\(.*\\)\\'" link)
  8706. (match-string 1 link)))
  8707. (path
  8708. (if search
  8709. (substring-no-properties
  8710. link path-start (match-beginning 0))
  8711. (substring-no-properties link (match-end 0))))
  8712. (origpath path))
  8713. (cond
  8714. ((or (eq org-link-file-path-type 'absolute)
  8715. (equal complete-file '(16)))
  8716. (setq path (abbreviate-file-name (expand-file-name path))))
  8717. ((eq org-link-file-path-type 'noabbrev)
  8718. (setq path (expand-file-name path)))
  8719. ((eq org-link-file-path-type 'relative)
  8720. (setq path (file-relative-name path)))
  8721. (t
  8722. (save-match-data
  8723. (if (string-match (concat "^" (regexp-quote
  8724. (expand-file-name
  8725. (file-name-as-directory
  8726. default-directory))))
  8727. (expand-file-name path))
  8728. ;; We are linking a file with relative path name.
  8729. (setq path (substring (expand-file-name path)
  8730. (match-end 0)))
  8731. (setq path (abbreviate-file-name (expand-file-name path)))))))
  8732. (setq link (concat type path (and search (concat "::" search))))
  8733. (when (equal desc origpath)
  8734. (setq desc path)))))
  8735. (unless auto-desc
  8736. (let ((initial-input
  8737. (cond
  8738. (default-description)
  8739. ((not org-make-link-description-function) desc)
  8740. (t (condition-case nil
  8741. (funcall org-make-link-description-function link desc)
  8742. (error
  8743. (message "Can't get link description from `%s'"
  8744. (symbol-name org-make-link-description-function))
  8745. (sit-for 2)
  8746. nil))))))
  8747. (setq desc (if (called-interactively-p 'any)
  8748. (read-string "Description: " initial-input)
  8749. initial-input))))
  8750. (unless (org-string-nw-p desc) (setq desc nil))
  8751. (when remove (apply 'delete-region remove))
  8752. (insert (org-make-link-string link desc))
  8753. ;; Redisplay so as the new link has proper invisible characters.
  8754. (sit-for 0)))
  8755. (defun org-link-try-special-completion (type)
  8756. "If there is completion support for link type TYPE, offer it."
  8757. (let ((fun (org-link-get-parameter type :complete)))
  8758. (if (functionp fun)
  8759. (funcall fun)
  8760. (read-string "Link (no completion support): " (concat type ":")))))
  8761. (defun org-file-complete-link (&optional arg)
  8762. "Create a file link using completion."
  8763. (let ((file (read-file-name "File: "))
  8764. (pwd (file-name-as-directory (expand-file-name ".")))
  8765. (pwd1 (file-name-as-directory (abbreviate-file-name
  8766. (expand-file-name ".")))))
  8767. (cond ((equal arg '(16))
  8768. (concat "file:"
  8769. (abbreviate-file-name (expand-file-name file))))
  8770. ((string-match
  8771. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  8772. (concat "file:" (match-string 1 file)))
  8773. ((string-match
  8774. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  8775. (expand-file-name file))
  8776. (concat "file:"
  8777. (match-string 1 (expand-file-name file))))
  8778. (t (concat "file:" file)))))
  8779. ;;; Opening/following a link
  8780. (defvar org-link-search-failed nil)
  8781. (defvar org-open-link-functions nil
  8782. "Hook for functions finding a plain text link.
  8783. These functions must take a single argument, the link content.
  8784. They will be called for links that look like [[link text][description]]
  8785. when LINK TEXT does not have a protocol like \"http:\" and does not look
  8786. like a filename (e.g. \"./blue.png\").
  8787. These functions will be called *before* Org attempts to resolve the
  8788. link by doing text searches in the current buffer - so if you want a
  8789. link \"[[target]]\" to still find \"<<target>>\", your function should
  8790. handle this as a special case.
  8791. When the function does handle the link, it must return a non-nil value.
  8792. If it decides that it is not responsible for this link, it must return
  8793. nil to indicate that that Org can continue with other options like
  8794. exact and fuzzy text search.")
  8795. (defun org-next-link (&optional search-backward)
  8796. "Move forward to the next link.
  8797. If the link is in hidden text, expose it."
  8798. (interactive "P")
  8799. (when (and org-link-search-failed (eq this-command last-command))
  8800. (goto-char (point-min))
  8801. (message "Link search wrapped back to beginning of buffer"))
  8802. (setq org-link-search-failed nil)
  8803. (let* ((pos (point))
  8804. (ct (org-context))
  8805. (a (assq :link ct))
  8806. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  8807. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  8808. ((looking-at org-any-link-re)
  8809. ;; Don't stay stuck at link without an org-link face
  8810. (forward-char (if search-backward -1 1))))
  8811. (if (funcall srch-fun org-any-link-re nil t)
  8812. (progn
  8813. (goto-char (match-beginning 0))
  8814. (when (org-invisible-p) (org-show-context)))
  8815. (goto-char pos)
  8816. (setq org-link-search-failed t)
  8817. (message "No further link found"))))
  8818. (defun org-previous-link ()
  8819. "Move backward to the previous link.
  8820. If the link is in hidden text, expose it."
  8821. (interactive)
  8822. (org-next-link t))
  8823. (defun org-translate-link (s)
  8824. "Translate a link string if a translation function has been defined."
  8825. (with-temp-buffer
  8826. (insert (org-trim s))
  8827. (org-trim (org-element-interpret-data (org-element-context)))))
  8828. (defun org-translate-link-from-planner (type path)
  8829. "Translate a link from Emacs Planner syntax so that Org can follow it.
  8830. This is still an experimental function, your mileage may vary."
  8831. (cond
  8832. ((member type '("http" "https" "news" "ftp"))
  8833. ;; standard Internet links are the same.
  8834. nil)
  8835. ((and (equal type "irc") (string-match "^//" path))
  8836. ;; Planner has two / at the beginning of an irc link, we have 1.
  8837. ;; We should have zero, actually....
  8838. (setq path (substring path 1)))
  8839. ((and (equal type "lisp") (string-match "^/" path))
  8840. ;; Planner has a slash, we do not.
  8841. (setq type "elisp" path (substring path 1)))
  8842. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  8843. ;; A typical message link. Planner has the id after the final slash,
  8844. ;; we separate it with a hash mark
  8845. (setq path (concat (match-string 1 path) "#"
  8846. (org-unbracket-string "<" ">" (match-string 2 path))))))
  8847. (cons type path))
  8848. (defun org-find-file-at-mouse (ev)
  8849. "Open file link or URL at mouse."
  8850. (interactive "e")
  8851. (mouse-set-point ev)
  8852. (org-open-at-point 'in-emacs))
  8853. (defun org-open-at-mouse (ev)
  8854. "Open file link or URL at mouse.
  8855. See the docstring of `org-open-file' for details."
  8856. (interactive "e")
  8857. (mouse-set-point ev)
  8858. (when (eq major-mode 'org-agenda-mode)
  8859. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  8860. (org-open-at-point))
  8861. (defvar org-window-config-before-follow-link nil
  8862. "The window configuration before following a link.
  8863. This is saved in case the need arises to restore it.")
  8864. ;;;###autoload
  8865. (defun org-open-at-point-global ()
  8866. "Follow a link or a time-stamp like Org mode does.
  8867. Also follow links and emails as seen by `thing-at-point'.
  8868. This command can be called in any mode to follow an external
  8869. link or a time-stamp that has Org mode syntax. Its behavior
  8870. is undefined when called on internal links like fuzzy links.
  8871. Raise a user error when there is nothing to follow."
  8872. (interactive)
  8873. (let ((tap-url (thing-at-point 'url))
  8874. (tap-email (thing-at-point 'email)))
  8875. (cond ((org-in-regexp org-any-link-re)
  8876. (org-open-link-from-string (match-string-no-properties 0)))
  8877. ((or (org-in-regexp org-ts-regexp-both nil t)
  8878. (org-in-regexp org-tsr-regexp-both nil t))
  8879. (org-follow-timestamp-link))
  8880. (tap-url (org-open-link-from-string tap-url))
  8881. (tap-email (org-open-link-from-string
  8882. (concat "mailto:" tap-email)))
  8883. (t (user-error "No link found")))))
  8884. ;;;###autoload
  8885. (defun org-open-link-from-string (s &optional arg reference-buffer)
  8886. "Open a link in the string S, as if it was in Org mode."
  8887. (interactive "sLink: \nP")
  8888. (let ((reference-buffer (or reference-buffer (current-buffer))))
  8889. (with-temp-buffer
  8890. (let ((org-inhibit-startup (not reference-buffer)))
  8891. (org-mode)
  8892. (insert s)
  8893. (goto-char (point-min))
  8894. (when reference-buffer
  8895. (setq org-link-abbrev-alist-local
  8896. (with-current-buffer reference-buffer
  8897. org-link-abbrev-alist-local)))
  8898. (org-open-at-point arg reference-buffer)))))
  8899. (defvar org-open-at-point-functions nil
  8900. "Hook that is run when following a link at point.
  8901. Functions in this hook must return t if they identify and follow
  8902. a link at point. If they don't find anything interesting at point,
  8903. they must return nil.")
  8904. (defvar org-link-search-inhibit-query nil)
  8905. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  8906. (defun org--open-doi-link (path)
  8907. "Open a \"doi\" type link.
  8908. PATH is a the path to search for, as a string."
  8909. (browse-url (url-encode-url (concat org-doi-server-url path))))
  8910. (defun org--open-elisp-link (path)
  8911. "Open a \"elisp\" type link.
  8912. PATH is the sexp to evaluate, as a string."
  8913. (let ((cmd path))
  8914. (if (or (and (org-string-nw-p
  8915. org-confirm-elisp-link-not-regexp)
  8916. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  8917. (not org-confirm-elisp-link-function)
  8918. (funcall org-confirm-elisp-link-function
  8919. (format "Execute \"%s\" as elisp? "
  8920. (org-add-props cmd nil 'face 'org-warning))))
  8921. (message "%s => %s" cmd
  8922. (if (eq (string-to-char cmd) ?\()
  8923. (eval (read cmd))
  8924. (call-interactively (read cmd))))
  8925. (user-error "Abort"))))
  8926. (defun org--open-help-link (path)
  8927. "Open a \"help\" type link.
  8928. PATH is a symbol name, as a string."
  8929. (pcase (intern path)
  8930. ((and (pred fboundp) variable) (describe-function variable))
  8931. ((and (pred boundp) function) (describe-variable function))
  8932. (name (user-error "Unknown function or variable: %s" name))))
  8933. (defun org--open-shell-link (path)
  8934. "Open a \"shell\" type link.
  8935. PATH is the command to execute, as a string."
  8936. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  8937. (cmd path))
  8938. (if (or (and (org-string-nw-p
  8939. org-confirm-shell-link-not-regexp)
  8940. (string-match
  8941. org-confirm-shell-link-not-regexp cmd))
  8942. (not org-confirm-shell-link-function)
  8943. (funcall org-confirm-shell-link-function
  8944. (format "Execute \"%s\" in shell? "
  8945. (org-add-props cmd nil
  8946. 'face 'org-warning))))
  8947. (progn
  8948. (message "Executing %s" cmd)
  8949. (shell-command cmd buf)
  8950. (when (featurep 'midnight)
  8951. (setq clean-buffer-list-kill-buffer-names
  8952. (cons (buffer-name buf)
  8953. clean-buffer-list-kill-buffer-names))))
  8954. (user-error "Abort"))))
  8955. (defun org-open-at-point (&optional arg reference-buffer)
  8956. "Open link, timestamp, footnote or tags at point.
  8957. When point is on a link, follow it. Normally, files will be
  8958. opened by an appropriate application. If the optional prefix
  8959. argument ARG is non-nil, Emacs will visit the file. With
  8960. a double prefix argument, try to open outside of Emacs, in the
  8961. application the system uses for this file type.
  8962. When point is on a timestamp, open the agenda at the day
  8963. specified.
  8964. When point is a footnote definition, move to the first reference
  8965. found. If it is on a reference, move to the associated
  8966. definition.
  8967. When point is on a headline, display a list of every link in the
  8968. entry, so it is possible to pick one, or all, of them. If point
  8969. is on a tag, call `org-tags-view' instead.
  8970. When optional argument REFERENCE-BUFFER is non-nil, it should
  8971. specify a buffer from where the link search should happen. This
  8972. is used internally by `org-open-link-from-string'.
  8973. On top of syntactically correct links, this function also tries
  8974. to open links and time-stamps in comments, node properties, and
  8975. keywords if point is on something looking like a timestamp or
  8976. a link."
  8977. (interactive "P")
  8978. (org-load-modules-maybe)
  8979. (setq org-window-config-before-follow-link (current-window-configuration))
  8980. (org-remove-occur-highlights nil nil t)
  8981. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  8982. (let* ((context
  8983. ;; Only consider supported types, even if they are not the
  8984. ;; closest one.
  8985. (org-element-lineage
  8986. (org-element-context)
  8987. '(clock comment comment-block footnote-definition
  8988. footnote-reference headline inline-src-block inlinetask
  8989. keyword link node-property src-block timestamp)
  8990. t))
  8991. (type (org-element-type context))
  8992. (value (org-element-property :value context)))
  8993. (cond
  8994. ((not type) (user-error "No link found"))
  8995. ;; No valid link at point. For convenience, look if something
  8996. ;; looks like a link under point in some specific places.
  8997. ((memq type '(comment comment-block node-property keyword))
  8998. (call-interactively #'org-open-at-point-global))
  8999. ;; On a headline or an inlinetask, but not on a timestamp,
  9000. ;; a link, a footnote reference.
  9001. ((memq type '(headline inlinetask))
  9002. (org-match-line org-complex-heading-regexp)
  9003. (if (and (match-beginning 5)
  9004. (>= (point) (match-beginning 5))
  9005. (< (point) (match-end 5)))
  9006. ;; On tags.
  9007. (org-tags-view arg (substring (match-string 5) 0 -1))
  9008. ;; Not on tags.
  9009. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  9010. (`(nil . ,_)
  9011. (require 'org-attach)
  9012. (org-attach-reveal 'if-exists))
  9013. (`(,links . ,links-end)
  9014. (dolist (link (if (stringp links) (list links) links))
  9015. (search-forward link nil links-end)
  9016. (goto-char (match-beginning 0))
  9017. (org-open-at-point))))))
  9018. ;; On a footnote reference or at definition's label.
  9019. ((or (eq type 'footnote-reference)
  9020. (and (eq type 'footnote-definition)
  9021. (save-excursion
  9022. ;; Do not validate action when point is on the
  9023. ;; spaces right after the footnote label, in order
  9024. ;; to be on par with behavior on links.
  9025. (skip-chars-forward " \t")
  9026. (let ((begin
  9027. (org-element-property :contents-begin context)))
  9028. (if begin (< (point) begin)
  9029. (= (org-element-property :post-affiliated context)
  9030. (line-beginning-position)))))))
  9031. (org-footnote-action))
  9032. ;; On a clock line, make sure point is on the timestamp
  9033. ;; before opening it.
  9034. ((and (eq type 'clock)
  9035. value
  9036. (>= (point) (org-element-property :begin value))
  9037. (<= (point) (org-element-property :end value)))
  9038. (org-follow-timestamp-link))
  9039. ((eq type 'src-block) (org-babel-open-src-block-result))
  9040. ;; Do nothing on white spaces after an object.
  9041. ((>= (point)
  9042. (save-excursion
  9043. (goto-char (org-element-property :end context))
  9044. (skip-chars-backward " \t")
  9045. (point)))
  9046. (user-error "No link found"))
  9047. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  9048. ((eq type 'timestamp) (org-follow-timestamp-link))
  9049. ((eq type 'link)
  9050. (let ((type (org-element-property :type context))
  9051. (path (org-link-unescape (org-element-property :path context))))
  9052. ;; Switch back to REFERENCE-BUFFER needed when called in
  9053. ;; a temporary buffer through `org-open-link-from-string'.
  9054. (with-current-buffer (or reference-buffer (current-buffer))
  9055. (cond
  9056. ((equal type "file")
  9057. (if (string-match "[*?{]" (file-name-nondirectory path))
  9058. (dired path)
  9059. ;; Look into `org-link-parameters' in order to find
  9060. ;; a DEDICATED-FUNCTION to open file. The function
  9061. ;; will be applied on raw link instead of parsed link
  9062. ;; due to the limitation in `org-add-link-type'
  9063. ;; ("open" function called with a single argument).
  9064. ;; If no such function is found, fallback to
  9065. ;; `org-open-file'.
  9066. (let* ((option (org-element-property :search-option context))
  9067. (app (org-element-property :application context))
  9068. (dedicated-function
  9069. (org-link-get-parameter
  9070. (if app (concat type "+" app) type)
  9071. :follow)))
  9072. (if dedicated-function
  9073. (funcall dedicated-function
  9074. (concat path
  9075. (and option (concat "::" option))))
  9076. (apply #'org-open-file
  9077. path
  9078. (cond (arg)
  9079. ((equal app "emacs") 'emacs)
  9080. ((equal app "sys") 'system))
  9081. (cond ((not option) nil)
  9082. ((string-match-p "\\`[0-9]+\\'" option)
  9083. (list (string-to-number option)))
  9084. (t (list nil
  9085. (org-link-unescape option)))))))))
  9086. ((functionp (org-link-get-parameter type :follow))
  9087. (funcall (org-link-get-parameter type :follow) path))
  9088. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9089. (unless (run-hook-with-args-until-success
  9090. 'org-open-link-functions path)
  9091. (if (not arg) (org-mark-ring-push)
  9092. (switch-to-buffer-other-window
  9093. (org-get-buffer-for-internal-link (current-buffer))))
  9094. (let ((destination
  9095. (org-with-wide-buffer
  9096. (if (equal type "radio")
  9097. (org-search-radio-target
  9098. (org-element-property :path context))
  9099. (org-link-search
  9100. (pcase type
  9101. ("custom-id" (concat "#" path))
  9102. ("coderef" (format "(%s)" path))
  9103. (_ path))
  9104. ;; Prevent fuzzy links from matching
  9105. ;; themselves.
  9106. (and (equal type "fuzzy")
  9107. (+ 2 (org-element-property :begin context)))))
  9108. (point))))
  9109. (unless (and (<= (point-min) destination)
  9110. (>= (point-max) destination))
  9111. (widen))
  9112. (goto-char destination))))
  9113. (t (browse-url-at-point))))))
  9114. (t (user-error "No link found")))))
  9115. (run-hook-with-args 'org-follow-link-hook))
  9116. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9117. "Offer links in the current entry and return the selected link.
  9118. If there is only one link, return it.
  9119. If NTH is an integer, return the NTH link found.
  9120. If ZERO is a string, check also this string for a link, and if
  9121. there is one, return it."
  9122. (with-current-buffer buffer
  9123. (org-with-wide-buffer
  9124. (goto-char marker)
  9125. (let ((cnt ?0)
  9126. have-zero end links link c)
  9127. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9128. (push (match-string 0 zero) links)
  9129. (setq cnt (1- cnt) have-zero t))
  9130. (save-excursion
  9131. (org-back-to-heading t)
  9132. (setq end (save-excursion (outline-next-heading) (point)))
  9133. (while (re-search-forward org-any-link-re end t)
  9134. (push (match-string 0) links))
  9135. (setq links (org-uniquify (reverse links))))
  9136. (cond
  9137. ((null links)
  9138. (message "No links"))
  9139. ((equal (length links) 1)
  9140. (setq link (car links)))
  9141. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9142. (setq link (nth (if have-zero nth (1- nth)) links)))
  9143. (t ; we have to select a link
  9144. (save-excursion
  9145. (save-window-excursion
  9146. (delete-other-windows)
  9147. (with-output-to-temp-buffer "*Select Link*"
  9148. (dolist (l links)
  9149. (cond
  9150. ((not (string-match org-bracket-link-regexp l))
  9151. (princ (format "[%c] %s\n" (cl-incf cnt)
  9152. (org-unbracket-string "<" ">" l))))
  9153. ((match-end 3)
  9154. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9155. (match-string 3 l) (match-string 1 l))))
  9156. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9157. (match-string 1 l)))))))
  9158. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9159. (message "Select link to open, RET to open all:")
  9160. (setq c (read-char-exclusive))
  9161. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9162. (when (equal c ?q) (user-error "Abort"))
  9163. (if (equal c ?\C-m)
  9164. (setq link links)
  9165. (setq nth (- c ?0))
  9166. (when have-zero (setq nth (1+ nth)))
  9167. (unless (and (integerp nth) (>= (length links) nth))
  9168. (user-error "Invalid link selection"))
  9169. (setq link (nth (1- nth) links)))))
  9170. (cons link end)))))
  9171. ;; TODO: These functions are deprecated since `org-open-at-point'
  9172. ;; hard-codes behavior for "file+emacs" and "file+sys" types.
  9173. (defun org-open-file-with-system (path)
  9174. "Open file at PATH using the system way of opening it."
  9175. (org-open-file path 'system))
  9176. (defun org-open-file-with-emacs (path)
  9177. "Open file at PATH in Emacs."
  9178. (org-open-file path 'emacs))
  9179. ;;; File search
  9180. (defvar org-create-file-search-functions nil
  9181. "List of functions to construct the right search string for a file link.
  9182. These functions are called in turn with point at the location to
  9183. which the link should point.
  9184. A function in the hook should first test if it would like to
  9185. handle this file type, for example by checking the `major-mode'
  9186. or the file extension. If it decides not to handle this file, it
  9187. should just return nil to give other functions a chance. If it
  9188. does handle the file, it must return the search string to be used
  9189. when following the link. The search string will be part of the
  9190. file link, given after a double colon, and `org-open-at-point'
  9191. will automatically search for it. If special measures must be
  9192. taken to make the search successful, another function should be
  9193. added to the companion hook `org-execute-file-search-functions',
  9194. which see.
  9195. A function in this hook may also use `setq' to set the variable
  9196. `description' to provide a suggestion for the descriptive text to
  9197. be used for this link when it gets inserted into an Org buffer
  9198. with \\[org-insert-link].")
  9199. (defvar org-execute-file-search-functions nil
  9200. "List of functions to execute a file search triggered by a link.
  9201. Functions added to this hook must accept a single argument, the
  9202. search string that was part of the file link, the part after the
  9203. double colon. The function must first check if it would like to
  9204. handle this search, for example by checking the `major-mode' or
  9205. the file extension. If it decides not to handle this search, it
  9206. should just return nil to give other functions a chance. If it
  9207. does handle the search, it must return a non-nil value to keep
  9208. other functions from trying.
  9209. Each function can access the current prefix argument through the
  9210. variable `current-prefix-arg'. Note that a single prefix is used
  9211. to force opening a link in Emacs, so it may be good to only use a
  9212. numeric or double prefix to guide the search function.
  9213. In case this is needed, a function in this hook can also restore
  9214. the window configuration before `org-open-at-point' was called using:
  9215. (set-window-configuration org-window-config-before-follow-link)")
  9216. (defun org-search-radio-target (target)
  9217. "Search a radio target matching TARGET in current buffer.
  9218. White spaces are not significant."
  9219. (let ((re (format "<<<%s>>>"
  9220. (mapconcat #'regexp-quote
  9221. (split-string target)
  9222. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9223. (origin (point)))
  9224. (goto-char (point-min))
  9225. (catch :radio-match
  9226. (while (re-search-forward re nil t)
  9227. (backward-char)
  9228. (let ((object (org-element-context)))
  9229. (when (eq (org-element-type object) 'radio-target)
  9230. (goto-char (org-element-property :begin object))
  9231. (org-show-context 'link-search)
  9232. (throw :radio-match nil))))
  9233. (goto-char origin)
  9234. (user-error "No match for radio target: %s" target))))
  9235. (defun org-link-search (s &optional avoid-pos stealth)
  9236. "Search for a search string S.
  9237. If S starts with \"#\", it triggers a custom ID search.
  9238. If S is enclosed within parenthesis, it initiates a coderef
  9239. search.
  9240. If S is surrounded by forward slashes, it is interpreted as
  9241. a regular expression. In Org mode files, this will create an
  9242. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9243. to list matches. If the current buffer is in `dired-mode', grep
  9244. will be used to search in all files.
  9245. When AVOID-POS is given, ignore matches near that position.
  9246. When optional argument STEALTH is non-nil, do not modify
  9247. visibility around point, thus ignoring `org-show-context-detail'
  9248. variable.
  9249. Search is case-insensitive and ignores white spaces. Return type
  9250. of matched result, which is either `dedicated' or `fuzzy'."
  9251. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9252. (let* ((case-fold-search t)
  9253. (origin (point))
  9254. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9255. (starred (eq (string-to-char normalized) ?*))
  9256. (words (split-string (if starred (substring s 1) s)))
  9257. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9258. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9259. type)
  9260. (cond
  9261. ;; Check if there are any special search functions.
  9262. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9263. ((eq (string-to-char s) ?#)
  9264. ;; Look for a custom ID S if S starts with "#".
  9265. (let* ((id (substring normalized 1))
  9266. (match (org-find-property "CUSTOM_ID" id)))
  9267. (if match (progn (goto-char match) (setf type 'dedicated))
  9268. (error "No match for custom ID: %s" id))))
  9269. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9270. ;; Look for coderef targets if S is enclosed within parenthesis.
  9271. (let ((coderef (match-string-no-properties 1 normalized))
  9272. (re (substring s-single-re 1 -1)))
  9273. (goto-char (point-min))
  9274. (catch :coderef-match
  9275. (while (re-search-forward re nil t)
  9276. (let ((element (org-element-at-point)))
  9277. (when (and (memq (org-element-type element)
  9278. '(example-block src-block))
  9279. (org-match-line
  9280. (concat ".*?" (org-src-coderef-regexp
  9281. (org-src-coderef-format element)
  9282. coderef))))
  9283. (setq type 'dedicated)
  9284. (goto-char (match-beginning 2))
  9285. (throw :coderef-match nil))))
  9286. (goto-char origin)
  9287. (error "No match for coderef: %s" coderef))))
  9288. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9289. ;; Look for a regular expression.
  9290. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9291. (match-string 1 s)))
  9292. ;; From here, we handle fuzzy links.
  9293. ;;
  9294. ;; Look for targets, only if not in a headline search.
  9295. ((and (not starred)
  9296. (let ((target (format "<<%s>>" s-multi-re)))
  9297. (catch :target-match
  9298. (goto-char (point-min))
  9299. (while (re-search-forward target nil t)
  9300. (backward-char)
  9301. (let ((context (org-element-context)))
  9302. (when (eq (org-element-type context) 'target)
  9303. (setq type 'dedicated)
  9304. (goto-char (org-element-property :begin context))
  9305. (throw :target-match t))))
  9306. nil))))
  9307. ;; Look for elements named after S, only if not in a headline
  9308. ;; search.
  9309. ((and (not starred)
  9310. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9311. (catch :name-match
  9312. (goto-char (point-min))
  9313. (while (re-search-forward name nil t)
  9314. (let ((element (org-element-at-point)))
  9315. (when (equal words
  9316. (split-string
  9317. (org-element-property :name element)))
  9318. (setq type 'dedicated)
  9319. (beginning-of-line)
  9320. (throw :name-match t))))
  9321. nil))))
  9322. ;; Regular text search. Prefer headlines in Org mode buffers.
  9323. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9324. ;; statistics cookies and tags.
  9325. ((and (derived-mode-p 'org-mode)
  9326. (let ((title-re
  9327. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9328. org-outline-regexp-bol
  9329. org-comment-string
  9330. (mapconcat #'regexp-quote words ".+")))
  9331. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9332. (comment-re (eval-when-compile
  9333. (format "\\`%s[ \t]+" org-comment-string))))
  9334. (goto-char (point-min))
  9335. (catch :found
  9336. (while (re-search-forward title-re nil t)
  9337. (when (equal words
  9338. (split-string
  9339. (replace-regexp-in-string
  9340. cookie-re ""
  9341. (replace-regexp-in-string
  9342. comment-re "" (org-get-heading t t t)))))
  9343. (throw :found t)))
  9344. nil)))
  9345. (beginning-of-line)
  9346. (setq type 'dedicated))
  9347. ;; Offer to create non-existent headline depending on
  9348. ;; `org-link-search-must-match-exact-headline'.
  9349. ((and (derived-mode-p 'org-mode)
  9350. (not org-link-search-inhibit-query)
  9351. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9352. (yes-or-no-p "No match - create this as a new heading? "))
  9353. (goto-char (point-max))
  9354. (unless (bolp) (newline))
  9355. (org-insert-heading nil t t)
  9356. (insert s "\n")
  9357. (beginning-of-line 0))
  9358. ;; Only headlines are looked after. No need to process
  9359. ;; further: throw an error.
  9360. ((and (derived-mode-p 'org-mode)
  9361. (or starred org-link-search-must-match-exact-headline))
  9362. (goto-char origin)
  9363. (error "No match for fuzzy expression: %s" normalized))
  9364. ;; Regular text search.
  9365. ((catch :fuzzy-match
  9366. (goto-char (point-min))
  9367. (while (re-search-forward s-multi-re nil t)
  9368. ;; Skip match if it contains AVOID-POS or it is included in
  9369. ;; a link with a description but outside the description.
  9370. (unless (or (and avoid-pos
  9371. (<= (match-beginning 0) avoid-pos)
  9372. (> (match-end 0) avoid-pos))
  9373. (and (save-match-data
  9374. (org-in-regexp org-bracket-link-regexp))
  9375. (match-beginning 3)
  9376. (or (> (match-beginning 3) (point))
  9377. (<= (match-end 3) (point)))
  9378. (org-element-lineage
  9379. (save-match-data (org-element-context))
  9380. '(link) t)))
  9381. (goto-char (match-beginning 0))
  9382. (setq type 'fuzzy)
  9383. (throw :fuzzy-match t)))
  9384. nil))
  9385. ;; All failed. Throw an error.
  9386. (t (goto-char origin)
  9387. (error "No match for fuzzy expression: %s" normalized)))
  9388. ;; Disclose surroundings of match, if appropriate.
  9389. (when (and (derived-mode-p 'org-mode) (not stealth))
  9390. (org-show-context 'link-search))
  9391. type))
  9392. (defun org-get-buffer-for-internal-link (buffer)
  9393. "Return a buffer to be used for displaying the link target of internal links."
  9394. (cond
  9395. ((not org-display-internal-link-with-indirect-buffer)
  9396. buffer)
  9397. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9398. (message "Buffer is already a clone, not making another one")
  9399. ;; we also do not modify visibility in this case
  9400. buffer)
  9401. (t ; make a new indirect buffer for displaying the link
  9402. (let* ((bn (buffer-name buffer))
  9403. (ibn (concat bn "(Clone)"))
  9404. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9405. (with-current-buffer ib (org-overview))
  9406. ib))))
  9407. (defun org-do-occur (regexp &optional cleanup)
  9408. "Call the Emacs command `occur'.
  9409. If CLEANUP is non-nil, remove the printout of the regular expression
  9410. in the *Occur* buffer. This is useful if the regex is long and not useful
  9411. to read."
  9412. (occur regexp)
  9413. (when cleanup
  9414. (let ((cwin (selected-window)) win beg end)
  9415. (when (setq win (get-buffer-window "*Occur*"))
  9416. (select-window win))
  9417. (goto-char (point-min))
  9418. (when (re-search-forward "match[a-z]+" nil t)
  9419. (setq beg (match-end 0))
  9420. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  9421. (setq end (1- (match-beginning 0)))))
  9422. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  9423. (goto-char (point-min))
  9424. (select-window cwin))))
  9425. ;;; The Mark Ring
  9426. (defvar org-mark-ring nil
  9427. "Mark ring for positions before jumps in Org mode.")
  9428. (defvar org-mark-ring-last-goto nil
  9429. "Last position in the mark ring used to go back.")
  9430. ;; Fill and close the ring
  9431. (setq org-mark-ring nil)
  9432. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  9433. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  9434. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  9435. org-mark-ring)
  9436. (defun org-mark-ring-push (&optional pos buffer)
  9437. "Put the current position into the mark ring and rotate it.
  9438. Also push position into the Emacs mark ring. If optional
  9439. argument POS and BUFFER are not nil, mark this location instead."
  9440. (interactive)
  9441. (let ((pos (or pos (point)))
  9442. (buffer (or buffer (current-buffer))))
  9443. (with-current-buffer buffer
  9444. (org-with-point-at pos (push-mark nil t)))
  9445. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  9446. (move-marker (car org-mark-ring) pos buffer))
  9447. (message
  9448. (substitute-command-keys
  9449. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  9450. (defun org-mark-ring-goto (&optional n)
  9451. "Jump to the previous position in the mark ring.
  9452. With prefix arg N, jump back that many stored positions. When
  9453. called several times in succession, walk through the entire ring.
  9454. Org mode commands jumping to a different position in the current file,
  9455. or to another Org file, automatically push the old position onto the ring."
  9456. (interactive "p")
  9457. (let (p m)
  9458. (if (eq last-command this-command)
  9459. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  9460. (setq p org-mark-ring))
  9461. (setq org-mark-ring-last-goto p)
  9462. (setq m (car p))
  9463. (pop-to-buffer-same-window (marker-buffer m))
  9464. (goto-char m)
  9465. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  9466. (defun org-add-angle-brackets (s)
  9467. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  9468. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  9469. s)
  9470. ;;; Following specific links
  9471. (defvar org-agenda-buffer-tmp-name)
  9472. (defvar org-agenda-start-on-weekday)
  9473. (defun org-follow-timestamp-link ()
  9474. "Open an agenda view for the time-stamp date/range at point."
  9475. (cond
  9476. ((org-at-date-range-p t)
  9477. (let ((org-agenda-start-on-weekday)
  9478. (t1 (match-string 1))
  9479. (t2 (match-string 2)) tt1 tt2)
  9480. (setq tt1 (time-to-days (org-time-string-to-time t1))
  9481. tt2 (time-to-days (org-time-string-to-time t2)))
  9482. (let ((org-agenda-buffer-tmp-name
  9483. (format "*Org Agenda(a:%s)"
  9484. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  9485. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  9486. ((org-at-timestamp-p 'lax)
  9487. (let ((org-agenda-buffer-tmp-name
  9488. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  9489. (org-agenda-list nil (time-to-days (org-time-string-to-time
  9490. (substring (match-string 1) 0 10)))
  9491. 1)))
  9492. (t (error "This should not happen"))))
  9493. ;;; Following file links
  9494. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  9495. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  9496. (declare-function mailcap-mime-info
  9497. "mailcap" (string &optional request no-decode))
  9498. (defvar org-wait nil)
  9499. (defun org-open-file (path &optional in-emacs line search)
  9500. "Open the file at PATH.
  9501. First, this expands any special file name abbreviations. Then the
  9502. configuration variable `org-file-apps' is checked if it contains an
  9503. entry for this file type, and if yes, the corresponding command is launched.
  9504. If no application is found, Emacs simply visits the file.
  9505. With optional prefix argument IN-EMACS, Emacs will visit the file.
  9506. With a double \\[universal-argument] \\[universal-argument] \
  9507. prefix arg, Org tries to avoid opening in Emacs
  9508. and to use an external application to visit the file.
  9509. Optional LINE specifies a line to go to, optional SEARCH a string
  9510. to search for. If LINE or SEARCH is given, the file will be
  9511. opened in Emacs, unless an entry from org-file-apps that makes
  9512. use of groups in a regexp matches.
  9513. If you want to change the way frames are used when following a
  9514. link, please customize `org-link-frame-setup'.
  9515. If the file does not exist, an error is thrown."
  9516. (let* ((file (if (equal path "")
  9517. buffer-file-name
  9518. (substitute-in-file-name (expand-file-name path))))
  9519. (file-apps (append org-file-apps (org-default-apps)))
  9520. (apps (cl-remove-if
  9521. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9522. (apps-dlink (cl-remove-if-not
  9523. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9524. (remp (and (assq 'remote apps) (file-remote-p file)))
  9525. (dirp (unless remp (file-directory-p file)))
  9526. (file (if (and dirp org-open-directory-means-index-dot-org)
  9527. (concat (file-name-as-directory file) "index.org")
  9528. file))
  9529. (a-m-a-p (assq 'auto-mode apps))
  9530. (dfile (downcase file))
  9531. ;; Reconstruct the original link from the PATH, LINE and
  9532. ;; SEARCH args.
  9533. (link (cond (line (concat file "::" (number-to-string line)))
  9534. (search (concat file "::" search))
  9535. (t file)))
  9536. (dlink (downcase link))
  9537. (ext
  9538. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  9539. (match-string 1 dfile)))
  9540. (save-position-maybe
  9541. (let ((old-buffer (current-buffer))
  9542. (old-pos (point))
  9543. (old-mode major-mode))
  9544. (lambda ()
  9545. (and (derived-mode-p 'org-mode)
  9546. (eq old-mode 'org-mode)
  9547. (or (not (eq old-buffer (current-buffer)))
  9548. (not (eq old-pos (point))))
  9549. (org-mark-ring-push old-pos old-buffer)))))
  9550. cmd link-match-data)
  9551. (cond
  9552. ((member in-emacs '((16) system))
  9553. (setq cmd (cdr (assq 'system apps))))
  9554. (in-emacs (setq cmd 'emacs))
  9555. (t
  9556. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  9557. (and dirp (cdr (assq 'directory apps)))
  9558. ;; First, try matching against apps-dlink if we
  9559. ;; get a match here, store the match data for
  9560. ;; later.
  9561. (let ((match (assoc-default dlink apps-dlink
  9562. 'string-match)))
  9563. (if match
  9564. (progn (setq link-match-data (match-data))
  9565. match)
  9566. (progn (setq in-emacs (or in-emacs line search))
  9567. nil))) ; if we have no match in apps-dlink,
  9568. ; always open the file in emacs if line or search
  9569. ; is given (for backwards compatibility)
  9570. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  9571. 'string-match)
  9572. (cdr (assoc ext apps))
  9573. (cdr (assq t apps))))))
  9574. (when (eq cmd 'system)
  9575. (setq cmd (cdr (assq 'system apps))))
  9576. (when (eq cmd 'default)
  9577. (setq cmd (cdr (assoc t apps))))
  9578. (when (eq cmd 'mailcap)
  9579. (require 'mailcap)
  9580. (mailcap-parse-mailcaps)
  9581. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  9582. (command (mailcap-mime-info mime-type)))
  9583. (if (stringp command)
  9584. (setq cmd command)
  9585. (setq cmd 'emacs))))
  9586. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  9587. (not (file-exists-p file))
  9588. (not org-open-non-existing-files))
  9589. (user-error "No such file: %s" file))
  9590. (cond
  9591. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  9592. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  9593. (while (string-match "['\"]%s['\"]" cmd)
  9594. (setq cmd (replace-match "%s" t t cmd)))
  9595. (setq cmd (replace-regexp-in-string
  9596. "%s"
  9597. (shell-quote-argument (convert-standard-filename file))
  9598. cmd
  9599. nil t))
  9600. ;; Replace "%1", "%2" etc. in command with group matches from regex
  9601. (save-match-data
  9602. (let ((match-index 1)
  9603. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  9604. (set-match-data link-match-data)
  9605. (while (<= match-index number-of-groups)
  9606. (let ((regex (concat "%" (number-to-string match-index)))
  9607. (replace-with (match-string match-index dlink)))
  9608. (while (string-match regex cmd)
  9609. (setq cmd (replace-match replace-with t t cmd))))
  9610. (setq match-index (+ match-index 1)))))
  9611. (save-window-excursion
  9612. (message "Running %s...done" cmd)
  9613. (start-process-shell-command cmd nil cmd)
  9614. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  9615. ((or (stringp cmd)
  9616. (eq cmd 'emacs))
  9617. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  9618. (widen)
  9619. (cond (line (org-goto-line line)
  9620. (when (derived-mode-p 'org-mode) (org-reveal)))
  9621. (search (condition-case err
  9622. (org-link-search search)
  9623. ;; Save position before error-ing out so user
  9624. ;; can easily move back to the original buffer.
  9625. (error (funcall save-position-maybe)
  9626. (error (nth 1 err)))))))
  9627. ((functionp cmd)
  9628. (save-match-data
  9629. (set-match-data link-match-data)
  9630. (condition-case nil
  9631. (funcall cmd file link)
  9632. ;; FIXME: Remove this check when most default installations
  9633. ;; of Emacs have at least Org 9.0.
  9634. ((debug wrong-number-of-arguments wrong-type-argument
  9635. invalid-function)
  9636. (user-error "Please see Org News for version 9.0 about \
  9637. `org-file-apps'--Lisp error: %S" cmd)))))
  9638. ((consp cmd)
  9639. ;; FIXME: Remove this check when most default installations of
  9640. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  9641. ;; fall back to `org-link-frame-setup' for an old usage of
  9642. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  9643. (user-error "Please see Org News for version 9.0 about \
  9644. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  9645. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  9646. (funcall save-position-maybe)))
  9647. (defun org-file-apps-entry-match-against-dlink-p (entry)
  9648. "This function returns non-nil if `entry' uses a regular
  9649. expression which should be matched against the whole link by
  9650. org-open-file.
  9651. It assumes that is the case when the entry uses a regular
  9652. expression which has at least one grouping construct and the
  9653. action is either a lisp form or a command string containing
  9654. `%1', i.e. using at least one subexpression match as a
  9655. parameter."
  9656. (let ((selector (car entry))
  9657. (action (cdr entry)))
  9658. (if (stringp selector)
  9659. (and (> (regexp-opt-depth selector) 0)
  9660. (or (and (stringp action)
  9661. (string-match "%[0-9]" action))
  9662. (consp action)))
  9663. nil)))
  9664. (defun org-default-apps ()
  9665. "Return the default applications for this operating system."
  9666. (cond
  9667. ((eq system-type 'darwin)
  9668. org-file-apps-defaults-macosx)
  9669. ((eq system-type 'windows-nt)
  9670. org-file-apps-defaults-windowsnt)
  9671. (t org-file-apps-defaults-gnu)))
  9672. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  9673. "Convert extensions to regular expressions in the cars of LIST.
  9674. Also, weed out any non-string entries, because the return value is used
  9675. only for regexp matching.
  9676. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  9677. point to the symbol `emacs', indicating that the file should
  9678. be opened in Emacs."
  9679. (append
  9680. (delq nil
  9681. (mapcar (lambda (x)
  9682. (unless (not (stringp (car x)))
  9683. (if (string-match "\\W" (car x))
  9684. x
  9685. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  9686. list))
  9687. (when add-auto-mode
  9688. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  9689. ;;;; Refiling
  9690. (defun org-get-org-file ()
  9691. "Read a filename, with default directory `org-directory'."
  9692. (let ((default (or org-default-notes-file remember-data-file)))
  9693. (read-file-name (format "File name [%s]: " default)
  9694. (file-name-as-directory org-directory)
  9695. default)))
  9696. (defun org-notes-order-reversed-p ()
  9697. "Check if the current file should receive notes in reversed order."
  9698. (cond
  9699. ((not org-reverse-note-order) nil)
  9700. ((eq t org-reverse-note-order) t)
  9701. ((not (listp org-reverse-note-order)) nil)
  9702. (t (catch 'exit
  9703. (dolist (entry org-reverse-note-order)
  9704. (when (string-match (car entry) buffer-file-name)
  9705. (throw 'exit (cdr entry))))))))
  9706. (defvar org-refile-target-table nil
  9707. "The list of refile targets, created by `org-refile'.")
  9708. (defvar org-agenda-new-buffers nil
  9709. "Buffers created to visit agenda files.")
  9710. (defvar org-refile-cache nil
  9711. "Cache for refile targets.")
  9712. (defvar org-refile-markers nil
  9713. "All the markers used for caching refile locations.")
  9714. (defun org-refile-marker (pos)
  9715. "Get a new refile marker, but only if caching is in use."
  9716. (if (not org-refile-use-cache)
  9717. pos
  9718. (let ((m (make-marker)))
  9719. (move-marker m pos)
  9720. (push m org-refile-markers)
  9721. m)))
  9722. (defun org-refile-cache-clear ()
  9723. "Clear the refile cache and disable all the markers."
  9724. (dolist (m org-refile-markers) (move-marker m nil))
  9725. (setq org-refile-markers nil)
  9726. (setq org-refile-cache nil)
  9727. (message "Refile cache has been cleared"))
  9728. (defun org-refile-cache-check-set (set)
  9729. "Check if all the markers in the cache still have live buffers."
  9730. (let (marker)
  9731. (catch 'exit
  9732. (while (and set (setq marker (nth 3 (pop set))))
  9733. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  9734. (when (and marker (null (marker-buffer marker)))
  9735. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  9736. (sit-for 3)
  9737. (throw 'exit nil)))
  9738. t)))
  9739. (defun org-refile-cache-put (set &rest identifiers)
  9740. "Push the refile targets SET into the cache, under IDENTIFIERS."
  9741. (let* ((key (sha1 (prin1-to-string identifiers)))
  9742. (entry (assoc key org-refile-cache)))
  9743. (if entry
  9744. (setcdr entry set)
  9745. (push (cons key set) org-refile-cache))))
  9746. (defun org-refile-cache-get (&rest identifiers)
  9747. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  9748. (cond
  9749. ((not org-refile-cache) nil)
  9750. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  9751. (t
  9752. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  9753. org-refile-cache))))
  9754. (and set (org-refile-cache-check-set set) set)))))
  9755. (defvar org-outline-path-cache nil
  9756. "Alist between buffer positions and outline paths.
  9757. It value is an alist (POSITION . PATH) where POSITION is the
  9758. buffer position at the beginning of an entry and PATH is a list
  9759. of strings describing the outline path for that entry, in reverse
  9760. order.")
  9761. (defun org-refile-get-targets (&optional default-buffer)
  9762. "Produce a table with refile targets."
  9763. (let ((case-fold-search nil)
  9764. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  9765. (entries (or org-refile-targets '((nil . (:level . 1)))))
  9766. targets tgs files desc descre)
  9767. (message "Getting targets...")
  9768. (with-current-buffer (or default-buffer (current-buffer))
  9769. (dolist (entry entries)
  9770. (setq files (car entry) desc (cdr entry))
  9771. (cond
  9772. ((null files) (setq files (list (current-buffer))))
  9773. ((eq files 'org-agenda-files)
  9774. (setq files (org-agenda-files 'unrestricted)))
  9775. ((and (symbolp files) (fboundp files))
  9776. (setq files (funcall files)))
  9777. ((and (symbolp files) (boundp files))
  9778. (setq files (symbol-value files))))
  9779. (when (stringp files) (setq files (list files)))
  9780. (cond
  9781. ((eq (car desc) :tag)
  9782. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  9783. ((eq (car desc) :todo)
  9784. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  9785. ((eq (car desc) :regexp)
  9786. (setq descre (cdr desc)))
  9787. ((eq (car desc) :level)
  9788. (setq descre (concat "^\\*\\{" (number-to-string
  9789. (if org-odd-levels-only
  9790. (1- (* 2 (cdr desc)))
  9791. (cdr desc)))
  9792. "\\}[ \t]")))
  9793. ((eq (car desc) :maxlevel)
  9794. (setq descre (concat "^\\*\\{1," (number-to-string
  9795. (if org-odd-levels-only
  9796. (1- (* 2 (cdr desc)))
  9797. (cdr desc)))
  9798. "\\}[ \t]")))
  9799. (t (error "Bad refiling target description %s" desc)))
  9800. (dolist (f files)
  9801. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  9802. (or
  9803. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  9804. (progn
  9805. (when (bufferp f)
  9806. (setq f (buffer-file-name (buffer-base-buffer f))))
  9807. (setq f (and f (expand-file-name f)))
  9808. (when (eq org-refile-use-outline-path 'file)
  9809. (push (list (file-name-nondirectory f) f nil nil) tgs))
  9810. (when (eq org-refile-use-outline-path 'buffer-name)
  9811. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  9812. (when (eq org-refile-use-outline-path 'full-file-path)
  9813. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  9814. (org-with-wide-buffer
  9815. (goto-char (point-min))
  9816. (setq org-outline-path-cache nil)
  9817. (while (re-search-forward descre nil t)
  9818. (beginning-of-line)
  9819. (let ((case-fold-search nil))
  9820. (looking-at org-complex-heading-regexp))
  9821. (let ((begin (point))
  9822. (heading (match-string-no-properties 4)))
  9823. (unless (or (and
  9824. org-refile-target-verify-function
  9825. (not
  9826. (funcall org-refile-target-verify-function)))
  9827. (not heading))
  9828. (let ((re (format org-complex-heading-regexp-format
  9829. (regexp-quote heading)))
  9830. (target
  9831. (if (not org-refile-use-outline-path) heading
  9832. (mapconcat
  9833. #'identity
  9834. (append
  9835. (pcase org-refile-use-outline-path
  9836. (`file (list (file-name-nondirectory
  9837. (buffer-file-name
  9838. (buffer-base-buffer)))))
  9839. (`full-file-path
  9840. (list (buffer-file-name
  9841. (buffer-base-buffer))))
  9842. (`buffer-name
  9843. (list (buffer-name
  9844. (buffer-base-buffer))))
  9845. (_ nil))
  9846. (mapcar (lambda (s) (replace-regexp-in-string
  9847. "/" "\\/" s nil t))
  9848. (org-get-outline-path t t)))
  9849. "/"))))
  9850. (push (list target f re (org-refile-marker (point)))
  9851. tgs)))
  9852. (when (= (point) begin)
  9853. ;; Verification function has not moved point.
  9854. (end-of-line)))))))
  9855. (when org-refile-use-cache
  9856. (org-refile-cache-put tgs (buffer-file-name) descre))
  9857. (setq targets (append tgs targets))))))
  9858. (message "Getting targets...done")
  9859. (delete-dups (nreverse targets))))
  9860. (defun org--get-outline-path-1 (&optional use-cache)
  9861. "Return outline path to current headline.
  9862. Outline path is a list of strings, in reverse order. When
  9863. optional argument USE-CACHE is non-nil, make use of a cache. See
  9864. `org-get-outline-path' for details.
  9865. Assume buffer is widened and point is on a headline."
  9866. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  9867. (let ((p (point))
  9868. (heading (let ((case-fold-search nil))
  9869. (looking-at org-complex-heading-regexp)
  9870. (if (not (match-end 4)) ""
  9871. ;; Remove statistics cookies.
  9872. (org-trim
  9873. (org-link-display-format
  9874. (replace-regexp-in-string
  9875. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  9876. (match-string-no-properties 4))))))))
  9877. (if (org-up-heading-safe)
  9878. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  9879. (when use-cache
  9880. (push (cons p path) org-outline-path-cache))
  9881. path)
  9882. ;; This is a new root node. Since we assume we are moving
  9883. ;; forward, we can drop previous cache so as to limit number
  9884. ;; of associations there.
  9885. (let ((path (list heading)))
  9886. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  9887. path)))))
  9888. (defun org-get-outline-path (&optional with-self use-cache)
  9889. "Return the outline path to the current entry.
  9890. An outline path is a list of ancestors for current headline, as
  9891. a list of strings. Statistics cookies are removed and links are
  9892. replaced with their description, if any, or their path otherwise.
  9893. When optional argument WITH-SELF is non-nil, the path also
  9894. includes the current headline.
  9895. When optional argument USE-CACHE is non-nil, cache outline paths
  9896. between calls to this function so as to avoid backtracking. This
  9897. argument is useful when planning to find more than one outline
  9898. path in the same document. In that case, there are two
  9899. conditions to satisfy:
  9900. - `org-outline-path-cache' is set to nil before starting the
  9901. process;
  9902. - outline paths are computed by increasing buffer positions."
  9903. (org-with-wide-buffer
  9904. (and (or (and with-self (org-back-to-heading t))
  9905. (org-up-heading-safe))
  9906. (reverse (org--get-outline-path-1 use-cache)))))
  9907. (defun org-format-outline-path (path &optional width prefix separator)
  9908. "Format the outline path PATH for display.
  9909. WIDTH is the maximum number of characters that is available.
  9910. PREFIX is a prefix to be included in the returned string,
  9911. such as the file name.
  9912. SEPARATOR is inserted between the different parts of the path,
  9913. the default is \"/\"."
  9914. (setq width (or width 79))
  9915. (setq path (delq nil path))
  9916. (unless (> width 0)
  9917. (user-error "Argument `width' must be positive"))
  9918. (setq separator (or separator "/"))
  9919. (let* ((org-odd-levels-only nil)
  9920. (fpath (concat
  9921. prefix (and prefix path separator)
  9922. (mapconcat
  9923. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  9924. (cl-loop for head in path
  9925. for n from 0
  9926. collect (org-add-props
  9927. head nil 'face
  9928. (nth (% n org-n-level-faces) org-level-faces)))
  9929. separator))))
  9930. (when (> (length fpath) width)
  9931. (if (< width 7)
  9932. ;; It's unlikely that `width' will be this small, but don't
  9933. ;; waste characters by adding ".." if it is.
  9934. (setq fpath (substring fpath 0 width))
  9935. (setf (substring fpath (- width 2)) "..")))
  9936. fpath))
  9937. (defun org-display-outline-path (&optional file current separator just-return-string)
  9938. "Display the current outline path in the echo area.
  9939. If FILE is non-nil, prepend the output with the file name.
  9940. If CURRENT is non-nil, append the current heading to the output.
  9941. SEPARATOR is passed through to `org-format-outline-path'. It separates
  9942. the different parts of the path and defaults to \"/\".
  9943. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  9944. (interactive "P")
  9945. (let* (case-fold-search
  9946. (bfn (buffer-file-name (buffer-base-buffer)))
  9947. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  9948. res)
  9949. (when current (setq path (append path
  9950. (save-excursion
  9951. (org-back-to-heading t)
  9952. (when (looking-at org-complex-heading-regexp)
  9953. (list (match-string 4)))))))
  9954. (setq res
  9955. (org-format-outline-path
  9956. path
  9957. (1- (frame-width))
  9958. (and file bfn (concat (file-name-nondirectory bfn) separator))
  9959. separator))
  9960. (if just-return-string
  9961. (org-no-properties res)
  9962. (org-unlogged-message "%s" res))))
  9963. (defvar org-refile-history nil
  9964. "History for refiling operations.")
  9965. (defvar org-after-refile-insert-hook nil
  9966. "Hook run after `org-refile' has inserted its stuff at the new location.
  9967. Note that this is still *before* the stuff will be removed from
  9968. the *old* location.")
  9969. (defvar org-capture-last-stored-marker)
  9970. (defvar org-refile-keep nil
  9971. "Non-nil means `org-refile' will copy instead of refile.")
  9972. (defun org-copy ()
  9973. "Like `org-refile', but copy."
  9974. (interactive)
  9975. (let ((org-refile-keep t))
  9976. (org-refile nil nil nil "Copy")))
  9977. (defun org-refile (&optional arg default-buffer rfloc msg)
  9978. "Move the entry or entries at point to another heading.
  9979. The list of target headings is compiled using the information in
  9980. `org-refile-targets', which see.
  9981. At the target location, the entry is filed as a subitem of the
  9982. target heading. Depending on `org-reverse-note-order', the new
  9983. subitem will either be the first or the last subitem.
  9984. If there is an active region, all entries in that region will be
  9985. refiled. However, the region must fulfill the requirement that
  9986. the first heading sets the top-level of the moved text.
  9987. With a `\\[universal-argument]' ARG, the command will only visit the target \
  9988. location
  9989. and not actually move anything.
  9990. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  9991. location where the last
  9992. refiling operation has put the subtree.
  9993. With a numeric prefix argument of `2', refile to the running clock.
  9994. With a numeric prefix argument of `3', emulate `org-refile-keep'
  9995. being set to t and copy to the target location, don't move it.
  9996. Beware that keeping refiled entries may result in duplicated ID
  9997. properties.
  9998. RFLOC can be a refile location obtained in a different way.
  9999. MSG is a string to replace \"Refile\" in the default prompt with
  10000. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10001. See also `org-refile-use-outline-path'.
  10002. If you are using target caching (see `org-refile-use-cache'), you
  10003. have to clear the target cache in order to find new targets.
  10004. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10005. prefix argument (`C-u C-u C-u C-c C-w')."
  10006. (interactive "P")
  10007. (if (member arg '(0 (64)))
  10008. (org-refile-cache-clear)
  10009. (let* ((actionmsg (cond (msg msg)
  10010. ((equal arg 3) "Refile (and keep)")
  10011. (t "Refile")))
  10012. (regionp (org-region-active-p))
  10013. (region-start (and regionp (region-beginning)))
  10014. (region-end (and regionp (region-end)))
  10015. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10016. pos it nbuf file level reversed)
  10017. (setq last-command nil)
  10018. (when regionp
  10019. (goto-char region-start)
  10020. (or (bolp) (goto-char (point-at-bol)))
  10021. (setq region-start (point))
  10022. (unless (or (org-kill-is-subtree-p
  10023. (buffer-substring region-start region-end))
  10024. (prog1 org-refile-active-region-within-subtree
  10025. (let ((s (point-at-eol)))
  10026. (org-toggle-heading)
  10027. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10028. (user-error "The region is not a (sequence of) subtree(s)")))
  10029. (if (equal arg '(16))
  10030. (org-refile-goto-last-stored)
  10031. (when (or
  10032. (and (equal arg 2)
  10033. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10034. (prog1
  10035. (setq it (list (or org-clock-heading "running clock")
  10036. (buffer-file-name
  10037. (marker-buffer org-clock-hd-marker))
  10038. ""
  10039. (marker-position org-clock-hd-marker)))
  10040. (setq arg nil)))
  10041. (setq it
  10042. (or rfloc
  10043. (let (heading-text)
  10044. (save-excursion
  10045. (unless (and arg (listp arg))
  10046. (org-back-to-heading t)
  10047. (setq heading-text
  10048. (replace-regexp-in-string
  10049. org-bracket-link-regexp
  10050. "\\3"
  10051. (or (nth 4 (org-heading-components))
  10052. ""))))
  10053. (org-refile-get-location
  10054. (cond ((and arg (listp arg)) "Goto")
  10055. (regionp (concat actionmsg " region to"))
  10056. (t (concat actionmsg " subtree \""
  10057. heading-text "\" to")))
  10058. default-buffer
  10059. (and (not (equal '(4) arg))
  10060. org-refile-allow-creating-parent-nodes)))))))
  10061. (setq file (nth 1 it)
  10062. pos (nth 3 it))
  10063. (when (and (not arg)
  10064. pos
  10065. (equal (buffer-file-name) file)
  10066. (if regionp
  10067. (and (>= pos region-start)
  10068. (<= pos region-end))
  10069. (and (>= pos (point))
  10070. (< pos (save-excursion
  10071. (org-end-of-subtree t t))))))
  10072. (error "Cannot refile to position inside the tree or region"))
  10073. (setq nbuf (or (find-buffer-visiting file)
  10074. (find-file-noselect file)))
  10075. (if (and arg (not (equal arg 3)))
  10076. (progn
  10077. (pop-to-buffer-same-window nbuf)
  10078. (goto-char (cond (pos)
  10079. ((org-notes-order-reversed-p) (point-min))
  10080. (t (point-max))))
  10081. (org-show-context 'org-goto))
  10082. (if regionp
  10083. (progn
  10084. (org-kill-new (buffer-substring region-start region-end))
  10085. (org-save-markers-in-region region-start region-end))
  10086. (org-copy-subtree 1 nil t))
  10087. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10088. (find-file-noselect file)))
  10089. (setq reversed (org-notes-order-reversed-p))
  10090. (org-with-wide-buffer
  10091. (if pos
  10092. (progn
  10093. (goto-char pos)
  10094. (setq level (org-get-valid-level (funcall outline-level) 1))
  10095. (goto-char
  10096. (if reversed
  10097. (or (outline-next-heading) (point-max))
  10098. (or (save-excursion (org-get-next-sibling))
  10099. (org-end-of-subtree t t)
  10100. (point-max)))))
  10101. (setq level 1)
  10102. (if (not reversed)
  10103. (goto-char (point-max))
  10104. (goto-char (point-min))
  10105. (or (outline-next-heading) (goto-char (point-max)))))
  10106. (unless (bolp) (newline))
  10107. (org-paste-subtree level nil nil t)
  10108. (when org-log-refile
  10109. (org-add-log-setup 'refile nil nil org-log-refile)
  10110. (unless (eq org-log-refile 'note)
  10111. (save-excursion (org-add-log-note))))
  10112. (and org-auto-align-tags
  10113. (let ((org-loop-over-headlines-in-active-region nil))
  10114. (org-align-tags)))
  10115. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10116. :last-refile)))
  10117. (when bookmark-name
  10118. (with-demoted-errors
  10119. (bookmark-set bookmark-name))))
  10120. ;; If we are refiling for capture, make sure that the
  10121. ;; last-capture pointers point here
  10122. (when (bound-and-true-p org-capture-is-refiling)
  10123. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10124. :last-capture-marker)))
  10125. (when bookmark-name
  10126. (with-demoted-errors
  10127. (bookmark-set bookmark-name))))
  10128. (move-marker org-capture-last-stored-marker (point)))
  10129. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10130. (run-hooks 'org-after-refile-insert-hook)))
  10131. (unless org-refile-keep
  10132. (if regionp
  10133. (delete-region (point) (+ (point) (- region-end region-start)))
  10134. (org-preserve-local-variables
  10135. (delete-region
  10136. (and (org-back-to-heading t) (point))
  10137. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
  10138. (when (featurep 'org-inlinetask)
  10139. (org-inlinetask-remove-END-maybe))
  10140. (setq org-markers-to-move nil)
  10141. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10142. (defun org-refile-goto-last-stored ()
  10143. "Go to the location where the last refile was stored."
  10144. (interactive)
  10145. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10146. (message "This is the location of the last refile"))
  10147. (defun org-refile--get-location (refloc tbl)
  10148. "When user refile to REFLOC, find the associated target in TBL.
  10149. Also check `org-refile-target-table'."
  10150. (car (delq
  10151. nil
  10152. (mapcar
  10153. (lambda (r) (or (assoc r tbl)
  10154. (assoc r org-refile-target-table)))
  10155. (list (replace-regexp-in-string "/$" "" refloc)
  10156. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10157. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10158. "Prompt the user for a refile location, using PROMPT.
  10159. PROMPT should not be suffixed with a colon and a space, because
  10160. this function appends the default value from
  10161. `org-refile-history' automatically, if that is not empty."
  10162. (let ((org-refile-targets org-refile-targets)
  10163. (org-refile-use-outline-path org-refile-use-outline-path))
  10164. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10165. (unless org-refile-target-table
  10166. (user-error "No refile targets"))
  10167. (let* ((cbuf (current-buffer))
  10168. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10169. (cfunc (if (and org-refile-use-outline-path
  10170. org-outline-path-complete-in-steps)
  10171. #'org-olpath-completing-read
  10172. #'completing-read))
  10173. (extra (if org-refile-use-outline-path "/" ""))
  10174. (cbnex (concat (buffer-name) extra))
  10175. (filename (and cfn (expand-file-name cfn)))
  10176. (tbl (mapcar
  10177. (lambda (x)
  10178. (if (and (not (member org-refile-use-outline-path
  10179. '(file full-file-path)))
  10180. (not (equal filename (nth 1 x))))
  10181. (cons (concat (car x) extra " ("
  10182. (file-name-nondirectory (nth 1 x)) ")")
  10183. (cdr x))
  10184. (cons (concat (car x) extra) (cdr x))))
  10185. org-refile-target-table))
  10186. (completion-ignore-case t)
  10187. cdef
  10188. (prompt (concat prompt
  10189. (or (and (car org-refile-history)
  10190. (concat " (default " (car org-refile-history) ")"))
  10191. (and (assoc cbnex tbl) (setq cdef cbnex)
  10192. (concat " (default " cbnex ")"))) ": "))
  10193. pa answ parent-target child parent old-hist)
  10194. (setq old-hist org-refile-history)
  10195. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10196. nil 'org-refile-history (or cdef (car org-refile-history))))
  10197. (if (setq pa (org-refile--get-location answ tbl))
  10198. (progn
  10199. (org-refile-check-position pa)
  10200. (when (or (not org-refile-history)
  10201. (not (eq old-hist org-refile-history))
  10202. (not (equal (car pa) (car org-refile-history))))
  10203. (setq org-refile-history
  10204. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10205. org-refile-history
  10206. (cdr org-refile-history))))
  10207. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10208. (pop org-refile-history)))
  10209. pa)
  10210. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10211. (progn
  10212. (setq parent (match-string 1 answ)
  10213. child (match-string 2 answ))
  10214. (setq parent-target (org-refile--get-location parent tbl))
  10215. (when (and parent-target
  10216. (or (eq new-nodes t)
  10217. (and (eq new-nodes 'confirm)
  10218. (y-or-n-p (format "Create new node \"%s\"? "
  10219. child)))))
  10220. (org-refile-new-child parent-target child)))
  10221. (user-error "Invalid target location")))))
  10222. (declare-function org-string-nw-p "org-macs" (s))
  10223. (defun org-refile-check-position (refile-pointer)
  10224. "Check if the refile pointer matches the headline to which it points."
  10225. (let* ((file (nth 1 refile-pointer))
  10226. (re (nth 2 refile-pointer))
  10227. (pos (nth 3 refile-pointer))
  10228. buffer)
  10229. (if (and (not (markerp pos)) (not file))
  10230. (user-error "Please indicate a target file in the refile path")
  10231. (when (org-string-nw-p re)
  10232. (setq buffer (if (markerp pos)
  10233. (marker-buffer pos)
  10234. (or (find-buffer-visiting file)
  10235. (find-file-noselect file))))
  10236. (with-current-buffer buffer
  10237. (org-with-wide-buffer
  10238. (goto-char pos)
  10239. (beginning-of-line 1)
  10240. (unless (looking-at-p re)
  10241. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10242. (defun org-refile-new-child (parent-target child)
  10243. "Use refile target PARENT-TARGET to add new CHILD below it."
  10244. (unless parent-target
  10245. (error "Cannot find parent for new node"))
  10246. (let ((file (nth 1 parent-target))
  10247. (pos (nth 3 parent-target))
  10248. level)
  10249. (with-current-buffer (or (find-buffer-visiting file)
  10250. (find-file-noselect file))
  10251. (org-with-wide-buffer
  10252. (if pos
  10253. (goto-char pos)
  10254. (goto-char (point-max))
  10255. (unless (bolp) (newline)))
  10256. (when (looking-at org-outline-regexp)
  10257. (setq level (funcall outline-level))
  10258. (org-end-of-subtree t t))
  10259. (org-back-over-empty-lines)
  10260. (insert "\n" (make-string
  10261. (if pos (org-get-valid-level level 1) 1) ?*)
  10262. " " child "\n")
  10263. (beginning-of-line 0)
  10264. (list (concat (car parent-target) "/" child) file "" (point))))))
  10265. (defun org-olpath-completing-read (prompt collection &rest args)
  10266. "Read an outline path like a file name."
  10267. (let ((thetable collection))
  10268. (apply #'completing-read
  10269. prompt
  10270. (lambda (string predicate &optional flag)
  10271. (cond
  10272. ((eq flag nil) (try-completion string thetable))
  10273. ((eq flag t)
  10274. (let ((l (length string)))
  10275. (mapcar (lambda (x)
  10276. (let ((r (substring x l))
  10277. (f (if (string-match " ([^)]*)$" x)
  10278. (match-string 0 x)
  10279. "")))
  10280. (if (string-match "/" r)
  10281. (concat string (substring r 0 (match-end 0)) f)
  10282. x)))
  10283. (all-completions string thetable predicate))))
  10284. ;; Exact match?
  10285. ((eq flag 'lambda) (assoc string thetable))))
  10286. args)))
  10287. ;;;; Dynamic blocks
  10288. (defun org-find-dblock (name)
  10289. "Find the first dynamic block with name NAME in the buffer.
  10290. If not found, stay at current position and return nil."
  10291. (let ((case-fold-search t) pos)
  10292. (save-excursion
  10293. (goto-char (point-min))
  10294. (setq pos (and (re-search-forward
  10295. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10296. (match-beginning 0))))
  10297. (when pos (goto-char pos))
  10298. pos))
  10299. (defun org-create-dblock (plist)
  10300. "Create a dynamic block section, with parameters taken from PLIST.
  10301. PLIST must contain a :name entry which is used as the name of the block."
  10302. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10303. (end-of-line 1)
  10304. (newline))
  10305. (let ((col (current-column))
  10306. (name (plist-get plist :name)))
  10307. (insert "#+BEGIN: " name)
  10308. (while plist
  10309. (if (eq (car plist) :name)
  10310. (setq plist (cddr plist))
  10311. (insert " " (prin1-to-string (pop plist)))))
  10312. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10313. (beginning-of-line -2)))
  10314. (defun org-prepare-dblock ()
  10315. "Prepare dynamic block for refresh.
  10316. This empties the block, puts the cursor at the insert position and returns
  10317. the property list including an extra property :name with the block name."
  10318. (unless (looking-at org-dblock-start-re)
  10319. (user-error "Not at a dynamic block"))
  10320. (let* ((begdel (1+ (match-end 0)))
  10321. (name (org-no-properties (match-string 1)))
  10322. (params (append (list :name name)
  10323. (read (concat "(" (match-string 3) ")")))))
  10324. (save-excursion
  10325. (beginning-of-line 1)
  10326. (skip-chars-forward " \t")
  10327. (setq params (plist-put params :indentation-column (current-column))))
  10328. (unless (re-search-forward org-dblock-end-re nil t)
  10329. (error "Dynamic block not terminated"))
  10330. (setq params
  10331. (append params
  10332. (list :content (buffer-substring
  10333. begdel (match-beginning 0)))))
  10334. (delete-region begdel (match-beginning 0))
  10335. (goto-char begdel)
  10336. (open-line 1)
  10337. params))
  10338. (defun org-map-dblocks (&optional command)
  10339. "Apply COMMAND to all dynamic blocks in the current buffer.
  10340. If COMMAND is not given, use `org-update-dblock'."
  10341. (let ((cmd (or command 'org-update-dblock)))
  10342. (save-excursion
  10343. (goto-char (point-min))
  10344. (while (re-search-forward org-dblock-start-re nil t)
  10345. (goto-char (match-beginning 0))
  10346. (save-excursion
  10347. (condition-case nil
  10348. (funcall cmd)
  10349. (error (message "Error during update of dynamic block"))))
  10350. (unless (re-search-forward org-dblock-end-re nil t)
  10351. (error "Dynamic block not terminated"))))))
  10352. (defcustom org-dynamic-block-alist nil
  10353. "Alist defining all the Org dynamic blocks.
  10354. The key is the dynamic block type name, as a string. The value
  10355. is the function used to insert the dynamic block."
  10356. :group 'org-block
  10357. :package-version '(Org . "9.3")
  10358. :type '(alist :tag "Dynamic block name"
  10359. :key-type string
  10360. :value-type function)
  10361. :safe #'listp)
  10362. (defun org-dynamic-block-function (type)
  10363. "Return function associated to a given dynamic block type.
  10364. TYPE is the dynamic block type, as a string."
  10365. (cdr (assoc type org-dynamic-block-alist)))
  10366. (defun org-dynamic-block-types ()
  10367. "List all defined dynamic block types."
  10368. (mapcar #'car org-dynamic-block-alist))
  10369. (defun org-dynamic-block-define (type func)
  10370. "Define dynamic block TYPE with FUNC."
  10371. (push (cons type func) org-dynamic-block-alist))
  10372. (defun org-dynamic-block-insert-dblock (type)
  10373. "Insert a dynamic block of type TYPE.
  10374. When used interactively, select the dynamic block types among
  10375. defined types, per `org-dynamic-block-define'."
  10376. (interactive (list (completing-read "Dynamic block: "
  10377. (org-dynamic-block-types))))
  10378. (pcase (org-dynamic-block-function type)
  10379. (`nil (error "No such dynamic block: %S" type))
  10380. ((and f (pred functionp)) (funcall f))
  10381. (_ (error "Invalid function for dynamic block %S" type))))
  10382. (defun org-dblock-update (&optional arg)
  10383. "User command for updating dynamic blocks.
  10384. Update the dynamic block at point. With prefix ARG, update all dynamic
  10385. blocks in the buffer."
  10386. (interactive "P")
  10387. (if arg
  10388. (org-update-all-dblocks)
  10389. (or (looking-at org-dblock-start-re)
  10390. (org-beginning-of-dblock))
  10391. (org-update-dblock)))
  10392. (defun org-update-dblock ()
  10393. "Update the dynamic block at point.
  10394. This means to empty the block, parse for parameters and then call
  10395. the correct writing function."
  10396. (interactive)
  10397. (save-excursion
  10398. (let* ((win (selected-window))
  10399. (pos (point))
  10400. (line (org-current-line))
  10401. (params (org-prepare-dblock))
  10402. (name (plist-get params :name))
  10403. (indent (plist-get params :indentation-column))
  10404. (cmd (intern (concat "org-dblock-write:" name))))
  10405. (message "Updating dynamic block `%s' at line %d..." name line)
  10406. (funcall cmd params)
  10407. (message "Updating dynamic block `%s' at line %d...done" name line)
  10408. (goto-char pos)
  10409. (when (and indent (> indent 0))
  10410. (setq indent (make-string indent ?\ ))
  10411. (save-excursion
  10412. (select-window win)
  10413. (org-beginning-of-dblock)
  10414. (forward-line 1)
  10415. (while (not (looking-at org-dblock-end-re))
  10416. (insert indent)
  10417. (beginning-of-line 2))
  10418. (when (looking-at org-dblock-end-re)
  10419. (and (looking-at "[ \t]+")
  10420. (replace-match ""))
  10421. (insert indent)))))))
  10422. (defun org-beginning-of-dblock ()
  10423. "Find the beginning of the dynamic block at point.
  10424. Error if there is no such block at point."
  10425. (let ((pos (point))
  10426. beg)
  10427. (end-of-line 1)
  10428. (if (and (re-search-backward org-dblock-start-re nil t)
  10429. (setq beg (match-beginning 0))
  10430. (re-search-forward org-dblock-end-re nil t)
  10431. (> (match-end 0) pos))
  10432. (goto-char beg)
  10433. (goto-char pos)
  10434. (error "Not in a dynamic block"))))
  10435. (defun org-update-all-dblocks ()
  10436. "Update all dynamic blocks in the buffer.
  10437. This function can be used in a hook."
  10438. (interactive)
  10439. (when (derived-mode-p 'org-mode)
  10440. (org-map-dblocks 'org-update-dblock)))
  10441. ;;;; Completion
  10442. (declare-function org-export-backend-options "ox" (cl-x) t)
  10443. (defun org-get-export-keywords ()
  10444. "Return a list of all currently understood export keywords.
  10445. Export keywords include options, block names, attributes and
  10446. keywords relative to each registered export back-end."
  10447. (let (keywords)
  10448. (dolist (backend
  10449. (bound-and-true-p org-export-registered-backends)
  10450. (delq nil keywords))
  10451. ;; Back-end name (for keywords, like #+LATEX:)
  10452. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  10453. (dolist (option-entry (org-export-backend-options backend))
  10454. ;; Back-end options.
  10455. (push (nth 1 option-entry) keywords)))))
  10456. (defconst org-options-keywords
  10457. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  10458. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  10459. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  10460. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  10461. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  10462. (defcustom org-structure-template-alist
  10463. '(("a" . "export ascii")
  10464. ("c" . "center")
  10465. ("C" . "comment")
  10466. ("e" . "example")
  10467. ("E" . "export")
  10468. ("h" . "export html")
  10469. ("l" . "export latex")
  10470. ("q" . "quote")
  10471. ("s" . "src")
  10472. ("v" . "verse"))
  10473. "An alist of keys and block types.
  10474. `org-insert-structure-template' will display a menu with this
  10475. list of templates to choose from. The block type is inserted,
  10476. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  10477. The menu keys are defined by the car of each entry in this alist.
  10478. If two entries have the keys \"a\" and \"aa\" respectively, the
  10479. former will be inserted by typing \"a TAB/RET/SPC\" and the
  10480. latter will be inserted by typing \"aa\". If an entry with the
  10481. key \"aab\" is later added, it can be inserted by typing \"ab\".
  10482. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  10483. block can be inserted by pressing TAB after the string \"<KEY\"."
  10484. :group 'org-edit-structure
  10485. :type '(repeat
  10486. (cons (string :tag "Key")
  10487. (string :tag "Template")))
  10488. :package-version '(Org . "9.2"))
  10489. (defun org--check-org-structure-template-alist (&optional checklist)
  10490. "Check whether `org-structure-template-alist' is set up correctly.
  10491. In particular, check if the Org 9.2 format is used as opposed to
  10492. previous format.
  10493. "
  10494. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  10495. (or (eval checklist)
  10496. org-structure-template-alist))))
  10497. (when elm
  10498. (org-display-warning
  10499. (format "
  10500. Please update the entries of `%s'.
  10501. In Org 9.2 the format was changed from something like
  10502. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  10503. to something like
  10504. (\"s\" . \"src\")
  10505. Please refer to the documentation of `org-structure-template-alist'.
  10506. The following entries must be updated:
  10507. %s"
  10508. (or checklist 'org-structure-template-alist)
  10509. (pp-to-string elm))))))
  10510. (defun org--insert-structure-template-mks ()
  10511. "Present `org-structure-template-alist' with `org-mks'.
  10512. Menus are added if keys require more than one keystroke. Tabs
  10513. are added to single key entries when more than one stroke is
  10514. needed. Keys longer than two characters are reduced to two
  10515. characters."
  10516. (org--check-org-structure-template-alist)
  10517. (let* (case-fold-search
  10518. (templates (append org-structure-template-alist
  10519. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  10520. (keys (mapcar #'car templates))
  10521. (start-letters
  10522. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  10523. ;; Sort each element of `org-structure-template-alist' into
  10524. ;; sublists according to the first letter.
  10525. (superlist
  10526. (mapcar (lambda (letter)
  10527. (list letter
  10528. (cl-remove-if-not
  10529. (apply-partially #'string-match-p (concat "^" letter))
  10530. templates :key #'car)))
  10531. start-letters)))
  10532. (org-mks
  10533. (apply #'append
  10534. ;; Make an `org-mks' table. If only one element is
  10535. ;; present in a sublist, make it part of the top-menu,
  10536. ;; otherwise make a submenu according to the starting
  10537. ;; letter and populate it.
  10538. (mapcar (lambda (sublist)
  10539. (if (eq 1 (length (cadr sublist)))
  10540. (mapcar (lambda (elm)
  10541. (list (substring (car elm) 0 1)
  10542. (cdr elm) ""))
  10543. (cadr sublist))
  10544. ;; Create submenu.
  10545. (let* ((topkey (car sublist))
  10546. (elms (cadr sublist))
  10547. (keys (mapcar #'car elms))
  10548. (long (> (length elms) 3)))
  10549. (append
  10550. (list
  10551. ;; Make a description of the submenu.
  10552. (list topkey
  10553. (concat
  10554. (mapconcat #'cdr
  10555. (cl-subseq elms 0 (if long 3 (length elms)))
  10556. ", ")
  10557. (when long ", ..."))))
  10558. ;; List of entries in submenu.
  10559. (cl-mapcar #'list
  10560. (org--insert-structure-template-unique-keys keys)
  10561. (mapcar #'cdr elms)
  10562. (make-list (length elms) ""))))))
  10563. superlist))
  10564. "Select a key\n============"
  10565. "Key: ")))
  10566. (defun org--insert-structure-template-unique-keys (keys)
  10567. "Make a list of unique, two characters long elements from KEYS.
  10568. Elements of length one have a tab appended. Elements of length
  10569. two are kept as is. Longer elements are truncated to length two.
  10570. If an element cannot be made unique, an error is raised."
  10571. (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  10572. menu-keys)
  10573. (dolist (key orderd-keys)
  10574. (let ((potential-key
  10575. (cl-case (length key)
  10576. (1 (concat key "\t"))
  10577. (2 key)
  10578. (otherwise
  10579. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  10580. (mapcar (apply-partially #'concat (substring key 0 1))
  10581. (split-string (substring key 1) "" t)))))))
  10582. (if (or (not potential-key) (assoc potential-key menu-keys))
  10583. (user-error "Could not make unique key for %s." key)
  10584. (push (cons potential-key key) menu-keys))))
  10585. (mapcar #'car
  10586. (cl-sort menu-keys #'<
  10587. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  10588. (defun org-insert-structure-template (type)
  10589. "Insert a block structure of the type #+begin_foo/#+end_foo.
  10590. Select a block from `org-structure-template-alist' then type
  10591. either RET, TAB or SPC to write the block type. With an active
  10592. region, wrap the region in the block. Otherwise, insert an empty
  10593. block."
  10594. (interactive
  10595. (list (pcase (org--insert-structure-template-mks)
  10596. (`("\t" . ,_) (read-string "Structure type: "))
  10597. (`(,_ ,choice . ,_) choice))))
  10598. (let* ((region? (use-region-p))
  10599. (region-start (and region? (region-beginning)))
  10600. (region-end (and region? (copy-marker (region-end))))
  10601. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  10602. (verbatim? (string-match-p
  10603. (concat "\\`" (regexp-opt '("example" "export" "src")))
  10604. type)))
  10605. (when region? (goto-char region-start))
  10606. (let ((column (current-indentation)))
  10607. (if (save-excursion (skip-chars-backward " \t") (bolp))
  10608. (beginning-of-line)
  10609. (insert "\n"))
  10610. (save-excursion
  10611. (indent-to column)
  10612. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  10613. (when region?
  10614. (when verbatim? (org-escape-code-in-region (point) region-end))
  10615. (goto-char region-end)
  10616. ;; Ignore empty lines at the end of the region.
  10617. (skip-chars-backward " \r\t\n")
  10618. (end-of-line))
  10619. (unless (bolp) (insert "\n"))
  10620. (indent-to column)
  10621. (insert (format "#+end_%s" (car (split-string type))))
  10622. (if (looking-at "[ \t]*$") (replace-match "")
  10623. (insert "\n"))
  10624. (when (and (eobp) (not (bolp))) (insert "\n")))
  10625. (if extended? (end-of-line)
  10626. (forward-line)
  10627. (skip-chars-forward " \t")))))
  10628. ;;;; TODO, DEADLINE, Comments
  10629. (defun org-toggle-comment ()
  10630. "Change the COMMENT state of an entry."
  10631. (interactive)
  10632. (save-excursion
  10633. (org-back-to-heading)
  10634. (let ((case-fold-search nil))
  10635. (looking-at org-complex-heading-regexp))
  10636. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  10637. (skip-chars-forward " \t")
  10638. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  10639. (if (org-in-commented-heading-p t)
  10640. (delete-region (point)
  10641. (progn (search-forward " " (line-end-position) 'move)
  10642. (skip-chars-forward " \t")
  10643. (point)))
  10644. (insert org-comment-string)
  10645. (unless (eolp) (insert " ")))))
  10646. (defvar org-last-todo-state-is-todo nil
  10647. "This is non-nil when the last TODO state change led to a TODO state.
  10648. If the last change removed the TODO tag or switched to DONE, then
  10649. this is nil.")
  10650. (defvar org-todo-setup-filter-hook nil
  10651. "Hook for functions that pre-filter todo specs.
  10652. Each function takes a todo spec and returns either nil or the spec
  10653. transformed into canonical form." )
  10654. (defvar org-todo-get-default-hook nil
  10655. "Hook for functions that get a default item for todo.
  10656. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  10657. nil or a string to be used for the todo mark." )
  10658. (defvar org-agenda-headline-snapshot-before-repeat)
  10659. (defun org-current-effective-time ()
  10660. "Return current time adjusted for `org-extend-today-until' variable."
  10661. (let* ((ct (org-current-time))
  10662. (dct (decode-time ct))
  10663. (ct1
  10664. (cond
  10665. (org-use-last-clock-out-time-as-effective-time
  10666. (or (org-clock-get-last-clock-out-time) ct))
  10667. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  10668. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  10669. (t ct))))
  10670. ct1))
  10671. (defun org-todo-yesterday (&optional arg)
  10672. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  10673. (interactive "P")
  10674. (if (eq major-mode 'org-agenda-mode)
  10675. (apply 'org-agenda-todo-yesterday arg)
  10676. (let* ((org-use-effective-time t)
  10677. (hour (nth 2 (decode-time (org-current-time))))
  10678. (org-extend-today-until (1+ hour)))
  10679. (org-todo arg))))
  10680. (defvar org-block-entry-blocking ""
  10681. "First entry preventing the TODO state change.")
  10682. (defun org-cancel-repeater ()
  10683. "Cancel a repeater by setting its numeric value to zero."
  10684. (interactive)
  10685. (save-excursion
  10686. (org-back-to-heading t)
  10687. (let ((bound1 (point))
  10688. (bound0 (save-excursion (outline-next-heading) (point))))
  10689. (when (and (re-search-forward
  10690. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  10691. org-deadline-time-regexp "\\)\\|\\("
  10692. org-ts-regexp "\\)")
  10693. bound0 t)
  10694. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  10695. bound1 t))
  10696. (replace-match "0" t nil nil 1)))))
  10697. (defvar org-state)
  10698. (defvar org-blocked-by-checkboxes)
  10699. (defun org-todo (&optional arg)
  10700. "Change the TODO state of an item.
  10701. The state of an item is given by a keyword at the start of the heading,
  10702. like
  10703. *** TODO Write paper
  10704. *** DONE Call mom
  10705. The different keywords are specified in the variable `org-todo-keywords'.
  10706. By default the available states are \"TODO\" and \"DONE\". So, for this
  10707. example: when the item starts with TODO, it is changed to DONE.
  10708. When it starts with DONE, the DONE is removed. And when neither TODO nor
  10709. DONE are present, add TODO at the beginning of the heading.
  10710. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  10711. state.
  10712. With numeric prefix ARG, switch to that state.
  10713. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  10714. next set of TODO \
  10715. keywords (nextset).
  10716. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  10717. prefix, circumvent any state blocking.
  10718. With a numeric prefix arg of 0, inhibit note taking for the change.
  10719. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  10720. When called through ELisp, arg is also interpreted in the following way:
  10721. `none' -> empty state
  10722. \"\" -> switch to empty state
  10723. `done' -> switch to DONE
  10724. `nextset' -> switch to the next set of keywords
  10725. `previousset' -> switch to the previous set of keywords
  10726. \"WAITING\" -> switch to the specified keyword, but only if it
  10727. really is a member of `org-todo-keywords'."
  10728. (interactive "P")
  10729. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10730. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10731. 'region-start-level 'region))
  10732. org-loop-over-headlines-in-active-region)
  10733. (org-map-entries
  10734. `(org-todo ,arg)
  10735. org-loop-over-headlines-in-active-region
  10736. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  10737. (when (equal arg '(16)) (setq arg 'nextset))
  10738. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  10739. (let ((org-blocker-hook org-blocker-hook)
  10740. commentp
  10741. case-fold-search)
  10742. (when (equal arg '(64))
  10743. (setq arg nil org-blocker-hook nil))
  10744. (when (and org-blocker-hook
  10745. (or org-inhibit-blocking
  10746. (org-entry-get nil "NOBLOCKING")))
  10747. (setq org-blocker-hook nil))
  10748. (save-excursion
  10749. (catch 'exit
  10750. (org-back-to-heading t)
  10751. (when (org-in-commented-heading-p t)
  10752. (org-toggle-comment)
  10753. (setq commentp t))
  10754. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  10755. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  10756. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  10757. (let* ((match-data (match-data))
  10758. (startpos (copy-marker (line-beginning-position)))
  10759. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  10760. (org-log-done org-log-done)
  10761. (org-log-repeat org-log-repeat)
  10762. (org-todo-log-states org-todo-log-states)
  10763. (org-inhibit-logging
  10764. (if (equal arg 0)
  10765. (progn (setq arg nil) 'note) org-inhibit-logging))
  10766. (this (match-string 1))
  10767. (hl-pos (match-beginning 0))
  10768. (head (org-get-todo-sequence-head this))
  10769. (ass (assoc head org-todo-kwd-alist))
  10770. (interpret (nth 1 ass))
  10771. (done-word (nth 3 ass))
  10772. (final-done-word (nth 4 ass))
  10773. (org-last-state (or this ""))
  10774. (completion-ignore-case t)
  10775. (member (member this org-todo-keywords-1))
  10776. (tail (cdr member))
  10777. (org-state (cond
  10778. ((and org-todo-key-trigger
  10779. (or (and (equal arg '(4))
  10780. (eq org-use-fast-todo-selection 'prefix))
  10781. (and (not arg) org-use-fast-todo-selection
  10782. (not (eq org-use-fast-todo-selection
  10783. 'prefix)))))
  10784. ;; Use fast selection.
  10785. (org-fast-todo-selection))
  10786. ((and (equal arg '(4))
  10787. (or (not org-use-fast-todo-selection)
  10788. (not org-todo-key-trigger)))
  10789. ;; Read a state with completion.
  10790. (completing-read
  10791. "State: " (mapcar #'list org-todo-keywords-1)
  10792. nil t))
  10793. ((eq arg 'right)
  10794. (if this
  10795. (if tail (car tail) nil)
  10796. (car org-todo-keywords-1)))
  10797. ((eq arg 'left)
  10798. (unless (equal member org-todo-keywords-1)
  10799. (if this
  10800. (nth (- (length org-todo-keywords-1)
  10801. (length tail) 2)
  10802. org-todo-keywords-1)
  10803. (org-last org-todo-keywords-1))))
  10804. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  10805. (setq arg nil))) ;hack to fall back to cycling
  10806. (arg
  10807. ;; User or caller requests a specific state.
  10808. (cond
  10809. ((equal arg "") nil)
  10810. ((eq arg 'none) nil)
  10811. ((eq arg 'done) (or done-word (car org-done-keywords)))
  10812. ((eq arg 'nextset)
  10813. (or (car (cdr (member head org-todo-heads)))
  10814. (car org-todo-heads)))
  10815. ((eq arg 'previousset)
  10816. (let ((org-todo-heads (reverse org-todo-heads)))
  10817. (or (car (cdr (member head org-todo-heads)))
  10818. (car org-todo-heads))))
  10819. ((car (member arg org-todo-keywords-1)))
  10820. ((stringp arg)
  10821. (user-error "State `%s' not valid in this file" arg))
  10822. ((nth (1- (prefix-numeric-value arg))
  10823. org-todo-keywords-1))))
  10824. ((null member) (or head (car org-todo-keywords-1)))
  10825. ((equal this final-done-word) nil) ;-> make empty
  10826. ((null tail) nil) ;-> first entry
  10827. ((memq interpret '(type priority))
  10828. (if (eq this-command last-command)
  10829. (car tail)
  10830. (if (> (length tail) 0)
  10831. (or done-word (car org-done-keywords))
  10832. nil)))
  10833. (t
  10834. (car tail))))
  10835. (org-state (or
  10836. (run-hook-with-args-until-success
  10837. 'org-todo-get-default-hook org-state org-last-state)
  10838. org-state))
  10839. (next (if org-state (concat " " org-state " ") " "))
  10840. (change-plist (list :type 'todo-state-change :from this :to org-state
  10841. :position startpos))
  10842. dolog now-done-p)
  10843. (when org-blocker-hook
  10844. (let (org-blocked-by-checkboxes block-reason)
  10845. (setq org-last-todo-state-is-todo
  10846. (not (member this org-done-keywords)))
  10847. (unless (save-excursion
  10848. (save-match-data
  10849. (org-with-wide-buffer
  10850. (run-hook-with-args-until-failure
  10851. 'org-blocker-hook change-plist))))
  10852. (setq block-reason (if org-blocked-by-checkboxes
  10853. "contained checkboxes"
  10854. (format "\"%s\"" org-block-entry-blocking)))
  10855. (if (called-interactively-p 'interactive)
  10856. (user-error "TODO state change from %s to %s blocked (by %s)"
  10857. this org-state block-reason)
  10858. ;; Fail silently.
  10859. (message "TODO state change from %s to %s blocked (by %s)"
  10860. this org-state block-reason)
  10861. (throw 'exit nil)))))
  10862. (store-match-data match-data)
  10863. (replace-match next t t)
  10864. (cond ((equal this org-state)
  10865. (message "TODO state was already %s" (org-trim next)))
  10866. ((not (pos-visible-in-window-p hl-pos))
  10867. (message "TODO state changed to %s" (org-trim next))))
  10868. (unless head
  10869. (setq head (org-get-todo-sequence-head org-state)
  10870. ass (assoc head org-todo-kwd-alist)
  10871. interpret (nth 1 ass)
  10872. done-word (nth 3 ass)
  10873. final-done-word (nth 4 ass)))
  10874. (when (memq arg '(nextset previousset))
  10875. (message "Keyword-Set %d/%d: %s"
  10876. (- (length org-todo-sets) -1
  10877. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  10878. (length org-todo-sets)
  10879. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  10880. (setq org-last-todo-state-is-todo
  10881. (not (member org-state org-done-keywords)))
  10882. (setq now-done-p (and (member org-state org-done-keywords)
  10883. (not (member this org-done-keywords))))
  10884. (and logging (org-local-logging logging))
  10885. (when (and (or org-todo-log-states org-log-done)
  10886. (not (eq org-inhibit-logging t))
  10887. (not (memq arg '(nextset previousset))))
  10888. ;; We need to look at recording a time and note.
  10889. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  10890. (nth 2 (assoc this org-todo-log-states))))
  10891. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  10892. (setq dolog 'time))
  10893. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  10894. (and org-state
  10895. (member org-state org-not-done-keywords)
  10896. (not (member this org-not-done-keywords))))
  10897. ;; This is now a todo state and was not one before
  10898. ;; If there was a CLOSED time stamp, get rid of it.
  10899. (org-add-planning-info nil nil 'closed))
  10900. (when (and now-done-p org-log-done)
  10901. ;; It is now done, and it was not done before.
  10902. (org-add-planning-info 'closed (org-current-effective-time))
  10903. (when (and (not dolog) (eq 'note org-log-done))
  10904. (org-add-log-setup 'done org-state this 'note)))
  10905. (when (and org-state dolog)
  10906. ;; This is a non-nil state, and we need to log it.
  10907. (org-add-log-setup 'state org-state this dolog)))
  10908. ;; Fixup tag positioning.
  10909. (org-todo-trigger-tag-changes org-state)
  10910. (when org-auto-align-tags (org-align-tags))
  10911. (when org-provide-todo-statistics
  10912. (org-update-parent-todo-statistics))
  10913. (run-hooks 'org-after-todo-state-change-hook)
  10914. (when (and arg (not (member org-state org-done-keywords)))
  10915. (setq head (org-get-todo-sequence-head org-state)))
  10916. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  10917. ;; Do we need to trigger a repeat?
  10918. (when now-done-p
  10919. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  10920. ;; This is for the agenda, take a snapshot of the headline.
  10921. (save-match-data
  10922. (setq org-agenda-headline-snapshot-before-repeat
  10923. (org-get-heading))))
  10924. (org-auto-repeat-maybe org-state))
  10925. ;; Fixup cursor location if close to the keyword.
  10926. (when (and (outline-on-heading-p)
  10927. (not (bolp))
  10928. (save-excursion (beginning-of-line 1)
  10929. (looking-at org-todo-line-regexp))
  10930. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  10931. (goto-char (or (match-end 2) (match-end 1)))
  10932. (and (looking-at " ") (just-one-space)))
  10933. (when org-trigger-hook
  10934. (save-excursion
  10935. (run-hook-with-args 'org-trigger-hook change-plist)))
  10936. (when commentp (org-toggle-comment))))))))
  10937. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  10938. "Block turning an entry into a TODO, using the hierarchy.
  10939. This checks whether the current task should be blocked from state
  10940. changes. Such blocking occurs when:
  10941. 1. The task has children which are not all in a completed state.
  10942. 2. A task has a parent with the property :ORDERED:, and there
  10943. are siblings prior to the current task with incomplete
  10944. status.
  10945. 3. The parent of the task is blocked because it has siblings that should
  10946. be done first, or is child of a block grandparent TODO entry."
  10947. (if (not org-enforce-todo-dependencies)
  10948. t ; if locally turned off don't block
  10949. (catch 'dont-block
  10950. ;; If this is not a todo state change, or if this entry is already DONE,
  10951. ;; do not block
  10952. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  10953. (member (plist-get change-plist :from)
  10954. (cons 'done org-done-keywords))
  10955. (member (plist-get change-plist :to)
  10956. (cons 'todo org-not-done-keywords))
  10957. (not (plist-get change-plist :to)))
  10958. (throw 'dont-block t))
  10959. ;; If this task has children, and any are undone, it's blocked
  10960. (save-excursion
  10961. (org-back-to-heading t)
  10962. (let ((this-level (funcall outline-level)))
  10963. (outline-next-heading)
  10964. (let ((child-level (funcall outline-level)))
  10965. (while (and (not (eobp))
  10966. (> child-level this-level))
  10967. ;; this todo has children, check whether they are all
  10968. ;; completed
  10969. (when (and (not (org-entry-is-done-p))
  10970. (org-entry-is-todo-p))
  10971. (setq org-block-entry-blocking (org-get-heading))
  10972. (throw 'dont-block nil))
  10973. (outline-next-heading)
  10974. (setq child-level (funcall outline-level))))))
  10975. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  10976. ;; any previous siblings are undone, it's blocked
  10977. (save-excursion
  10978. (org-back-to-heading t)
  10979. (let* ((pos (point))
  10980. (parent-pos (and (org-up-heading-safe) (point)))
  10981. (case-fold-search nil))
  10982. (unless parent-pos (throw 'dont-block t)) ; no parent
  10983. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  10984. (forward-line 1)
  10985. (re-search-forward org-not-done-heading-regexp pos t))
  10986. (setq org-block-entry-blocking (match-string 0))
  10987. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  10988. ;; Search further up the hierarchy, to see if an ancestor is blocked
  10989. (while t
  10990. (goto-char parent-pos)
  10991. (unless (looking-at org-not-done-heading-regexp)
  10992. (throw 'dont-block t)) ; do not block, parent is not a TODO
  10993. (setq pos (point))
  10994. (setq parent-pos (and (org-up-heading-safe) (point)))
  10995. (unless parent-pos (throw 'dont-block t)) ; no parent
  10996. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  10997. (forward-line 1)
  10998. (re-search-forward org-not-done-heading-regexp pos t)
  10999. (setq org-block-entry-blocking (org-get-heading)))
  11000. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11001. (defcustom org-track-ordered-property-with-tag nil
  11002. "Should the ORDERED property also be shown as a tag?
  11003. The ORDERED property decides if an entry should require subtasks to be
  11004. completed in sequence. Since a property is not very visible, setting
  11005. this option means that toggling the ORDERED property with the command
  11006. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11007. not relevant for the behavior, but it makes things more visible.
  11008. Note that toggling the tag with tags commands will not change the property
  11009. and therefore not influence behavior!
  11010. This can be t, meaning the tag ORDERED should be used, It can also be a
  11011. string to select a different tag for this task."
  11012. :group 'org-todo
  11013. :type '(choice
  11014. (const :tag "No tracking" nil)
  11015. (const :tag "Track with ORDERED tag" t)
  11016. (string :tag "Use other tag")))
  11017. (defun org-toggle-ordered-property ()
  11018. "Toggle the ORDERED property of the current entry.
  11019. For better visibility, you can track the value of this property with a tag.
  11020. See variable `org-track-ordered-property-with-tag'."
  11021. (interactive)
  11022. (let* ((t1 org-track-ordered-property-with-tag)
  11023. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11024. (save-excursion
  11025. (org-back-to-heading)
  11026. (if (org-entry-get nil "ORDERED")
  11027. (progn
  11028. (org-delete-property "ORDERED")
  11029. (and tag (org-toggle-tag tag 'off))
  11030. (message "Subtasks can be completed in arbitrary order"))
  11031. (org-entry-put nil "ORDERED" "t")
  11032. (and tag (org-toggle-tag tag 'on))
  11033. (message "Subtasks must be completed in sequence")))))
  11034. (defun org-block-todo-from-checkboxes (change-plist)
  11035. "Block turning an entry into a TODO, using checkboxes.
  11036. This checks whether the current task should be blocked from state
  11037. changes because there are unchecked boxes in this entry."
  11038. (if (not org-enforce-todo-checkbox-dependencies)
  11039. t ; if locally turned off don't block
  11040. (catch 'dont-block
  11041. ;; If this is not a todo state change, or if this entry is already DONE,
  11042. ;; do not block
  11043. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11044. (member (plist-get change-plist :from)
  11045. (cons 'done org-done-keywords))
  11046. (member (plist-get change-plist :to)
  11047. (cons 'todo org-not-done-keywords))
  11048. (not (plist-get change-plist :to)))
  11049. (throw 'dont-block t))
  11050. ;; If this task has checkboxes that are not checked, it's blocked
  11051. (save-excursion
  11052. (org-back-to-heading t)
  11053. (let ((beg (point)) end)
  11054. (outline-next-heading)
  11055. (setq end (point))
  11056. (goto-char beg)
  11057. (when (org-list-search-forward
  11058. (concat (org-item-beginning-re)
  11059. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11060. "\\[[- ]\\]")
  11061. end t)
  11062. (when (boundp 'org-blocked-by-checkboxes)
  11063. (setq org-blocked-by-checkboxes t))
  11064. (throw 'dont-block nil))))
  11065. t))) ; do not block
  11066. (defun org-entry-blocked-p ()
  11067. "Non-nil if entry at point is blocked."
  11068. (and (not (org-entry-get nil "NOBLOCKING"))
  11069. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11070. (not (run-hook-with-args-until-failure
  11071. 'org-blocker-hook
  11072. (list :type 'todo-state-change
  11073. :position (point)
  11074. :from 'todo
  11075. :to 'done)))))
  11076. (defun org-update-statistics-cookies (all)
  11077. "Update the statistics cookie, either from TODO or from checkboxes.
  11078. This should be called with the cursor in a line with a statistics
  11079. cookie. When called with a \\[universal-argument] prefix, update
  11080. all statistics cookies in the buffer."
  11081. (interactive "P")
  11082. (if all
  11083. (progn
  11084. (org-update-checkbox-count 'all)
  11085. (org-map-entries 'org-update-parent-todo-statistics))
  11086. (if (not (org-at-heading-p))
  11087. (org-update-checkbox-count)
  11088. (let ((pos (point-marker))
  11089. end l1 l2)
  11090. (ignore-errors (org-back-to-heading t))
  11091. (if (not (org-at-heading-p))
  11092. (org-update-checkbox-count)
  11093. (setq l1 (org-outline-level))
  11094. (setq end (save-excursion
  11095. (outline-next-heading)
  11096. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11097. (point)))
  11098. (if (and (save-excursion
  11099. (re-search-forward
  11100. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11101. (not (save-excursion (re-search-forward
  11102. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11103. (org-update-checkbox-count)
  11104. (if (and l2 (> l2 l1))
  11105. (progn
  11106. (goto-char end)
  11107. (org-update-parent-todo-statistics))
  11108. (goto-char pos)
  11109. (beginning-of-line 1)
  11110. (while (re-search-forward
  11111. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11112. (point-at-eol) t)
  11113. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11114. (goto-char pos)
  11115. (move-marker pos nil)))))
  11116. (defvar org-entry-property-inherited-from) ;; defined below
  11117. (defun org-update-parent-todo-statistics ()
  11118. "Update any statistics cookie in the parent of the current headline.
  11119. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11120. the entire subtree and this will travel up the hierarchy and update
  11121. statistics everywhere."
  11122. (let* ((prop (save-excursion (org-up-heading-safe)
  11123. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11124. (recursive (or (not org-hierarchical-todo-statistics)
  11125. (and prop (string-match "\\<recursive\\>" prop))))
  11126. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11127. 0))
  11128. (first t)
  11129. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11130. level ltoggle l1 new ndel
  11131. (cnt-all 0) (cnt-done 0) is-percent kwd
  11132. checkbox-beg cookie-present)
  11133. (catch 'exit
  11134. (save-excursion
  11135. (beginning-of-line 1)
  11136. (setq ltoggle (funcall outline-level))
  11137. ;; Three situations are to consider:
  11138. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11139. ;; to the top-level ancestor on the headline;
  11140. ;; 2. If parent has "recursive" property, repeat up to the
  11141. ;; headline setting that property, taking inheritance into
  11142. ;; account;
  11143. ;; 3. Else, move up to direct parent and proceed only once.
  11144. (while (and (setq level (org-up-heading-safe))
  11145. (or recursive first)
  11146. (>= (point) lim))
  11147. (setq first nil cookie-present nil)
  11148. (unless (and level
  11149. (not (string-match
  11150. "\\<checkbox\\>"
  11151. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11152. "")))))
  11153. (throw 'exit nil))
  11154. (while (re-search-forward box-re (point-at-eol) t)
  11155. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11156. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11157. (save-match-data
  11158. (unless (outline-next-heading) (throw 'exit nil))
  11159. (while (and (looking-at org-complex-heading-regexp)
  11160. (> (setq l1 (length (match-string 1))) level))
  11161. (setq kwd (and (or recursive (= l1 ltoggle))
  11162. (match-string 2)))
  11163. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11164. (and (eq org-provide-todo-statistics t)
  11165. (or (member kwd org-done-keywords)))
  11166. (and (listp org-provide-todo-statistics)
  11167. (stringp (car org-provide-todo-statistics))
  11168. (or (member kwd org-provide-todo-statistics)
  11169. (member kwd org-done-keywords)))
  11170. (and (listp org-provide-todo-statistics)
  11171. (listp (car org-provide-todo-statistics))
  11172. (or (member kwd (car org-provide-todo-statistics))
  11173. (and (member kwd org-done-keywords)
  11174. (member kwd (cadr org-provide-todo-statistics))))))
  11175. (setq cnt-all (1+ cnt-all))
  11176. (and (eq org-provide-todo-statistics t)
  11177. kwd
  11178. (setq cnt-all (1+ cnt-all))))
  11179. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11180. (member kwd org-done-keywords))
  11181. (and (listp org-provide-todo-statistics)
  11182. (listp (car org-provide-todo-statistics))
  11183. (member kwd org-done-keywords)
  11184. (member kwd (cadr org-provide-todo-statistics)))
  11185. (and (listp org-provide-todo-statistics)
  11186. (stringp (car org-provide-todo-statistics))
  11187. (member kwd org-done-keywords)))
  11188. (setq cnt-done (1+ cnt-done)))
  11189. (outline-next-heading)))
  11190. (setq new
  11191. (if is-percent
  11192. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11193. (max 1 cnt-all)))
  11194. (format "[%d/%d]" cnt-done cnt-all))
  11195. ndel (- (match-end 0) checkbox-beg))
  11196. (goto-char checkbox-beg)
  11197. (insert new)
  11198. (delete-region (point) (+ (point) ndel))
  11199. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11200. (when cookie-present
  11201. (run-hook-with-args 'org-after-todo-statistics-hook
  11202. cnt-done (- cnt-all cnt-done))))))
  11203. (run-hooks 'org-todo-statistics-hook)))
  11204. (defvar org-after-todo-statistics-hook nil
  11205. "Hook that is called after a TODO statistics cookie has been updated.
  11206. Each function is called with two arguments: the number of not-done entries
  11207. and the number of done entries.
  11208. For example, the following function, when added to this hook, will switch
  11209. an entry to DONE when all children are done, and back to TODO when new
  11210. entries are set to a TODO status. Note that this hook is only called
  11211. when there is a statistics cookie in the headline!
  11212. (defun org-summary-todo (n-done n-not-done)
  11213. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11214. (let (org-log-done org-log-states) ; turn off logging
  11215. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11216. ")
  11217. (defvar org-todo-statistics-hook nil
  11218. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11219. This hook runs even if there is no statistics cookie present, in which case
  11220. `org-after-todo-statistics-hook' would not run.")
  11221. (defun org-todo-trigger-tag-changes (state)
  11222. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11223. (let ((l org-todo-state-tags-triggers)
  11224. changes)
  11225. (when (or (not state) (equal state ""))
  11226. (setq changes (append changes (cdr (assoc "" l)))))
  11227. (when (and (stringp state) (> (length state) 0))
  11228. (setq changes (append changes (cdr (assoc state l)))))
  11229. (when (member state org-not-done-keywords)
  11230. (setq changes (append changes (cdr (assq 'todo l)))))
  11231. (when (member state org-done-keywords)
  11232. (setq changes (append changes (cdr (assq 'done l)))))
  11233. (dolist (c changes)
  11234. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11235. (defun org-local-logging (value)
  11236. "Get logging settings from a property VALUE."
  11237. ;; Directly set the variables, they are already local.
  11238. (setq org-log-done nil
  11239. org-log-repeat nil
  11240. org-todo-log-states nil)
  11241. (dolist (w (split-string value))
  11242. (let (a)
  11243. (cond
  11244. ((setq a (assoc w org-startup-options))
  11245. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11246. (set (nth 1 a) (nth 2 a))))
  11247. ((setq a (org-extract-log-state-settings w))
  11248. (and (member (car a) org-todo-keywords-1)
  11249. (push a org-todo-log-states)))))))
  11250. (defun org-get-todo-sequence-head (kwd)
  11251. "Return the head of the TODO sequence to which KWD belongs.
  11252. If KWD is not set, check if there is a text property remembering the
  11253. right sequence."
  11254. (let (p)
  11255. (cond
  11256. ((not kwd)
  11257. (or (get-text-property (point-at-bol) 'org-todo-head)
  11258. (progn
  11259. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11260. nil (point-at-eol)))
  11261. (get-text-property p 'org-todo-head))))
  11262. ((not (member kwd org-todo-keywords-1))
  11263. (car org-todo-keywords-1))
  11264. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11265. (defun org-fast-todo-selection ()
  11266. "Fast TODO keyword selection with single keys.
  11267. Returns the new TODO keyword, or nil if no state change should occur."
  11268. (let* ((fulltable org-todo-key-alist)
  11269. (done-keywords org-done-keywords) ;; needed for the faces.
  11270. (maxlen (apply 'max (mapcar
  11271. (lambda (x)
  11272. (if (stringp (car x)) (string-width (car x)) 0))
  11273. fulltable)))
  11274. (expert nil)
  11275. (fwidth (+ maxlen 3 1 3))
  11276. (ncol (/ (- (window-width) 4) fwidth))
  11277. tg cnt e c tbl
  11278. groups ingroup)
  11279. (save-excursion
  11280. (save-window-excursion
  11281. (if expert
  11282. (set-buffer (get-buffer-create " *Org todo*"))
  11283. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11284. (erase-buffer)
  11285. (setq-local org-done-keywords done-keywords)
  11286. (setq tbl fulltable cnt 0)
  11287. (while (setq e (pop tbl))
  11288. (cond
  11289. ((equal e '(:startgroup))
  11290. (push '() groups) (setq ingroup t)
  11291. (unless (= cnt 0)
  11292. (setq cnt 0)
  11293. (insert "\n"))
  11294. (insert "{ "))
  11295. ((equal e '(:endgroup))
  11296. (setq ingroup nil cnt 0)
  11297. (insert "}\n"))
  11298. ((equal e '(:newline))
  11299. (unless (= cnt 0)
  11300. (setq cnt 0)
  11301. (insert "\n")
  11302. (setq e (car tbl))
  11303. (while (equal (car tbl) '(:newline))
  11304. (insert "\n")
  11305. (setq tbl (cdr tbl)))))
  11306. (t
  11307. (setq tg (car e) c (cdr e))
  11308. (when ingroup (push tg (car groups)))
  11309. (setq tg (org-add-props tg nil 'face
  11310. (org-get-todo-face tg)))
  11311. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11312. (insert "[" c "] " tg (make-string
  11313. (- fwidth 4 (length tg)) ?\ ))
  11314. (when (= (setq cnt (1+ cnt)) ncol)
  11315. (insert "\n")
  11316. (when ingroup (insert " "))
  11317. (setq cnt 0)))))
  11318. (insert "\n")
  11319. (goto-char (point-min))
  11320. (unless expert (org-fit-window-to-buffer))
  11321. (message "[a-z..]:Set [SPC]:clear")
  11322. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11323. (cond
  11324. ((or (= c ?\C-g)
  11325. (and (= c ?q) (not (rassoc c fulltable))))
  11326. (setq quit-flag t))
  11327. ((= c ?\ ) nil)
  11328. ((setq e (rassoc c fulltable) tg (car e))
  11329. tg)
  11330. (t (setq quit-flag t)))))))
  11331. (defun org-entry-is-todo-p ()
  11332. (member (org-get-todo-state) org-not-done-keywords))
  11333. (defun org-entry-is-done-p ()
  11334. (member (org-get-todo-state) org-done-keywords))
  11335. (defun org-get-todo-state ()
  11336. "Return the TODO keyword of the current subtree."
  11337. (save-excursion
  11338. (org-back-to-heading t)
  11339. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11340. (match-end 2)
  11341. (match-string 2))))
  11342. (defun org-at-date-range-p (&optional inactive-ok)
  11343. "Non-nil if point is inside a date range.
  11344. When optional argument INACTIVE-OK is non-nil, also consider
  11345. inactive time ranges.
  11346. When this function returns a non-nil value, match data is set
  11347. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11348. on INACTIVE-OK."
  11349. (interactive)
  11350. (save-excursion
  11351. (catch 'exit
  11352. (let ((pos (point)))
  11353. (skip-chars-backward "^[<\r\n")
  11354. (skip-chars-backward "<[")
  11355. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11356. (>= (match-end 0) pos)
  11357. (throw 'exit t))
  11358. (skip-chars-backward "^<[\r\n")
  11359. (skip-chars-backward "<[")
  11360. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11361. (>= (match-end 0) pos)
  11362. (throw 'exit t)))
  11363. nil)))
  11364. (defun org-get-repeat (&optional timestamp)
  11365. "Check if there is a time-stamp with repeater in this entry.
  11366. Return the repeater, as a string, or nil. Also return nil when
  11367. this function is called before first heading.
  11368. When optional argument TIMESTAMP is a string, extract the
  11369. repeater from there instead."
  11370. (save-match-data
  11371. (cond (timestamp
  11372. (and (string-match org-repeat-re timestamp)
  11373. (match-string-no-properties 1 timestamp)))
  11374. ((org-before-first-heading-p) nil)
  11375. (t
  11376. (save-excursion
  11377. (org-back-to-heading t)
  11378. (let ((end (org-entry-end-position)))
  11379. (catch :repeat
  11380. (while (re-search-forward org-repeat-re end t)
  11381. (when (save-match-data (org-at-timestamp-p 'agenda))
  11382. (throw :repeat (match-string-no-properties 1)))))))))))
  11383. (defvar org-last-changed-timestamp)
  11384. (defvar org-last-inserted-timestamp)
  11385. (defvar org-log-post-message)
  11386. (defvar org-log-note-purpose)
  11387. (defvar org-log-note-how nil)
  11388. (defvar org-log-note-extra)
  11389. (defun org-auto-repeat-maybe (done-word)
  11390. "Check if the current headline contains a repeated time-stamp.
  11391. If yes, set TODO state back to what it was and change the base date
  11392. of repeating deadline/scheduled time stamps to new date.
  11393. This function is run automatically after each state change to a DONE state."
  11394. (let* ((repeat (org-get-repeat))
  11395. (aa (assoc org-last-state org-todo-kwd-alist))
  11396. (interpret (nth 1 aa))
  11397. (head (nth 2 aa))
  11398. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11399. (msg "Entry repeats: ")
  11400. (org-log-done nil)
  11401. (org-todo-log-states nil)
  11402. (end (copy-marker (org-entry-end-position))))
  11403. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  11404. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11405. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11406. (and (stringp org-todo-repeat-to-state)
  11407. org-todo-repeat-to-state)
  11408. (and org-todo-repeat-to-state org-last-state))))
  11409. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  11410. to-state)
  11411. ((eq interpret 'type) org-last-state)
  11412. (head)
  11413. (t 'none))))
  11414. (org-back-to-heading t)
  11415. (org-add-planning-info nil nil 'closed)
  11416. ;; When `org-log-repeat' is non-nil or entry contains
  11417. ;; a clock, set LAST_REPEAT property.
  11418. (when (or org-log-repeat
  11419. (catch :clock
  11420. (save-excursion
  11421. (while (re-search-forward org-clock-line-re end t)
  11422. (when (org-at-clock-log-p) (throw :clock t))))))
  11423. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11424. (org-time-stamp-format t t)
  11425. (current-time))))
  11426. (when org-log-repeat
  11427. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11428. (memq 'org-add-log-note post-command-hook))
  11429. ;; We are already setup for some record.
  11430. (when (eq org-log-repeat 'note)
  11431. ;; Make sure we take a note, not only a time stamp.
  11432. (setq org-log-note-how 'note))
  11433. ;; Set up for taking a record.
  11434. (org-add-log-setup 'state
  11435. (or done-word (car org-done-keywords))
  11436. org-last-state
  11437. org-log-repeat)))
  11438. ;; Time-stamps without a repeater are usually skipped. However,
  11439. ;; a SCHEDULED time-stamp without one is removed, as they are no
  11440. ;; longer relevant.
  11441. (save-excursion
  11442. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  11443. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  11444. (org-remove-timestamp-with-keyword org-scheduled-string))))
  11445. ;; Update every time-stamp with a repeater in the entry.
  11446. (let ((planning-re (regexp-opt
  11447. (list org-scheduled-string org-deadline-string))))
  11448. (while (re-search-forward org-repeat-re end t)
  11449. (let* ((ts (match-string 0))
  11450. (type (if (not (org-at-planning-p)) "Plain:"
  11451. (save-excursion
  11452. (re-search-backward
  11453. planning-re (line-beginning-position) t)
  11454. (match-string 0)))))
  11455. (when (and (org-at-timestamp-p 'agenda)
  11456. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  11457. (let ((n (string-to-number (match-string 2 ts)))
  11458. (what (match-string 3 ts)))
  11459. (when (equal what "w") (setq n (* n 7) what "d"))
  11460. (when (and (equal what "h")
  11461. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11462. ts)))
  11463. (user-error
  11464. "Cannot repeat in %d hour(s) because no hour has been set"
  11465. n))
  11466. ;; Preparation, see if we need to modify the start
  11467. ;; date for the change.
  11468. (when (match-end 1)
  11469. (let ((time (save-match-data (org-time-string-to-time ts)))
  11470. (repeater-type (match-string 1 ts)))
  11471. (cond
  11472. ((equal "." repeater-type)
  11473. ;; Shift starting date to today.
  11474. (org-timestamp-change (- (org-today) (time-to-days time))
  11475. 'day))
  11476. ((equal "+" repeater-type)
  11477. (let ((nshiftmax 10)
  11478. (nshift 0))
  11479. (while (or (= nshift 0)
  11480. (not (time-less-p (current-time) time)))
  11481. (when (= nshiftmax (cl-incf nshift))
  11482. (or (y-or-n-p
  11483. (format "%d repeater intervals were not \
  11484. enough to shift date past today. Continue? "
  11485. nshift))
  11486. (user-error "Abort")))
  11487. (org-timestamp-change n (cdr (assoc what whata)))
  11488. (org-in-regexp org-ts-regexp3)
  11489. (setq ts (match-string 1))
  11490. (setq time
  11491. (save-match-data
  11492. (org-time-string-to-time ts)))))
  11493. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11494. ;; Rematch, so that we have everything in place
  11495. ;; for the real shift.
  11496. (org-in-regexp org-ts-regexp3)
  11497. (setq ts (match-string 1))
  11498. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11499. ts)))))
  11500. (save-excursion
  11501. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11502. (setq msg
  11503. (concat msg type " " org-last-changed-timestamp " ")))))))
  11504. (setq org-log-post-message msg)
  11505. (message msg))))
  11506. (defun org-show-todo-tree (arg)
  11507. "Make a compact tree which shows all headlines marked with TODO.
  11508. The tree will show the lines where the regexp matches, and all higher
  11509. headlines above the match.
  11510. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11511. With a numeric prefix N, construct a sparse tree for the Nth element
  11512. of `org-todo-keywords-1'."
  11513. (interactive "P")
  11514. (let ((case-fold-search nil)
  11515. (kwd-re
  11516. (cond ((null arg) org-not-done-regexp)
  11517. ((equal arg '(4))
  11518. (let ((kwd
  11519. (completing-read "Keyword (or KWD1|KWD2|...): "
  11520. (mapcar #'list org-todo-keywords-1))))
  11521. (concat "\\("
  11522. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11523. "\\)\\>")))
  11524. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11525. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11526. org-todo-keywords-1)))
  11527. (t (user-error "Invalid prefix argument: %s" arg)))))
  11528. (message "%d TODO entries found"
  11529. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11530. (defun org--deadline-or-schedule (arg type time)
  11531. "Insert DEADLINE or SCHEDULE information in current entry.
  11532. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  11533. `org-schedule' for information about ARG and TIME arguments."
  11534. (let* ((deadline? (eq type 'deadline))
  11535. (keyword (if deadline? org-deadline-string org-scheduled-string))
  11536. (log (if deadline? org-log-redeadline org-log-reschedule))
  11537. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  11538. (old-date-time (and old-date (org-time-string-to-time old-date)))
  11539. ;; Save repeater cookie from either TIME or current scheduled
  11540. ;; time stamp. We are going to insert it back at the end of
  11541. ;; the process.
  11542. (repeater (or (and (org-string-nw-p time)
  11543. ;; We use `org-repeat-re' because we need
  11544. ;; to tell the difference between a real
  11545. ;; repeater and a time delta, e.g. "+2d".
  11546. (string-match org-repeat-re time)
  11547. (match-string 1 time))
  11548. (and (org-string-nw-p old-date)
  11549. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  11550. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  11551. old-date)
  11552. (match-string 1 old-date)))))
  11553. (pcase arg
  11554. (`(4)
  11555. (if (not old-date)
  11556. (message (if deadline? "Entry had no deadline to remove"
  11557. "Entry was not scheduled"))
  11558. (when (and old-date log)
  11559. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  11560. nil old-date log))
  11561. (org-remove-timestamp-with-keyword keyword)
  11562. (message (if deadline? "Entry no longer has a deadline."
  11563. "Entry is no longer scheduled."))))
  11564. (`(16)
  11565. (save-excursion
  11566. (org-back-to-heading t)
  11567. (let ((regexp (if deadline? org-deadline-time-regexp
  11568. org-scheduled-time-regexp)))
  11569. (if (not (re-search-forward regexp (line-end-position 2) t))
  11570. (user-error (if deadline? "No deadline information to update"
  11571. "No scheduled information to update"))
  11572. (let* ((rpl0 (match-string 1))
  11573. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  11574. (msg (if deadline? "Warn starting from" "Delay until")))
  11575. (replace-match
  11576. (concat keyword
  11577. " <" rpl
  11578. (format " -%dd"
  11579. (abs (- (time-to-days
  11580. (save-match-data
  11581. (org-read-date
  11582. nil t nil msg old-date-time)))
  11583. (time-to-days old-date-time))))
  11584. ">") t t))))))
  11585. (_
  11586. (org-add-planning-info type time 'closed)
  11587. (when (and old-date
  11588. log
  11589. (not (equal old-date org-last-inserted-timestamp)))
  11590. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  11591. org-last-inserted-timestamp
  11592. old-date
  11593. log))
  11594. (when repeater
  11595. (save-excursion
  11596. (org-back-to-heading t)
  11597. (when (re-search-forward
  11598. (concat keyword " " org-last-inserted-timestamp)
  11599. (line-end-position 2)
  11600. t)
  11601. (goto-char (1- (match-end 0)))
  11602. (insert " " repeater)
  11603. (setq org-last-inserted-timestamp
  11604. (concat (substring org-last-inserted-timestamp 0 -1)
  11605. " " repeater
  11606. (substring org-last-inserted-timestamp -1))))))
  11607. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  11608. org-last-inserted-timestamp)))))
  11609. (defun org-deadline (arg &optional time)
  11610. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  11611. With one universal prefix argument, remove any deadline from the item.
  11612. With two universal prefix arguments, prompt for a warning delay.
  11613. With argument TIME, set the deadline at the corresponding date. TIME
  11614. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11615. (interactive "P")
  11616. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11617. (org-map-entries
  11618. (lambda () (org--deadline-or-schedule arg 'deadline time))
  11619. nil
  11620. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11621. 'region-start-level
  11622. 'region)
  11623. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11624. (org--deadline-or-schedule arg 'deadline time)))
  11625. (defun org-schedule (arg &optional time)
  11626. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  11627. With one universal prefix argument, remove any scheduling date from the item.
  11628. With two universal prefix arguments, prompt for a delay cookie.
  11629. With argument TIME, scheduled at the corresponding date. TIME can
  11630. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11631. (interactive "P")
  11632. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11633. (org-map-entries
  11634. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  11635. nil
  11636. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11637. 'region-start-level
  11638. 'region)
  11639. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11640. (org--deadline-or-schedule arg 'scheduled time)))
  11641. (defun org-get-scheduled-time (pom &optional inherit)
  11642. "Get the scheduled time as a time tuple, of a format suitable
  11643. for calling org-schedule with, or if there is no scheduling,
  11644. returns nil."
  11645. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  11646. (when time
  11647. (apply 'encode-time (org-parse-time-string time)))))
  11648. (defun org-get-deadline-time (pom &optional inherit)
  11649. "Get the deadline as a time tuple, of a format suitable for
  11650. calling org-deadline with, or if there is no scheduling, returns
  11651. nil."
  11652. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  11653. (when time
  11654. (apply 'encode-time (org-parse-time-string time)))))
  11655. (defun org-remove-timestamp-with-keyword (keyword)
  11656. "Remove all time stamps with KEYWORD in the current entry."
  11657. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  11658. beg)
  11659. (save-excursion
  11660. (org-back-to-heading t)
  11661. (setq beg (point))
  11662. (outline-next-heading)
  11663. (while (re-search-backward re beg t)
  11664. (replace-match "")
  11665. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  11666. (equal (char-before) ?\ ))
  11667. (backward-delete-char 1)
  11668. (when (string-match "^[ \t]*$" (buffer-substring
  11669. (point-at-bol) (point-at-eol)))
  11670. (delete-region (point-at-bol)
  11671. (min (point-max) (1+ (point-at-eol))))))))))
  11672. (defvar org-time-was-given) ; dynamically scoped parameter
  11673. (defvar org-end-time-was-given) ; dynamically scoped parameter
  11674. (defun org-at-planning-p ()
  11675. "Non-nil when point is on a planning info line."
  11676. ;; This is as accurate and faster than `org-element-at-point' since
  11677. ;; planning info location is fixed in the section.
  11678. (org-with-wide-buffer
  11679. (beginning-of-line)
  11680. (and (looking-at-p org-planning-line-re)
  11681. (eq (point)
  11682. (ignore-errors
  11683. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  11684. (org-back-to-heading t)
  11685. (org-with-limited-levels (org-back-to-heading t)))
  11686. (line-beginning-position 2))))))
  11687. (defun org-add-planning-info (what &optional time &rest remove)
  11688. "Insert new timestamp with keyword in the planning line.
  11689. WHAT indicates what kind of time stamp to add. It is a symbol
  11690. among `closed', `deadline', `scheduled' and nil. TIME indicates
  11691. the time to use. If none is given, the user is prompted for
  11692. a date. REMOVE indicates what kind of entries to remove. An old
  11693. WHAT entry will also be removed."
  11694. (let (org-time-was-given org-end-time-was-given default-time default-input)
  11695. (catch 'exit
  11696. (when (and (memq what '(scheduled deadline))
  11697. (or (not time)
  11698. (and (stringp time)
  11699. (string-match "^[-+]+[0-9]" time))))
  11700. ;; Try to get a default date/time from existing timestamp
  11701. (save-excursion
  11702. (org-back-to-heading t)
  11703. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  11704. (when (re-search-forward (if (eq what 'scheduled)
  11705. org-scheduled-time-regexp
  11706. org-deadline-time-regexp)
  11707. end t)
  11708. (setq ts (match-string 1)
  11709. default-time (apply 'encode-time (org-parse-time-string ts))
  11710. default-input (and ts (org-get-compact-tod ts)))))))
  11711. (when what
  11712. (setq time
  11713. (if (stringp time)
  11714. ;; This is a string (relative or absolute), set
  11715. ;; proper date.
  11716. (apply #'encode-time
  11717. (org-read-date-analyze
  11718. time default-time (decode-time default-time)))
  11719. ;; If necessary, get the time from the user
  11720. (or time (org-read-date nil 'to-time nil
  11721. (cl-case what
  11722. (deadline "DEADLINE")
  11723. (scheduled "SCHEDULED")
  11724. (otherwise nil))
  11725. default-time default-input)))))
  11726. (org-with-wide-buffer
  11727. (org-back-to-heading t)
  11728. (forward-line)
  11729. (unless (bolp) (insert "\n"))
  11730. (cond ((looking-at-p org-planning-line-re)
  11731. ;; Move to current indentation.
  11732. (skip-chars-forward " \t")
  11733. ;; Check if we have to remove something.
  11734. (dolist (type (if what (cons what remove) remove))
  11735. (save-excursion
  11736. (when (re-search-forward
  11737. (cl-case type
  11738. (closed org-closed-time-regexp)
  11739. (deadline org-deadline-time-regexp)
  11740. (scheduled org-scheduled-time-regexp)
  11741. (otherwise
  11742. (error "Invalid planning type: %s" type)))
  11743. (line-end-position) t)
  11744. ;; Delete until next keyword or end of line.
  11745. (delete-region
  11746. (match-beginning 0)
  11747. (if (re-search-forward org-keyword-time-not-clock-regexp
  11748. (line-end-position)
  11749. t)
  11750. (match-beginning 0)
  11751. (line-end-position))))))
  11752. ;; If there is nothing more to add and no more keyword
  11753. ;; is left, remove the line completely.
  11754. (if (and (looking-at-p "[ \t]*$") (not what))
  11755. (delete-region (line-beginning-position)
  11756. (line-beginning-position 2))
  11757. ;; If we removed last keyword, do not leave trailing
  11758. ;; white space at the end of line.
  11759. (let ((p (point)))
  11760. (save-excursion
  11761. (end-of-line)
  11762. (unless (= (skip-chars-backward " \t" p) 0)
  11763. (delete-region (point) (line-end-position)))))))
  11764. ((not what) (throw 'exit nil)) ; Nothing to do.
  11765. (t (insert-before-markers "\n")
  11766. (backward-char 1)
  11767. (when org-adapt-indentation
  11768. (indent-to-column (1+ (org-outline-level))))))
  11769. (when what
  11770. ;; Insert planning keyword.
  11771. (insert (cl-case what
  11772. (closed org-closed-string)
  11773. (deadline org-deadline-string)
  11774. (scheduled org-scheduled-string)
  11775. (otherwise (error "Invalid planning type: %s" what)))
  11776. " ")
  11777. ;; Insert associated timestamp.
  11778. (let ((ts (org-insert-time-stamp
  11779. time
  11780. (or org-time-was-given
  11781. (and (eq what 'closed) org-log-done-with-time))
  11782. (eq what 'closed)
  11783. nil nil (list org-end-time-was-given))))
  11784. (unless (eolp) (insert " "))
  11785. ts))))))
  11786. (defvar org-log-note-marker (make-marker)
  11787. "Marker pointing at the entry where the note is to be inserted.")
  11788. (defvar org-log-note-purpose nil)
  11789. (defvar org-log-note-state nil)
  11790. (defvar org-log-note-previous-state nil)
  11791. (defvar org-log-note-extra nil)
  11792. (defvar org-log-note-window-configuration nil)
  11793. (defvar org-log-note-return-to (make-marker))
  11794. (defvar org-log-note-effective-time nil
  11795. "Remembered current time so that dynamically scoped
  11796. `org-extend-today-until' affects timestamps in state change log")
  11797. (defvar org-log-post-message nil
  11798. "Message to be displayed after a log note has been stored.
  11799. The auto-repeater uses this.")
  11800. (defun org-add-note ()
  11801. "Add a note to the current entry.
  11802. This is done in the same way as adding a state change note."
  11803. (interactive)
  11804. (org-add-log-setup 'note))
  11805. (defun org-log-beginning (&optional create)
  11806. "Return expected start of log notes in current entry.
  11807. When optional argument CREATE is non-nil, the function creates
  11808. a drawer to store notes, if necessary. Returned position ignores
  11809. narrowing."
  11810. (org-with-wide-buffer
  11811. (let ((drawer (org-log-into-drawer)))
  11812. (cond
  11813. (drawer
  11814. (org-end-of-meta-data)
  11815. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  11816. (end (if (org-at-heading-p) (point)
  11817. (save-excursion (outline-next-heading) (point))))
  11818. (case-fold-search t))
  11819. (catch 'exit
  11820. ;; Try to find existing drawer.
  11821. (while (re-search-forward regexp end t)
  11822. (let ((element (org-element-at-point)))
  11823. (when (eq (org-element-type element) 'drawer)
  11824. (let ((cend (org-element-property :contents-end element)))
  11825. (when (and (not org-log-states-order-reversed) cend)
  11826. (goto-char cend)))
  11827. (throw 'exit nil))))
  11828. ;; No drawer found. Create one, if permitted.
  11829. (when create
  11830. (unless (bolp) (insert "\n"))
  11831. (let ((beg (point)))
  11832. (insert ":" drawer ":\n:END:\n")
  11833. (org-indent-region beg (point))
  11834. (org-flag-region
  11835. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  11836. (end-of-line -1)))))
  11837. (t
  11838. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  11839. (skip-chars-forward " \t\n")
  11840. (beginning-of-line)
  11841. (unless org-log-states-order-reversed
  11842. (org-skip-over-state-notes)
  11843. (skip-chars-backward " \t\n")
  11844. (forward-line)))))
  11845. (if (bolp) (point) (line-beginning-position 2))))
  11846. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  11847. "Set up the post command hook to take a note.
  11848. If this is about to TODO state change, the new state is expected in STATE.
  11849. HOW is an indicator what kind of note should be created.
  11850. EXTRA is additional text that will be inserted into the notes buffer."
  11851. (move-marker org-log-note-marker (point))
  11852. (setq org-log-note-purpose purpose
  11853. org-log-note-state state
  11854. org-log-note-previous-state prev-state
  11855. org-log-note-how how
  11856. org-log-note-extra extra
  11857. org-log-note-effective-time (org-current-effective-time))
  11858. (add-hook 'post-command-hook 'org-add-log-note 'append))
  11859. (defun org-skip-over-state-notes ()
  11860. "Skip past the list of State notes in an entry."
  11861. (when (ignore-errors (goto-char (org-in-item-p)))
  11862. (let* ((struct (org-list-struct))
  11863. (prevs (org-list-prevs-alist struct))
  11864. (regexp
  11865. (concat "[ \t]*- +"
  11866. (replace-regexp-in-string
  11867. " +" " +"
  11868. (org-replace-escapes
  11869. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  11870. `(("%d" . ,org-ts-regexp-inactive)
  11871. ("%D" . ,org-ts-regexp)
  11872. ("%s" . "\\(?:\"\\S-+\"\\)?")
  11873. ("%S" . "\\(?:\"\\S-+\"\\)?")
  11874. ("%t" . ,org-ts-regexp-inactive)
  11875. ("%T" . ,org-ts-regexp)
  11876. ("%u" . ".*?")
  11877. ("%U" . ".*?")))))))
  11878. (while (looking-at-p regexp)
  11879. (goto-char (or (org-list-get-next-item (point) struct prevs)
  11880. (org-list-get-item-end (point) struct)))))))
  11881. (defun org-add-log-note (&optional _purpose)
  11882. "Pop up a window for taking a note, and add this note later."
  11883. (remove-hook 'post-command-hook 'org-add-log-note)
  11884. (setq org-log-note-window-configuration (current-window-configuration))
  11885. (delete-other-windows)
  11886. (move-marker org-log-note-return-to (point))
  11887. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  11888. (goto-char org-log-note-marker)
  11889. (org-switch-to-buffer-other-window "*Org Note*")
  11890. (erase-buffer)
  11891. (if (memq org-log-note-how '(time state))
  11892. (org-store-log-note)
  11893. (let ((org-inhibit-startup t)) (org-mode))
  11894. (insert (format "# Insert note for %s.
  11895. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  11896. (cl-case org-log-note-purpose
  11897. (clock-out "stopped clock")
  11898. (done "closed todo item")
  11899. (reschedule "rescheduling")
  11900. (delschedule "no longer scheduled")
  11901. (redeadline "changing deadline")
  11902. (deldeadline "removing deadline")
  11903. (refile "refiling")
  11904. (note "this entry")
  11905. (state
  11906. (format "state change from \"%s\" to \"%s\""
  11907. (or org-log-note-previous-state "")
  11908. (or org-log-note-state "")))
  11909. (t (error "This should not happen")))))
  11910. (when org-log-note-extra (insert org-log-note-extra))
  11911. (setq-local org-finish-function 'org-store-log-note)
  11912. (run-hooks 'org-log-buffer-setup-hook)))
  11913. (defvar org-note-abort nil) ; dynamically scoped
  11914. (defun org-store-log-note ()
  11915. "Finish taking a log note, and insert it to where it belongs."
  11916. (let ((txt (prog1 (buffer-string)
  11917. (kill-buffer)))
  11918. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  11919. lines)
  11920. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  11921. (setq txt (replace-match "" t t txt)))
  11922. (when (string-match "\\s-+\\'" txt)
  11923. (setq txt (replace-match "" t t txt)))
  11924. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  11925. (when (org-string-nw-p note)
  11926. (setq note
  11927. (org-replace-escapes
  11928. note
  11929. (list (cons "%u" (user-login-name))
  11930. (cons "%U" user-full-name)
  11931. (cons "%t" (format-time-string
  11932. (org-time-stamp-format 'long 'inactive)
  11933. org-log-note-effective-time))
  11934. (cons "%T" (format-time-string
  11935. (org-time-stamp-format 'long nil)
  11936. org-log-note-effective-time))
  11937. (cons "%d" (format-time-string
  11938. (org-time-stamp-format nil 'inactive)
  11939. org-log-note-effective-time))
  11940. (cons "%D" (format-time-string
  11941. (org-time-stamp-format nil nil)
  11942. org-log-note-effective-time))
  11943. (cons "%s" (cond
  11944. ((not org-log-note-state) "")
  11945. ((string-match-p org-ts-regexp
  11946. org-log-note-state)
  11947. (format "\"[%s]\""
  11948. (substring org-log-note-state 1 -1)))
  11949. (t (format "\"%s\"" org-log-note-state))))
  11950. (cons "%S"
  11951. (cond
  11952. ((not org-log-note-previous-state) "")
  11953. ((string-match-p org-ts-regexp
  11954. org-log-note-previous-state)
  11955. (format "\"[%s]\""
  11956. (substring
  11957. org-log-note-previous-state 1 -1)))
  11958. (t (format "\"%s\""
  11959. org-log-note-previous-state)))))))
  11960. (when lines (setq note (concat note " \\\\")))
  11961. (push note lines))
  11962. (when (and lines (not org-note-abort))
  11963. (with-current-buffer (marker-buffer org-log-note-marker)
  11964. (org-with-wide-buffer
  11965. ;; Find location for the new note.
  11966. (goto-char org-log-note-marker)
  11967. (set-marker org-log-note-marker nil)
  11968. ;; Note associated to a clock is to be located right after
  11969. ;; the clock. Do not move point.
  11970. (unless (eq org-log-note-purpose 'clock-out)
  11971. (goto-char (org-log-beginning t)))
  11972. ;; Make sure point is at the beginning of an empty line.
  11973. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  11974. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  11975. ;; In an existing list, add a new item at the top level.
  11976. ;; Otherwise, indent line like a regular one.
  11977. (let ((itemp (org-in-item-p)))
  11978. (if itemp
  11979. (indent-line-to
  11980. (let ((struct (save-excursion
  11981. (goto-char itemp) (org-list-struct))))
  11982. (org-list-get-ind (org-list-get-top-point struct) struct)))
  11983. (org-indent-line)))
  11984. (insert (org-list-bullet-string "-") (pop lines))
  11985. (let ((ind (org-list-item-body-column (line-beginning-position))))
  11986. (dolist (line lines)
  11987. (insert "\n")
  11988. (indent-line-to ind)
  11989. (insert line)))
  11990. (message "Note stored")
  11991. (org-back-to-heading t))
  11992. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  11993. ;; from within `org-add-log-note' because `buffer-undo-list'
  11994. ;; is then modified outside of `org-with-remote-undo'.
  11995. (when (eq this-command 'org-agenda-todo)
  11996. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  11997. ;; Don't add undo information when called from `org-agenda-todo'.
  11998. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  11999. (set-window-configuration org-log-note-window-configuration)
  12000. (with-current-buffer (marker-buffer org-log-note-return-to)
  12001. (goto-char org-log-note-return-to))
  12002. (move-marker org-log-note-return-to nil)
  12003. (when org-log-post-message (message "%s" org-log-post-message))))
  12004. (defun org-remove-empty-drawer-at (pos)
  12005. "Remove an empty drawer at position POS.
  12006. POS may also be a marker."
  12007. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12008. (org-with-wide-buffer
  12009. (goto-char pos)
  12010. (let ((drawer (org-element-at-point)))
  12011. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12012. (not (org-element-property :contents-begin drawer)))
  12013. (delete-region (org-element-property :begin drawer)
  12014. (progn (goto-char (org-element-property :end drawer))
  12015. (skip-chars-backward " \r\t\n")
  12016. (forward-line)
  12017. (point))))))))
  12018. (defvar org-ts-type nil)
  12019. (defun org-sparse-tree (&optional arg type)
  12020. "Create a sparse tree, prompt for the details.
  12021. This command can create sparse trees. You first need to select the type
  12022. of match used to create the tree:
  12023. t Show all TODO entries.
  12024. T Show entries with a specific TODO keyword.
  12025. m Show entries selected by a tags/property match.
  12026. p Enter a property name and its value (both with completion on existing
  12027. names/values) and show entries with that property.
  12028. r Show entries matching a regular expression (`/' can be used as well).
  12029. b Show deadlines and scheduled items before a date.
  12030. a Show deadlines and scheduled items after a date.
  12031. d Show deadlines due within `org-deadline-warning-days'.
  12032. D Show deadlines and scheduled items between a date range."
  12033. (interactive "P")
  12034. (setq type (or type org-sparse-tree-default-date-type))
  12035. (setq org-ts-type type)
  12036. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12037. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12038. \[c]ycle through date types: %s"
  12039. (cl-case type
  12040. (all "all timestamps")
  12041. (scheduled "only scheduled")
  12042. (deadline "only deadline")
  12043. (active "only active timestamps")
  12044. (inactive "only inactive timestamps")
  12045. (closed "with a closed time-stamp")
  12046. (otherwise "scheduled/deadline")))
  12047. (let ((answer (read-char-exclusive)))
  12048. (cl-case answer
  12049. (?c
  12050. (org-sparse-tree
  12051. arg
  12052. (cadr
  12053. (memq type '(nil all scheduled deadline active inactive closed)))))
  12054. (?d (call-interactively 'org-check-deadlines))
  12055. (?b (call-interactively 'org-check-before-date))
  12056. (?a (call-interactively 'org-check-after-date))
  12057. (?D (call-interactively 'org-check-dates-range))
  12058. (?t (call-interactively 'org-show-todo-tree))
  12059. (?T (org-show-todo-tree '(4)))
  12060. (?m (call-interactively 'org-match-sparse-tree))
  12061. ((?p ?P)
  12062. (let* ((kwd (completing-read
  12063. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12064. (value (completing-read
  12065. "Value: " (mapcar #'list (org-property-values kwd)))))
  12066. (unless (string-match "\\`{.*}\\'" value)
  12067. (setq value (concat "\"" value "\"")))
  12068. (org-match-sparse-tree arg (concat kwd "=" value))))
  12069. ((?r ?R ?/) (call-interactively 'org-occur))
  12070. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12071. (defvar-local org-occur-highlights nil
  12072. "List of overlays used for occur matches.")
  12073. (defvar-local org-occur-parameters nil
  12074. "Parameters of the active org-occur calls.
  12075. This is a list, each call to org-occur pushes as cons cell,
  12076. containing the regular expression and the callback, onto the list.
  12077. The list can contain several entries if `org-occur' has been called
  12078. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12079. will only contain one set of parameters. When the highlights are
  12080. removed (for example with `C-c C-c', or with the next edit (depending
  12081. on `org-remove-highlights-with-change'), this variable is emptied
  12082. as well.")
  12083. (defun org-occur (regexp &optional keep-previous callback)
  12084. "Make a compact tree which shows all matches of REGEXP.
  12085. The tree will show the lines where the regexp matches, and any other context
  12086. defined in `org-show-context-detail', which see.
  12087. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12088. done by a previous call to `org-occur' will be kept, to allow stacking of
  12089. calls to this command.
  12090. Optional argument CALLBACK can be a function of no argument. In this case,
  12091. it is called with point at the end of the match, match data being set
  12092. accordingly. Current match is shown only if the return value is non-nil.
  12093. The function must neither move point nor alter narrowing."
  12094. (interactive "sRegexp: \nP")
  12095. (when (equal regexp "")
  12096. (user-error "Regexp cannot be empty"))
  12097. (unless keep-previous
  12098. (org-remove-occur-highlights nil nil t))
  12099. (push (cons regexp callback) org-occur-parameters)
  12100. (let ((cnt 0))
  12101. (save-excursion
  12102. (goto-char (point-min))
  12103. (when (or (not keep-previous) ; do not want to keep
  12104. (not org-occur-highlights)) ; no previous matches
  12105. ;; hide everything
  12106. (org-overview))
  12107. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12108. (isearch-no-upper-case-p regexp t)
  12109. org-occur-case-fold-search)))
  12110. (while (re-search-forward regexp nil t)
  12111. (when (or (not callback)
  12112. (save-match-data (funcall callback)))
  12113. (setq cnt (1+ cnt))
  12114. (when org-highlight-sparse-tree-matches
  12115. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12116. (org-show-context 'occur-tree)))))
  12117. (when org-remove-highlights-with-change
  12118. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12119. nil 'local))
  12120. (unless org-sparse-tree-open-archived-trees
  12121. (org-hide-archived-subtrees (point-min) (point-max)))
  12122. (run-hooks 'org-occur-hook)
  12123. (when (called-interactively-p 'interactive)
  12124. (message "%d match(es) for regexp %s" cnt regexp))
  12125. cnt))
  12126. (defun org-occur-next-match (&optional n _reset)
  12127. "Function for `next-error-function' to find sparse tree matches.
  12128. N is the number of matches to move, when negative move backwards.
  12129. This function always goes back to the starting point when no
  12130. match is found."
  12131. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12132. (search-func (if (< n 0)
  12133. 'previous-single-char-property-change
  12134. 'next-single-char-property-change))
  12135. (n (abs n))
  12136. (pos (point))
  12137. p1)
  12138. (catch 'exit
  12139. (while (setq p1 (funcall search-func (point) 'org-type))
  12140. (when (equal p1 limit)
  12141. (goto-char pos)
  12142. (user-error "No more matches"))
  12143. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12144. (setq n (1- n))
  12145. (when (= n 0)
  12146. (goto-char p1)
  12147. (throw 'exit (point))))
  12148. (goto-char p1))
  12149. (goto-char p1)
  12150. (user-error "No more matches"))))
  12151. (defun org-highlight-new-match (beg end)
  12152. "Highlight from BEG to END and mark the highlight is an occur headline."
  12153. (let ((ov (make-overlay beg end)))
  12154. (overlay-put ov 'face 'secondary-selection)
  12155. (overlay-put ov 'org-type 'org-occur)
  12156. (push ov org-occur-highlights)))
  12157. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12158. "Remove the occur highlights from the buffer.
  12159. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12160. from the `before-change-functions' in the current buffer."
  12161. (interactive)
  12162. (unless org-inhibit-highlight-removal
  12163. (mapc #'delete-overlay org-occur-highlights)
  12164. (setq org-occur-highlights nil)
  12165. (setq org-occur-parameters nil)
  12166. (unless noremove
  12167. (remove-hook 'before-change-functions
  12168. 'org-remove-occur-highlights 'local))))
  12169. ;;;; Priorities
  12170. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12171. "Regular expression matching the priority indicator.")
  12172. (defvar org-remove-priority-next-time nil)
  12173. (defun org-priority-up ()
  12174. "Increase the priority of the current item."
  12175. (interactive)
  12176. (org-priority 'up))
  12177. (defun org-priority-down ()
  12178. "Decrease the priority of the current item."
  12179. (interactive)
  12180. (org-priority 'down))
  12181. (defun org-priority (&optional action show)
  12182. "Change the priority of an item.
  12183. When called interactively with a `\\[universal-argument]' prefix,
  12184. show the priority in the minibuffer instead of changing it.
  12185. When called programatically, ACTION can be `set', `up', `down',
  12186. or a character."
  12187. (interactive "P")
  12188. (when show
  12189. ;; Deprecation warning inserted for Org 9.2; once enough time has
  12190. ;; passed the SHOW argument should be removed.
  12191. (warn "`org-priority' called with deprecated SHOW argument"))
  12192. (if (equal action '(4))
  12193. (org-show-priority)
  12194. (unless org-enable-priority-commands
  12195. (user-error "Priority commands are disabled"))
  12196. (setq action (or action 'set))
  12197. (let (current new news have remove)
  12198. (save-excursion
  12199. (org-back-to-heading t)
  12200. (when (looking-at org-priority-regexp)
  12201. (setq current (string-to-char (match-string 2))
  12202. have t))
  12203. (cond
  12204. ((eq action 'remove)
  12205. (setq remove t new ?\ ))
  12206. ((or (eq action 'set)
  12207. (integerp action))
  12208. (if (not (eq action 'set))
  12209. (setq new action)
  12210. (message "Priority %c-%c, SPC to remove: "
  12211. org-highest-priority org-lowest-priority)
  12212. (save-match-data
  12213. (setq new (read-char-exclusive))))
  12214. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12215. (= (upcase org-lowest-priority) org-lowest-priority))
  12216. (setq new (upcase new)))
  12217. (cond ((equal new ?\s) (setq remove t))
  12218. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12219. (user-error "Priority must be between `%c' and `%c'"
  12220. org-highest-priority org-lowest-priority))))
  12221. ((eq action 'up)
  12222. (setq new (if have
  12223. (1- current) ; normal cycling
  12224. ;; last priority was empty
  12225. (if (eq last-command this-command)
  12226. org-lowest-priority ; wrap around empty to lowest
  12227. ;; default
  12228. (if org-priority-start-cycle-with-default
  12229. org-default-priority
  12230. (1- org-default-priority))))))
  12231. ((eq action 'down)
  12232. (setq new (if have
  12233. (1+ current) ; normal cycling
  12234. ;; last priority was empty
  12235. (if (eq last-command this-command)
  12236. org-highest-priority ; wrap around empty to highest
  12237. ;; default
  12238. (if org-priority-start-cycle-with-default
  12239. org-default-priority
  12240. (1+ org-default-priority))))))
  12241. (t (user-error "Invalid action")))
  12242. (when (or (< (upcase new) org-highest-priority)
  12243. (> (upcase new) org-lowest-priority))
  12244. (if (and (memq action '(up down))
  12245. (not have) (not (eq last-command this-command)))
  12246. ;; `new' is from default priority
  12247. (error
  12248. "The default can not be set, see `org-default-priority' why")
  12249. ;; normal cycling: `new' is beyond highest/lowest priority
  12250. ;; and is wrapped around to the empty priority
  12251. (setq remove t)))
  12252. (setq news (format "%c" new))
  12253. (if have
  12254. (if remove
  12255. (replace-match "" t t nil 1)
  12256. (replace-match news t t nil 2))
  12257. (if remove
  12258. (user-error "No priority cookie found in line")
  12259. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12260. (if (match-end 2)
  12261. (progn
  12262. (goto-char (match-end 2))
  12263. (insert " [#" news "]"))
  12264. (goto-char (match-beginning 3))
  12265. (insert "[#" news "] "))))
  12266. (org-align-tags))
  12267. (if remove
  12268. (message "Priority removed")
  12269. (message "Priority of current item set to %s" news)))))
  12270. (defun org-show-priority ()
  12271. "Show the priority of the current item.
  12272. This priority is composed of the main priority given with the [#A] cookies,
  12273. and by additional input from the age of a schedules or deadline entry."
  12274. (interactive)
  12275. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12276. (org-get-at-bol 'priority)
  12277. (save-excursion
  12278. (save-match-data
  12279. (beginning-of-line)
  12280. (and (looking-at org-heading-regexp)
  12281. (org-get-priority (match-string 0))))))))
  12282. (message "Priority is %d" (if pri pri -1000))))
  12283. (defun org-get-priority (s)
  12284. "Find priority cookie and return priority."
  12285. (save-match-data
  12286. (if (functionp org-get-priority-function)
  12287. (funcall org-get-priority-function)
  12288. (if (not (string-match org-priority-regexp s))
  12289. (* 1000 (- org-lowest-priority org-default-priority))
  12290. (* 1000 (- org-lowest-priority
  12291. (string-to-char (match-string 2 s))))))))
  12292. ;;;; Tags
  12293. (defvar org-agenda-archives-mode)
  12294. (defvar org-map-continue-from nil
  12295. "Position from where mapping should continue.
  12296. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12297. (defvar org-scanner-tags nil
  12298. "The current tag list while the tags scanner is running.")
  12299. (defvar org-trust-scanner-tags nil
  12300. "Should `org-get-tags' use the tags for the scanner.
  12301. This is for internal dynamical scoping only.
  12302. When this is non-nil, the function `org-get-tags' will return the value
  12303. of `org-scanner-tags' instead of building the list by itself. This
  12304. can lead to large speed-ups when the tags scanner is used in a file with
  12305. many entries, and when the list of tags is retrieved, for example to
  12306. obtain a list of properties. Building the tags list for each entry in such
  12307. a file becomes an N^2 operation - but with this variable set, it scales
  12308. as N.")
  12309. (defvar org--matcher-tags-todo-only nil)
  12310. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12311. "Scan headline tags with inheritance and produce output ACTION.
  12312. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12313. or `agenda' to produce an entry list for an agenda view. It can also be
  12314. a Lisp form or a function that should be called at each matched headline, in
  12315. this case the return value is a list of all return values from these calls.
  12316. MATCHER is a function accepting three arguments, returning
  12317. a non-nil value whenever a given set of tags qualifies a headline
  12318. for inclusion. See `org-make-tags-matcher' for more information.
  12319. As a special case, it can also be set to t (respectively nil) in
  12320. order to match all (respectively none) headline.
  12321. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  12322. included in the output.
  12323. START-LEVEL can be a string with asterisks, reducing the scope to
  12324. headlines matching this string."
  12325. (require 'org-agenda)
  12326. (let* ((re (concat "^"
  12327. (if start-level
  12328. ;; Get the correct level to match
  12329. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12330. org-outline-regexp)
  12331. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  12332. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  12333. (props (list 'face 'default
  12334. 'done-face 'org-agenda-done
  12335. 'undone-face 'default
  12336. 'mouse-face 'highlight
  12337. 'org-not-done-regexp org-not-done-regexp
  12338. 'org-todo-regexp org-todo-regexp
  12339. 'org-complex-heading-regexp org-complex-heading-regexp
  12340. 'help-echo
  12341. (format "mouse-2 or RET jump to Org file %S"
  12342. (abbreviate-file-name
  12343. (or (buffer-file-name (buffer-base-buffer))
  12344. (buffer-name (buffer-base-buffer)))))))
  12345. (org-map-continue-from nil)
  12346. lspos tags tags-list
  12347. (tags-alist (list (cons 0 org-file-tags)))
  12348. (llast 0) rtn rtn1 level category i txt
  12349. todo marker entry priority
  12350. ts-date ts-date-type ts-date-pair)
  12351. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12352. (setq action (list 'lambda nil action)))
  12353. (save-excursion
  12354. (goto-char (point-min))
  12355. (when (eq action 'sparse-tree)
  12356. (org-overview)
  12357. (org-remove-occur-highlights))
  12358. (while (let (case-fold-search)
  12359. (re-search-forward re nil t))
  12360. (setq org-map-continue-from nil)
  12361. (catch :skip
  12362. ;; Ignore closing parts of inline tasks.
  12363. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  12364. (throw :skip t))
  12365. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  12366. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  12367. (goto-char (setq lspos (match-beginning 0)))
  12368. (setq level (org-reduced-level (org-outline-level))
  12369. category (org-get-category))
  12370. (when (eq action 'agenda)
  12371. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12372. ts-date (car ts-date-pair)
  12373. ts-date-type (cdr ts-date-pair)))
  12374. (setq i llast llast level)
  12375. ;; remove tag lists from same and sublevels
  12376. (while (>= i level)
  12377. (when (setq entry (assoc i tags-alist))
  12378. (setq tags-alist (delete entry tags-alist)))
  12379. (setq i (1- i)))
  12380. ;; add the next tags
  12381. (when tags
  12382. (setq tags (org-split-string tags ":")
  12383. tags-alist
  12384. (cons (cons level tags) tags-alist)))
  12385. ;; compile tags for current headline
  12386. (setq tags-list
  12387. (if org-use-tag-inheritance
  12388. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12389. tags)
  12390. org-scanner-tags tags-list)
  12391. (when org-use-tag-inheritance
  12392. (setcdr (car tags-alist)
  12393. (mapcar (lambda (x)
  12394. (setq x (copy-sequence x))
  12395. (org-add-prop-inherited x))
  12396. (cdar tags-alist))))
  12397. (when (and tags org-use-tag-inheritance
  12398. (or (not (eq t org-use-tag-inheritance))
  12399. org-tags-exclude-from-inheritance))
  12400. ;; Selective inheritance, remove uninherited ones.
  12401. (setcdr (car tags-alist)
  12402. (org-remove-uninherited-tags (cdar tags-alist))))
  12403. (when (and
  12404. ;; eval matcher only when the todo condition is OK
  12405. (and (or (not todo-only) (member todo org-todo-keywords-1))
  12406. (if (functionp matcher)
  12407. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12408. (funcall matcher todo tags-list level))
  12409. matcher))
  12410. ;; Call the skipper, but return t if it does not
  12411. ;; skip, so that the `and' form continues evaluating.
  12412. (progn
  12413. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12414. t)
  12415. ;; Check if timestamps are deselecting this entry
  12416. (or (not todo-only)
  12417. (and (member todo org-todo-keywords-1)
  12418. (or (not org-agenda-tags-todo-honor-ignore-options)
  12419. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12420. ;; select this headline
  12421. (cond
  12422. ((eq action 'sparse-tree)
  12423. (and org-highlight-sparse-tree-matches
  12424. (org-get-heading) (match-end 0)
  12425. (org-highlight-new-match
  12426. (match-beginning 1) (match-end 1)))
  12427. (org-show-context 'tags-tree))
  12428. ((eq action 'agenda)
  12429. (setq txt (org-agenda-format-item
  12430. ""
  12431. (concat
  12432. (if (eq org-tags-match-list-sublevels 'indented)
  12433. (make-string (1- level) ?.) "")
  12434. (org-get-heading))
  12435. (make-string level ?\s)
  12436. category
  12437. tags-list)
  12438. priority (org-get-priority txt))
  12439. (goto-char lspos)
  12440. (setq marker (org-agenda-new-marker))
  12441. (org-add-props txt props
  12442. 'org-marker marker 'org-hd-marker marker 'org-category category
  12443. 'todo-state todo
  12444. 'ts-date ts-date
  12445. 'priority priority
  12446. 'type (concat "tagsmatch" ts-date-type))
  12447. (push txt rtn))
  12448. ((functionp action)
  12449. (setq org-map-continue-from nil)
  12450. (save-excursion
  12451. (setq rtn1 (funcall action))
  12452. (push rtn1 rtn)))
  12453. (t (user-error "Invalid action")))
  12454. ;; if we are to skip sublevels, jump to end of subtree
  12455. (unless org-tags-match-list-sublevels
  12456. (org-end-of-subtree t)
  12457. (backward-char 1))))
  12458. ;; Get the correct position from where to continue
  12459. (if org-map-continue-from
  12460. (goto-char org-map-continue-from)
  12461. (and (= (point) lspos) (end-of-line 1)))))
  12462. (when (and (eq action 'sparse-tree)
  12463. (not org-sparse-tree-open-archived-trees))
  12464. (org-hide-archived-subtrees (point-min) (point-max)))
  12465. (nreverse rtn)))
  12466. (defun org-remove-uninherited-tags (tags)
  12467. "Remove all tags that are not inherited from the list TAGS."
  12468. (cond
  12469. ((eq org-use-tag-inheritance t)
  12470. (if org-tags-exclude-from-inheritance
  12471. (org-delete-all org-tags-exclude-from-inheritance tags)
  12472. tags))
  12473. ((not org-use-tag-inheritance) nil)
  12474. ((stringp org-use-tag-inheritance)
  12475. (delq nil (mapcar
  12476. (lambda (x)
  12477. (if (and (string-match org-use-tag-inheritance x)
  12478. (not (member x org-tags-exclude-from-inheritance)))
  12479. x nil))
  12480. tags)))
  12481. ((listp org-use-tag-inheritance)
  12482. (delq nil (mapcar
  12483. (lambda (x)
  12484. (if (member x org-use-tag-inheritance) x nil))
  12485. tags)))))
  12486. (defun org-match-sparse-tree (&optional todo-only match)
  12487. "Create a sparse tree according to tags string MATCH.
  12488. MATCH is a string with match syntax. It can contain a selection
  12489. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  12490. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  12491. those. See the manual for details.
  12492. If optional argument TODO-ONLY is non-nil, only select lines that
  12493. are also TODO tasks."
  12494. (interactive "P")
  12495. (org-agenda-prepare-buffers (list (current-buffer)))
  12496. (let ((org--matcher-tags-todo-only todo-only))
  12497. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  12498. org--matcher-tags-todo-only)))
  12499. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  12500. (defvar org-cached-props nil)
  12501. (defun org-cached-entry-get (pom property)
  12502. (if (or (eq t org-use-property-inheritance)
  12503. (and (stringp org-use-property-inheritance)
  12504. (let ((case-fold-search t))
  12505. (string-match-p org-use-property-inheritance property)))
  12506. (and (listp org-use-property-inheritance)
  12507. (member-ignore-case property org-use-property-inheritance)))
  12508. ;; Caching is not possible, check it directly.
  12509. (org-entry-get pom property 'inherit)
  12510. ;; Get all properties, so we can do complicated checks easily.
  12511. (cdr (assoc-string property
  12512. (or org-cached-props
  12513. (setq org-cached-props (org-entry-properties pom)))
  12514. t))))
  12515. (defun org-global-tags-completion-table (&optional files)
  12516. "Return the list of all tags in all agenda buffer/files.
  12517. Optional FILES argument is a list of files which can be used
  12518. instead of the agenda files."
  12519. (save-excursion
  12520. (org-uniquify
  12521. (delq nil
  12522. (apply #'append
  12523. (mapcar
  12524. (lambda (file)
  12525. (set-buffer (find-file-noselect file))
  12526. (org--tag-add-to-alist
  12527. (org-get-buffer-tags)
  12528. (mapcar (lambda (x)
  12529. (and (stringp (car-safe x))
  12530. (list (car-safe x))))
  12531. org-current-tag-alist)))
  12532. (if (car-safe files) files
  12533. (org-agenda-files))))))))
  12534. (defun org-make-tags-matcher (match)
  12535. "Create the TAGS/TODO matcher form for the selection string MATCH.
  12536. Returns a cons of the selection string MATCH and a function
  12537. implementing the matcher.
  12538. The matcher is to be called at an Org entry, with point on the
  12539. headline, and returns non-nil if the entry matches the selection
  12540. string MATCH. It must be called with three arguments: the TODO
  12541. keyword at the entry (or nil if none), the list of all tags at
  12542. the entry including inherited ones and the reduced level of the
  12543. headline. Additionally, the category of the entry, if any, must
  12544. be specified as the text property `org-category' on the headline.
  12545. This function sets the variable `org--matcher-tags-todo-only' to
  12546. a non-nil value if the matcher restricts matching to TODO
  12547. entries, otherwise it is not touched.
  12548. See also `org-scan-tags'."
  12549. (unless match
  12550. ;; Get a new match request, with completion against the global
  12551. ;; tags table and the local tags in current buffer.
  12552. (let ((org-last-tags-completion-table
  12553. (org--tag-add-to-alist
  12554. (org-get-buffer-tags)
  12555. (org-global-tags-completion-table))))
  12556. (setq match
  12557. (completing-read
  12558. "Match: "
  12559. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  12560. (let ((match0 match)
  12561. (re (concat
  12562. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  12563. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  12564. "\\([<>=]\\{1,2\\}\\)"
  12565. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  12566. "\\|" org-tag-re "\\)"))
  12567. (start 0)
  12568. tagsmatch todomatch tagsmatcher todomatcher)
  12569. ;; Expand group tags.
  12570. (setq match (org-tags-expand match))
  12571. ;; Check if there is a TODO part of this match, which would be the
  12572. ;; part after a "/". To make sure that this slash is not part of
  12573. ;; a property value to be matched against, we also check that
  12574. ;; there is no / after that slash. First, find the last slash.
  12575. (let ((s 0))
  12576. (while (string-match "/+" match s)
  12577. (setq start (match-beginning 0))
  12578. (setq s (match-end 0))))
  12579. (if (and (string-match "/+" match start)
  12580. (not (string-match-p "\"" match start)))
  12581. ;; Match contains also a TODO-matching request.
  12582. (progn
  12583. (setq tagsmatch (substring match 0 (match-beginning 0)))
  12584. (setq todomatch (substring match (match-end 0)))
  12585. (when (string-prefix-p "!" todomatch)
  12586. (setq org--matcher-tags-todo-only t)
  12587. (setq todomatch (substring todomatch 1)))
  12588. (when (string-match "\\`\\s-*\\'" todomatch)
  12589. (setq todomatch nil)))
  12590. ;; Only matching tags.
  12591. (setq tagsmatch match)
  12592. (setq todomatch nil))
  12593. ;; Make the tags matcher.
  12594. (when (org-string-nw-p tagsmatch)
  12595. (let ((orlist nil)
  12596. (orterms (org-split-string tagsmatch "|"))
  12597. term)
  12598. (while (setq term (pop orterms))
  12599. (while (and (equal (substring term -1) "\\") orterms)
  12600. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  12601. (while (string-match re term)
  12602. (let* ((rest (substring term (match-end 0)))
  12603. (minus (and (match-end 1)
  12604. (equal (match-string 1 term) "-")))
  12605. (tag (save-match-data
  12606. (replace-regexp-in-string
  12607. "\\\\-" "-" (match-string 2 term))))
  12608. (regexp (eq (string-to-char tag) ?{))
  12609. (levelp (match-end 4))
  12610. (propp (match-end 5))
  12611. (mm
  12612. (cond
  12613. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  12614. (levelp
  12615. `(,(org-op-to-function (match-string 3 term))
  12616. level
  12617. ,(string-to-number (match-string 4 term))))
  12618. (propp
  12619. (let* ((gv (pcase (upcase (match-string 5 term))
  12620. ("CATEGORY"
  12621. '(get-text-property (point) 'org-category))
  12622. ("TODO" 'todo)
  12623. (p `(org-cached-entry-get nil ,p))))
  12624. (pv (match-string 7 term))
  12625. (regexp (eq (string-to-char pv) ?{))
  12626. (strp (eq (string-to-char pv) ?\"))
  12627. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  12628. (po (org-op-to-function (match-string 6 term)
  12629. (if timep 'time strp))))
  12630. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  12631. (when timep (setq pv (org-matcher-time pv)))
  12632. (cond ((and regexp (eq po '/=))
  12633. `(not (string-match ,pv (or ,gv ""))))
  12634. (regexp `(string-match ,pv (or ,gv "")))
  12635. (strp `(,po (or ,gv "") ,pv))
  12636. (t
  12637. `(,po
  12638. (string-to-number (or ,gv ""))
  12639. ,(string-to-number pv))))))
  12640. (t `(member ,tag tags-list)))))
  12641. (push (if minus `(not ,mm) mm) tagsmatcher)
  12642. (setq term rest)))
  12643. (push `(and ,@tagsmatcher) orlist)
  12644. (setq tagsmatcher nil))
  12645. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  12646. ;; Make the TODO matcher.
  12647. (when (org-string-nw-p todomatch)
  12648. (let ((orlist nil))
  12649. (dolist (term (org-split-string todomatch "|"))
  12650. (while (string-match re term)
  12651. (let* ((minus (and (match-end 1)
  12652. (equal (match-string 1 term) "-")))
  12653. (kwd (match-string 2 term))
  12654. (regexp (eq (string-to-char kwd) ?{))
  12655. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  12656. `(equal todo ,kwd))))
  12657. (push (if minus `(not ,mm) mm) todomatcher))
  12658. (setq term (substring term (match-end 0))))
  12659. (push (if (> (length todomatcher) 1)
  12660. (cons 'and todomatcher)
  12661. (car todomatcher))
  12662. orlist)
  12663. (setq todomatcher nil))
  12664. (setq todomatcher (cons 'or orlist))))
  12665. ;; Return the string and function of the matcher. If no
  12666. ;; tags-specific or todo-specific matcher exists, match
  12667. ;; everything.
  12668. (let ((matcher (if (and tagsmatcher todomatcher)
  12669. `(and ,tagsmatcher ,todomatcher)
  12670. (or tagsmatcher todomatcher t))))
  12671. (when org--matcher-tags-todo-only
  12672. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  12673. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  12674. (defun org--tags-expand-group (group tag-groups expanded)
  12675. "Recursively Expand all tags in GROUP, according to TAG-GROUPS.
  12676. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  12677. an accumulator used in recursive calls."
  12678. (dolist (tag group)
  12679. (unless (member tag expanded)
  12680. (let ((group (assoc tag tag-groups)))
  12681. (push tag expanded)
  12682. (when group
  12683. (setq expanded
  12684. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  12685. expanded)
  12686. (defun org-tags-expand (match &optional single-as-list downcased)
  12687. "Expand group tags in MATCH.
  12688. This replaces every group tag in MATCH with a regexp tag search.
  12689. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  12690. will be replaced like this:
  12691. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12692. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12693. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12694. Replacing by a regexp preserves the structure of the match.
  12695. E.g., this expansion
  12696. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  12697. will match anything tagged with \"Lab\" and \"Home\", or tagged
  12698. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  12699. A group tag in MATCH can contain regular expressions of its own.
  12700. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  12701. will be replaced like this:
  12702. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  12703. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  12704. assumed to be a single group tag, and the function will return
  12705. the list of tags in this group.
  12706. When DOWNCASED is non-nil, expand downcased TAGS."
  12707. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  12708. (let ((tag-groups
  12709. (let ((g (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  12710. (if (not downcased) g
  12711. (mapcar (lambda (s) (mapcar #'downcase s)) g)))))
  12712. (cond
  12713. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  12714. (org-group-tags
  12715. (let* ((case-fold-search t)
  12716. (tag-syntax org-mode-syntax-table)
  12717. (group-keys (mapcar #'car tag-groups))
  12718. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  12719. (return-match (if downcased (downcase match) match)))
  12720. ;; Mark regexp-expressions in the match-expression so that we
  12721. ;; do not replace them later on.
  12722. (let ((s 0))
  12723. (while (string-match "{.+?}" return-match s)
  12724. (setq s (match-end 0))
  12725. (add-text-properties
  12726. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  12727. ;; @ and _ are allowed as word-components in tags.
  12728. (modify-syntax-entry ?@ "w" tag-syntax)
  12729. (modify-syntax-entry ?_ "w" tag-syntax)
  12730. ;; For each tag token found in MATCH, compute a regexp and it
  12731. (with-syntax-table tag-syntax
  12732. (replace-regexp-in-string
  12733. key-regexp
  12734. (lambda (m)
  12735. (if (get-text-property (match-beginning 2) 'regexp m)
  12736. m ;regexp tag: ignore
  12737. (let* ((operator (match-string 1 m))
  12738. (tag-token (let ((tag (match-string 2 m)))
  12739. (list (if downcased (downcase tag) tag))))
  12740. regexp-tags regular-tags)
  12741. ;; Partition tags between regexp and regular tags.
  12742. ;; Remove curly bracket syntax from regexp tags.
  12743. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  12744. (save-match-data
  12745. (if (string-match "{\\(.+?\\)}" tag)
  12746. (push (match-string 1 tag) regexp-tags)
  12747. (push tag regular-tags))))
  12748. ;; Replace tag token by the appropriate regexp.
  12749. ;; Regular tags need to be regexp-quoted, whereas
  12750. ;; regexp-tags are inserted as-is.
  12751. (let ((regular (regexp-opt regular-tags))
  12752. (regexp (mapconcat #'identity regexp-tags "\\|")))
  12753. (concat operator
  12754. (cond
  12755. ((null regular-tags) (format "{%s}" regexp))
  12756. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  12757. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  12758. return-match
  12759. t t))))
  12760. (t match))))
  12761. (defun org-op-to-function (op &optional stringp)
  12762. "Turn an operator into the appropriate function."
  12763. (setq op
  12764. (cond
  12765. ((equal op "<" ) '(< org-string< org-time<))
  12766. ((equal op ">" ) '(> org-string> org-time>))
  12767. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  12768. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  12769. ((member op '("=" "==")) '(= string= org-time=))
  12770. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  12771. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  12772. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  12773. (defvar org-tags-overlay (make-overlay 1 1))
  12774. (delete-overlay org-tags-overlay)
  12775. (defun org-add-prop-inherited (s)
  12776. (add-text-properties 0 (length s) '(inherited t) s)
  12777. s)
  12778. (defun org-toggle-tag (tag &optional onoff)
  12779. "Toggle the tag TAG for the current line.
  12780. If ONOFF is `on' or `off', don't toggle but set to this state."
  12781. (save-excursion
  12782. (org-back-to-heading t)
  12783. (let ((current
  12784. ;; Reverse the tags list so any new tag is appended to the
  12785. ;; current list of tags.
  12786. (nreverse (org-get-tags nil t)))
  12787. res)
  12788. (pcase onoff
  12789. (`off (setq current (delete tag current)))
  12790. ((or `on (guard (not (member tag current))))
  12791. (setq res t)
  12792. (cl-pushnew tag current :test #'equal))
  12793. (_ (setq current (delete tag current))))
  12794. (org-set-tags (nreverse current))
  12795. res)))
  12796. (defun org--align-tags-here (to-col)
  12797. "Align tags on the current headline to TO-COL.
  12798. Assume point is on a headline. Preserve point when aligning
  12799. tags."
  12800. (when (org-match-line org-tag-line-re)
  12801. (let* ((tags-start (match-beginning 1))
  12802. (blank-start (save-excursion
  12803. (goto-char tags-start)
  12804. (skip-chars-backward " \t")
  12805. (point)))
  12806. (new (max (if (>= to-col 0) to-col
  12807. (- (abs to-col) (string-width (match-string 1))))
  12808. ;; Introduce at least one space after the heading
  12809. ;; or the stars.
  12810. (save-excursion
  12811. (goto-char blank-start)
  12812. (1+ (current-column)))))
  12813. (current
  12814. (save-excursion (goto-char tags-start) (current-column)))
  12815. (origin (point-marker))
  12816. (column (current-column))
  12817. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  12818. (when (/= new current)
  12819. (delete-region blank-start tags-start)
  12820. (goto-char blank-start)
  12821. (let ((indent-tabs-mode nil)) (indent-to new))
  12822. ;; Try to move back to original position. If point was in the
  12823. ;; blanks before the tags, ORIGIN marker is of no use because
  12824. ;; it now points to BLANK-START. Use COLUMN instead.
  12825. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  12826. (defun org-set-tags-command (&optional arg)
  12827. "Set the tags for the current visible entry.
  12828. When called with `\\[universal-argument]' prefix argument ARG, \
  12829. realign all tags
  12830. in the current buffer. If a region is active, set tags for
  12831. all headlines in the region.
  12832. This function is for interactive use only;
  12833. in Lisp code use `org-set-tags' instead."
  12834. (interactive "P")
  12835. (cond
  12836. (arg (org-align-tags t))
  12837. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12838. ;; Disable `org-loop-over-headlines-in-active-region' for
  12839. ;; successive calls.
  12840. (let (org-loop-over-headlines-in-active-region)
  12841. (org-map-entries
  12842. #'org-set-tags-command
  12843. nil
  12844. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12845. 'region-start-level
  12846. 'region)
  12847. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  12848. (t
  12849. (save-excursion
  12850. (org-back-to-heading)
  12851. (let* ((all-tags (org-get-tags))
  12852. (table (setq org-last-tags-completion-table
  12853. (org--tag-add-to-alist
  12854. (and org-complete-tags-always-offer-all-agenda-tags
  12855. (org-global-tags-completion-table
  12856. (org-agenda-files)))
  12857. (or org-current-tag-alist (org-get-buffer-tags)))))
  12858. (current-tags
  12859. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  12860. all-tags))
  12861. (inherited-tags
  12862. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  12863. all-tags))
  12864. (tags
  12865. (replace-regexp-in-string
  12866. ;; Ignore all forbidden characters in tags.
  12867. "[^[:alnum:]_@#%]+" ":"
  12868. (if (or (eq t org-use-fast-tag-selection)
  12869. (and org-use-fast-tag-selection
  12870. (delq nil (mapcar #'cdr table))))
  12871. (org-fast-tag-selection
  12872. current-tags
  12873. inherited-tags
  12874. table
  12875. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  12876. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  12877. (org-trim (completing-read
  12878. "Tags: "
  12879. #'org-tags-completion-function
  12880. nil nil (org-make-tag-string current-tags)
  12881. 'org-tags-history)))))))
  12882. (org-set-tags tags))))))
  12883. (defun org-align-tags (&optional all)
  12884. "Align tags in current entry.
  12885. When optional argument ALL is non-nil, align all tags in the
  12886. visible part of the buffer."
  12887. (let ((get-indent-column
  12888. (lambda ()
  12889. (let ((offset (if (bound-and-true-p org-indent-mode)
  12890. (* (1- org-indent-indentation-per-level)
  12891. (1- (org-current-level)))
  12892. 0)))
  12893. (+ org-tags-column
  12894. (if (> org-tags-column 0) (- offset) offset))))))
  12895. (if (and (not all) (org-at-heading-p))
  12896. (org--align-tags-here (funcall get-indent-column))
  12897. (save-excursion
  12898. (if all
  12899. (while (re-search-forward org-tag-line-re nil t)
  12900. (org--align-tags-here (funcall get-indent-column)))
  12901. (org-back-to-heading t)
  12902. (org--align-tags-here (funcall get-indent-column)))))))
  12903. (defun org-set-tags (tags)
  12904. "Set the tags of the current entry to TAGS, replacing current tags.
  12905. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  12906. If TAGS is nil or the empty string, all tags are removed.
  12907. This function assumes point is on a headline."
  12908. (org-with-wide-buffer
  12909. (let ((tags (pcase tags
  12910. ((pred listp) tags)
  12911. ((pred stringp) (split-string (org-trim tags) ":" t))
  12912. (_ (error "Invalid tag specification: %S" tags))))
  12913. (old-tags (org-get-tags nil t))
  12914. (tags-change? nil))
  12915. (when (functionp org-tags-sort-function)
  12916. (setq tags (sort tags org-tags-sort-function)))
  12917. (setq tags-change? (not (equal tags old-tags)))
  12918. (when tags-change?
  12919. ;; Delete previous tags and any trailing white space.
  12920. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  12921. (line-end-position)))
  12922. (skip-chars-backward " \t")
  12923. (delete-region (point) (line-end-position))
  12924. ;; Deleting white spaces may break an otherwise empty headline.
  12925. ;; Re-introduce one space in this case.
  12926. (unless (org-at-heading-p) (insert " "))
  12927. (when tags
  12928. (save-excursion (insert " " (org-make-tag-string tags)))
  12929. ;; When text is being inserted on an invisible region
  12930. ;; boundary, it can be inadvertently sucked into
  12931. ;; invisibility.
  12932. (unless (org-invisible-p (line-beginning-position))
  12933. (org-flag-region (point) (line-end-position) nil 'outline))))
  12934. ;; Align tags, if any.
  12935. (when tags (org-align-tags))
  12936. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  12937. (defun org-change-tag-in-region (beg end tag off)
  12938. "Add or remove TAG for each entry in the region.
  12939. This works in the agenda, and also in an Org buffer."
  12940. (interactive
  12941. (list (region-beginning) (region-end)
  12942. (let ((org-last-tags-completion-table
  12943. (if (derived-mode-p 'org-mode)
  12944. (org--tag-add-to-alist
  12945. (org-get-buffer-tags)
  12946. (org-global-tags-completion-table))
  12947. (org-global-tags-completion-table))))
  12948. (completing-read
  12949. "Tag: " 'org-tags-completion-function nil nil nil
  12950. 'org-tags-history))
  12951. (progn
  12952. (message "[s]et or [r]emove? ")
  12953. (equal (read-char-exclusive) ?r))))
  12954. (when (fboundp 'deactivate-mark) (deactivate-mark))
  12955. (let ((agendap (equal major-mode 'org-agenda-mode))
  12956. l1 l2 m buf pos newhead (cnt 0))
  12957. (goto-char end)
  12958. (setq l2 (1- (org-current-line)))
  12959. (goto-char beg)
  12960. (setq l1 (org-current-line))
  12961. (cl-loop for l from l1 to l2 do
  12962. (org-goto-line l)
  12963. (setq m (get-text-property (point) 'org-hd-marker))
  12964. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  12965. (and agendap m))
  12966. (setq buf (if agendap (marker-buffer m) (current-buffer))
  12967. pos (if agendap m (point)))
  12968. (with-current-buffer buf
  12969. (save-excursion
  12970. (save-restriction
  12971. (goto-char pos)
  12972. (setq cnt (1+ cnt))
  12973. (org-toggle-tag tag (if off 'off 'on))
  12974. (setq newhead (org-get-heading)))))
  12975. (and agendap (org-agenda-change-all-lines newhead m))))
  12976. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  12977. (defun org-tags-completion-function (string _predicate &optional flag)
  12978. "Complete tag STRING.
  12979. FLAG specifies the type of completion operation to perform. This
  12980. function is passed as a collection function to `completing-read',
  12981. which see."
  12982. (let ((completion-ignore-case nil) ;tags are case-sensitive
  12983. (confirm (lambda (x) (stringp (car x))))
  12984. (prefix ""))
  12985. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  12986. (setq prefix (match-string 1 string))
  12987. (setq string (match-string 2 string)))
  12988. (pcase flag
  12989. (`t (all-completions string org-last-tags-completion-table confirm))
  12990. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  12991. (`nil
  12992. (pcase (try-completion string org-last-tags-completion-table confirm)
  12993. ((and completion (pred stringp))
  12994. (concat prefix
  12995. completion
  12996. (if (and org-add-colon-after-tag-completion
  12997. (assoc completion org-last-tags-completion-table))
  12998. ":"
  12999. "")))
  13000. (completion completion)))
  13001. (_ nil))))
  13002. (defun org-fast-tag-insert (kwd tags face &optional end)
  13003. "Insert KWD, and the TAGS, the latter with face FACE.
  13004. Also insert END."
  13005. (insert (format "%-12s" (concat kwd ":"))
  13006. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13007. (or end "")))
  13008. (defun org-fast-tag-show-exit (flag)
  13009. (save-excursion
  13010. (org-goto-line 3)
  13011. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13012. (replace-match ""))
  13013. (when flag
  13014. (end-of-line 1)
  13015. (org-move-to-column (- (window-width) 19) t)
  13016. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13017. (defun org-set-current-tags-overlay (current prefix)
  13018. "Add an overlay to CURRENT tag with PREFIX."
  13019. (let ((s (org-make-tag-string current)))
  13020. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13021. (org-overlay-display org-tags-overlay (concat prefix s))))
  13022. (defvar org-last-tag-selection-key nil)
  13023. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13024. "Fast tag selection with single keys.
  13025. CURRENT is the current list of tags in the headline, INHERITED is the
  13026. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13027. possibly with grouping information. TODO-TABLE is a similar table with
  13028. TODO keywords, should these have keys assigned to them.
  13029. If the keys are nil, a-z are automatically assigned.
  13030. Returns the new tags string, or nil to not change the current settings."
  13031. (let* ((fulltable (append table todo-table))
  13032. (maxlen (if (null fulltable) 0
  13033. (apply #'max
  13034. (mapcar (lambda (x)
  13035. (if (stringp (car x)) (string-width (car x))
  13036. 0))
  13037. fulltable))))
  13038. (buf (current-buffer))
  13039. (expert (eq org-fast-tag-selection-single-key 'expert))
  13040. (buffer-tags nil)
  13041. (fwidth (+ maxlen 3 1 3))
  13042. (ncol (/ (- (window-width) 4) fwidth))
  13043. (i-face 'org-done)
  13044. (c-face 'org-todo)
  13045. tg cnt e c char c1 c2 ntable tbl rtn
  13046. ov-start ov-end ov-prefix
  13047. (exit-after-next org-fast-tag-selection-single-key)
  13048. (done-keywords org-done-keywords)
  13049. groups ingroup intaggroup)
  13050. (save-excursion
  13051. (beginning-of-line)
  13052. (if (looking-at org-tag-line-re)
  13053. (setq ov-start (match-beginning 1)
  13054. ov-end (match-end 1)
  13055. ov-prefix "")
  13056. (setq ov-start (1- (point-at-eol))
  13057. ov-end (1+ ov-start))
  13058. (skip-chars-forward "^\n\r")
  13059. (setq ov-prefix
  13060. (concat
  13061. (buffer-substring (1- (point)) (point))
  13062. (if (> (current-column) org-tags-column)
  13063. " "
  13064. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13065. (move-overlay org-tags-overlay ov-start ov-end)
  13066. (save-window-excursion
  13067. (if expert
  13068. (set-buffer (get-buffer-create " *Org tags*"))
  13069. (delete-other-windows)
  13070. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13071. (org-switch-to-buffer-other-window " *Org tags*"))
  13072. (erase-buffer)
  13073. (setq-local org-done-keywords done-keywords)
  13074. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13075. (org-fast-tag-insert "Current" current c-face "\n\n")
  13076. (org-fast-tag-show-exit exit-after-next)
  13077. (org-set-current-tags-overlay current ov-prefix)
  13078. (setq tbl fulltable char ?a cnt 0)
  13079. (while (setq e (pop tbl))
  13080. (cond
  13081. ((eq (car e) :startgroup)
  13082. (push '() groups) (setq ingroup t)
  13083. (unless (zerop cnt)
  13084. (setq cnt 0)
  13085. (insert "\n"))
  13086. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13087. ((eq (car e) :endgroup)
  13088. (setq ingroup nil cnt 0)
  13089. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13090. ((eq (car e) :startgrouptag)
  13091. (setq intaggroup t)
  13092. (unless (zerop cnt)
  13093. (setq cnt 0)
  13094. (insert "\n"))
  13095. (insert "[ "))
  13096. ((eq (car e) :endgrouptag)
  13097. (setq intaggroup nil cnt 0)
  13098. (insert "]\n"))
  13099. ((equal e '(:newline))
  13100. (unless (zerop cnt)
  13101. (setq cnt 0)
  13102. (insert "\n")
  13103. (setq e (car tbl))
  13104. (while (equal (car tbl) '(:newline))
  13105. (insert "\n")
  13106. (setq tbl (cdr tbl)))))
  13107. ((equal e '(:grouptags)) (insert " : "))
  13108. (t
  13109. (setq tg (copy-sequence (car e)) c2 nil)
  13110. (if (cdr e)
  13111. (setq c (cdr e))
  13112. ;; automatically assign a character.
  13113. (setq c1 (string-to-char
  13114. (downcase (substring
  13115. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13116. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13117. (while (or (rassoc char ntable) (rassoc char table))
  13118. (setq char (1+ char)))
  13119. (setq c2 c1))
  13120. (setq c (or c2 char)))
  13121. (when ingroup (push tg (car groups)))
  13122. (setq tg (org-add-props tg nil 'face
  13123. (cond
  13124. ((not (assoc tg table))
  13125. (org-get-todo-face tg))
  13126. ((member tg current) c-face)
  13127. ((member tg inherited) i-face))))
  13128. (when (equal (caar tbl) :grouptags)
  13129. (org-add-props tg nil 'face 'org-tag-group))
  13130. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13131. (insert "[" c "] " tg (make-string
  13132. (- fwidth 4 (length tg)) ?\ ))
  13133. (push (cons tg c) ntable)
  13134. (when (= (cl-incf cnt) ncol)
  13135. (insert "\n")
  13136. (when (or ingroup intaggroup) (insert " "))
  13137. (setq cnt 0)))))
  13138. (setq ntable (nreverse ntable))
  13139. (insert "\n")
  13140. (goto-char (point-min))
  13141. (unless expert (org-fit-window-to-buffer))
  13142. (setq rtn
  13143. (catch 'exit
  13144. (while t
  13145. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  13146. (if (not groups) "no " "")
  13147. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13148. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13149. (setq org-last-tag-selection-key c)
  13150. (cond
  13151. ((= c ?\r) (throw 'exit t))
  13152. ((= c ?!)
  13153. (setq groups (not groups))
  13154. (goto-char (point-min))
  13155. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13156. ((= c ?\C-c)
  13157. (if (not expert)
  13158. (org-fast-tag-show-exit
  13159. (setq exit-after-next (not exit-after-next)))
  13160. (setq expert nil)
  13161. (delete-other-windows)
  13162. (set-window-buffer (split-window-vertically) " *Org tags*")
  13163. (org-switch-to-buffer-other-window " *Org tags*")
  13164. (org-fit-window-to-buffer)))
  13165. ((or (= c ?\C-g)
  13166. (and (= c ?q) (not (rassoc c ntable))))
  13167. (delete-overlay org-tags-overlay)
  13168. (setq quit-flag t))
  13169. ((= c ?\ )
  13170. (setq current nil)
  13171. (when exit-after-next (setq exit-after-next 'now)))
  13172. ((= c ?\t)
  13173. (condition-case nil
  13174. (setq tg (completing-read
  13175. "Tag: "
  13176. (or buffer-tags
  13177. (with-current-buffer buf
  13178. (setq buffer-tags
  13179. (org-get-buffer-tags))))))
  13180. (quit (setq tg "")))
  13181. (when (string-match "\\S-" tg)
  13182. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13183. (if (member tg current)
  13184. (setq current (delete tg current))
  13185. (push tg current)))
  13186. (when exit-after-next (setq exit-after-next 'now)))
  13187. ((setq e (rassoc c todo-table) tg (car e))
  13188. (with-current-buffer buf
  13189. (save-excursion (org-todo tg)))
  13190. (when exit-after-next (setq exit-after-next 'now)))
  13191. ((setq e (rassoc c ntable) tg (car e))
  13192. (if (member tg current)
  13193. (setq current (delete tg current))
  13194. (cl-loop for g in groups do
  13195. (when (member tg g)
  13196. (dolist (x g) (setq current (delete x current)))))
  13197. (push tg current))
  13198. (when exit-after-next (setq exit-after-next 'now))))
  13199. ;; Create a sorted list
  13200. (setq current
  13201. (sort current
  13202. (lambda (a b)
  13203. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13204. (when (eq exit-after-next 'now) (throw 'exit t))
  13205. (goto-char (point-min))
  13206. (beginning-of-line 2)
  13207. (delete-region (point) (point-at-eol))
  13208. (org-fast-tag-insert "Current" current c-face)
  13209. (org-set-current-tags-overlay current ov-prefix)
  13210. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  13211. (while (re-search-forward tag-re nil t)
  13212. (let ((tag (match-string 1)))
  13213. (add-text-properties
  13214. (match-beginning 1) (match-end 1)
  13215. (list 'face
  13216. (cond
  13217. ((member tag current) c-face)
  13218. ((member tag inherited) i-face)
  13219. (t (get-text-property (match-beginning 1) '
  13220. face))))))))
  13221. (goto-char (point-min)))))
  13222. (delete-overlay org-tags-overlay)
  13223. (if rtn
  13224. (mapconcat 'identity current ":")
  13225. nil))))
  13226. (defun org-make-tag-string (tags)
  13227. "Return string associated to TAGS.
  13228. TAGS is a list of strings."
  13229. (if (null tags) ""
  13230. (format ":%s:" (mapconcat #'identity tags ":"))))
  13231. (defun org--get-local-tags ()
  13232. "Return list of tags for the current headline.
  13233. Assume point is at the beginning of the headline."
  13234. (and (looking-at org-tag-line-re)
  13235. (split-string (match-string-no-properties 2) ":" t)))
  13236. (defun org-get-tags (&optional pos local)
  13237. "Get the list of tags specified in the current headline.
  13238. When argument POS is non-nil, retrieve tags for headline at POS.
  13239. According to `org-use-tags-inheritance', tags may be inherited
  13240. from parent headlines, and from the whole document, through
  13241. `org-file-tags'. However, when optional argument LOCAL is
  13242. non-nil, only return tags specified at the headline.
  13243. Inherited tags have the `inherited' text property."
  13244. (if (and org-trust-scanner-tags
  13245. (or (not pos) (eq pos (point)))
  13246. (not local))
  13247. org-scanner-tags
  13248. (org-with-point-at (or pos (point))
  13249. (unless (org-before-first-heading-p)
  13250. (org-back-to-heading t)
  13251. (let ((ltags (org--get-local-tags)) itags)
  13252. (if (or local (not org-use-tag-inheritance)) ltags
  13253. (setq itags org-file-tags)
  13254. (while (org-up-heading-safe)
  13255. (setq itags (append (mapcar #'org-add-prop-inherited
  13256. (org--get-local-tags))
  13257. itags)))
  13258. (delete-dups
  13259. (append (org-remove-uninherited-tags itags) ltags))))))))
  13260. (defun org-get-buffer-tags ()
  13261. "Get a table of all tags used in the buffer, for completion."
  13262. (org-with-point-at 1
  13263. (let (tags)
  13264. (while (re-search-forward org-tag-line-re nil t)
  13265. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  13266. tags)))
  13267. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  13268. ;;;; The mapping API
  13269. (defvar org-agenda-skip-comment-trees)
  13270. (defvar org-agenda-skip-function)
  13271. (defun org-map-entries (func &optional match scope &rest skip)
  13272. "Call FUNC at each headline selected by MATCH in SCOPE.
  13273. FUNC is a function or a lisp form. The function will be called without
  13274. arguments, with the cursor positioned at the beginning of the headline.
  13275. The return values of all calls to the function will be collected and
  13276. returned as a list.
  13277. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13278. does not need to preserve point. After evaluation, the cursor will be
  13279. moved to the end of the line (presumably of the headline of the
  13280. processed entry) and search continues from there. Under some
  13281. circumstances, this may not produce the wanted results. For example,
  13282. if you have removed (e.g. archived) the current (sub)tree it could
  13283. mean that the next entry will be skipped entirely. In such cases, you
  13284. can specify the position from where search should continue by making
  13285. FUNC set the variable `org-map-continue-from' to the desired buffer
  13286. position.
  13287. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13288. Only headlines that are matched by this query will be considered during
  13289. the iteration. When MATCH is nil or t, all headlines will be
  13290. visited by the iteration.
  13291. SCOPE determines the scope of this command. It can be any of:
  13292. nil The current buffer, respecting the restriction if any
  13293. tree The subtree started with the entry at point
  13294. region The entries within the active region, if any
  13295. region-start-level
  13296. The entries within the active region, but only those at
  13297. the same level than the first one.
  13298. file The current buffer, without restriction
  13299. file-with-archives
  13300. The current buffer, and any archives associated with it
  13301. agenda All agenda files
  13302. agenda-with-archives
  13303. All agenda files with any archive files associated with them
  13304. \(file1 file2 ...)
  13305. If this is a list, all files in the list will be scanned
  13306. The remaining args are treated as settings for the skipping facilities of
  13307. the scanner. The following items can be given here:
  13308. archive skip trees with the archive tag
  13309. comment skip trees with the COMMENT keyword
  13310. function or Emacs Lisp form:
  13311. will be used as value for `org-agenda-skip-function', so
  13312. whenever the function returns a position, FUNC will not be
  13313. called for that entry and search will continue from the
  13314. position returned
  13315. If your function needs to retrieve the tags including inherited tags
  13316. at the *current* entry, you can use the value of the variable
  13317. `org-scanner-tags' which will be much faster than getting the value
  13318. with `org-get-tags'. If your function gets properties with
  13319. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  13320. to t around the call to `org-entry-properties' to get the same speedup.
  13321. Note that if your function moves around to retrieve tags and properties at
  13322. a *different* entry, you cannot use these techniques."
  13323. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  13324. (not (org-region-active-p)))
  13325. (let* ((org-agenda-archives-mode nil) ; just to make sure
  13326. (org-agenda-skip-archived-trees (memq 'archive skip))
  13327. (org-agenda-skip-comment-trees (memq 'comment skip))
  13328. (org-agenda-skip-function
  13329. (car (org-delete-all '(comment archive) skip)))
  13330. (org-tags-match-list-sublevels t)
  13331. (start-level (eq scope 'region-start-level))
  13332. matcher res
  13333. org-todo-keywords-for-agenda
  13334. org-done-keywords-for-agenda
  13335. org-todo-keyword-alist-for-agenda
  13336. org-tag-alist-for-agenda
  13337. org--matcher-tags-todo-only)
  13338. (cond
  13339. ((eq match t) (setq matcher t))
  13340. ((eq match nil) (setq matcher t))
  13341. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  13342. (save-excursion
  13343. (save-restriction
  13344. (cond ((eq scope 'tree)
  13345. (org-back-to-heading t)
  13346. (org-narrow-to-subtree)
  13347. (setq scope nil))
  13348. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  13349. (org-region-active-p))
  13350. ;; If needed, set start-level to a string like "2"
  13351. (when start-level
  13352. (save-excursion
  13353. (goto-char (region-beginning))
  13354. (unless (org-at-heading-p) (outline-next-heading))
  13355. (setq start-level (org-current-level))))
  13356. (narrow-to-region (region-beginning)
  13357. (save-excursion
  13358. (goto-char (region-end))
  13359. (unless (and (bolp) (org-at-heading-p))
  13360. (outline-next-heading))
  13361. (point)))
  13362. (setq scope nil)))
  13363. (if (not scope)
  13364. (progn
  13365. (org-agenda-prepare-buffers
  13366. (and buffer-file-name (list buffer-file-name)))
  13367. (setq res
  13368. (org-scan-tags
  13369. func matcher org--matcher-tags-todo-only start-level)))
  13370. ;; Get the right scope
  13371. (cond
  13372. ((and scope (listp scope) (symbolp (car scope)))
  13373. (setq scope (eval scope)))
  13374. ((eq scope 'agenda)
  13375. (setq scope (org-agenda-files t)))
  13376. ((eq scope 'agenda-with-archives)
  13377. (setq scope (org-agenda-files t))
  13378. (setq scope (org-add-archive-files scope)))
  13379. ((eq scope 'file)
  13380. (setq scope (and buffer-file-name (list buffer-file-name))))
  13381. ((eq scope 'file-with-archives)
  13382. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  13383. (org-agenda-prepare-buffers scope)
  13384. (dolist (file scope)
  13385. (with-current-buffer (org-find-base-buffer-visiting file)
  13386. (org-with-wide-buffer
  13387. (goto-char (point-min))
  13388. (setq res
  13389. (append
  13390. res
  13391. (org-scan-tags
  13392. func matcher org--matcher-tags-todo-only)))))))))
  13393. res)))
  13394. ;;; Properties API
  13395. (defconst org-special-properties
  13396. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  13397. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  13398. "The special properties valid in Org mode.
  13399. These are properties that are not defined in the property drawer,
  13400. but in some other way.")
  13401. (defconst org-default-properties
  13402. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  13403. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  13404. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  13405. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  13406. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  13407. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  13408. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  13409. "Some properties that are used by Org mode for various purposes.
  13410. Being in this list makes sure that they are offered for completion.")
  13411. (defun org--valid-property-p (property)
  13412. "Non nil when string PROPERTY is a valid property name."
  13413. (not
  13414. (or (equal property "")
  13415. (string-match-p "\\s-" property))))
  13416. (defun org--update-property-plist (key val props)
  13417. "Associate KEY to VAL in alist PROPS.
  13418. Modifications are made by side-effect. Return new alist."
  13419. (let* ((appending (string= (substring key -1) "+"))
  13420. (key (if appending (substring key 0 -1) key))
  13421. (old (assoc-string key props t)))
  13422. (if (not old) (cons (cons key val) props)
  13423. (setcdr old (if appending (concat (cdr old) " " val) val))
  13424. props)))
  13425. (defun org-get-property-block (&optional beg force)
  13426. "Return the (beg . end) range of the body of the property drawer.
  13427. BEG is the beginning of the current subtree, or of the part
  13428. before the first headline. If it is not given, it will be found.
  13429. If the drawer does not exist, create it if FORCE is non-nil, or
  13430. return nil."
  13431. (org-with-wide-buffer
  13432. (when beg (goto-char beg))
  13433. (unless (org-before-first-heading-p)
  13434. (let ((beg (cond (beg)
  13435. ((or (not (featurep 'org-inlinetask))
  13436. (org-inlinetask-in-task-p))
  13437. (org-back-to-heading t))
  13438. (t (org-with-limited-levels (org-back-to-heading t))))))
  13439. (forward-line)
  13440. (when (looking-at-p org-planning-line-re) (forward-line))
  13441. (cond ((looking-at org-property-drawer-re)
  13442. (forward-line)
  13443. (cons (point) (progn (goto-char (match-end 0))
  13444. (line-beginning-position))))
  13445. (force
  13446. (goto-char beg)
  13447. (org-insert-property-drawer)
  13448. (let ((pos (save-excursion (search-forward ":END:")
  13449. (line-beginning-position))))
  13450. (cons pos pos))))))))
  13451. (defun org-at-property-p ()
  13452. "Non-nil when point is inside a property drawer.
  13453. See `org-property-re' for match data, if applicable."
  13454. (save-excursion
  13455. (beginning-of-line)
  13456. (and (looking-at org-property-re)
  13457. (let ((property-drawer (save-match-data (org-get-property-block))))
  13458. (and property-drawer
  13459. (>= (point) (car property-drawer))
  13460. (< (point) (cdr property-drawer)))))))
  13461. (defun org-property-action ()
  13462. "Do an action on properties."
  13463. (interactive)
  13464. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  13465. (let ((c (read-char-exclusive)))
  13466. (cl-case c
  13467. (?s (call-interactively #'org-set-property))
  13468. (?d (call-interactively #'org-delete-property))
  13469. (?D (call-interactively #'org-delete-property-globally))
  13470. (?c (call-interactively #'org-compute-property-at-point))
  13471. (otherwise (user-error "No such property action %c" c)))))
  13472. (defun org-inc-effort ()
  13473. "Increment the value of the effort property in the current entry."
  13474. (interactive)
  13475. (org-set-effort t))
  13476. (defvar org-clock-effort) ; Defined in org-clock.el.
  13477. (defvar org-clock-current-task) ; Defined in org-clock.el.
  13478. (defun org-set-effort (&optional increment value)
  13479. "Set the effort property of the current entry.
  13480. If INCREMENT is non-nil, set the property to the next allowed
  13481. value. Otherwise, if optional argument VALUE is provided, use
  13482. it. Eventually, prompt for the new value if none of the previous
  13483. variables is set."
  13484. (interactive "P")
  13485. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  13486. (current (org-entry-get nil org-effort-property))
  13487. (value
  13488. (cond
  13489. (increment
  13490. (unless allowed (user-error "Allowed effort values are not set"))
  13491. (or (cl-caadr (member (list current) allowed))
  13492. (user-error "Unknown value %S among allowed values" current)))
  13493. (value
  13494. (if (stringp value) value
  13495. (error "Invalid effort value: %S" value)))
  13496. (t
  13497. (let ((must-match
  13498. (and allowed
  13499. (not (get-text-property 0 'org-unrestricted
  13500. (caar allowed))))))
  13501. (completing-read "Effort: " allowed nil must-match))))))
  13502. (unless (equal current value)
  13503. (org-entry-put nil org-effort-property value))
  13504. (org-refresh-property '((effort . identity)
  13505. (effort-minutes . org-duration-to-minutes))
  13506. value)
  13507. (when (equal (org-get-heading t t t t)
  13508. (bound-and-true-p org-clock-current-task))
  13509. (setq org-clock-effort value)
  13510. (org-clock-update-mode-line))
  13511. (message "%s is now %s" org-effort-property value)))
  13512. (defun org-entry-properties (&optional pom which)
  13513. "Get all properties of the current entry.
  13514. When POM is a buffer position, get all properties from the entry
  13515. there instead.
  13516. This includes the TODO keyword, the tags, time strings for
  13517. deadline, scheduled, and clocking, and any additional properties
  13518. defined in the entry.
  13519. If WHICH is nil or `all', get all properties. If WHICH is
  13520. `special' or `standard', only get that subclass. If WHICH is
  13521. a string, only get that property.
  13522. Return value is an alist. Keys are properties, as upcased
  13523. strings."
  13524. (org-with-point-at pom
  13525. (when (and (derived-mode-p 'org-mode)
  13526. (ignore-errors (org-back-to-heading t)))
  13527. (catch 'exit
  13528. (let* ((beg (point))
  13529. (specific (and (stringp which) (upcase which)))
  13530. (which (cond ((not specific) which)
  13531. ((member specific org-special-properties) 'special)
  13532. (t 'standard)))
  13533. props)
  13534. ;; Get the special properties, like TODO and TAGS.
  13535. (when (memq which '(nil all special))
  13536. (when (or (not specific) (string= specific "CLOCKSUM"))
  13537. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  13538. (when clocksum
  13539. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  13540. props)))
  13541. (when specific (throw 'exit props)))
  13542. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  13543. (let ((clocksumt (get-text-property (point)
  13544. :org-clock-minutes-today)))
  13545. (when clocksumt
  13546. (push (cons "CLOCKSUM_T"
  13547. (org-duration-from-minutes clocksumt))
  13548. props)))
  13549. (when specific (throw 'exit props)))
  13550. (when (or (not specific) (string= specific "ITEM"))
  13551. (let ((case-fold-search nil))
  13552. (when (looking-at org-complex-heading-regexp)
  13553. (push (cons "ITEM"
  13554. (let ((title (match-string-no-properties 4)))
  13555. (if (org-string-nw-p title)
  13556. (org-remove-tabs title)
  13557. "")))
  13558. props)))
  13559. (when specific (throw 'exit props)))
  13560. (when (or (not specific) (string= specific "TODO"))
  13561. (let ((case-fold-search nil))
  13562. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  13563. (push (cons "TODO" (match-string-no-properties 2)) props)))
  13564. (when specific (throw 'exit props)))
  13565. (when (or (not specific) (string= specific "PRIORITY"))
  13566. (push (cons "PRIORITY"
  13567. (if (looking-at org-priority-regexp)
  13568. (match-string-no-properties 2)
  13569. (char-to-string org-default-priority)))
  13570. props)
  13571. (when specific (throw 'exit props)))
  13572. (when (or (not specific) (string= specific "FILE"))
  13573. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  13574. props)
  13575. (when specific (throw 'exit props)))
  13576. (when (or (not specific) (string= specific "TAGS"))
  13577. (let ((tags (org-get-tags nil t)))
  13578. (when tags
  13579. (push (cons "TAGS" (org-make-tag-string tags))
  13580. props)))
  13581. (when specific (throw 'exit props)))
  13582. (when (or (not specific) (string= specific "ALLTAGS"))
  13583. (let ((tags (org-get-tags)))
  13584. (when tags
  13585. (push (cons "ALLTAGS" (org-make-tag-string tags))
  13586. props)))
  13587. (when specific (throw 'exit props)))
  13588. (when (or (not specific) (string= specific "BLOCKED"))
  13589. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  13590. (when specific (throw 'exit props)))
  13591. (when (or (not specific)
  13592. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  13593. (forward-line)
  13594. (when (looking-at-p org-planning-line-re)
  13595. (end-of-line)
  13596. (let ((bol (line-beginning-position))
  13597. ;; Backward compatibility: time keywords used to
  13598. ;; be configurable (before 8.3). Make sure we
  13599. ;; get the correct keyword.
  13600. (key-assoc `(("CLOSED" . ,org-closed-string)
  13601. ("DEADLINE" . ,org-deadline-string)
  13602. ("SCHEDULED" . ,org-scheduled-string))))
  13603. (dolist (pair (if specific (list (assoc specific key-assoc))
  13604. key-assoc))
  13605. (save-excursion
  13606. (when (search-backward (cdr pair) bol t)
  13607. (goto-char (match-end 0))
  13608. (skip-chars-forward " \t")
  13609. (and (looking-at org-ts-regexp-both)
  13610. (push (cons (car pair)
  13611. (match-string-no-properties 0))
  13612. props)))))))
  13613. (when specific (throw 'exit props)))
  13614. (when (or (not specific)
  13615. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  13616. (let ((find-ts
  13617. (lambda (end ts)
  13618. ;; Fix next time-stamp before END. TS is the
  13619. ;; list of time-stamps found so far.
  13620. (let ((ts ts)
  13621. (regexp (cond
  13622. ((string= specific "TIMESTAMP")
  13623. org-ts-regexp)
  13624. ((string= specific "TIMESTAMP_IA")
  13625. org-ts-regexp-inactive)
  13626. ((assoc "TIMESTAMP_IA" ts)
  13627. org-ts-regexp)
  13628. ((assoc "TIMESTAMP" ts)
  13629. org-ts-regexp-inactive)
  13630. (t org-ts-regexp-both))))
  13631. (catch 'next
  13632. (while (re-search-forward regexp end t)
  13633. (backward-char)
  13634. (let ((object (org-element-context)))
  13635. ;; Accept to match timestamps in node
  13636. ;; properties, too.
  13637. (when (memq (org-element-type object)
  13638. '(node-property timestamp))
  13639. (let ((type
  13640. (org-element-property :type object)))
  13641. (cond
  13642. ((and (memq type '(active active-range))
  13643. (not (equal specific "TIMESTAMP_IA")))
  13644. (unless (assoc "TIMESTAMP" ts)
  13645. (push (cons "TIMESTAMP"
  13646. (org-element-property
  13647. :raw-value object))
  13648. ts)
  13649. (when specific (throw 'exit ts))))
  13650. ((and (memq type '(inactive inactive-range))
  13651. (not (string= specific "TIMESTAMP")))
  13652. (unless (assoc "TIMESTAMP_IA" ts)
  13653. (push (cons "TIMESTAMP_IA"
  13654. (org-element-property
  13655. :raw-value object))
  13656. ts)
  13657. (when specific (throw 'exit ts))))))
  13658. ;; Both timestamp types are found,
  13659. ;; move to next part.
  13660. (when (= (length ts) 2) (throw 'next ts)))))
  13661. ts)))))
  13662. (goto-char beg)
  13663. ;; First look for timestamps within headline.
  13664. (let ((ts (funcall find-ts (line-end-position) nil)))
  13665. (if (= (length ts) 2) (setq props (nconc ts props))
  13666. ;; Then find timestamps in the section, skipping
  13667. ;; planning line.
  13668. (let ((end (save-excursion (outline-next-heading))))
  13669. (forward-line)
  13670. (when (looking-at-p org-planning-line-re) (forward-line))
  13671. (setq props (nconc (funcall find-ts end ts) props))))))))
  13672. ;; Get the standard properties, like :PROP:.
  13673. (when (memq which '(nil all standard))
  13674. ;; If we are looking after a specific property, delegate
  13675. ;; to `org-entry-get', which is faster. However, make an
  13676. ;; exception for "CATEGORY", since it can be also set
  13677. ;; through keywords (i.e. #+CATEGORY).
  13678. (if (and specific (not (equal specific "CATEGORY")))
  13679. (let ((value (org-entry-get beg specific nil t)))
  13680. (throw 'exit (and value (list (cons specific value)))))
  13681. (let ((range (org-get-property-block beg)))
  13682. (when range
  13683. (let ((end (cdr range)) seen-base)
  13684. (goto-char (car range))
  13685. ;; Unlike to `org--update-property-plist', we
  13686. ;; handle the case where base values is found
  13687. ;; after its extension. We also forbid standard
  13688. ;; properties to be named as special properties.
  13689. (while (re-search-forward org-property-re end t)
  13690. (let* ((key (upcase (match-string-no-properties 2)))
  13691. (extendp (string-match-p "\\+\\'" key))
  13692. (key-base (if extendp (substring key 0 -1) key))
  13693. (value (match-string-no-properties 3)))
  13694. (cond
  13695. ((member-ignore-case key-base org-special-properties))
  13696. (extendp
  13697. (setq props
  13698. (org--update-property-plist key value props)))
  13699. ((member key seen-base))
  13700. (t (push key seen-base)
  13701. (let ((p (assoc-string key props t)))
  13702. (if p (setcdr p (concat value " " (cdr p)))
  13703. (push (cons key value) props))))))))))))
  13704. (unless (assoc "CATEGORY" props)
  13705. (push (cons "CATEGORY" (org-get-category beg)) props)
  13706. (when (string= specific "CATEGORY") (throw 'exit props)))
  13707. ;; Return value.
  13708. props)))))
  13709. (defun org--property-local-values (property literal-nil)
  13710. "Return value for PROPERTY in current entry.
  13711. Value is a list whose car is the base value for PROPERTY and cdr
  13712. a list of accumulated values. Return nil if neither is found in
  13713. the entry. Also return nil when PROPERTY is set to \"nil\",
  13714. unless LITERAL-NIL is non-nil."
  13715. (let ((range (org-get-property-block)))
  13716. (when range
  13717. (goto-char (car range))
  13718. (let* ((case-fold-search t)
  13719. (end (cdr range))
  13720. (value
  13721. ;; Base value.
  13722. (save-excursion
  13723. (let ((v (and (re-search-forward
  13724. (org-re-property property nil t) end t)
  13725. (match-string-no-properties 3))))
  13726. (list (if literal-nil v (org-not-nil v)))))))
  13727. ;; Find additional values.
  13728. (let* ((property+ (org-re-property (concat property "+") nil t)))
  13729. (while (re-search-forward property+ end t)
  13730. (push (match-string-no-properties 3) value)))
  13731. ;; Return final values.
  13732. (and (not (equal value '(nil))) (nreverse value))))))
  13733. (defun org--property-global-value (property literal-nil)
  13734. "Return value for PROPERTY in current buffer.
  13735. Return value is a string. Return nil if property is not set
  13736. globally. Also return nil when PROPERTY is set to \"nil\",
  13737. unless LITERAL-NIL is non-nil."
  13738. (let ((global
  13739. (cdr (or (assoc-string property org-file-properties t)
  13740. (assoc-string property org-global-properties t)
  13741. (assoc-string property org-global-properties-fixed t)))))
  13742. (if literal-nil global (org-not-nil global))))
  13743. (defun org-entry-get (pom property &optional inherit literal-nil)
  13744. "Get value of PROPERTY for entry or content at point-or-marker POM.
  13745. If INHERIT is non-nil and the entry does not have the property,
  13746. then also check higher levels of the hierarchy. If INHERIT is
  13747. the symbol `selective', use inheritance only if the setting in
  13748. `org-use-property-inheritance' selects PROPERTY for inheritance.
  13749. If the property is present but empty, the return value is the
  13750. empty string. If the property is not present at all, nil is
  13751. returned. In any other case, return the value as a string.
  13752. Search is case-insensitive.
  13753. If LITERAL-NIL is set, return the string value \"nil\" as
  13754. a string, do not interpret it as the list atom nil. This is used
  13755. for inheritance when a \"nil\" value can supersede a non-nil
  13756. value higher up the hierarchy."
  13757. (org-with-point-at pom
  13758. (cond
  13759. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  13760. ;; We need a special property. Use `org-entry-properties' to
  13761. ;; retrieve it, but specify the wanted property.
  13762. (cdr (assoc-string property (org-entry-properties nil property))))
  13763. ((and inherit
  13764. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  13765. (org-entry-get-with-inheritance property literal-nil))
  13766. (t
  13767. (let* ((local (org--property-local-values property literal-nil))
  13768. (value (and local (mapconcat #'identity (delq nil local) " "))))
  13769. (if literal-nil value (org-not-nil value)))))))
  13770. (defun org-property-or-variable-value (var &optional inherit)
  13771. "Check if there is a property fixing the value of VAR.
  13772. If yes, return this value. If not, return the current value of the variable."
  13773. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  13774. (if (and prop (stringp prop) (string-match "\\S-" prop))
  13775. (read prop)
  13776. (symbol-value var))))
  13777. (defun org-entry-delete (pom property)
  13778. "Delete PROPERTY from entry at point-or-marker POM.
  13779. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  13780. non-nil when a property was removed."
  13781. (org-with-point-at pom
  13782. (pcase (org-get-property-block)
  13783. (`(,begin . ,origin)
  13784. (let* ((end (copy-marker origin))
  13785. (re (org-re-property
  13786. (concat (regexp-quote property) "\\+?") t t)))
  13787. (goto-char begin)
  13788. (while (re-search-forward re end t)
  13789. (delete-region (match-beginning 0) (line-beginning-position 2)))
  13790. ;; If drawer is empty, remove it altogether.
  13791. (when (= begin end)
  13792. (delete-region (line-beginning-position 0)
  13793. (line-beginning-position 2)))
  13794. ;; Return non-nil if some property was removed.
  13795. (prog1 (/= end origin) (set-marker end nil))))
  13796. (_ nil))))
  13797. ;; Multi-values properties are properties that contain multiple values
  13798. ;; These values are assumed to be single words, separated by whitespace.
  13799. (defun org-entry-add-to-multivalued-property (pom property value)
  13800. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  13801. (let* ((old (org-entry-get pom property))
  13802. (values (and old (split-string old))))
  13803. (setq value (org-entry-protect-space value))
  13804. (unless (member value values)
  13805. (setq values (append values (list value)))
  13806. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13807. (defun org-entry-remove-from-multivalued-property (pom property value)
  13808. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  13809. (let* ((old (org-entry-get pom property))
  13810. (values (and old (split-string old))))
  13811. (setq value (org-entry-protect-space value))
  13812. (when (member value values)
  13813. (setq values (delete value values))
  13814. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13815. (defun org-entry-member-in-multivalued-property (pom property value)
  13816. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  13817. (let* ((old (org-entry-get pom property))
  13818. (values (and old (split-string old))))
  13819. (setq value (org-entry-protect-space value))
  13820. (member value values)))
  13821. (defun org-entry-get-multivalued-property (pom property)
  13822. "Return a list of values in a multivalued property."
  13823. (let* ((value (org-entry-get pom property))
  13824. (values (and value (split-string value))))
  13825. (mapcar #'org-entry-restore-space values)))
  13826. (defun org-entry-put-multivalued-property (pom property &rest values)
  13827. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  13828. VALUES should be a list of strings. Spaces will be protected."
  13829. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  13830. (let* ((value (org-entry-get pom property))
  13831. (values (and value (split-string value))))
  13832. (mapcar #'org-entry-restore-space values)))
  13833. (defun org-entry-protect-space (s)
  13834. "Protect spaces and newline in string S."
  13835. (while (string-match " " s)
  13836. (setq s (replace-match "%20" t t s)))
  13837. (while (string-match "\n" s)
  13838. (setq s (replace-match "%0A" t t s)))
  13839. s)
  13840. (defun org-entry-restore-space (s)
  13841. "Restore spaces and newline in string S."
  13842. (while (string-match "%20" s)
  13843. (setq s (replace-match " " t t s)))
  13844. (while (string-match "%0A" s)
  13845. (setq s (replace-match "\n" t t s)))
  13846. s)
  13847. (defvar org-entry-property-inherited-from (make-marker)
  13848. "Marker pointing to the entry from where a property was inherited.
  13849. Each call to `org-entry-get-with-inheritance' will set this marker to the
  13850. location of the entry where the inheritance search matched. If there was
  13851. no match, the marker will point nowhere.
  13852. Note that also `org-entry-get' calls this function, if the INHERIT flag
  13853. is set.")
  13854. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  13855. "Get PROPERTY of entry or content at point, search higher levels if needed.
  13856. The search will stop at the first ancestor which has the property defined.
  13857. If the value found is \"nil\", return nil to show that the property
  13858. should be considered as undefined (this is the meaning of nil here).
  13859. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  13860. (move-marker org-entry-property-inherited-from nil)
  13861. (org-with-wide-buffer
  13862. (let (value)
  13863. (catch 'exit
  13864. (while t
  13865. (let ((v (org--property-local-values property literal-nil)))
  13866. (when v
  13867. (setq value
  13868. (concat (mapconcat #'identity (delq nil v) " ")
  13869. (and value " ")
  13870. value)))
  13871. (cond
  13872. ((car v)
  13873. (org-back-to-heading t)
  13874. (move-marker org-entry-property-inherited-from (point))
  13875. (throw 'exit nil))
  13876. ((org-up-heading-safe))
  13877. (t
  13878. (let ((global (org--property-global-value property literal-nil)))
  13879. (cond ((not global))
  13880. (value (setq value (concat global " " value)))
  13881. (t (setq value global))))
  13882. (throw 'exit nil))))))
  13883. (if literal-nil value (org-not-nil value)))))
  13884. (defvar org-property-changed-functions nil
  13885. "Hook called when the value of a property has changed.
  13886. Each hook function should accept two arguments, the name of the property
  13887. and the new value.")
  13888. (defun org-entry-put (pom property value)
  13889. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  13890. If the value is nil, it is converted to the empty string. If it
  13891. is not a string, an error is raised. Also raise an error on
  13892. invalid property names.
  13893. PROPERTY can be any regular property (see
  13894. `org-special-properties'). It can also be \"TODO\",
  13895. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  13896. For the last two properties, VALUE may have any of the special
  13897. values \"earlier\" and \"later\". The function then increases or
  13898. decreases scheduled or deadline date by one day."
  13899. (cond ((null value) (setq value ""))
  13900. ((not (stringp value)) (error "Properties values should be strings"))
  13901. ((not (org--valid-property-p property))
  13902. (user-error "Invalid property name: \"%s\"" property)))
  13903. (org-with-point-at pom
  13904. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  13905. (org-back-to-heading t)
  13906. (org-with-limited-levels (org-back-to-heading t)))
  13907. (let ((beg (point)))
  13908. (cond
  13909. ((equal property "TODO")
  13910. (cond ((not (org-string-nw-p value)) (setq value 'none))
  13911. ((not (member value org-todo-keywords-1))
  13912. (user-error "\"%s\" is not a valid TODO state" value)))
  13913. (org-todo value)
  13914. (org-align-tags))
  13915. ((equal property "PRIORITY")
  13916. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  13917. (org-align-tags))
  13918. ((equal property "SCHEDULED")
  13919. (forward-line)
  13920. (if (and (looking-at-p org-planning-line-re)
  13921. (re-search-forward
  13922. org-scheduled-time-regexp (line-end-position) t))
  13923. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  13924. ((string= value "later") (org-timestamp-change 1 'day))
  13925. ((string= value "") (org-schedule '(4)))
  13926. (t (org-schedule nil value)))
  13927. (if (member value '("earlier" "later" ""))
  13928. (call-interactively #'org-schedule)
  13929. (org-schedule nil value))))
  13930. ((equal property "DEADLINE")
  13931. (forward-line)
  13932. (if (and (looking-at-p org-planning-line-re)
  13933. (re-search-forward
  13934. org-deadline-time-regexp (line-end-position) t))
  13935. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  13936. ((string= value "later") (org-timestamp-change 1 'day))
  13937. ((string= value "") (org-deadline '(4)))
  13938. (t (org-deadline nil value)))
  13939. (if (member value '("earlier" "later" ""))
  13940. (call-interactively #'org-deadline)
  13941. (org-deadline nil value))))
  13942. ((member property org-special-properties)
  13943. (error "The %s property cannot be set with `org-entry-put'" property))
  13944. (t
  13945. (let* ((range (org-get-property-block beg 'force))
  13946. (end (cdr range))
  13947. (case-fold-search t))
  13948. (goto-char (car range))
  13949. (if (re-search-forward (org-re-property property nil t) end t)
  13950. (progn (delete-region (match-beginning 0) (match-end 0))
  13951. (goto-char (match-beginning 0)))
  13952. (goto-char end)
  13953. (insert "\n")
  13954. (backward-char))
  13955. (insert ":" property ":")
  13956. (when value (insert " " value))
  13957. (org-indent-line)))))
  13958. (run-hook-with-args 'org-property-changed-functions property value)))
  13959. (defun org-buffer-property-keys (&optional specials defaults columns)
  13960. "Get all property keys in the current buffer.
  13961. When SPECIALS is non-nil, also list the special properties that
  13962. reflect things like tags and TODO state.
  13963. When DEFAULTS is non-nil, also include properties that has
  13964. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  13965. DESCRIPTION, LOCATION, and LOGGING and others.
  13966. When COLUMNS in non-nil, also include property names given in
  13967. COLUMN formats in the current buffer."
  13968. (let ((case-fold-search t)
  13969. (props (append
  13970. (and specials org-special-properties)
  13971. (and defaults (cons org-effort-property org-default-properties))
  13972. nil)))
  13973. (org-with-wide-buffer
  13974. (goto-char (point-min))
  13975. (while (re-search-forward org-property-start-re nil t)
  13976. (catch :skip
  13977. (let ((range (org-get-property-block)))
  13978. (unless range (throw :skip nil))
  13979. (goto-char (car range))
  13980. (let ((begin (car range))
  13981. (end (cdr range)))
  13982. ;; Make sure that found property block is not located
  13983. ;; before current point, as it would generate an infloop.
  13984. ;; It can happen, for example, in the following
  13985. ;; situation:
  13986. ;;
  13987. ;; * Headline
  13988. ;; :PROPERTIES:
  13989. ;; ...
  13990. ;; :END:
  13991. ;; *************** Inlinetask
  13992. ;; #+BEGIN_EXAMPLE
  13993. ;; :PROPERTIES:
  13994. ;; #+END_EXAMPLE
  13995. ;;
  13996. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  13997. (while (< (point) end)
  13998. (let ((p (progn (looking-at org-property-re)
  13999. (match-string-no-properties 2))))
  14000. ;; Only add true property name, not extension symbol.
  14001. (push (if (not (string-match-p "\\+\\'" p)) p
  14002. (substring p 0 -1))
  14003. props))
  14004. (forward-line))))
  14005. (outline-next-heading)))
  14006. (when columns
  14007. (goto-char (point-min))
  14008. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14009. (let ((element (org-element-at-point)))
  14010. (when (memq (org-element-type element) '(keyword node-property))
  14011. (let ((value (org-element-property :value element))
  14012. (start 0))
  14013. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  14014. \\(?:{[^}]+}\\)?"
  14015. value start)
  14016. (setq start (match-end 0))
  14017. (let ((p (match-string-no-properties 1 value)))
  14018. (unless (member-ignore-case p org-special-properties)
  14019. (push p props))))))))))
  14020. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14021. (defun org-property-values (key)
  14022. "List all non-nil values of property KEY in current buffer."
  14023. (org-with-wide-buffer
  14024. (goto-char (point-min))
  14025. (let ((case-fold-search t)
  14026. (re (org-re-property key))
  14027. values)
  14028. (while (re-search-forward re nil t)
  14029. (push (org-entry-get (point) key) values))
  14030. (delete-dups values))))
  14031. (defun org-insert-property-drawer ()
  14032. "Insert a property drawer into the current entry."
  14033. (org-with-wide-buffer
  14034. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14035. (org-back-to-heading t)
  14036. (org-with-limited-levels (org-back-to-heading t)))
  14037. (forward-line)
  14038. (when (looking-at-p org-planning-line-re) (forward-line))
  14039. (unless (looking-at-p org-property-drawer-re)
  14040. ;; Make sure we start editing a line from current entry, not from
  14041. ;; next one. It prevents extending text properties or overlays
  14042. ;; belonging to the latter.
  14043. (when (bolp) (backward-char))
  14044. (let ((begin (1+ (point)))
  14045. (inhibit-read-only t))
  14046. (insert "\n:PROPERTIES:\n:END:")
  14047. (when (eobp) (insert "\n"))
  14048. (org-indent-region begin (point))))))
  14049. (defun org-insert-drawer (&optional arg drawer)
  14050. "Insert a drawer at point.
  14051. When optional argument ARG is non-nil, insert a property drawer.
  14052. Optional argument DRAWER, when non-nil, is a string representing
  14053. drawer's name. Otherwise, the user is prompted for a name.
  14054. If a region is active, insert the drawer around that region
  14055. instead.
  14056. Point is left between drawer's boundaries."
  14057. (interactive "P")
  14058. (let* ((drawer (if arg "PROPERTIES"
  14059. (or drawer (read-from-minibuffer "Drawer: ")))))
  14060. (cond
  14061. ;; With C-u, fall back on `org-insert-property-drawer'
  14062. (arg (org-insert-property-drawer))
  14063. ;; Check validity of suggested drawer's name.
  14064. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14065. (user-error "Invalid drawer name"))
  14066. ;; With an active region, insert a drawer at point.
  14067. ((not (org-region-active-p))
  14068. (progn
  14069. (unless (bolp) (insert "\n"))
  14070. (insert (format ":%s:\n\n:END:\n" drawer))
  14071. (forward-line -2)))
  14072. ;; Otherwise, insert the drawer at point
  14073. (t
  14074. (let ((rbeg (region-beginning))
  14075. (rend (copy-marker (region-end))))
  14076. (unwind-protect
  14077. (progn
  14078. (goto-char rbeg)
  14079. (beginning-of-line)
  14080. (when (save-excursion
  14081. (re-search-forward org-outline-regexp-bol rend t))
  14082. (user-error "Drawers cannot contain headlines"))
  14083. ;; Position point at the beginning of the first
  14084. ;; non-blank line in region. Insert drawer's opening
  14085. ;; there, then indent it.
  14086. (org-skip-whitespace)
  14087. (beginning-of-line)
  14088. (insert ":" drawer ":\n")
  14089. (forward-line -1)
  14090. (indent-for-tab-command)
  14091. ;; Move point to the beginning of the first blank line
  14092. ;; after the last non-blank line in region. Insert
  14093. ;; drawer's closing, then indent it.
  14094. (goto-char rend)
  14095. (skip-chars-backward " \r\t\n")
  14096. (insert "\n:END:")
  14097. (deactivate-mark t)
  14098. (indent-for-tab-command)
  14099. (unless (eolp) (insert "\n")))
  14100. ;; Clear marker, whatever the outcome of insertion is.
  14101. (set-marker rend nil)))))))
  14102. (defvar org-property-set-functions-alist nil
  14103. "Property set function alist.
  14104. Each entry should have the following format:
  14105. (PROPERTY . READ-FUNCTION)
  14106. The read function will be called with the same argument as
  14107. `org-completing-read'.")
  14108. (defun org-set-property-function (property)
  14109. "Get the function that should be used to set PROPERTY.
  14110. This is computed according to `org-property-set-functions-alist'."
  14111. (or (cdr (assoc property org-property-set-functions-alist))
  14112. 'org-completing-read))
  14113. (defun org-read-property-value (property &optional pom)
  14114. "Read value for PROPERTY, as a string.
  14115. When optional argument POM is non-nil, completion uses additional
  14116. information, i.e., allowed or existing values at point or marker
  14117. POM."
  14118. (let* ((completion-ignore-case t)
  14119. (allowed
  14120. (or (org-property-get-allowed-values nil property 'table)
  14121. (and pom (org-property-get-allowed-values pom property 'table))))
  14122. (current (org-entry-get nil property))
  14123. (prompt (format "%s value%s: "
  14124. property
  14125. (if (org-string-nw-p current)
  14126. (format " [%s]" current)
  14127. "")))
  14128. (set-function (org-set-property-function property)))
  14129. (org-trim
  14130. (if allowed
  14131. (funcall set-function
  14132. prompt allowed nil
  14133. (not (get-text-property 0 'org-unrestricted (caar allowed))))
  14134. (let ((all (mapcar #'list
  14135. (append (org-property-values property)
  14136. (and pom
  14137. (org-with-point-at pom
  14138. (org-property-values property)))))))
  14139. (funcall set-function prompt all nil nil "" nil current))))))
  14140. (defvar org-last-set-property nil)
  14141. (defvar org-last-set-property-value nil)
  14142. (defun org-read-property-name ()
  14143. "Read a property name."
  14144. (let ((completion-ignore-case t)
  14145. (default-prop (or (and (org-at-property-p)
  14146. (match-string-no-properties 2))
  14147. org-last-set-property)))
  14148. (org-completing-read
  14149. (concat "Property"
  14150. (if default-prop (concat " [" default-prop "]") "")
  14151. ": ")
  14152. (mapcar #'list (org-buffer-property-keys nil t t))
  14153. nil nil nil nil default-prop)))
  14154. (defun org-set-property-and-value (use-last)
  14155. "Allow to set [PROPERTY]: [value] direction from prompt.
  14156. When use-default, don't even ask, just use the last
  14157. \"[PROPERTY]: [value]\" string from the history."
  14158. (interactive "P")
  14159. (let* ((completion-ignore-case t)
  14160. (pv (or (and use-last org-last-set-property-value)
  14161. (org-completing-read
  14162. "Enter a \"[Property]: [value]\" pair: "
  14163. nil nil nil nil nil
  14164. org-last-set-property-value)))
  14165. prop val)
  14166. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14167. (setq prop (match-string 1 pv)
  14168. val (match-string 2 pv))
  14169. (org-set-property prop val))))
  14170. (defun org-set-property (property value)
  14171. "In the current entry, set PROPERTY to VALUE.
  14172. When called interactively, this will prompt for a property name, offering
  14173. completion on existing and default properties. And then it will prompt
  14174. for a value, offering completion either on allowed values (via an inherited
  14175. xxx_ALL property) or on existing values in other instances of this property
  14176. in the current file.
  14177. Throw an error when trying to set a property with an invalid name."
  14178. (interactive (list nil nil))
  14179. (let ((property (or property (org-read-property-name))))
  14180. ;; `org-entry-put' also makes the following check, but this one
  14181. ;; avoids polluting `org-last-set-property' and
  14182. ;; `org-last-set-property-value' needlessly.
  14183. (unless (org--valid-property-p property)
  14184. (user-error "Invalid property name: \"%s\"" property))
  14185. (let ((value (or value (org-read-property-value property)))
  14186. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14187. (setq org-last-set-property property)
  14188. (setq org-last-set-property-value (concat property ": " value))
  14189. ;; Possibly postprocess the inserted value:
  14190. (when fn (setq value (funcall fn value)))
  14191. (unless (equal (org-entry-get nil property) value)
  14192. (org-entry-put nil property value)))))
  14193. (defun org-find-property (property &optional value)
  14194. "Find first entry in buffer that sets PROPERTY.
  14195. When optional argument VALUE is non-nil, only consider an entry
  14196. if it contains PROPERTY set to this value. If PROPERTY should be
  14197. explicitly set to nil, use string \"nil\" for VALUE.
  14198. Return position where the entry begins, or nil if there is no
  14199. such entry. If narrowing is in effect, only search the visible
  14200. part of the buffer."
  14201. (save-excursion
  14202. (goto-char (point-min))
  14203. (let ((case-fold-search t)
  14204. (re (org-re-property property nil (not value) value)))
  14205. (catch 'exit
  14206. (while (re-search-forward re nil t)
  14207. (when (if value (org-at-property-p)
  14208. (org-entry-get (point) property nil t))
  14209. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14210. (defun org-delete-property (property)
  14211. "In the current entry, delete PROPERTY."
  14212. (interactive
  14213. (let* ((completion-ignore-case t)
  14214. (cat (org-entry-get (point) "CATEGORY"))
  14215. (props0 (org-entry-properties nil 'standard))
  14216. (props (if cat props0
  14217. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14218. (prop (if (< 1 (length props))
  14219. (completing-read "Property: " props nil t)
  14220. (caar props))))
  14221. (list prop)))
  14222. (if (not property)
  14223. (message "No property to delete in this entry")
  14224. (org-entry-delete nil property)
  14225. (message "Property \"%s\" deleted" property)))
  14226. (defun org-delete-property-globally (property)
  14227. "Remove PROPERTY globally, from all entries.
  14228. This function ignores narrowing, if any."
  14229. (interactive
  14230. (let* ((completion-ignore-case t)
  14231. (prop (completing-read
  14232. "Globally remove property: "
  14233. (mapcar #'list (org-buffer-property-keys)))))
  14234. (list prop)))
  14235. (org-with-wide-buffer
  14236. (goto-char (point-min))
  14237. (let ((count 0)
  14238. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14239. (while (re-search-forward re nil t)
  14240. (when (org-entry-delete (point) property) (cl-incf count)))
  14241. (message "Property \"%s\" removed from %d entries" property count))))
  14242. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14243. (defun org-compute-property-at-point ()
  14244. "Compute the property at point.
  14245. This looks for an enclosing column format, extracts the operator and
  14246. then applies it to the property in the column format's scope."
  14247. (interactive)
  14248. (unless (org-at-property-p)
  14249. (user-error "Not at a property"))
  14250. (let ((prop (match-string-no-properties 2)))
  14251. (org-columns-get-format-and-top-level)
  14252. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14253. (user-error "No operator defined for property %s" prop))
  14254. (org-columns-compute prop)))
  14255. (defvar org-property-allowed-value-functions nil
  14256. "Hook for functions supplying allowed values for a specific property.
  14257. The functions must take a single argument, the name of the property, and
  14258. return a flat list of allowed values. If \":ETC\" is one of
  14259. the values, this means that these values are intended as defaults for
  14260. completion, but that other values should be allowed too.
  14261. The functions must return nil if they are not responsible for this
  14262. property.")
  14263. (defun org-property-get-allowed-values (pom property &optional table)
  14264. "Get allowed values for the property PROPERTY.
  14265. When TABLE is non-nil, return an alist that can directly be used for
  14266. completion."
  14267. (let (vals)
  14268. (cond
  14269. ((equal property "TODO")
  14270. (setq vals (org-with-point-at pom
  14271. (append org-todo-keywords-1 '("")))))
  14272. ((equal property "PRIORITY")
  14273. (let ((n org-lowest-priority))
  14274. (while (>= n org-highest-priority)
  14275. (push (char-to-string n) vals)
  14276. (setq n (1- n)))))
  14277. ((equal property "CATEGORY"))
  14278. ((member property org-special-properties))
  14279. ((setq vals (run-hook-with-args-until-success
  14280. 'org-property-allowed-value-functions property)))
  14281. (t
  14282. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14283. (when (and vals (string-match "\\S-" vals))
  14284. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14285. (setq vals (mapcar (lambda (x)
  14286. (cond ((stringp x) x)
  14287. ((numberp x) (number-to-string x))
  14288. ((symbolp x) (symbol-name x))
  14289. (t "???")))
  14290. vals)))))
  14291. (when (member ":ETC" vals)
  14292. (setq vals (remove ":ETC" vals))
  14293. (org-add-props (car vals) '(org-unrestricted t)))
  14294. (if table (mapcar 'list vals) vals)))
  14295. (defun org-property-previous-allowed-value (&optional _previous)
  14296. "Switch to the next allowed value for this property."
  14297. (interactive)
  14298. (org-property-next-allowed-value t))
  14299. (defun org-property-next-allowed-value (&optional previous)
  14300. "Switch to the next allowed value for this property."
  14301. (interactive)
  14302. (unless (org-at-property-p)
  14303. (user-error "Not at a property"))
  14304. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  14305. (key (match-string 2))
  14306. (value (match-string 3))
  14307. (allowed (or (org-property-get-allowed-values (point) key)
  14308. (and (member value '("[ ]" "[-]" "[X]"))
  14309. '("[ ]" "[X]"))))
  14310. (heading (save-match-data (nth 4 (org-heading-components))))
  14311. nval)
  14312. (unless allowed
  14313. (user-error "Allowed values for this property have not been defined"))
  14314. (when previous (setq allowed (reverse allowed)))
  14315. (when (member value allowed)
  14316. (setq nval (car (cdr (member value allowed)))))
  14317. (setq nval (or nval (car allowed)))
  14318. (when (equal nval value)
  14319. (user-error "Only one allowed value for this property"))
  14320. (org-at-property-p)
  14321. (replace-match (concat " :" key ": " nval) t t)
  14322. (org-indent-line)
  14323. (beginning-of-line 1)
  14324. (skip-chars-forward " \t")
  14325. (when (equal prop org-effort-property)
  14326. (org-refresh-property
  14327. '((effort . identity)
  14328. (effort-minutes . org-duration-to-minutes))
  14329. nval)
  14330. (when (string= org-clock-current-task heading)
  14331. (setq org-clock-effort nval)
  14332. (org-clock-update-mode-line)))
  14333. (run-hook-with-args 'org-property-changed-functions key nval)))
  14334. (defun org-find-olp (path &optional this-buffer)
  14335. "Return a marker pointing to the entry at outline path OLP.
  14336. If anything goes wrong, throw an error.
  14337. You can wrap this call to catch the error like this:
  14338. (condition-case msg
  14339. (org-mobile-locate-entry (match-string 4))
  14340. (error (nth 1 msg)))
  14341. The return value will then be either a string with the error message,
  14342. or a marker if everything is OK.
  14343. If THIS-BUFFER is set, the outline path does not contain a file,
  14344. only headings."
  14345. (let* ((file (if this-buffer buffer-file-name (pop path)))
  14346. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  14347. (level 1)
  14348. (lmin 1)
  14349. (lmax 1)
  14350. end found flevel)
  14351. (unless buffer (error "File not found :%s" file))
  14352. (with-current-buffer buffer
  14353. (unless (derived-mode-p 'org-mode)
  14354. (error "Buffer %s needs to be in Org mode" buffer))
  14355. (org-with-wide-buffer
  14356. (goto-char (point-min))
  14357. (dolist (heading path)
  14358. (let ((re (format org-complex-heading-regexp-format
  14359. (regexp-quote heading)))
  14360. (cnt 0))
  14361. (while (re-search-forward re end t)
  14362. (setq level (- (match-end 1) (match-beginning 1)))
  14363. (when (and (>= level lmin) (<= level lmax))
  14364. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  14365. (when (= cnt 0)
  14366. (error "Heading not found on level %d: %s" lmax heading))
  14367. (when (> cnt 1)
  14368. (error "Heading not unique on level %d: %s" lmax heading))
  14369. (goto-char found)
  14370. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  14371. (setq end (save-excursion (org-end-of-subtree t t)))))
  14372. (when (org-at-heading-p)
  14373. (point-marker))))))
  14374. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  14375. "Find node HEADING in BUFFER.
  14376. Return a marker to the heading if it was found, or nil if not.
  14377. If POS-ONLY is set, return just the position instead of a marker.
  14378. The heading text must match exact, but it may have a TODO keyword,
  14379. a priority cookie and tags in the standard locations."
  14380. (with-current-buffer (or buffer (current-buffer))
  14381. (org-with-wide-buffer
  14382. (goto-char (point-min))
  14383. (let (case-fold-search)
  14384. (when (re-search-forward
  14385. (format org-complex-heading-regexp-format
  14386. (regexp-quote heading)) nil t)
  14387. (if pos-only
  14388. (match-beginning 0)
  14389. (move-marker (make-marker) (match-beginning 0))))))))
  14390. (defun org-find-exact-heading-in-directory (heading &optional dir)
  14391. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  14392. When the target headline is found, return a marker to this location."
  14393. (let ((files (directory-files (or dir default-directory)
  14394. t "\\`[^.#].*\\.org\\'"))
  14395. visiting m buffer)
  14396. (catch 'found
  14397. (dolist (file files)
  14398. (message "trying %s" file)
  14399. (setq visiting (org-find-base-buffer-visiting file))
  14400. (setq buffer (or visiting (find-file-noselect file)))
  14401. (setq m (org-find-exact-headline-in-buffer
  14402. heading buffer))
  14403. (when (and (not m) (not visiting)) (kill-buffer buffer))
  14404. (and m (throw 'found m))))))
  14405. (defun org-find-entry-with-id (ident)
  14406. "Locate the entry that contains the ID property with exact value IDENT.
  14407. IDENT can be a string, a symbol or a number, this function will search for
  14408. the string representation of it.
  14409. Return the position where this entry starts, or nil if there is no such entry."
  14410. (interactive "sID: ")
  14411. (let ((id (cond
  14412. ((stringp ident) ident)
  14413. ((symbolp ident) (symbol-name ident))
  14414. ((numberp ident) (number-to-string ident))
  14415. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  14416. (org-with-wide-buffer (org-find-property "ID" id))))
  14417. ;;;; Timestamps
  14418. (defvar org-last-changed-timestamp nil)
  14419. (defvar org-last-inserted-timestamp nil
  14420. "The last time stamp inserted with `org-insert-time-stamp'.")
  14421. (defun org-time-stamp (arg &optional inactive)
  14422. "Prompt for a date/time and insert a time stamp.
  14423. If the user specifies a time like HH:MM or if this command is
  14424. called with at least one prefix argument, the time stamp contains
  14425. the date and the time. Otherwise, only the date is included.
  14426. All parts of a date not specified by the user are filled in from
  14427. the timestamp at point, if any, or the current date/time
  14428. otherwise.
  14429. If there is already a timestamp at the cursor, it is replaced.
  14430. With two universal prefix arguments, insert an active timestamp
  14431. with the current time without prompting the user.
  14432. When called from lisp, the timestamp is inactive if INACTIVE is
  14433. non-nil."
  14434. (interactive "P")
  14435. (let* ((ts (cond
  14436. ((org-at-date-range-p t)
  14437. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  14438. ((org-at-timestamp-p 'lax) (match-string 0))))
  14439. ;; Default time is either the timestamp at point or today.
  14440. ;; When entering a range, only the range start is considered.
  14441. (default-time (if (not ts) (current-time)
  14442. (apply #'encode-time (org-parse-time-string ts))))
  14443. (default-input (and ts (org-get-compact-tod ts)))
  14444. (repeater (and ts
  14445. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  14446. (match-string 0 ts)))
  14447. org-time-was-given
  14448. org-end-time-was-given
  14449. (time
  14450. (and (if (equal arg '(16)) (current-time)
  14451. ;; Preserve `this-command' and `last-command'.
  14452. (let ((this-command this-command)
  14453. (last-command last-command))
  14454. (org-read-date
  14455. arg 'totime nil nil default-time default-input
  14456. inactive))))))
  14457. (cond
  14458. ((and ts
  14459. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  14460. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  14461. (insert "--")
  14462. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  14463. (ts
  14464. ;; Make sure we're on a timestamp. When in the middle of a date
  14465. ;; range, move arbitrarily to range end.
  14466. (unless (org-at-timestamp-p 'lax)
  14467. (skip-chars-forward "-")
  14468. (org-at-timestamp-p 'lax))
  14469. (replace-match "")
  14470. (setq org-last-changed-timestamp
  14471. (org-insert-time-stamp
  14472. time (or org-time-was-given arg)
  14473. inactive nil nil (list org-end-time-was-given)))
  14474. (when repeater
  14475. (backward-char)
  14476. (insert " " repeater)
  14477. (setq org-last-changed-timestamp
  14478. (concat (substring org-last-inserted-timestamp 0 -1)
  14479. " " repeater ">")))
  14480. (message "Timestamp updated"))
  14481. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  14482. (t (org-insert-time-stamp
  14483. time (or org-time-was-given arg) inactive nil nil
  14484. (list org-end-time-was-given))))))
  14485. ;; FIXME: can we use this for something else, like computing time differences?
  14486. (defun org-get-compact-tod (s)
  14487. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  14488. (let* ((t1 (match-string 1 s))
  14489. (h1 (string-to-number (match-string 2 s)))
  14490. (m1 (string-to-number (match-string 3 s)))
  14491. (t2 (and (match-end 4) (match-string 5 s)))
  14492. (h2 (and t2 (string-to-number (match-string 6 s))))
  14493. (m2 (and t2 (string-to-number (match-string 7 s))))
  14494. dh dm)
  14495. (if (not t2)
  14496. t1
  14497. (setq dh (- h2 h1) dm (- m2 m1))
  14498. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  14499. (concat t1 "+" (number-to-string dh)
  14500. (and (/= 0 dm) (format ":%02d" dm)))))))
  14501. (defun org-time-stamp-inactive (&optional arg)
  14502. "Insert an inactive time stamp.
  14503. An inactive time stamp is enclosed in square brackets instead of angle
  14504. brackets. It is inactive in the sense that it does not trigger agenda entries,
  14505. does not link to the calendar and cannot be changed with the S-cursor keys.
  14506. So these are more for recording a certain time/date.
  14507. If the user specifies a time like HH:MM or if this command is called with
  14508. at least one prefix argument, the time stamp contains the date and the time.
  14509. Otherwise, only the date is included.
  14510. When called with two universal prefix arguments, insert an active time stamp
  14511. with the current time without prompting the user."
  14512. (interactive "P")
  14513. (org-time-stamp arg 'inactive))
  14514. (defvar org-date-ovl (make-overlay 1 1))
  14515. (overlay-put org-date-ovl 'face 'org-date-selected)
  14516. (delete-overlay org-date-ovl)
  14517. (defvar org-ans1) ; dynamically scoped parameter
  14518. (defvar org-ans2) ; dynamically scoped parameter
  14519. (defvar org-plain-time-of-day-regexp) ; defined below
  14520. (defvar org-overriding-default-time nil) ; dynamically scoped
  14521. (defvar org-read-date-overlay nil)
  14522. (defvar org-dcst nil) ; dynamically scoped
  14523. (defvar org-read-date-history nil)
  14524. (defvar org-read-date-final-answer nil)
  14525. (defvar org-read-date-analyze-futurep nil)
  14526. (defvar org-read-date-analyze-forced-year nil)
  14527. (defvar org-read-date-inactive)
  14528. (defvar org-def)
  14529. (defvar org-defdecode)
  14530. (defvar org-with-time)
  14531. (defvar calendar-setup) ; Dynamically scoped.
  14532. (defun org-read-date (&optional with-time to-time from-string prompt
  14533. default-time default-input inactive)
  14534. "Read a date, possibly a time, and make things smooth for the user.
  14535. The prompt will suggest to enter an ISO date, but you can also enter anything
  14536. which will at least partially be understood by `parse-time-string'.
  14537. Unrecognized parts of the date will default to the current day, month, year,
  14538. hour and minute. If this command is called to replace a timestamp at point,
  14539. or to enter the second timestamp of a range, the default time is taken
  14540. from the existing stamp. Furthermore, the command prefers the future,
  14541. so if you are giving a date where the year is not given, and the day-month
  14542. combination is already past in the current year, it will assume you
  14543. mean next year. For details, see the manual. A few examples:
  14544. 3-2-5 --> 2003-02-05
  14545. feb 15 --> currentyear-02-15
  14546. 2/15 --> currentyear-02-15
  14547. sep 12 9 --> 2009-09-12
  14548. 12:45 --> today 12:45
  14549. 22 sept 0:34 --> currentyear-09-22 0:34
  14550. 12 --> currentyear-currentmonth-12
  14551. Fri --> nearest Friday after today
  14552. -Tue --> last Tuesday
  14553. etc.
  14554. Furthermore you can specify a relative date by giving, as the *first* thing
  14555. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  14556. change in days weeks, months, years.
  14557. With a single plus or minus, the date is relative to today. With a double
  14558. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  14559. +4d --> four days from today
  14560. +4 --> same as above
  14561. +2w --> two weeks from today
  14562. ++5 --> five days from default date
  14563. The function understands only English month and weekday abbreviations.
  14564. While prompting, a calendar is popped up - you can also select the
  14565. date with the mouse (button 1). The calendar shows a period of three
  14566. months. To scroll it to other months, use the keys `>' and `<'.
  14567. If you don't like the calendar, turn it off with
  14568. (setq org-read-date-popup-calendar nil)
  14569. With optional argument TO-TIME, the date will immediately be converted
  14570. to an internal time.
  14571. With an optional argument WITH-TIME, the prompt will suggest to
  14572. also insert a time. Note that when WITH-TIME is not set, you can
  14573. still enter a time, and this function will inform the calling routine
  14574. about this change. The calling routine may then choose to change the
  14575. format used to insert the time stamp into the buffer to include the time.
  14576. With optional argument FROM-STRING, read from this string instead from
  14577. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  14578. the time/date that is used for everything that is not specified by the
  14579. user."
  14580. (require 'parse-time)
  14581. (let* ((org-with-time with-time)
  14582. (org-time-stamp-rounding-minutes
  14583. (if (equal org-with-time '(16))
  14584. '(0 0)
  14585. org-time-stamp-rounding-minutes))
  14586. (org-dcst org-display-custom-times)
  14587. (ct (org-current-time))
  14588. (org-def (or org-overriding-default-time default-time ct))
  14589. (org-defdecode (decode-time org-def))
  14590. (cur-frame (selected-frame))
  14591. (mouse-autoselect-window nil) ; Don't let the mouse jump
  14592. (calendar-setup
  14593. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  14594. (calendar-move-hook nil)
  14595. (calendar-view-diary-initially-flag nil)
  14596. (calendar-view-holidays-initially-flag nil)
  14597. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  14598. ;; Rationalize `org-def' and `org-defdecode', if required.
  14599. (when (< (nth 2 org-defdecode) org-extend-today-until)
  14600. (setf (nth 2 org-defdecode) -1)
  14601. (setf (nth 1 org-defdecode) 59)
  14602. (setq org-def (apply #'encode-time org-defdecode))
  14603. (setq org-defdecode (decode-time org-def)))
  14604. (let* ((timestr (format-time-string
  14605. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  14606. org-def))
  14607. (prompt (concat (if prompt (concat prompt " ") "")
  14608. (format "Date+time [%s]: " timestr))))
  14609. (cond
  14610. (from-string (setq ans from-string))
  14611. (org-read-date-popup-calendar
  14612. (save-excursion
  14613. (save-window-excursion
  14614. (calendar)
  14615. (when (eq calendar-setup 'calendar-only)
  14616. (setq cal-frame
  14617. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  14618. (select-frame cal-frame))
  14619. (org-eval-in-calendar '(setq cursor-type nil) t)
  14620. (unwind-protect
  14621. (progn
  14622. (calendar-forward-day (- (time-to-days org-def)
  14623. (calendar-absolute-from-gregorian
  14624. (calendar-current-date))))
  14625. (org-eval-in-calendar nil t)
  14626. (let* ((old-map (current-local-map))
  14627. (map (copy-keymap calendar-mode-map))
  14628. (minibuffer-local-map
  14629. (copy-keymap org-read-date-minibuffer-local-map)))
  14630. (org-defkey map (kbd "RET") 'org-calendar-select)
  14631. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  14632. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  14633. (unwind-protect
  14634. (progn
  14635. (use-local-map map)
  14636. (setq org-read-date-inactive inactive)
  14637. (add-hook 'post-command-hook 'org-read-date-display)
  14638. (setq org-ans0
  14639. (read-string prompt
  14640. default-input
  14641. 'org-read-date-history
  14642. nil))
  14643. ;; org-ans0: from prompt
  14644. ;; org-ans1: from mouse click
  14645. ;; org-ans2: from calendar motion
  14646. (setq ans
  14647. (concat org-ans0 " " (or org-ans1 org-ans2))))
  14648. (remove-hook 'post-command-hook 'org-read-date-display)
  14649. (use-local-map old-map)
  14650. (when org-read-date-overlay
  14651. (delete-overlay org-read-date-overlay)
  14652. (setq org-read-date-overlay nil)))))
  14653. (bury-buffer "*Calendar*")
  14654. (when cal-frame
  14655. (delete-frame cal-frame)
  14656. (select-frame-set-input-focus cur-frame))))))
  14657. (t ; Naked prompt only
  14658. (unwind-protect
  14659. (setq ans (read-string prompt default-input
  14660. 'org-read-date-history timestr))
  14661. (when org-read-date-overlay
  14662. (delete-overlay org-read-date-overlay)
  14663. (setq org-read-date-overlay nil))))))
  14664. (setq final (org-read-date-analyze ans org-def org-defdecode))
  14665. (when org-read-date-analyze-forced-year
  14666. (message "Year was forced into %s"
  14667. (if org-read-date-force-compatible-dates
  14668. "compatible range (1970-2037)"
  14669. "range representable on this machine"))
  14670. (ding))
  14671. ;; One round trip to get rid of 34th of August and stuff like that....
  14672. (setq final (decode-time (apply 'encode-time final)))
  14673. (setq org-read-date-final-answer ans)
  14674. (if to-time
  14675. (apply 'encode-time final)
  14676. (if (and (boundp 'org-time-was-given) org-time-was-given)
  14677. (format "%04d-%02d-%02d %02d:%02d"
  14678. (nth 5 final) (nth 4 final) (nth 3 final)
  14679. (nth 2 final) (nth 1 final))
  14680. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  14681. (defun org-read-date-display ()
  14682. "Display the current date prompt interpretation in the minibuffer."
  14683. (when org-read-date-display-live
  14684. (when org-read-date-overlay
  14685. (delete-overlay org-read-date-overlay))
  14686. (when (minibufferp (current-buffer))
  14687. (save-excursion
  14688. (end-of-line 1)
  14689. (while (not (equal (buffer-substring
  14690. (max (point-min) (- (point) 4)) (point))
  14691. " "))
  14692. (insert " ")))
  14693. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  14694. " " (or org-ans1 org-ans2)))
  14695. (org-end-time-was-given nil)
  14696. (f (org-read-date-analyze ans org-def org-defdecode))
  14697. (fmts (if org-dcst
  14698. org-time-stamp-custom-formats
  14699. org-time-stamp-formats))
  14700. (fmt (if (or org-with-time
  14701. (and (boundp 'org-time-was-given) org-time-was-given))
  14702. (cdr fmts)
  14703. (car fmts)))
  14704. (txt (format-time-string fmt (apply 'encode-time f)))
  14705. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  14706. (txt (concat "=> " txt)))
  14707. (when (and org-end-time-was-given
  14708. (string-match org-plain-time-of-day-regexp txt))
  14709. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  14710. org-end-time-was-given
  14711. (substring txt (match-end 0)))))
  14712. (when org-read-date-analyze-futurep
  14713. (setq txt (concat txt " (=>F)")))
  14714. (setq org-read-date-overlay
  14715. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  14716. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  14717. (defun org-read-date-analyze (ans def defdecode)
  14718. "Analyze the combined answer of the date prompt."
  14719. ;; FIXME: cleanup and comment
  14720. ;; Pass `current-time' result to `decode-time' (instead of calling
  14721. ;; without arguments) so that only `current-time' has to be
  14722. ;; overridden in tests.
  14723. (let ((org-def def)
  14724. (org-defdecode defdecode)
  14725. (nowdecode (decode-time (current-time)))
  14726. delta deltan deltaw deltadef year month day
  14727. hour minute second wday pm h2 m2 tl wday1
  14728. iso-year iso-weekday iso-week iso-date futurep kill-year)
  14729. (setq org-read-date-analyze-futurep nil
  14730. org-read-date-analyze-forced-year nil)
  14731. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  14732. (setq ans "+0"))
  14733. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  14734. (setq ans (replace-match "" t t ans)
  14735. deltan (car delta)
  14736. deltaw (nth 1 delta)
  14737. deltadef (nth 2 delta)))
  14738. ;; Check if there is an iso week date in there. If yes, store the
  14739. ;; info and postpone interpreting it until the rest of the parsing
  14740. ;; is done.
  14741. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  14742. (setq iso-year (when (match-end 1)
  14743. (org-small-year-to-year
  14744. (string-to-number (match-string 1 ans))))
  14745. iso-weekday (when (match-end 3)
  14746. (string-to-number (match-string 3 ans)))
  14747. iso-week (string-to-number (match-string 2 ans)))
  14748. (setq ans (replace-match "" t t ans)))
  14749. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  14750. (when (string-match
  14751. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  14752. (setq year (if (match-end 2)
  14753. (string-to-number (match-string 2 ans))
  14754. (progn (setq kill-year t)
  14755. (string-to-number (format-time-string "%Y"))))
  14756. month (string-to-number (match-string 3 ans))
  14757. day (string-to-number (match-string 4 ans)))
  14758. (setq year (org-small-year-to-year year))
  14759. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14760. t nil ans)))
  14761. ;; Help matching dotted european dates
  14762. (when (string-match
  14763. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  14764. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  14765. (setq kill-year t)
  14766. (string-to-number (format-time-string "%Y")))
  14767. day (string-to-number (match-string 1 ans))
  14768. month (string-to-number (match-string 2 ans))
  14769. ans (replace-match (format "%04d-%02d-%02d" year month day)
  14770. t nil ans)))
  14771. ;; Help matching american dates, like 5/30 or 5/30/7
  14772. (when (string-match
  14773. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  14774. (setq year (if (match-end 4)
  14775. (string-to-number (match-string 4 ans))
  14776. (progn (setq kill-year t)
  14777. (string-to-number (format-time-string "%Y"))))
  14778. month (string-to-number (match-string 1 ans))
  14779. day (string-to-number (match-string 2 ans)))
  14780. (setq year (org-small-year-to-year year))
  14781. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14782. t nil ans)))
  14783. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  14784. ;; If there is a time with am/pm, and *no* time without it, we convert
  14785. ;; so that matching will be successful.
  14786. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  14787. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  14788. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  14789. (setq hour (string-to-number (match-string 1 ans))
  14790. minute (if (match-end 3)
  14791. (string-to-number (match-string 3 ans))
  14792. 0)
  14793. pm (equal ?p
  14794. (string-to-char (downcase (match-string 4 ans)))))
  14795. (if (and (= hour 12) (not pm))
  14796. (setq hour 0)
  14797. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  14798. (setq ans (replace-match (format "%02d:%02d" hour minute)
  14799. t t ans))))
  14800. ;; Check if a time range is given as a duration
  14801. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  14802. (setq hour (string-to-number (match-string 1 ans))
  14803. h2 (+ hour (string-to-number (match-string 3 ans)))
  14804. minute (string-to-number (match-string 2 ans))
  14805. m2 (+ minute (if (match-end 5) (string-to-number
  14806. (match-string 5 ans))0)))
  14807. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  14808. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  14809. t t ans)))
  14810. ;; Check if there is a time range
  14811. (when (boundp 'org-end-time-was-given)
  14812. (setq org-time-was-given nil)
  14813. (when (and (string-match org-plain-time-of-day-regexp ans)
  14814. (match-end 8))
  14815. (setq org-end-time-was-given (match-string 8 ans))
  14816. (setq ans (concat (substring ans 0 (match-beginning 7))
  14817. (substring ans (match-end 7))))))
  14818. (setq tl (parse-time-string ans)
  14819. day (or (nth 3 tl) (nth 3 org-defdecode))
  14820. month
  14821. (cond ((nth 4 tl))
  14822. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  14823. ;; Day was specified. Make sure DAY+MONTH
  14824. ;; combination happens in the future.
  14825. ((nth 3 tl)
  14826. (setq futurep t)
  14827. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  14828. (nth 4 nowdecode)))
  14829. (t (nth 4 org-defdecode)))
  14830. year
  14831. (cond ((and (not kill-year) (nth 5 tl)))
  14832. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  14833. ;; Month was guessed in the future and is at least
  14834. ;; equal to NOWDECODE's. Fix year accordingly.
  14835. (futurep
  14836. (if (or (> month (nth 4 nowdecode))
  14837. (>= day (nth 3 nowdecode)))
  14838. (nth 5 nowdecode)
  14839. (1+ (nth 5 nowdecode))))
  14840. ;; Month was specified. Make sure MONTH+YEAR
  14841. ;; combination happens in the future.
  14842. ((nth 4 tl)
  14843. (setq futurep t)
  14844. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  14845. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  14846. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  14847. (t (nth 5 nowdecode))))
  14848. (t (nth 5 org-defdecode)))
  14849. hour (or (nth 2 tl) (nth 2 org-defdecode))
  14850. minute (or (nth 1 tl) (nth 1 org-defdecode))
  14851. second (or (nth 0 tl) 0)
  14852. wday (nth 6 tl))
  14853. (when (and (eq org-read-date-prefer-future 'time)
  14854. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  14855. (equal day (nth 3 nowdecode))
  14856. (equal month (nth 4 nowdecode))
  14857. (equal year (nth 5 nowdecode))
  14858. (nth 2 tl)
  14859. (or (< (nth 2 tl) (nth 2 nowdecode))
  14860. (and (= (nth 2 tl) (nth 2 nowdecode))
  14861. (nth 1 tl)
  14862. (< (nth 1 tl) (nth 1 nowdecode)))))
  14863. (setq day (1+ day)
  14864. futurep t))
  14865. ;; Special date definitions below
  14866. (cond
  14867. (iso-week
  14868. ;; There was an iso week
  14869. (require 'cal-iso)
  14870. (setq futurep nil)
  14871. (setq year (or iso-year year)
  14872. day (or iso-weekday wday 1)
  14873. wday nil ; to make sure that the trigger below does not match
  14874. iso-date (calendar-gregorian-from-absolute
  14875. (calendar-iso-to-absolute
  14876. (list iso-week day year))))
  14877. ; FIXME: Should we also push ISO weeks into the future?
  14878. ; (when (and org-read-date-prefer-future
  14879. ; (not iso-year)
  14880. ; (< (calendar-absolute-from-gregorian iso-date)
  14881. ; (time-to-days (current-time))))
  14882. ; (setq year (1+ year)
  14883. ; iso-date (calendar-gregorian-from-absolute
  14884. ; (calendar-iso-to-absolute
  14885. ; (list iso-week day year)))))
  14886. (setq month (car iso-date)
  14887. year (nth 2 iso-date)
  14888. day (nth 1 iso-date)))
  14889. (deltan
  14890. (setq futurep nil)
  14891. (unless deltadef
  14892. ;; Pass `current-time' result to `decode-time' (instead of
  14893. ;; calling without arguments) so that only `current-time' has
  14894. ;; to be overridden in tests.
  14895. (let ((now (decode-time (current-time))))
  14896. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  14897. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  14898. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  14899. ((equal deltaw "m") (setq month (+ month deltan)))
  14900. ((equal deltaw "y") (setq year (+ year deltan)))))
  14901. ((and wday (not (nth 3 tl)))
  14902. ;; Weekday was given, but no day, so pick that day in the week
  14903. ;; on or after the derived date.
  14904. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  14905. (unless (equal wday wday1)
  14906. (setq day (+ day (% (- wday wday1 -7) 7))))))
  14907. (when (and (boundp 'org-time-was-given)
  14908. (nth 2 tl))
  14909. (setq org-time-was-given t))
  14910. (when (< year 100) (setq year (+ 2000 year)))
  14911. ;; Check of the date is representable
  14912. (if org-read-date-force-compatible-dates
  14913. (progn
  14914. (when (< year 1970)
  14915. (setq year 1970 org-read-date-analyze-forced-year t))
  14916. (when (> year 2037)
  14917. (setq year 2037 org-read-date-analyze-forced-year t)))
  14918. (condition-case nil
  14919. (ignore (encode-time second minute hour day month year))
  14920. (error
  14921. (setq year (nth 5 org-defdecode))
  14922. (setq org-read-date-analyze-forced-year t))))
  14923. (setq org-read-date-analyze-futurep futurep)
  14924. (list second minute hour day month year)))
  14925. (defvar parse-time-weekdays)
  14926. (defun org-read-date-get-relative (s today default)
  14927. "Check string S for special relative date string.
  14928. TODAY and DEFAULT are internal times, for today and for a default.
  14929. Return shift list (N what def-flag)
  14930. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  14931. N is the number of WHATs to shift.
  14932. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  14933. the DEFAULT date rather than TODAY."
  14934. (require 'parse-time)
  14935. (when (and
  14936. (string-match
  14937. (concat
  14938. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  14939. "\\([0-9]+\\)?"
  14940. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  14941. "\\([ \t]\\|$\\)") s)
  14942. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  14943. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  14944. (string-to-char (substring (match-string 1 s) -1))
  14945. ?+))
  14946. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  14947. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  14948. (what (if (match-end 3) (match-string 3 s) "d"))
  14949. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  14950. (date (if rel default today))
  14951. (wday (nth 6 (decode-time date)))
  14952. delta)
  14953. (if wday1
  14954. (progn
  14955. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  14956. (when (= delta 0) (setq delta 7))
  14957. (when (= dir ?-)
  14958. (setq delta (- delta 7))
  14959. (when (= delta 0) (setq delta -7)))
  14960. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  14961. (list delta "d" rel))
  14962. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  14963. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  14964. "Turn a user-specified date into the internal representation.
  14965. The internal representation needed by the calendar is (month day year).
  14966. This is a wrapper to handle the brain-dead convention in calendar that
  14967. user function argument order change dependent on argument order."
  14968. (pcase calendar-date-style
  14969. (`american (list arg1 arg2 arg3))
  14970. (`european (list arg2 arg1 arg3))
  14971. (`iso (list arg2 arg3 arg1))))
  14972. (defun org-eval-in-calendar (form &optional keepdate)
  14973. "Eval FORM in the calendar window and return to current window.
  14974. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  14975. (let ((sf (selected-frame))
  14976. (sw (selected-window)))
  14977. (select-window (get-buffer-window "*Calendar*" t))
  14978. (eval form)
  14979. (when (and (not keepdate) (calendar-cursor-to-date))
  14980. (let* ((date (calendar-cursor-to-date))
  14981. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  14982. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  14983. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  14984. (select-window sw)
  14985. (select-frame-set-input-focus sf)))
  14986. (defun org-calendar-select ()
  14987. "Return to `org-read-date' with the date currently selected.
  14988. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  14989. (interactive)
  14990. (when (calendar-cursor-to-date)
  14991. (let* ((date (calendar-cursor-to-date))
  14992. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  14993. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  14994. (when (active-minibuffer-window) (exit-minibuffer))))
  14995. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  14996. "Insert a date stamp for the date given by the internal TIME.
  14997. See `format-time-string' for the format of TIME.
  14998. WITH-HM means use the stamp format that includes the time of the day.
  14999. INACTIVE means use square brackets instead of angular ones, so that the
  15000. stamp will not contribute to the agenda.
  15001. PRE and POST are optional strings to be inserted before and after the
  15002. stamp.
  15003. The command returns the inserted time stamp."
  15004. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15005. stamp)
  15006. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15007. (insert-before-markers (or pre ""))
  15008. (when (listp extra)
  15009. (setq extra (car extra))
  15010. (if (and (stringp extra)
  15011. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15012. (setq extra (format "-%02d:%02d"
  15013. (string-to-number (match-string 1 extra))
  15014. (string-to-number (match-string 2 extra))))
  15015. (setq extra nil)))
  15016. (when extra
  15017. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15018. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15019. (insert-before-markers (or post ""))
  15020. (setq org-last-inserted-timestamp stamp)))
  15021. (defun org-toggle-time-stamp-overlays ()
  15022. "Toggle the use of custom time stamp formats."
  15023. (interactive)
  15024. (setq org-display-custom-times (not org-display-custom-times))
  15025. (unless org-display-custom-times
  15026. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15027. (while (setq p (next-single-property-change p 'display))
  15028. (when (and (get-text-property p 'display)
  15029. (eq (get-text-property p 'face) 'org-date))
  15030. (remove-text-properties
  15031. p (setq p (next-single-property-change p 'display))
  15032. '(display t))))
  15033. (set-buffer-modified-p bmp)))
  15034. (org-restart-font-lock)
  15035. (setq org-table-may-need-update t)
  15036. (if org-display-custom-times
  15037. (message "Time stamps are overlaid with custom format")
  15038. (message "Time stamp overlays removed")))
  15039. (defun org-display-custom-time (beg end)
  15040. "Overlay modified time stamp format over timestamp between BEG and END."
  15041. (let* ((ts (buffer-substring beg end))
  15042. t1 with-hm tf time str (off 0))
  15043. (save-match-data
  15044. (setq t1 (org-parse-time-string ts t))
  15045. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15046. (setq off (- (match-end 0) (match-beginning 0)))))
  15047. (setq end (- end off))
  15048. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  15049. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15050. time (org-fix-decoded-time t1)
  15051. str (org-add-props
  15052. (format-time-string
  15053. (substring tf 1 -1) (apply 'encode-time time))
  15054. nil 'mouse-face 'highlight))
  15055. (put-text-property beg end 'display str)))
  15056. (defun org-fix-decoded-time (time)
  15057. "Set 0 instead of nil for the first 6 elements of time.
  15058. Don't touch the rest."
  15059. (let ((n 0))
  15060. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15061. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15062. "Difference between TIMESTAMP-STRING and now in days.
  15063. If SECONDS is non-nil, return the difference in seconds."
  15064. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15065. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15066. (funcall fdiff (current-time)))))
  15067. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15068. "Is the time in TIMESTAMP-STRING close to the current date?"
  15069. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15070. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15071. (not (org-entry-is-done-p))))
  15072. (defun org-get-wdays (ts &optional delay zero-delay)
  15073. "Get the deadline lead time appropriate for timestring TS.
  15074. When DELAY is non-nil, get the delay time for scheduled items
  15075. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15076. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15077. don't try to find the delay cookie in the scheduled timestamp."
  15078. (let ((tv (if delay org-scheduled-delay-days
  15079. org-deadline-warning-days)))
  15080. (cond
  15081. ((or (and delay (< tv 0))
  15082. (and delay zero-delay (<= tv 0))
  15083. (and (not delay) (<= tv 0)))
  15084. ;; Enforce this value no matter what
  15085. (- tv))
  15086. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15087. ;; lead time is specified.
  15088. (floor (* (string-to-number (match-string 1 ts))
  15089. (cdr (assoc (match-string 2 ts)
  15090. '(("d" . 1) ("w" . 7)
  15091. ("m" . 30.4) ("y" . 365.25)
  15092. ("h" . 0.041667)))))))
  15093. ;; go for the default.
  15094. (t tv))))
  15095. (defun org-calendar-select-mouse (ev)
  15096. "Return to `org-read-date' with the date currently selected.
  15097. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15098. (interactive "e")
  15099. (mouse-set-point ev)
  15100. (when (calendar-cursor-to-date)
  15101. (let* ((date (calendar-cursor-to-date))
  15102. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15103. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15104. (when (active-minibuffer-window) (exit-minibuffer))))
  15105. (defun org-check-deadlines (ndays)
  15106. "Check if there are any deadlines due or past due.
  15107. A deadline is considered due if it happens within `org-deadline-warning-days'
  15108. days from today's date. If the deadline appears in an entry marked DONE,
  15109. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15110. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15111. are shown."
  15112. (interactive "P")
  15113. (let* ((org-warn-days
  15114. (cond
  15115. ((equal ndays '(4)) 100000)
  15116. (ndays (prefix-numeric-value ndays))
  15117. (t (abs org-deadline-warning-days))))
  15118. (case-fold-search nil)
  15119. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15120. (callback
  15121. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15122. (message "%d deadlines past-due or due within %d days"
  15123. (org-occur regexp nil callback)
  15124. org-warn-days)))
  15125. (defsubst org-re-timestamp (type)
  15126. "Return a regexp for timestamp TYPE.
  15127. Allowed values for TYPE are:
  15128. all: all timestamps
  15129. active: only active timestamps (<...>)
  15130. inactive: only inactive timestamps ([...])
  15131. scheduled: only scheduled timestamps
  15132. deadline: only deadline timestamps
  15133. closed: only closed time-stamps
  15134. When TYPE is nil, fall back on returning a regexp that matches
  15135. both scheduled and deadline timestamps."
  15136. (cl-case type
  15137. (all org-ts-regexp-both)
  15138. (active org-ts-regexp)
  15139. (inactive org-ts-regexp-inactive)
  15140. (scheduled org-scheduled-time-regexp)
  15141. (deadline org-deadline-time-regexp)
  15142. (closed org-closed-time-regexp)
  15143. (otherwise
  15144. (concat "\\<"
  15145. (regexp-opt (list org-deadline-string org-scheduled-string))
  15146. " *<\\([^>]+\\)>"))))
  15147. (defun org-check-before-date (d)
  15148. "Check if there are deadlines or scheduled entries before date D."
  15149. (interactive (list (org-read-date)))
  15150. (let* ((case-fold-search nil)
  15151. (regexp (org-re-timestamp org-ts-type))
  15152. (ts-type org-ts-type)
  15153. (callback
  15154. (lambda ()
  15155. (let ((match (match-string 1)))
  15156. (and (if (memq ts-type '(active inactive all))
  15157. (eq (org-element-type (save-excursion
  15158. (backward-char)
  15159. (org-element-context)))
  15160. 'timestamp)
  15161. (org-at-planning-p))
  15162. (time-less-p
  15163. (org-time-string-to-time match)
  15164. (org-time-string-to-time d)))))))
  15165. (message "%d entries before %s"
  15166. (org-occur regexp nil callback)
  15167. d)))
  15168. (defun org-check-after-date (d)
  15169. "Check if there are deadlines or scheduled entries after date D."
  15170. (interactive (list (org-read-date)))
  15171. (let* ((case-fold-search nil)
  15172. (regexp (org-re-timestamp org-ts-type))
  15173. (ts-type org-ts-type)
  15174. (callback
  15175. (lambda ()
  15176. (let ((match (match-string 1)))
  15177. (and (if (memq ts-type '(active inactive all))
  15178. (eq (org-element-type (save-excursion
  15179. (backward-char)
  15180. (org-element-context)))
  15181. 'timestamp)
  15182. (org-at-planning-p))
  15183. (not (time-less-p
  15184. (org-time-string-to-time match)
  15185. (org-time-string-to-time d))))))))
  15186. (message "%d entries after %s"
  15187. (org-occur regexp nil callback)
  15188. d)))
  15189. (defun org-check-dates-range (start-date end-date)
  15190. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15191. (interactive (list (org-read-date nil nil nil "Range starts")
  15192. (org-read-date nil nil nil "Range end")))
  15193. (let ((case-fold-search nil)
  15194. (regexp (org-re-timestamp org-ts-type))
  15195. (callback
  15196. (let ((type org-ts-type))
  15197. (lambda ()
  15198. (let ((match (match-string 1)))
  15199. (and
  15200. (if (memq type '(active inactive all))
  15201. (eq (org-element-type (save-excursion
  15202. (backward-char)
  15203. (org-element-context)))
  15204. 'timestamp)
  15205. (org-at-planning-p))
  15206. (not (time-less-p
  15207. (org-time-string-to-time match)
  15208. (org-time-string-to-time start-date)))
  15209. (time-less-p
  15210. (org-time-string-to-time match)
  15211. (org-time-string-to-time end-date))))))))
  15212. (message "%d entries between %s and %s"
  15213. (org-occur regexp nil callback) start-date end-date)))
  15214. (defun org-evaluate-time-range (&optional to-buffer)
  15215. "Evaluate a time range by computing the difference between start and end.
  15216. Normally the result is just printed in the echo area, but with prefix arg
  15217. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15218. If the time range is actually in a table, the result is inserted into the
  15219. next column.
  15220. For time difference computation, a year is assumed to be exactly 365
  15221. days in order to avoid rounding problems."
  15222. (interactive "P")
  15223. (or
  15224. (org-clock-update-time-maybe)
  15225. (save-excursion
  15226. (unless (org-at-date-range-p t)
  15227. (goto-char (point-at-bol))
  15228. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  15229. (unless (org-at-date-range-p t)
  15230. (user-error "Not at a time-stamp range, and none found in current line")))
  15231. (let* ((ts1 (match-string 1))
  15232. (ts2 (match-string 2))
  15233. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  15234. (match-end (match-end 0))
  15235. (time1 (org-time-string-to-time ts1))
  15236. (time2 (org-time-string-to-time ts2))
  15237. (t1 (float-time time1))
  15238. (t2 (float-time time2))
  15239. (diff (abs (- t2 t1)))
  15240. (negative (< (- t2 t1) 0))
  15241. ;; (ys (floor (* 365 24 60 60)))
  15242. (ds (* 24 60 60))
  15243. (hs (* 60 60))
  15244. (fy "%dy %dd %02d:%02d")
  15245. (fy1 "%dy %dd")
  15246. (fd "%dd %02d:%02d")
  15247. (fd1 "%dd")
  15248. (fh "%02d:%02d")
  15249. y d h m align)
  15250. (if havetime
  15251. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15252. y 0
  15253. d (floor (/ diff ds)) diff (mod diff ds)
  15254. h (floor (/ diff hs)) diff (mod diff hs)
  15255. m (floor (/ diff 60)))
  15256. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15257. y 0
  15258. d (floor (+ (/ diff ds) 0.5))
  15259. h 0 m 0))
  15260. (if (not to-buffer)
  15261. (message "%s" (org-make-tdiff-string y d h m))
  15262. (if (org-at-table-p)
  15263. (progn
  15264. (goto-char match-end)
  15265. (setq align t)
  15266. (and (looking-at " *|") (goto-char (match-end 0))))
  15267. (goto-char match-end))
  15268. (when (looking-at
  15269. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  15270. (replace-match ""))
  15271. (when negative (insert " -"))
  15272. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  15273. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  15274. (insert " " (format fh h m))))
  15275. (when align (org-table-align))
  15276. (message "Time difference inserted")))))
  15277. (defun org-make-tdiff-string (y d h m)
  15278. (let ((fmt "")
  15279. (l nil))
  15280. (when (> y 0)
  15281. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  15282. (push y l))
  15283. (when (> d 0)
  15284. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  15285. (push d l))
  15286. (when (> h 0)
  15287. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  15288. (push h l))
  15289. (when (> m 0)
  15290. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  15291. (push m l))
  15292. (apply 'format fmt (nreverse l))))
  15293. (defun org-time-string-to-time (s)
  15294. "Convert timestamp string S into internal time."
  15295. (apply #'encode-time (org-parse-time-string s)))
  15296. (defun org-time-string-to-seconds (s)
  15297. "Convert a timestamp string S into a number of seconds."
  15298. (float-time (org-time-string-to-time s)))
  15299. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  15300. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  15301. "Convert time stamp S to an absolute day number.
  15302. If DAYNR in non-nil, and there is a specifier for a cyclic time
  15303. stamp, get the closest date to DAYNR. If PREFER is
  15304. `past' (respectively `future') return a date past (respectively
  15305. after) or equal to DAYNR.
  15306. POS is the location of time stamp S, as a buffer position in
  15307. BUFFER.
  15308. Diary sexp timestamps are matched against DAYNR, when non-nil.
  15309. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  15310. signaled."
  15311. (cond
  15312. ((string-match "\\`%%\\((.*)\\)" s)
  15313. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  15314. ;; only able to match individual dates. If it fails, raise an
  15315. ;; error.
  15316. (if (and daynr
  15317. (org-diary-sexp-entry
  15318. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  15319. daynr
  15320. (signal 'org-diary-sexp-no-match (list s))))
  15321. (daynr (org-closest-date s daynr prefer))
  15322. (t (time-to-days
  15323. (condition-case errdata
  15324. (apply #'encode-time (org-parse-time-string s))
  15325. (error (error "Bad timestamp `%s'%s\nError was: %s"
  15326. s
  15327. (if (not (and buffer pos)) ""
  15328. (format-message " at %d in buffer `%s'" pos buffer))
  15329. (cdr errdata))))))))
  15330. (defun org-days-to-iso-week (days)
  15331. "Return the iso week number."
  15332. (require 'cal-iso)
  15333. (car (calendar-iso-from-absolute days)))
  15334. (defun org-small-year-to-year (year)
  15335. "Convert 2-digit years into 4-digit years.
  15336. YEAR is expanded into one of the 30 next years, if possible, or
  15337. into a past one. Any year larger than 99 is returned unchanged."
  15338. (if (>= year 100) year
  15339. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  15340. (century (/ current 100))
  15341. (offset (- year (% current 100))))
  15342. (cond ((> offset 30) (+ (* (1- century) 100) year))
  15343. ((> offset -70) (+ (* century 100) year))
  15344. (t (+ (* (1+ century) 100) year))))))
  15345. (defun org-time-from-absolute (d)
  15346. "Return the time corresponding to date D.
  15347. D may be an absolute day number, or a calendar-type list (month day year)."
  15348. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  15349. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  15350. (defvar org-agenda-current-date)
  15351. (defun org-calendar-holiday ()
  15352. "List of holidays, for Diary display in Org mode."
  15353. (require 'holidays)
  15354. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  15355. (and hl (mapconcat #'identity hl "; "))))
  15356. (defun org-diary-sexp-entry (sexp entry d)
  15357. "Process a SEXP diary ENTRY for date D."
  15358. (require 'diary-lib)
  15359. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  15360. ;; dynamically.
  15361. (let* ((sexp `(let ((entry ,entry)
  15362. (date ',d))
  15363. ,(car (read-from-string sexp))))
  15364. (result (if calendar-debug-sexp (eval sexp)
  15365. (condition-case nil
  15366. (eval sexp)
  15367. (error
  15368. (beep)
  15369. (message "Bad sexp at line %d in %s: %s"
  15370. (org-current-line)
  15371. (buffer-file-name) sexp)
  15372. (sleep-for 2))))))
  15373. (cond ((stringp result) (split-string result "; "))
  15374. ((and (consp result)
  15375. (not (consp (cdr result)))
  15376. (stringp (cdr result))) (cdr result))
  15377. ((and (consp result)
  15378. (stringp (car result))) result)
  15379. (result entry))))
  15380. (defun org-diary-to-ical-string (frombuf)
  15381. "Get iCalendar entries from diary entries in buffer FROMBUF.
  15382. This uses the icalendar.el library."
  15383. (let* ((tmpdir temporary-file-directory)
  15384. (tmpfile (make-temp-name
  15385. (expand-file-name "orgics" tmpdir)))
  15386. buf rtn b e)
  15387. (with-current-buffer frombuf
  15388. (icalendar-export-region (point-min) (point-max) tmpfile)
  15389. (setq buf (find-buffer-visiting tmpfile))
  15390. (set-buffer buf)
  15391. (goto-char (point-min))
  15392. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  15393. (setq b (match-beginning 0)))
  15394. (goto-char (point-max))
  15395. (when (re-search-backward "^END:VEVENT" nil t)
  15396. (setq e (match-end 0)))
  15397. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  15398. (kill-buffer buf)
  15399. (delete-file tmpfile)
  15400. rtn))
  15401. (defun org-closest-date (start current prefer)
  15402. "Return closest date to CURRENT starting from START.
  15403. CURRENT and START are both time stamps.
  15404. When PREFER is `past', return a date that is either CURRENT or
  15405. past. When PREFER is `future', return a date that is either
  15406. CURRENT or future.
  15407. Only time stamps with a repeater are modified. Any other time
  15408. stamp stay unchanged. In any case, return value is an absolute
  15409. day number."
  15410. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  15411. ;; No repeater. Do not shift time stamp.
  15412. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15413. (let ((value (string-to-number (match-string 1 start)))
  15414. (type (match-string 2 start)))
  15415. (if (= 0 value)
  15416. ;; Repeater with a 0-value is considered as void.
  15417. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15418. (let* ((base (org-date-to-gregorian start))
  15419. (target (org-date-to-gregorian current))
  15420. (sday (calendar-absolute-from-gregorian base))
  15421. (cday (calendar-absolute-from-gregorian target))
  15422. n1 n2)
  15423. ;; If START is already past CURRENT, just return START.
  15424. (if (<= cday sday) sday
  15425. ;; Compute closest date before (N1) and closest date past
  15426. ;; (N2) CURRENT.
  15427. (pcase type
  15428. ("h"
  15429. (let ((missing-hours
  15430. (mod (+ (- (* 24 (- cday sday))
  15431. (nth 2 (org-parse-time-string start)))
  15432. org-extend-today-until)
  15433. value)))
  15434. (setf n1 (if (= missing-hours 0) cday
  15435. (- cday (1+ (/ missing-hours 24)))))
  15436. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  15437. ((or "d" "w")
  15438. (let ((value (if (equal type "w") (* 7 value) value)))
  15439. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  15440. (setf n2 (+ n1 value))))
  15441. ("m"
  15442. (let* ((add-months
  15443. (lambda (d n)
  15444. ;; Add N months to gregorian date D, i.e.,
  15445. ;; a list (MONTH DAY YEAR). Return a valid
  15446. ;; gregorian date.
  15447. (let ((m (+ (nth 0 d) n)))
  15448. (list (mod m 12)
  15449. (nth 1 d)
  15450. (+ (/ m 12) (nth 2 d))))))
  15451. (months ; Complete months to TARGET.
  15452. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  15453. (- (nth 0 target) (nth 0 base))
  15454. ;; If START's day is greater than
  15455. ;; TARGET's, remove incomplete month.
  15456. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  15457. value)
  15458. value))
  15459. (before (funcall add-months base months)))
  15460. (setf n1 (calendar-absolute-from-gregorian before))
  15461. (setf n2
  15462. (calendar-absolute-from-gregorian
  15463. (funcall add-months before value)))))
  15464. (_
  15465. (let* ((d (nth 1 base))
  15466. (m (nth 0 base))
  15467. (y (nth 2 base))
  15468. (years ; Complete years to TARGET.
  15469. (* (/ (- (nth 2 target)
  15470. y
  15471. ;; If START's month and day are
  15472. ;; greater than TARGET's, remove
  15473. ;; incomplete year.
  15474. (if (or (> (nth 0 target) m)
  15475. (and (= (nth 0 target) m)
  15476. (> (nth 1 target) d)))
  15477. 0
  15478. 1))
  15479. value)
  15480. value))
  15481. (before (list m d (+ y years))))
  15482. (setf n1 (calendar-absolute-from-gregorian before))
  15483. (setf n2 (calendar-absolute-from-gregorian
  15484. (list m d (+ (nth 2 before) value)))))))
  15485. ;; Handle PREFER parameter, if any.
  15486. (cond
  15487. ((eq prefer 'past) (if (= cday n2) n2 n1))
  15488. ((eq prefer 'future) (if (= cday n1) n1 n2))
  15489. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  15490. (defun org-date-to-gregorian (d)
  15491. "Turn any specification of date D into a Gregorian date for the calendar."
  15492. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  15493. ((and (listp d) (= (length d) 3)) d)
  15494. ((stringp d)
  15495. (let ((d (org-parse-time-string d)))
  15496. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  15497. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  15498. (defun org-timestamp-up (&optional arg)
  15499. "Increase the date item at the cursor by one.
  15500. If the cursor is on the year, change the year. If it is on the month,
  15501. the day or the time, change that. If the cursor is on the enclosing
  15502. bracket, change the timestamp type.
  15503. With prefix ARG, change by that many units."
  15504. (interactive "p")
  15505. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  15506. (defun org-timestamp-down (&optional arg)
  15507. "Decrease the date item at the cursor by one.
  15508. If the cursor is on the year, change the year. If it is on the month,
  15509. the day or the time, change that. If the cursor is on the enclosing
  15510. bracket, change the timestamp type.
  15511. With prefix ARG, change by that many units."
  15512. (interactive "p")
  15513. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  15514. (defun org-timestamp-up-day (&optional arg)
  15515. "Increase the date in the time stamp by one day.
  15516. With prefix ARG, change that many days."
  15517. (interactive "p")
  15518. (if (and (not (org-at-timestamp-p 'lax))
  15519. (org-at-heading-p))
  15520. (org-todo 'up)
  15521. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  15522. (defun org-timestamp-down-day (&optional arg)
  15523. "Decrease the date in the time stamp by one day.
  15524. With prefix ARG, change that many days."
  15525. (interactive "p")
  15526. (if (and (not (org-at-timestamp-p 'lax))
  15527. (org-at-heading-p))
  15528. (org-todo 'down)
  15529. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  15530. (defun org-at-timestamp-p (&optional extended)
  15531. "Non-nil if point is inside a timestamp.
  15532. By default, the function only consider syntactically valid active
  15533. timestamps. However, the caller may have a broader definition
  15534. for timestamps. As a consequence, optional argument EXTENDED can
  15535. be set to the following values
  15536. `inactive'
  15537. Include also syntactically valid inactive timestamps.
  15538. `agenda'
  15539. Include timestamps allowed in Agenda, i.e., those in
  15540. properties drawers, planning lines and clock lines.
  15541. `lax'
  15542. Ignore context. The function matches any part of the
  15543. document looking like a timestamp. This includes comments,
  15544. example blocks...
  15545. For backward-compatibility with Org 9.0, every other non-nil
  15546. value is equivalent to `inactive'.
  15547. When at a timestamp, return the position of the point as a symbol
  15548. among `bracket', `after', `year', `month', `hour', `minute',
  15549. `day' or a number of character from the last know part of the
  15550. time stamp.
  15551. When matching, the match groups are the following:
  15552. group 1: year
  15553. group 2: month
  15554. group 3: day number
  15555. group 4: day name
  15556. group 5: hours, if any
  15557. group 6: minutes, if any"
  15558. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  15559. (pos (point))
  15560. (match?
  15561. (let ((boundaries (org-in-regexp regexp)))
  15562. (save-match-data
  15563. (cond ((null boundaries) nil)
  15564. ((eq extended 'lax) t)
  15565. (t
  15566. (or (and (eq extended 'agenda)
  15567. (or (org-at-planning-p)
  15568. (org-at-property-p)
  15569. (and (bound-and-true-p
  15570. org-agenda-include-inactive-timestamps)
  15571. (org-at-clock-log-p))))
  15572. (eq 'timestamp
  15573. (save-excursion
  15574. (when (= pos (cdr boundaries)) (forward-char -1))
  15575. (org-element-type (org-element-context)))))))))))
  15576. (cond
  15577. ((not match?) nil)
  15578. ((= pos (match-beginning 0)) 'bracket)
  15579. ;; Distinguish location right before the closing bracket from
  15580. ;; right after it.
  15581. ((= pos (1- (match-end 0))) 'bracket)
  15582. ((= pos (match-end 0)) 'after)
  15583. ((org-pos-in-match-range pos 2) 'year)
  15584. ((org-pos-in-match-range pos 3) 'month)
  15585. ((org-pos-in-match-range pos 7) 'hour)
  15586. ((org-pos-in-match-range pos 8) 'minute)
  15587. ((or (org-pos-in-match-range pos 4)
  15588. (org-pos-in-match-range pos 5)) 'day)
  15589. ((and (> pos (or (match-end 8) (match-end 5)))
  15590. (< pos (match-end 0)))
  15591. (- pos (or (match-end 8) (match-end 5))))
  15592. (t 'day))))
  15593. (defun org-toggle-timestamp-type ()
  15594. "Toggle the type (<active> or [inactive]) of a time stamp."
  15595. (interactive)
  15596. (when (org-at-timestamp-p 'lax)
  15597. (let ((beg (match-beginning 0)) (end (match-end 0))
  15598. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  15599. (save-excursion
  15600. (goto-char beg)
  15601. (while (re-search-forward "[][<>]" end t)
  15602. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  15603. t t)))
  15604. (message "Timestamp is now %sactive"
  15605. (if (equal (char-after beg) ?<) "" "in")))))
  15606. (defun org-at-clock-log-p ()
  15607. "Non-nil if point is on a clock log line."
  15608. (and (org-match-line org-clock-line-re)
  15609. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  15610. (defvar org-clock-history) ; defined in org-clock.el
  15611. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  15612. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  15613. "Change the date in the time stamp at point.
  15614. The date will be changed by N times WHAT. WHAT can be `day', `month',
  15615. `year', `minute', `second'. If WHAT is not given, the cursor position
  15616. in the timestamp determines what will be changed.
  15617. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  15618. (let ((origin (point))
  15619. (timestamp? (org-at-timestamp-p 'lax))
  15620. origin-cat
  15621. with-hm inactive
  15622. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  15623. extra rem
  15624. ts time time0 fixnext clrgx)
  15625. (unless timestamp? (user-error "Not at a timestamp"))
  15626. (if (and (not what) (eq timestamp? 'bracket))
  15627. (org-toggle-timestamp-type)
  15628. ;; Point isn't on brackets. Remember the part of the time-stamp
  15629. ;; the point was in. Indeed, size of time-stamps may change,
  15630. ;; but point must be kept in the same category nonetheless.
  15631. (setq origin-cat timestamp?)
  15632. (when (and (not what) (not (eq timestamp? 'day))
  15633. org-display-custom-times
  15634. (get-text-property (point) 'display)
  15635. (not (get-text-property (1- (point)) 'display)))
  15636. (setq timestamp? 'day))
  15637. (setq timestamp? (or what timestamp?)
  15638. inactive (= (char-after (match-beginning 0)) ?\[)
  15639. ts (match-string 0))
  15640. (replace-match "")
  15641. (when (string-match
  15642. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  15643. ts)
  15644. (setq extra (match-string 1 ts))
  15645. (when suppress-tmp-delay
  15646. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  15647. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  15648. (setq with-hm t))
  15649. (setq time0 (org-parse-time-string ts))
  15650. (when (and updown
  15651. (eq timestamp? 'minute)
  15652. (not current-prefix-arg))
  15653. ;; This looks like s-up and s-down. Change by one rounding step.
  15654. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  15655. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  15656. (setcar (cdr time0) (+ (nth 1 time0)
  15657. (if (> n 0) (- rem) (- dm rem))))))
  15658. (setq time
  15659. (apply #'encode-time
  15660. (or (car time0) 0)
  15661. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  15662. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  15663. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  15664. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  15665. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  15666. (nthcdr 6 time0)))
  15667. (when (and (memq timestamp? '(hour minute))
  15668. extra
  15669. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  15670. (setq extra (org-modify-ts-extra
  15671. extra
  15672. (if (eq timestamp? 'hour) 2 5)
  15673. n dm)))
  15674. (when (integerp timestamp?)
  15675. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  15676. (when (eq what 'calendar)
  15677. (let ((cal-date (org-get-date-from-calendar)))
  15678. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  15679. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  15680. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  15681. (setcar time0 (or (car time0) 0))
  15682. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  15683. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  15684. (setq time (apply 'encode-time time0))))
  15685. ;; Insert the new time-stamp, and ensure point stays in the same
  15686. ;; category as before (i.e. not after the last position in that
  15687. ;; category).
  15688. (let ((pos (point)))
  15689. ;; Stay before inserted string. `save-excursion' is of no use.
  15690. (setq org-last-changed-timestamp
  15691. (org-insert-time-stamp time with-hm inactive nil nil extra))
  15692. (goto-char pos))
  15693. (save-match-data
  15694. (looking-at org-ts-regexp3)
  15695. (goto-char
  15696. (pcase origin-cat
  15697. ;; `day' category ends before `hour' if any, or at the end
  15698. ;; of the day name.
  15699. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  15700. (`hour (min (match-end 7) origin))
  15701. (`minute (min (1- (match-end 8)) origin))
  15702. ((pred integerp) (min (1- (match-end 0)) origin))
  15703. ;; Point was right after the time-stamp. However, the
  15704. ;; time-stamp length might have changed, so refer to
  15705. ;; (match-end 0) instead.
  15706. (`after (match-end 0))
  15707. ;; `year' and `month' have both fixed size: point couldn't
  15708. ;; have moved into another part.
  15709. (_ origin))))
  15710. ;; Update clock if on a CLOCK line.
  15711. (org-clock-update-time-maybe)
  15712. ;; Maybe adjust the closest clock in `org-clock-history'
  15713. (when org-clock-adjust-closest
  15714. (if (not (and (org-at-clock-log-p)
  15715. (< 1 (length (delq nil (mapcar 'marker-position
  15716. org-clock-history))))))
  15717. (message "No clock to adjust")
  15718. (cond ((save-excursion ; fix previous clock?
  15719. (re-search-backward org-ts-regexp0 nil t)
  15720. (looking-back (concat org-clock-string " \\[")
  15721. (line-beginning-position)))
  15722. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  15723. ((save-excursion ; fix next clock?
  15724. (re-search-backward org-ts-regexp0 nil t)
  15725. (looking-at (concat org-ts-regexp0 "\\] =>")))
  15726. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  15727. (save-window-excursion
  15728. ;; Find closest clock to point, adjust the previous/next one in history
  15729. (let* ((p (save-excursion (org-back-to-heading t)))
  15730. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  15731. (clfixnth
  15732. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  15733. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  15734. (if (not clfixpos)
  15735. (message "No clock to adjust")
  15736. (save-excursion
  15737. (org-goto-marker-or-bmk clfixpos)
  15738. (org-show-subtree)
  15739. (when (re-search-forward clrgx nil t)
  15740. (goto-char (match-beginning 1))
  15741. (let (org-clock-adjust-closest)
  15742. (org-timestamp-change n timestamp? updown))
  15743. (message "Clock adjusted in %s for heading: %s"
  15744. (file-name-nondirectory (buffer-file-name))
  15745. (org-get-heading t t)))))))))
  15746. ;; Try to recenter the calendar window, if any.
  15747. (when (and org-calendar-follow-timestamp-change
  15748. (get-buffer-window "*Calendar*" t)
  15749. (memq timestamp? '(day month year)))
  15750. (org-recenter-calendar (time-to-days time))))))
  15751. (defun org-modify-ts-extra (s pos n dm)
  15752. "Change the different parts of the lead-time and repeat fields in timestamp."
  15753. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  15754. ng h m new rem)
  15755. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  15756. (cond
  15757. ((or (org-pos-in-match-range pos 2)
  15758. (org-pos-in-match-range pos 3))
  15759. (setq m (string-to-number (match-string 3 s))
  15760. h (string-to-number (match-string 2 s)))
  15761. (if (org-pos-in-match-range pos 2)
  15762. (setq h (+ h n))
  15763. (setq n (* dm (with-no-warnings (cl-signum n))))
  15764. (unless (= 0 (setq rem (% m dm)))
  15765. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  15766. (setq m (+ m n)))
  15767. (when (< m 0) (setq m (+ m 60) h (1- h)))
  15768. (when (> m 59) (setq m (- m 60) h (1+ h)))
  15769. (setq h (mod h 24))
  15770. (setq ng 1 new (format "-%02d:%02d" h m)))
  15771. ((org-pos-in-match-range pos 6)
  15772. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  15773. ((org-pos-in-match-range pos 5)
  15774. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  15775. ((org-pos-in-match-range pos 9)
  15776. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  15777. ((org-pos-in-match-range pos 8)
  15778. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  15779. (when ng
  15780. (setq s (concat
  15781. (substring s 0 (match-beginning ng))
  15782. new
  15783. (substring s (match-end ng))))))
  15784. s))
  15785. (defun org-recenter-calendar (d)
  15786. "If the calendar is visible, recenter it to date D."
  15787. (let ((cwin (get-buffer-window "*Calendar*" t)))
  15788. (when cwin
  15789. (let ((calendar-move-hook nil))
  15790. (with-selected-window cwin
  15791. (calendar-goto-date
  15792. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  15793. (defun org-goto-calendar (&optional arg)
  15794. "Go to the Emacs calendar at the current date.
  15795. If there is a time stamp in the current line, go to that date.
  15796. A prefix ARG can be used to force the current date."
  15797. (interactive "P")
  15798. (let ((calendar-move-hook nil)
  15799. (calendar-view-holidays-initially-flag nil)
  15800. (calendar-view-diary-initially-flag nil)
  15801. diff)
  15802. (when (or (org-at-timestamp-p 'lax)
  15803. (org-match-line (concat ".*" org-ts-regexp)))
  15804. (let ((d1 (time-to-days (current-time)))
  15805. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  15806. (setq diff (- d2 d1))))
  15807. (calendar)
  15808. (calendar-goto-today)
  15809. (when (and diff (not arg)) (calendar-forward-day diff))))
  15810. (defun org-get-date-from-calendar ()
  15811. "Return a list (month day year) of date at point in calendar."
  15812. (with-current-buffer "*Calendar*"
  15813. (save-match-data
  15814. (calendar-cursor-to-date))))
  15815. (defun org-date-from-calendar ()
  15816. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  15817. If there is already a time stamp at the cursor position, update it."
  15818. (interactive)
  15819. (if (org-at-timestamp-p 'lax)
  15820. (org-timestamp-change 0 'calendar)
  15821. (let ((cal-date (org-get-date-from-calendar)))
  15822. (org-insert-time-stamp
  15823. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  15824. (defcustom org-image-actual-width t
  15825. "Should we use the actual width of images when inlining them?
  15826. When set to t, always use the image width.
  15827. When set to a number, use imagemagick (when available) to set
  15828. the image's width to this value.
  15829. When set to a number in a list, try to get the width from any
  15830. #+ATTR.* keyword if it matches a width specification like
  15831. #+ATTR_HTML: :width 300px
  15832. and fall back on that number if none is found.
  15833. When set to nil, try to get the width from an #+ATTR.* keyword
  15834. and fall back on the original width if none is found.
  15835. This requires Emacs >= 24.1, build with imagemagick support."
  15836. :group 'org-appearance
  15837. :version "24.4"
  15838. :package-version '(Org . "8.0")
  15839. :type '(choice
  15840. (const :tag "Use the image width" t)
  15841. (integer :tag "Use a number of pixels")
  15842. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  15843. (const :tag "Use #+ATTR* or don't resize" nil)))
  15844. (defcustom org-agenda-inhibit-startup nil
  15845. "Inhibit startup when preparing agenda buffers.
  15846. When this variable is t, the initialization of the Org agenda
  15847. buffers is inhibited: e.g. the visibility state is not set, the
  15848. tables are not re-aligned, etc."
  15849. :type 'boolean
  15850. :version "24.3"
  15851. :group 'org-agenda)
  15852. (defcustom org-agenda-ignore-properties nil
  15853. "Avoid updating text properties when building the agenda.
  15854. Properties are used to prepare buffers for effort estimates,
  15855. appointments, statistics and subtree-local categories.
  15856. If you don't use these in the agenda, you can add them to this
  15857. list and agenda building will be a bit faster.
  15858. The value is a list, with zero or more of the symbols `effort', `appt',
  15859. `stats' or `category'."
  15860. :type '(set :greedy t
  15861. (const effort)
  15862. (const appt)
  15863. (const stats)
  15864. (const category))
  15865. :version "26.1"
  15866. :package-version '(Org . "8.3")
  15867. :group 'org-agenda)
  15868. ;;;; Files
  15869. (defun org-save-all-org-buffers ()
  15870. "Save all Org buffers without user confirmation."
  15871. (interactive)
  15872. (message "Saving all Org buffers...")
  15873. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  15874. (when (featurep 'org-id) (org-id-locations-save))
  15875. (message "Saving all Org buffers... done"))
  15876. (defun org-revert-all-org-buffers ()
  15877. "Revert all Org buffers.
  15878. Prompt for confirmation when there are unsaved changes.
  15879. Be sure you know what you are doing before letting this function
  15880. overwrite your changes.
  15881. This function is useful in a setup where one tracks Org files
  15882. with a version control system, to revert on one machine after pulling
  15883. changes from another. I believe the procedure must be like this:
  15884. 1. M-x org-save-all-org-buffers
  15885. 2. Pull changes from the other machine, resolve conflicts
  15886. 3. M-x org-revert-all-org-buffers"
  15887. (interactive)
  15888. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  15889. (user-error "Abort"))
  15890. (save-excursion
  15891. (save-window-excursion
  15892. (dolist (b (buffer-list))
  15893. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  15894. (with-current-buffer b buffer-file-name))
  15895. (pop-to-buffer-same-window b)
  15896. (revert-buffer t 'no-confirm)))
  15897. (when (and (featurep 'org-id) org-id-track-globally)
  15898. (org-id-locations-load)))))
  15899. ;;;; Agenda files
  15900. ;;;###autoload
  15901. (defun org-switchb (&optional arg)
  15902. "Switch between Org buffers.
  15903. With `\\[universal-argument]' prefix, restrict available buffers to files.
  15904. With `\\[universal-argument] \\[universal-argument]' \
  15905. prefix, restrict available buffers to agenda files."
  15906. (interactive "P")
  15907. (let ((blist (org-buffer-list
  15908. (cond ((equal arg '(4)) 'files)
  15909. ((equal arg '(16)) 'agenda)))))
  15910. (pop-to-buffer-same-window
  15911. (completing-read "Org buffer: "
  15912. (mapcar #'list (mapcar #'buffer-name blist))
  15913. nil t))))
  15914. (defun org-buffer-list (&optional predicate exclude-tmp)
  15915. "Return a list of Org buffers.
  15916. PREDICATE can be `export', `files' or `agenda'.
  15917. export restrict the list to Export buffers.
  15918. files restrict the list to buffers visiting Org files.
  15919. agenda restrict the list to buffers visiting agenda files.
  15920. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  15921. (let* ((bfn nil)
  15922. (agenda-files (and (eq predicate 'agenda)
  15923. (mapcar 'file-truename (org-agenda-files t))))
  15924. (filter
  15925. (cond
  15926. ((eq predicate 'files)
  15927. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  15928. ((eq predicate 'export)
  15929. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  15930. ((eq predicate 'agenda)
  15931. (lambda (b)
  15932. (with-current-buffer b
  15933. (and (derived-mode-p 'org-mode)
  15934. (setq bfn (buffer-file-name b))
  15935. (member (file-truename bfn) agenda-files)))))
  15936. (t (lambda (b) (with-current-buffer b
  15937. (or (derived-mode-p 'org-mode)
  15938. (string-match "\\*Org .*Export"
  15939. (buffer-name b)))))))))
  15940. (delq nil
  15941. (mapcar
  15942. (lambda(b)
  15943. (if (and (funcall filter b)
  15944. (or (not exclude-tmp)
  15945. (not (string-match "tmp" (buffer-name b)))))
  15946. b
  15947. nil))
  15948. (buffer-list)))))
  15949. (defun org-agenda-files (&optional unrestricted archives)
  15950. "Get the list of agenda files.
  15951. Optional UNRESTRICTED means return the full list even if a restriction
  15952. is currently in place.
  15953. When ARCHIVES is t, include all archive files that are really being
  15954. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  15955. `org-agenda-archives-mode' is t."
  15956. (let ((files
  15957. (cond
  15958. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  15959. ((stringp org-agenda-files) (org-read-agenda-file-list))
  15960. ((listp org-agenda-files) org-agenda-files)
  15961. (t (error "Invalid value of `org-agenda-files'")))))
  15962. (setq files (apply 'append
  15963. (mapcar (lambda (f)
  15964. (if (file-directory-p f)
  15965. (directory-files
  15966. f t org-agenda-file-regexp)
  15967. (list f)))
  15968. files)))
  15969. (when org-agenda-skip-unavailable-files
  15970. (setq files (delq nil
  15971. (mapcar (function
  15972. (lambda (file)
  15973. (and (file-readable-p file) file)))
  15974. files))))
  15975. (when (or (eq archives t)
  15976. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  15977. (setq files (org-add-archive-files files)))
  15978. files))
  15979. (defun org-agenda-file-p (&optional file)
  15980. "Return non-nil, if FILE is an agenda file.
  15981. If FILE is omitted, use the file associated with the current
  15982. buffer."
  15983. (let ((fname (or file (buffer-file-name))))
  15984. (and fname
  15985. (member (file-truename fname)
  15986. (mapcar #'file-truename (org-agenda-files t))))))
  15987. (defun org-edit-agenda-file-list ()
  15988. "Edit the list of agenda files.
  15989. Depending on setup, this either uses customize to edit the variable
  15990. `org-agenda-files', or it visits the file that is holding the list. In the
  15991. latter case, the buffer is set up in a way that saving it automatically kills
  15992. the buffer and restores the previous window configuration."
  15993. (interactive)
  15994. (if (stringp org-agenda-files)
  15995. (let ((cw (current-window-configuration)))
  15996. (find-file org-agenda-files)
  15997. (setq-local org-window-configuration cw)
  15998. (add-hook 'after-save-hook
  15999. (lambda ()
  16000. (set-window-configuration
  16001. (prog1 org-window-configuration
  16002. (kill-buffer (current-buffer))))
  16003. (org-install-agenda-files-menu)
  16004. (message "New agenda file list installed"))
  16005. nil 'local)
  16006. (message "%s" (substitute-command-keys
  16007. "Edit list and finish with \\[save-buffer]")))
  16008. (customize-variable 'org-agenda-files)))
  16009. (defun org-store-new-agenda-file-list (list)
  16010. "Set new value for the agenda file list and save it correctly."
  16011. (if (stringp org-agenda-files)
  16012. (let ((fe (org-read-agenda-file-list t)) b u)
  16013. (while (setq b (find-buffer-visiting org-agenda-files))
  16014. (kill-buffer b))
  16015. (with-temp-file org-agenda-files
  16016. (insert
  16017. (mapconcat
  16018. (lambda (f) ;; Keep un-expanded entries.
  16019. (if (setq u (assoc f fe))
  16020. (cdr u)
  16021. f))
  16022. list "\n")
  16023. "\n")))
  16024. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16025. (org-insert-mode-line-in-empty-file nil))
  16026. (setq org-agenda-files list)
  16027. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16028. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16029. "Read the list of agenda files from a file.
  16030. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16031. filenames, used by `org-store-new-agenda-file-list' to write back
  16032. un-expanded file names."
  16033. (when (file-directory-p org-agenda-files)
  16034. (error "`org-agenda-files' cannot be a single directory"))
  16035. (when (stringp org-agenda-files)
  16036. (with-temp-buffer
  16037. (insert-file-contents org-agenda-files)
  16038. (mapcar
  16039. (lambda (f)
  16040. (let ((e (expand-file-name (substitute-in-file-name f)
  16041. org-directory)))
  16042. (if pair-with-expansion
  16043. (cons e f)
  16044. e)))
  16045. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16046. ;;;###autoload
  16047. (defun org-cycle-agenda-files ()
  16048. "Cycle through the files in `org-agenda-files'.
  16049. If the current buffer visits an agenda file, find the next one in the list.
  16050. If the current buffer does not, find the first agenda file."
  16051. (interactive)
  16052. (let* ((fs (or (org-agenda-files t)
  16053. (user-error "No agenda files")))
  16054. (files (copy-sequence fs))
  16055. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16056. file)
  16057. (when tcf
  16058. (while (and (setq file (pop files))
  16059. (not (equal (file-truename file) tcf)))))
  16060. (find-file (car (or files fs)))
  16061. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16062. (defun org-agenda-file-to-front (&optional to-end)
  16063. "Move/add the current file to the top of the agenda file list.
  16064. If the file is not present in the list, it is added to the front. If it is
  16065. present, it is moved there. With optional argument TO-END, add/move to the
  16066. end of the list."
  16067. (interactive "P")
  16068. (let ((org-agenda-skip-unavailable-files nil)
  16069. (file-alist (mapcar (lambda (x)
  16070. (cons (file-truename x) x))
  16071. (org-agenda-files t)))
  16072. (ctf (file-truename
  16073. (or buffer-file-name
  16074. (user-error "Please save the current buffer to a file"))))
  16075. x had)
  16076. (setq x (assoc ctf file-alist) had x)
  16077. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16078. (if to-end
  16079. (setq file-alist (append (delq x file-alist) (list x)))
  16080. (setq file-alist (cons x (delq x file-alist))))
  16081. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16082. (org-install-agenda-files-menu)
  16083. (message "File %s to %s of agenda file list"
  16084. (if had "moved" "added") (if to-end "end" "front"))))
  16085. (defun org-remove-file (&optional file)
  16086. "Remove current file from the list of files in variable `org-agenda-files'.
  16087. These are the files which are being checked for agenda entries.
  16088. Optional argument FILE means use this file instead of the current."
  16089. (interactive)
  16090. (let* ((org-agenda-skip-unavailable-files nil)
  16091. (file (or file buffer-file-name
  16092. (user-error "Current buffer does not visit a file")))
  16093. (true-file (file-truename file))
  16094. (afile (abbreviate-file-name file))
  16095. (files (delq nil (mapcar
  16096. (lambda (x)
  16097. (unless (equal true-file
  16098. (file-truename x))
  16099. x))
  16100. (org-agenda-files t)))))
  16101. (if (not (= (length files) (length (org-agenda-files t))))
  16102. (progn
  16103. (org-store-new-agenda-file-list files)
  16104. (org-install-agenda-files-menu)
  16105. (message "Removed from Org Agenda list: %s" afile))
  16106. (message "File was not in list: %s (not removed)" afile))))
  16107. (defun org-file-menu-entry (file)
  16108. (vector file (list 'find-file file) t))
  16109. (defun org-check-agenda-file (file)
  16110. "Make sure FILE exists. If not, ask user what to do."
  16111. (unless (file-exists-p file)
  16112. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16113. (abbreviate-file-name file))
  16114. (let ((r (downcase (read-char-exclusive))))
  16115. (cond
  16116. ((equal r ?r)
  16117. (org-remove-file file)
  16118. (throw 'nextfile t))
  16119. (t (user-error "Abort"))))))
  16120. (defun org-get-agenda-file-buffer (file)
  16121. "Get an agenda buffer visiting FILE.
  16122. If the buffer needs to be created, add it to the list of buffers
  16123. which might be released later."
  16124. (let ((buf (org-find-base-buffer-visiting file)))
  16125. (if buf
  16126. buf ; just return it
  16127. ;; Make a new buffer and remember it
  16128. (setq buf (find-file-noselect file))
  16129. (when buf (push buf org-agenda-new-buffers))
  16130. buf)))
  16131. (defun org-release-buffers (blist)
  16132. "Release all buffers in list, asking the user for confirmation when needed.
  16133. When a buffer is unmodified, it is just killed. When modified, it is saved
  16134. \(if the user agrees) and then killed."
  16135. (let (file)
  16136. (dolist (buf blist)
  16137. (setq file (buffer-file-name buf))
  16138. (when (and (buffer-modified-p buf)
  16139. file
  16140. (y-or-n-p (format "Save file %s? " file)))
  16141. (with-current-buffer buf (save-buffer)))
  16142. (kill-buffer buf))))
  16143. (defun org-agenda-prepare-buffers (files)
  16144. "Create buffers for all agenda files, protect archived trees and comments."
  16145. (interactive)
  16146. (let ((pa '(:org-archived t))
  16147. (pc '(:org-comment t))
  16148. (pall '(:org-archived t :org-comment t))
  16149. (inhibit-read-only t)
  16150. (org-inhibit-startup org-agenda-inhibit-startup)
  16151. (rea (org-make-tag-string (list org-archive-tag)))
  16152. re pos)
  16153. (setq org-tag-alist-for-agenda nil
  16154. org-tag-groups-alist-for-agenda nil)
  16155. (save-excursion
  16156. (save-restriction
  16157. (dolist (file files)
  16158. (catch 'nextfile
  16159. (if (bufferp file)
  16160. (set-buffer file)
  16161. (org-check-agenda-file file)
  16162. (set-buffer (org-get-agenda-file-buffer file)))
  16163. (widen)
  16164. (org-set-regexps-and-options 'tags-only)
  16165. (setq pos (point))
  16166. (or (memq 'category org-agenda-ignore-properties)
  16167. (org-refresh-category-properties))
  16168. (or (memq 'stats org-agenda-ignore-properties)
  16169. (org-refresh-stats-properties))
  16170. (or (memq 'effort org-agenda-ignore-properties)
  16171. (org-refresh-effort-properties))
  16172. (or (memq 'appt org-agenda-ignore-properties)
  16173. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16174. (setq org-todo-keywords-for-agenda
  16175. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16176. (setq org-done-keywords-for-agenda
  16177. (append org-done-keywords-for-agenda org-done-keywords))
  16178. (setq org-todo-keyword-alist-for-agenda
  16179. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16180. (setq org-tag-alist-for-agenda
  16181. (org--tag-add-to-alist
  16182. org-tag-alist-for-agenda
  16183. org-current-tag-alist))
  16184. ;; Merge current file's tag groups into global
  16185. ;; `org-tag-groups-alist-for-agenda'.
  16186. (when org-group-tags
  16187. (dolist (alist org-tag-groups-alist)
  16188. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  16189. (if old
  16190. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  16191. (push alist org-tag-groups-alist-for-agenda)))))
  16192. (with-silent-modifications
  16193. (save-excursion
  16194. (remove-text-properties (point-min) (point-max) pall)
  16195. (when org-agenda-skip-archived-trees
  16196. (goto-char (point-min))
  16197. (while (re-search-forward rea nil t)
  16198. (when (org-at-heading-p t)
  16199. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  16200. (goto-char (point-min))
  16201. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  16202. (while (re-search-forward re nil t)
  16203. (when (save-match-data (org-in-commented-heading-p t))
  16204. (add-text-properties
  16205. (match-beginning 0) (org-end-of-subtree t) pc)))))
  16206. (goto-char pos)))))
  16207. (setq org-todo-keywords-for-agenda
  16208. (org-uniquify org-todo-keywords-for-agenda))
  16209. (setq org-todo-keyword-alist-for-agenda
  16210. (org-uniquify org-todo-keyword-alist-for-agenda))))
  16211. ;;;; CDLaTeX minor mode
  16212. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  16213. "Keymap for the minor `org-cdlatex-mode'.")
  16214. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  16215. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  16216. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  16217. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  16218. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  16219. (defvar org-cdlatex-texmathp-advice-is-done nil
  16220. "Flag remembering if we have applied the advice to texmathp already.")
  16221. (define-minor-mode org-cdlatex-mode
  16222. "Toggle the minor `org-cdlatex-mode'.
  16223. This mode supports entering LaTeX environment and math in LaTeX fragments
  16224. in Org mode.
  16225. \\{org-cdlatex-mode-map}"
  16226. nil " OCDL" nil
  16227. (when org-cdlatex-mode
  16228. (require 'cdlatex)
  16229. (run-hooks 'cdlatex-mode-hook)
  16230. (cdlatex-compute-tables))
  16231. (unless org-cdlatex-texmathp-advice-is-done
  16232. (setq org-cdlatex-texmathp-advice-is-done t)
  16233. (defadvice texmathp (around org-math-always-on activate)
  16234. "Always return t in Org buffers.
  16235. This is because we want to insert math symbols without dollars even outside
  16236. the LaTeX math segments. If Org mode thinks that point is actually inside
  16237. an embedded LaTeX fragment, let `texmathp' do its job.
  16238. `\\[org-cdlatex-mode-map]'"
  16239. (interactive)
  16240. (let (p)
  16241. (cond
  16242. ((not (derived-mode-p 'org-mode)) ad-do-it)
  16243. ((eq this-command 'cdlatex-math-symbol)
  16244. (setq ad-return-value t
  16245. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  16246. (t
  16247. (let ((p (org-inside-LaTeX-fragment-p)))
  16248. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  16249. (setq ad-return-value t
  16250. texmathp-why '("Org mode embedded math" . 0))
  16251. (when p ad-do-it)))))))))
  16252. (defun turn-on-org-cdlatex ()
  16253. "Unconditionally turn on `org-cdlatex-mode'."
  16254. (org-cdlatex-mode 1))
  16255. (defun org-try-cdlatex-tab ()
  16256. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  16257. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  16258. - inside a LaTeX fragment, or
  16259. - after the first word in a line, where an abbreviation expansion could
  16260. insert a LaTeX environment."
  16261. (when org-cdlatex-mode
  16262. (cond
  16263. ;; Before any word on the line: No expansion possible.
  16264. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  16265. ;; Just after first word on the line: Expand it. Make sure it
  16266. ;; cannot happen on headlines, though.
  16267. ((save-excursion
  16268. (skip-chars-backward "a-zA-Z0-9*")
  16269. (skip-chars-backward " \t")
  16270. (and (bolp) (not (org-at-heading-p))))
  16271. (cdlatex-tab) t)
  16272. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  16273. (defun org-cdlatex-underscore-caret (&optional _arg)
  16274. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  16275. Revert to the normal definition outside of these fragments."
  16276. (interactive "P")
  16277. (if (org-inside-LaTeX-fragment-p)
  16278. (call-interactively 'cdlatex-sub-superscript)
  16279. (let (org-cdlatex-mode)
  16280. (call-interactively (key-binding (vector last-input-event))))))
  16281. (defun org-cdlatex-math-modify (&optional _arg)
  16282. "Execute `cdlatex-math-modify' in LaTeX fragments.
  16283. Revert to the normal definition outside of these fragments."
  16284. (interactive "P")
  16285. (if (org-inside-LaTeX-fragment-p)
  16286. (call-interactively 'cdlatex-math-modify)
  16287. (let (org-cdlatex-mode)
  16288. (call-interactively (key-binding (vector last-input-event))))))
  16289. (defun org-cdlatex-environment-indent (&optional environment item)
  16290. "Execute `cdlatex-environment' and indent the inserted environment.
  16291. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  16292. The inserted environment is indented to current indentation
  16293. unless point is at the beginning of the line, in which the
  16294. environment remains unintended."
  16295. (interactive)
  16296. ;; cdlatex-environment always return nil. Therefore, capture output
  16297. ;; first and determine if an environment was selected.
  16298. (let* ((beg (point-marker))
  16299. (end (copy-marker (point) t))
  16300. (inserted (progn
  16301. (ignore-errors (cdlatex-environment environment item))
  16302. (< beg end)))
  16303. ;; Figure out how many lines to move forward after the
  16304. ;; environment has been inserted.
  16305. (lines (when inserted
  16306. (save-excursion
  16307. (- (cl-loop while (< beg (point))
  16308. with x = 0
  16309. do (forward-line -1)
  16310. (cl-incf x)
  16311. finally return x)
  16312. (if (progn (goto-char beg)
  16313. (and (progn (skip-chars-forward " \t") (eolp))
  16314. (progn (skip-chars-backward " \t") (bolp))))
  16315. 1 0)))))
  16316. (env (org-trim (delete-and-extract-region beg end))))
  16317. (when inserted
  16318. ;; Get indentation of next line unless at column 0.
  16319. (let ((ind (if (bolp) 0
  16320. (save-excursion
  16321. (org-return-indent)
  16322. (prog1 (current-indentation)
  16323. (when (progn (skip-chars-forward " \t") (eolp))
  16324. (delete-region beg (point)))))))
  16325. (bol (progn (skip-chars-backward " \t") (bolp))))
  16326. ;; Insert a newline before environment unless at column zero
  16327. ;; to "escape" the current line. Insert a newline if
  16328. ;; something is one the same line as \end{ENVIRONMENT}.
  16329. (insert
  16330. (concat (unless bol "\n") env
  16331. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  16332. (unless (zerop ind)
  16333. (save-excursion
  16334. (goto-char beg)
  16335. (while (< (point) end)
  16336. (unless (eolp) (indent-line-to ind))
  16337. (forward-line))))
  16338. (goto-char beg)
  16339. (forward-line lines)
  16340. (indent-line-to ind)))
  16341. (set-marker beg nil)
  16342. (set-marker end nil)))
  16343. ;;;; LaTeX fragments
  16344. (defun org-inside-LaTeX-fragment-p ()
  16345. "Test if point is inside a LaTeX fragment.
  16346. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  16347. sequence appearing also before point.
  16348. Even though the matchers for math are configurable, this function assumes
  16349. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  16350. delimiters are skipped when they have been removed by customization.
  16351. The return value is nil, or a cons cell with the delimiter and the
  16352. position of this delimiter.
  16353. This function does a reasonably good job, but can locally be fooled by
  16354. for example currency specifications. For example it will assume being in
  16355. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  16356. fragments that are properly closed, but during editing, we have to live
  16357. with the uncertainty caused by missing closing delimiters. This function
  16358. looks only before point, not after."
  16359. (catch 'exit
  16360. (let ((pos (point))
  16361. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  16362. (lim (save-excursion (org-backward-paragraph) (point)))
  16363. dd-on str (start 0) m re)
  16364. (goto-char pos)
  16365. (when dodollar
  16366. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  16367. re (nth 1 (assoc "$" org-latex-regexps)))
  16368. (while (string-match re str start)
  16369. (cond
  16370. ((= (match-end 0) (length str))
  16371. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  16372. ((= (match-end 0) (- (length str) 5))
  16373. (throw 'exit nil))
  16374. (t (setq start (match-end 0))))))
  16375. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  16376. (goto-char pos)
  16377. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  16378. (and (match-beginning 2) (throw 'exit nil))
  16379. ;; count $$
  16380. (while (re-search-backward "\\$\\$" lim t)
  16381. (setq dd-on (not dd-on)))
  16382. (goto-char pos)
  16383. (when dd-on (cons "$$" m))))))
  16384. (defun org-inside-latex-macro-p ()
  16385. "Is point inside a LaTeX macro or its arguments?"
  16386. (save-match-data
  16387. (org-in-regexp
  16388. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  16389. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  16390. "Build an overlay between BEG and END using IMAGE file.
  16391. Argument IMAGETYPE is the extension of the displayed image,
  16392. as a string. It defaults to \"png\"."
  16393. (let ((ov (make-overlay beg end))
  16394. (imagetype (or (intern imagetype) 'png)))
  16395. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  16396. (overlay-put ov 'evaporate t)
  16397. (overlay-put ov
  16398. 'modification-hooks
  16399. (list (lambda (o _flag _beg _end &optional _l)
  16400. (delete-overlay o))))
  16401. (overlay-put ov
  16402. 'display
  16403. (list 'image :type imagetype :file image :ascent 'center))))
  16404. (defun org--list-latex-overlays (&optional beg end)
  16405. "List all Org LaTeX overlays in current buffer.
  16406. Limit to overlays between BEG and END when those are provided."
  16407. (cl-remove-if-not
  16408. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  16409. (overlays-in (or beg (point-min)) (or end (point-max)))))
  16410. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  16411. "Remove all overlays with LaTeX fragment images in current buffer.
  16412. When optional arguments BEG and END are non-nil, remove all
  16413. overlays between them instead. Return a non-nil value when some
  16414. overlays were removed, nil otherwise."
  16415. (let ((overlays (org--list-latex-overlays beg end)))
  16416. (mapc #'delete-overlay overlays)
  16417. overlays))
  16418. (defun org-toggle-latex-fragment (&optional arg)
  16419. "Preview the LaTeX fragment at point, or all locally or globally.
  16420. If the cursor is on a LaTeX fragment, create the image and overlay
  16421. it over the source code, if there is none. Remove it otherwise.
  16422. If there is no fragment at point, display all fragments in the
  16423. current section.
  16424. With prefix ARG, preview or clear image for all fragments in the
  16425. current subtree or in the whole buffer when used before the first
  16426. headline. With a prefix ARG `\\[universal-argument] \
  16427. \\[universal-argument]' preview or clear images
  16428. for all fragments in the buffer."
  16429. (interactive "P")
  16430. (when (display-graphic-p)
  16431. (catch 'exit
  16432. (save-excursion
  16433. (let (beg end msg)
  16434. (cond
  16435. ((or (equal arg '(16))
  16436. (and (equal arg '(4))
  16437. (org-with-limited-levels (org-before-first-heading-p))))
  16438. (if (org-remove-latex-fragment-image-overlays)
  16439. (progn (message "LaTeX fragments images removed from buffer")
  16440. (throw 'exit nil))
  16441. (setq msg "Creating images for buffer...")))
  16442. ((equal arg '(4))
  16443. (org-with-limited-levels (org-back-to-heading t))
  16444. (setq beg (point))
  16445. (setq end (progn (org-end-of-subtree t) (point)))
  16446. (if (org-remove-latex-fragment-image-overlays beg end)
  16447. (progn
  16448. (message "LaTeX fragment images removed from subtree")
  16449. (throw 'exit nil))
  16450. (setq msg "Creating images for subtree...")))
  16451. ((let ((datum (org-element-context)))
  16452. (when (memq (org-element-type datum)
  16453. '(latex-environment latex-fragment))
  16454. (setq beg (org-element-property :begin datum))
  16455. (setq end (org-element-property :end datum))
  16456. (if (org-remove-latex-fragment-image-overlays beg end)
  16457. (progn (message "LaTeX fragment image removed")
  16458. (throw 'exit nil))
  16459. (setq msg "Creating image...")))))
  16460. (t
  16461. (org-with-limited-levels
  16462. (setq beg (if (org-at-heading-p) (line-beginning-position)
  16463. (outline-previous-heading)
  16464. (point)))
  16465. (setq end (progn (outline-next-heading) (point)))
  16466. (if (org-remove-latex-fragment-image-overlays beg end)
  16467. (progn
  16468. (message "LaTeX fragment images removed from section")
  16469. (throw 'exit nil))
  16470. (setq msg "Creating images for section...")))))
  16471. (let ((file (buffer-file-name (buffer-base-buffer))))
  16472. (org-format-latex
  16473. (concat org-preview-latex-image-directory "org-ltximg")
  16474. beg end
  16475. ;; Emacs cannot overlay images from remote hosts. Create
  16476. ;; it in `temporary-file-directory' instead.
  16477. (if (or (not file) (file-remote-p file))
  16478. temporary-file-directory
  16479. default-directory)
  16480. 'overlays msg 'forbuffer org-preview-latex-default-process))
  16481. (message (concat msg "done")))))))
  16482. (defun org-format-latex
  16483. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  16484. "Replace LaTeX fragments with links to an image.
  16485. The function takes care of creating the replacement image.
  16486. Only consider fragments between BEG and END when those are
  16487. provided.
  16488. When optional argument OVERLAYS is non-nil, display the image on
  16489. top of the fragment instead of replacing it.
  16490. PROCESSING-TYPE is the conversion method to use, as a symbol.
  16491. Some of the options can be changed using the variable
  16492. `org-format-latex-options', which see."
  16493. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  16494. (unless (eq processing-type 'verbatim)
  16495. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  16496. (cnt 0)
  16497. checkdir-flag)
  16498. (goto-char (or beg (point-min)))
  16499. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  16500. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  16501. (overlay-recenter (or end (point-max))))
  16502. (while (re-search-forward math-regexp end t)
  16503. (unless (and overlays
  16504. (eq (get-char-property (point) 'org-overlay-type)
  16505. 'org-latex-overlay))
  16506. (let* ((context (org-element-context))
  16507. (type (org-element-type context)))
  16508. (when (memq type '(latex-environment latex-fragment))
  16509. (let ((block-type (eq type 'latex-environment))
  16510. (value (org-element-property :value context))
  16511. (beg (org-element-property :begin context))
  16512. (end (save-excursion
  16513. (goto-char (org-element-property :end context))
  16514. (skip-chars-backward " \r\t\n")
  16515. (point))))
  16516. (cond
  16517. ((eq processing-type 'mathjax)
  16518. ;; Prepare for MathJax processing.
  16519. (if (not (string-match "\\`\\$\\$?" value))
  16520. (goto-char end)
  16521. (delete-region beg end)
  16522. (if (string= (match-string 0 value) "$$")
  16523. (insert "\\[" (substring value 2 -2) "\\]")
  16524. (insert "\\(" (substring value 1 -1) "\\)"))))
  16525. ((assq processing-type org-preview-latex-process-alist)
  16526. ;; Process to an image.
  16527. (cl-incf cnt)
  16528. (goto-char beg)
  16529. (let* ((processing-info
  16530. (cdr (assq processing-type org-preview-latex-process-alist)))
  16531. (face (face-at-point))
  16532. ;; Get the colors from the face at point.
  16533. (fg
  16534. (let ((color (plist-get org-format-latex-options
  16535. :foreground)))
  16536. (if (and forbuffer (eq color 'auto))
  16537. (face-attribute face :foreground nil 'default)
  16538. color)))
  16539. (bg
  16540. (let ((color (plist-get org-format-latex-options
  16541. :background)))
  16542. (if (and forbuffer (eq color 'auto))
  16543. (face-attribute face :background nil 'default)
  16544. color)))
  16545. (hash (sha1 (prin1-to-string
  16546. (list org-format-latex-header
  16547. org-latex-default-packages-alist
  16548. org-latex-packages-alist
  16549. org-format-latex-options
  16550. forbuffer value fg bg))))
  16551. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  16552. (absprefix (expand-file-name prefix dir))
  16553. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  16554. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  16555. (sep (and block-type "\n\n"))
  16556. (link (concat sep "[[file:" linkfile "]]" sep))
  16557. (options
  16558. (org-combine-plists
  16559. org-format-latex-options
  16560. `(:foreground ,fg :background ,bg))))
  16561. (when msg (message msg cnt))
  16562. (unless checkdir-flag ; Ensure the directory exists.
  16563. (setq checkdir-flag t)
  16564. (let ((todir (file-name-directory absprefix)))
  16565. (unless (file-directory-p todir)
  16566. (make-directory todir t))))
  16567. (unless (file-exists-p movefile)
  16568. (org-create-formula-image
  16569. value movefile options forbuffer processing-type))
  16570. (if overlays
  16571. (progn
  16572. (dolist (o (overlays-in beg end))
  16573. (when (eq (overlay-get o 'org-overlay-type)
  16574. 'org-latex-overlay)
  16575. (delete-overlay o)))
  16576. (org--format-latex-make-overlay beg end movefile imagetype)
  16577. (goto-char end))
  16578. (delete-region beg end)
  16579. (insert
  16580. (org-add-props link
  16581. (list 'org-latex-src
  16582. (replace-regexp-in-string "\"" "" value)
  16583. 'org-latex-src-embed-type
  16584. (if block-type 'paragraph 'character)))))))
  16585. ((eq processing-type 'mathml)
  16586. ;; Process to MathML.
  16587. (unless (org-format-latex-mathml-available-p)
  16588. (user-error "LaTeX to MathML converter not configured"))
  16589. (cl-incf cnt)
  16590. (when msg (message msg cnt))
  16591. (goto-char beg)
  16592. (delete-region beg end)
  16593. (insert (org-format-latex-as-mathml
  16594. value block-type prefix dir)))
  16595. (t
  16596. (error "Unknown conversion process %s for LaTeX fragments"
  16597. processing-type)))))))))))
  16598. (defun org-create-math-formula (latex-frag &optional mathml-file)
  16599. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  16600. Use `org-latex-to-mathml-convert-command'. If the conversion is
  16601. sucessful, return the portion between \"<math...> </math>\"
  16602. elements otherwise return nil. When MATHML-FILE is specified,
  16603. write the results in to that file. When invoked as an
  16604. interactive command, prompt for LATEX-FRAG, with initial value
  16605. set to the current active region and echo the results for user
  16606. inspection."
  16607. (interactive (list (let ((frag (when (org-region-active-p)
  16608. (buffer-substring-no-properties
  16609. (region-beginning) (region-end)))))
  16610. (read-string "LaTeX Fragment: " frag nil frag))))
  16611. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  16612. (let* ((tmp-in-file
  16613. (let ((file (file-relative-name
  16614. (make-temp-name (expand-file-name "ltxmathml-in")))))
  16615. (write-region latex-frag nil file)
  16616. file))
  16617. (tmp-out-file (file-relative-name
  16618. (make-temp-name (expand-file-name "ltxmathml-out"))))
  16619. (cmd (format-spec
  16620. org-latex-to-mathml-convert-command
  16621. `((?j . ,(and org-latex-to-mathml-jar-file
  16622. (shell-quote-argument
  16623. (expand-file-name
  16624. org-latex-to-mathml-jar-file))))
  16625. (?I . ,(shell-quote-argument tmp-in-file))
  16626. (?i . ,latex-frag)
  16627. (?o . ,(shell-quote-argument tmp-out-file)))))
  16628. mathml shell-command-output)
  16629. (when (called-interactively-p 'any)
  16630. (unless (org-format-latex-mathml-available-p)
  16631. (user-error "LaTeX to MathML converter not configured")))
  16632. (message "Running %s" cmd)
  16633. (setq shell-command-output (shell-command-to-string cmd))
  16634. (setq mathml
  16635. (when (file-readable-p tmp-out-file)
  16636. (with-current-buffer (find-file-noselect tmp-out-file t)
  16637. (goto-char (point-min))
  16638. (when (re-search-forward
  16639. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  16640. (regexp-quote
  16641. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  16642. nil t)
  16643. (prog1 (match-string 0) (kill-buffer))))))
  16644. (cond
  16645. (mathml
  16646. (setq mathml
  16647. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  16648. (when mathml-file
  16649. (write-region mathml nil mathml-file))
  16650. (when (called-interactively-p 'any)
  16651. (message mathml)))
  16652. ((message "LaTeX to MathML conversion failed")
  16653. (message shell-command-output)))
  16654. (delete-file tmp-in-file)
  16655. (when (file-exists-p tmp-out-file)
  16656. (delete-file tmp-out-file))
  16657. mathml))
  16658. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  16659. prefix &optional dir)
  16660. "Use `org-create-math-formula' but check local cache first."
  16661. (let* ((absprefix (expand-file-name prefix dir))
  16662. (print-length nil) (print-level nil)
  16663. (formula-id (concat
  16664. "formula-"
  16665. (sha1
  16666. (prin1-to-string
  16667. (list latex-frag
  16668. org-latex-to-mathml-convert-command)))))
  16669. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  16670. (formula-cache-dir (file-name-directory formula-cache)))
  16671. (unless (file-directory-p formula-cache-dir)
  16672. (make-directory formula-cache-dir t))
  16673. (unless (file-exists-p formula-cache)
  16674. (org-create-math-formula latex-frag formula-cache))
  16675. (if (file-exists-p formula-cache)
  16676. ;; Successful conversion. Return the link to MathML file.
  16677. (org-add-props
  16678. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  16679. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  16680. 'org-latex-src-embed-type (if latex-frag-type
  16681. 'paragraph 'character)))
  16682. ;; Failed conversion. Return the LaTeX fragment verbatim
  16683. latex-frag)))
  16684. (defun org--get-display-dpi ()
  16685. "Get the DPI of the display.
  16686. The function assumes that the display has the same pixel width in
  16687. the horizontal and vertical directions."
  16688. (if (display-graphic-p)
  16689. (round (/ (display-pixel-height)
  16690. (/ (display-mm-height) 25.4)))
  16691. (error "Attempt to calculate the dpi of a non-graphic display")))
  16692. (defun org-create-formula-image
  16693. (string tofile options buffer &optional processing-type)
  16694. "Create an image from LaTeX source using external processes.
  16695. The LaTeX STRING is saved to a temporary LaTeX file, then
  16696. converted to an image file by process PROCESSING-TYPE defined in
  16697. `org-preview-latex-process-alist'. A nil value defaults to
  16698. `org-preview-latex-default-process'.
  16699. The generated image file is eventually moved to TOFILE.
  16700. The OPTIONS argument controls the size, foreground color and
  16701. background color of the generated image.
  16702. When BUFFER non-nil, this function is used for LaTeX previewing.
  16703. Otherwise, it is used to deal with LaTeX snippets showed in
  16704. a HTML file."
  16705. (let* ((processing-type (or processing-type
  16706. org-preview-latex-default-process))
  16707. (processing-info
  16708. (cdr (assq processing-type org-preview-latex-process-alist)))
  16709. (programs (plist-get processing-info :programs))
  16710. (error-message (or (plist-get processing-info :message) ""))
  16711. (use-xcolor (plist-get processing-info :use-xcolor))
  16712. (image-input-type (plist-get processing-info :image-input-type))
  16713. (image-output-type (plist-get processing-info :image-output-type))
  16714. (post-clean (or (plist-get processing-info :post-clean)
  16715. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  16716. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  16717. (latex-header
  16718. (or (plist-get processing-info :latex-header)
  16719. (org-latex-make-preamble
  16720. (org-export-get-environment (org-export-get-backend 'latex))
  16721. org-format-latex-header
  16722. 'snippet)))
  16723. (latex-compiler (plist-get processing-info :latex-compiler))
  16724. (image-converter (plist-get processing-info :image-converter))
  16725. (tmpdir temporary-file-directory)
  16726. (texfilebase (make-temp-name
  16727. (expand-file-name "orgtex" tmpdir)))
  16728. (texfile (concat texfilebase ".tex"))
  16729. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  16730. '(1.0 . 1.0)))
  16731. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  16732. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  16733. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  16734. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  16735. "Black"))
  16736. (bg (or (plist-get options (if buffer :background :html-background))
  16737. "Transparent"))
  16738. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  16739. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  16740. (dolist (program programs)
  16741. (org-check-external-command program error-message))
  16742. (if use-xcolor
  16743. (progn (if (eq fg 'default)
  16744. (setq fg (org-latex-color :foreground))
  16745. (setq fg (org-latex-color-format fg)))
  16746. (if (eq bg 'default)
  16747. (setq bg (org-latex-color :background))
  16748. (setq bg (org-latex-color-format
  16749. (if (string= bg "Transparent") "white" bg))))
  16750. (with-temp-file texfile
  16751. (insert latex-header)
  16752. (insert "\n\\begin{document}\n"
  16753. "\\definecolor{fg}{rgb}{" fg "}\n"
  16754. "\\definecolor{bg}{rgb}{" bg "}\n"
  16755. "\n\\pagecolor{bg}\n"
  16756. "\n{\\color{fg}\n"
  16757. string
  16758. "\n}\n"
  16759. "\n\\end{document}\n")))
  16760. (if (eq fg 'default)
  16761. (setq fg (org-dvipng-color :foreground))
  16762. (unless (string= fg "Transparent")
  16763. (setq fg (org-dvipng-color-format fg))))
  16764. (if (eq bg 'default)
  16765. (setq bg (org-dvipng-color :background))
  16766. (unless (string= bg "Transparent")
  16767. (setq bg (org-dvipng-color-format bg))))
  16768. (with-temp-file texfile
  16769. (insert latex-header)
  16770. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  16771. (let* ((err-msg (format "Please adjust `%s' part of \
  16772. `org-preview-latex-process-alist'."
  16773. processing-type))
  16774. (image-input-file
  16775. (org-compile-file
  16776. texfile latex-compiler image-input-type err-msg log-buf))
  16777. (image-output-file
  16778. (org-compile-file
  16779. image-input-file image-converter image-output-type err-msg log-buf
  16780. `((?F . ,(shell-quote-argument fg))
  16781. (?B . ,(shell-quote-argument bg))
  16782. (?D . ,(shell-quote-argument (format "%s" dpi)))
  16783. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  16784. (copy-file image-output-file tofile 'replace)
  16785. (dolist (e post-clean)
  16786. (when (file-exists-p (concat texfilebase e))
  16787. (delete-file (concat texfilebase e))))
  16788. image-output-file)))
  16789. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  16790. "Fill a LaTeX header template TPL.
  16791. In the template, the following place holders will be recognized:
  16792. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  16793. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  16794. [PACKAGES] \\usepackage statements for PKG
  16795. [NO-PACKAGES] do not include PKG
  16796. [EXTRA] the string EXTRA
  16797. [NO-EXTRA] do not include EXTRA
  16798. For backward compatibility, if both the positive and the negative place
  16799. holder is missing, the positive one (without the \"NO-\") will be
  16800. assumed to be present at the end of the template.
  16801. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  16802. EXTRA is a string.
  16803. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  16804. (let (rpl (end ""))
  16805. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  16806. (setq rpl (if (or (match-end 1) (not def-pkg))
  16807. "" (org-latex-packages-to-string def-pkg snippets-p t))
  16808. tpl (replace-match rpl t t tpl))
  16809. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  16810. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  16811. (setq rpl (if (or (match-end 1) (not pkg))
  16812. "" (org-latex-packages-to-string pkg snippets-p t))
  16813. tpl (replace-match rpl t t tpl))
  16814. (when pkg (setq end
  16815. (concat end "\n"
  16816. (org-latex-packages-to-string pkg snippets-p)))))
  16817. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  16818. (setq rpl (if (or (match-end 1) (not extra))
  16819. "" (concat extra "\n"))
  16820. tpl (replace-match rpl t t tpl))
  16821. (when (and extra (string-match "\\S-" extra))
  16822. (setq end (concat end "\n" extra))))
  16823. (if (string-match "\\S-" end)
  16824. (concat tpl "\n" end)
  16825. tpl)))
  16826. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  16827. "Turn an alist of packages into a string with the \\usepackage macros."
  16828. (setq pkg (mapconcat (lambda(p)
  16829. (cond
  16830. ((stringp p) p)
  16831. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  16832. (format "%% Package %s omitted" (cadr p)))
  16833. ((equal "" (car p))
  16834. (format "\\usepackage{%s}" (cadr p)))
  16835. (t
  16836. (format "\\usepackage[%s]{%s}"
  16837. (car p) (cadr p)))))
  16838. pkg
  16839. "\n"))
  16840. (if newline (concat pkg "\n") pkg))
  16841. (defun org-dvipng-color (attr)
  16842. "Return a RGB color specification for dvipng."
  16843. (org-dvipng-color-format (face-attribute 'default attr nil)))
  16844. (defun org-dvipng-color-format (color-name)
  16845. "Convert COLOR-NAME to a RGB color value for dvipng."
  16846. (apply #'format "rgb %s %s %s"
  16847. (mapcar 'org-normalize-color
  16848. (color-values color-name))))
  16849. (defun org-latex-color (attr)
  16850. "Return a RGB color for the LaTeX color package."
  16851. (org-latex-color-format (face-attribute 'default attr nil)))
  16852. (defun org-latex-color-format (color-name)
  16853. "Convert COLOR-NAME to a RGB color value."
  16854. (apply #'format "%s,%s,%s"
  16855. (mapcar 'org-normalize-color
  16856. (color-values color-name))))
  16857. (defun org-normalize-color (value)
  16858. "Return string to be used as color value for an RGB component."
  16859. (format "%g" (/ value 65535.0)))
  16860. ;; Image display
  16861. (defvar-local org-inline-image-overlays nil)
  16862. (defun org-toggle-inline-images (&optional include-linked)
  16863. "Toggle the display of inline images.
  16864. INCLUDE-LINKED is passed to `org-display-inline-images'."
  16865. (interactive "P")
  16866. (if org-inline-image-overlays
  16867. (progn
  16868. (org-remove-inline-images)
  16869. (when (called-interactively-p 'interactive)
  16870. (message "Inline image display turned off")))
  16871. (org-display-inline-images include-linked)
  16872. (when (called-interactively-p 'interactive)
  16873. (message (if org-inline-image-overlays
  16874. (format "%d images displayed inline"
  16875. (length org-inline-image-overlays))
  16876. "No images to display inline")))))
  16877. (defun org-redisplay-inline-images ()
  16878. "Refresh the display of inline images."
  16879. (interactive)
  16880. (if (not org-inline-image-overlays)
  16881. (org-toggle-inline-images)
  16882. (org-toggle-inline-images)
  16883. (org-toggle-inline-images)))
  16884. (defun org-display-inline-images (&optional include-linked refresh beg end)
  16885. "Display inline images.
  16886. An inline image is a link which follows either of these
  16887. conventions:
  16888. 1. Its path is a file with an extension matching return value
  16889. from `image-file-name-regexp' and it has no contents.
  16890. 2. Its description consists in a single link of the previous
  16891. type.
  16892. When optional argument INCLUDE-LINKED is non-nil, also links with
  16893. a text description part will be inlined. This can be nice for
  16894. a quick look at those images, but it does not reflect what
  16895. exported files will look like.
  16896. When optional argument REFRESH is non-nil, refresh existing
  16897. images between BEG and END. This will create new image displays
  16898. only if necessary. BEG and END default to the buffer
  16899. boundaries."
  16900. (interactive "P")
  16901. (when (display-graphic-p)
  16902. (unless refresh
  16903. (org-remove-inline-images)
  16904. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  16905. (org-with-wide-buffer
  16906. (goto-char (or beg (point-min)))
  16907. (let* ((case-fold-search t)
  16908. (file-extension-re (image-file-name-regexp))
  16909. (link-abbrevs (mapcar #'car
  16910. (append org-link-abbrev-alist-local
  16911. org-link-abbrev-alist)))
  16912. ;; Check absolute, relative file names and explicit
  16913. ;; "file:" links. Also check link abbreviations since
  16914. ;; some might expand to "file" links.
  16915. (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
  16916. (if (not link-abbrevs) ""
  16917. (format "\\|\\(?:%s:\\)"
  16918. (regexp-opt link-abbrevs))))))
  16919. (while (re-search-forward file-types-re end t)
  16920. (let ((link (save-match-data (org-element-context))))
  16921. ;; Check if we're at an inline image, i.e., an image file
  16922. ;; link without a description (unless INCLUDE-LINKED is
  16923. ;; non-nil).
  16924. (when (and (equal "file" (org-element-property :type link))
  16925. (or include-linked
  16926. (null (org-element-contents link)))
  16927. (string-match-p file-extension-re
  16928. (org-element-property :path link)))
  16929. (let ((file (expand-file-name
  16930. (org-link-unescape
  16931. (org-element-property :path link)))))
  16932. (when (file-exists-p file)
  16933. (let ((width
  16934. ;; Apply `org-image-actual-width' specifications.
  16935. (cond
  16936. ((not (image-type-available-p 'imagemagick)) nil)
  16937. ((eq org-image-actual-width t) nil)
  16938. ((listp org-image-actual-width)
  16939. (or
  16940. ;; First try to find a width among
  16941. ;; attributes associated to the paragraph
  16942. ;; containing link.
  16943. (let ((paragraph
  16944. (let ((e link))
  16945. (while (and (setq e (org-element-property
  16946. :parent e))
  16947. (not (eq (org-element-type e)
  16948. 'paragraph))))
  16949. e)))
  16950. (when paragraph
  16951. (save-excursion
  16952. (goto-char (org-element-property :begin paragraph))
  16953. (when
  16954. (re-search-forward
  16955. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  16956. (org-element-property
  16957. :post-affiliated paragraph)
  16958. t)
  16959. (string-to-number (match-string 1))))))
  16960. ;; Otherwise, fall-back to provided number.
  16961. (car org-image-actual-width)))
  16962. ((numberp org-image-actual-width)
  16963. org-image-actual-width)))
  16964. (old (get-char-property-and-overlay
  16965. (org-element-property :begin link)
  16966. 'org-image-overlay)))
  16967. (if (and (car-safe old) refresh)
  16968. (image-refresh (overlay-get (cdr old) 'display))
  16969. (let ((image (create-image file
  16970. (and width 'imagemagick)
  16971. nil
  16972. :width width)))
  16973. (when image
  16974. (let ((ov (make-overlay
  16975. (org-element-property :begin link)
  16976. (progn
  16977. (goto-char
  16978. (org-element-property :end link))
  16979. (skip-chars-backward " \t")
  16980. (point)))))
  16981. (overlay-put ov 'display image)
  16982. (overlay-put ov 'face 'default)
  16983. (overlay-put ov 'org-image-overlay t)
  16984. (overlay-put
  16985. ov 'modification-hooks
  16986. (list 'org-display-inline-remove-overlay))
  16987. (push ov org-inline-image-overlays)))))))))))))))
  16988. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  16989. "Remove inline-display overlay if a corresponding region is modified."
  16990. (let ((inhibit-modification-hooks t))
  16991. (when (and ov after)
  16992. (delete ov org-inline-image-overlays)
  16993. (delete-overlay ov))))
  16994. (defun org-remove-inline-images ()
  16995. "Remove inline display of images."
  16996. (interactive)
  16997. (mapc #'delete-overlay org-inline-image-overlays)
  16998. (setq org-inline-image-overlays nil))
  16999. (defvar org-self-insert-command-undo-counter 0)
  17000. (defvar org-speed-command nil)
  17001. (defun org-self-insert-command (N)
  17002. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  17003. If the cursor is in a table looking at whitespace, the whitespace is
  17004. overwritten, and the table is not marked as requiring realignment."
  17005. (interactive "p")
  17006. (org-check-before-invisible-edit 'insert)
  17007. (cond
  17008. ((and org-use-speed-commands
  17009. (let ((kv (this-command-keys-vector)))
  17010. (setq org-speed-command
  17011. (run-hook-with-args-until-success
  17012. 'org-speed-command-hook
  17013. (make-string 1 (aref kv (1- (length kv))))))))
  17014. (cond
  17015. ((commandp org-speed-command)
  17016. (setq this-command org-speed-command)
  17017. (call-interactively org-speed-command))
  17018. ((functionp org-speed-command)
  17019. (funcall org-speed-command))
  17020. ((and org-speed-command (listp org-speed-command))
  17021. (eval org-speed-command))
  17022. (t (let (org-use-speed-commands)
  17023. (call-interactively 'org-self-insert-command)))))
  17024. ((and
  17025. (= N 1)
  17026. (not (org-region-active-p))
  17027. (org-at-table-p)
  17028. (progn
  17029. ;; Check if we blank the field, and if that triggers align.
  17030. (and (featurep 'org-table)
  17031. org-table-auto-blank-field
  17032. (memq last-command
  17033. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  17034. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  17035. ;; Got extra space, this field does not determine
  17036. ;; column width.
  17037. (let (org-table-may-need-update) (org-table-blank-field))
  17038. ;; No extra space, this field may determine column
  17039. ;; width.
  17040. (org-table-blank-field)))
  17041. t)
  17042. (looking-at "[^|\n]* |"))
  17043. ;; There is room for insertion without re-aligning the table.
  17044. (self-insert-command N)
  17045. (org-table-with-shrunk-field
  17046. (save-excursion
  17047. (skip-chars-forward "^|")
  17048. ;; Do not delete last space, which is
  17049. ;; `org-table-separator-space', but the regular space before
  17050. ;; it.
  17051. (delete-region (- (point) 2) (1- (point))))))
  17052. (t
  17053. (setq org-table-may-need-update t)
  17054. (self-insert-command N)
  17055. (org-fix-tags-on-the-fly)
  17056. (when org-self-insert-cluster-for-undo
  17057. (if (not (eq last-command 'org-self-insert-command))
  17058. (setq org-self-insert-command-undo-counter 1)
  17059. (if (>= org-self-insert-command-undo-counter 20)
  17060. (setq org-self-insert-command-undo-counter 1)
  17061. (and (> org-self-insert-command-undo-counter 0)
  17062. buffer-undo-list (listp buffer-undo-list)
  17063. (not (cadr buffer-undo-list)) ; remove nil entry
  17064. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  17065. (setq org-self-insert-command-undo-counter
  17066. (1+ org-self-insert-command-undo-counter))))))))
  17067. (defun org-check-before-invisible-edit (kind)
  17068. "Check is editing if kind KIND would be dangerous with invisible text around.
  17069. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  17070. ;; First, try to get out of here as quickly as possible, to reduce overhead
  17071. (when (and org-catch-invisible-edits
  17072. (or (not (boundp 'visible-mode)) (not visible-mode))
  17073. (or (get-char-property (point) 'invisible)
  17074. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  17075. ;; OK, we need to take a closer look. Do not consider
  17076. ;; invisibility obtained through text properties (e.g., link
  17077. ;; fontification), as it cannot be toggled.
  17078. (let* ((invisible-at-point
  17079. (pcase (get-char-property-and-overlay (point) 'invisible)
  17080. (`(,_ . ,(and (pred overlayp) o)) o)))
  17081. ;; Assume that point cannot land in the middle of an
  17082. ;; overlay, or between two overlays.
  17083. (invisible-before-point
  17084. (and (not invisible-at-point)
  17085. (not (bobp))
  17086. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  17087. (`(,_ . ,(and (pred overlayp) o)) o))))
  17088. (border-and-ok-direction
  17089. (or
  17090. ;; Check if we are acting predictably before invisible
  17091. ;; text.
  17092. (and invisible-at-point
  17093. (memq kind '(insert delete-backward)))
  17094. ;; Check if we are acting predictably after invisible text
  17095. ;; This works not well, and I have turned it off. It seems
  17096. ;; better to always show and stop after invisible text.
  17097. ;; (and (not invisible-at-point) invisible-before-point
  17098. ;; (memq kind '(insert delete)))
  17099. )))
  17100. (when (or invisible-at-point invisible-before-point)
  17101. (when (eq org-catch-invisible-edits 'error)
  17102. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  17103. (if (and org-custom-properties-overlays
  17104. (y-or-n-p "Display invisible properties in this buffer? "))
  17105. (org-toggle-custom-properties-visibility)
  17106. ;; Make the area visible
  17107. (save-excursion
  17108. (when invisible-before-point
  17109. (goto-char
  17110. (previous-single-char-property-change (point) 'invisible)))
  17111. ;; Remove whatever overlay is currently making yet-to-be
  17112. ;; edited text invisible. Also remove nested invisibility
  17113. ;; related overlays.
  17114. (delete-overlay (or invisible-at-point invisible-before-point))
  17115. (let ((origin (if invisible-at-point (point) (1- (point)))))
  17116. (while (pcase (get-char-property-and-overlay origin 'invisible)
  17117. (`(,_ . ,(and (pred overlayp) o))
  17118. (delete-overlay o)
  17119. t)))))
  17120. (cond
  17121. ((eq org-catch-invisible-edits 'show)
  17122. ;; That's it, we do the edit after showing
  17123. (message
  17124. "Unfolding invisible region around point before editing")
  17125. (sit-for 1))
  17126. ((and (eq org-catch-invisible-edits 'smart)
  17127. border-and-ok-direction)
  17128. (message "Unfolding invisible region around point before editing"))
  17129. (t
  17130. ;; Don't do the edit, make the user repeat it in full visibility
  17131. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  17132. (defun org-fix-tags-on-the-fly ()
  17133. "Align tags in headline at point.
  17134. Unlike `org-align-tags', this function does nothing if point is
  17135. either not currently on a tagged headline or on a tag."
  17136. (when (and (org-match-line org-tag-line-re)
  17137. (< (point) (match-beginning 1)))
  17138. (org-align-tags)))
  17139. (defun org-delete-backward-char (N)
  17140. "Like `delete-backward-char', insert whitespace at field end in tables.
  17141. When deleting backwards, in tables this function will insert whitespace in
  17142. front of the next \"|\" separator, to keep the table aligned. The table will
  17143. still be marked for re-alignment if the field did fill the entire column,
  17144. because, in this case the deletion might narrow the column."
  17145. (interactive "p")
  17146. (save-match-data
  17147. (org-check-before-invisible-edit 'delete-backward)
  17148. (if (and (= N 1)
  17149. (not overwrite-mode)
  17150. (not (org-region-active-p))
  17151. (not (eq (char-before) ?|))
  17152. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  17153. (looking-at-p ".*?|")
  17154. (org-at-table-p))
  17155. (progn (forward-char -1) (org-delete-char 1))
  17156. (backward-delete-char N)
  17157. (org-fix-tags-on-the-fly))))
  17158. (defun org-delete-char (N)
  17159. "Like `delete-char', but insert whitespace at field end in tables.
  17160. When deleting characters, in tables this function will insert whitespace in
  17161. front of the next \"|\" separator, to keep the table aligned. The table will
  17162. still be marked for re-alignment if the field did fill the entire column,
  17163. because, in this case the deletion might narrow the column."
  17164. (interactive "p")
  17165. (save-match-data
  17166. (org-check-before-invisible-edit 'delete)
  17167. (cond
  17168. ((or (/= N 1)
  17169. (eq (char-after) ?|)
  17170. (save-excursion (skip-chars-backward " \t") (bolp))
  17171. (not (org-at-table-p)))
  17172. (delete-char N)
  17173. (org-fix-tags-on-the-fly))
  17174. ((looking-at ".\\(.*?\\)|")
  17175. (let* ((update? org-table-may-need-update)
  17176. (noalign (looking-at-p ".*? |")))
  17177. (delete-char 1)
  17178. (org-table-with-shrunk-field
  17179. (save-excursion
  17180. ;; Last space is `org-table-separator-space', so insert
  17181. ;; a regular one before it instead.
  17182. (goto-char (- (match-end 0) 2))
  17183. (insert " ")))
  17184. ;; If there were two spaces at the end, this field does not
  17185. ;; determine the width of the column.
  17186. (when noalign (setq org-table-may-need-update update?))))
  17187. (t
  17188. (delete-char N)))))
  17189. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  17190. (put 'org-self-insert-command 'delete-selection
  17191. (lambda ()
  17192. (not (run-hook-with-args-until-success
  17193. 'self-insert-uses-region-functions))))
  17194. (put 'orgtbl-self-insert-command 'delete-selection
  17195. (lambda ()
  17196. (not (run-hook-with-args-until-success
  17197. 'self-insert-uses-region-functions))))
  17198. (put 'org-delete-char 'delete-selection 'supersede)
  17199. (put 'org-delete-backward-char 'delete-selection 'supersede)
  17200. (put 'org-yank 'delete-selection 'yank)
  17201. ;; Make `flyspell-mode' delay after some commands
  17202. (put 'org-self-insert-command 'flyspell-delayed t)
  17203. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  17204. (put 'org-delete-char 'flyspell-delayed t)
  17205. (put 'org-delete-backward-char 'flyspell-delayed t)
  17206. ;; Make pabbrev-mode expand after Org mode commands
  17207. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  17208. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  17209. (defun org-transpose-words ()
  17210. "Transpose words for Org.
  17211. This uses the `org-mode-transpose-word-syntax-table' syntax
  17212. table, which interprets characters in `org-emphasis-alist' as
  17213. word constituents."
  17214. (interactive)
  17215. (with-syntax-table org-mode-transpose-word-syntax-table
  17216. (call-interactively 'transpose-words)))
  17217. (defvar org-ctrl-c-ctrl-c-hook nil
  17218. "Hook for functions attaching themselves to `C-c C-c'.
  17219. This can be used to add additional functionality to the C-c C-c
  17220. key which executes context-dependent commands. This hook is run
  17221. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  17222. run after the last test.
  17223. Each function will be called with no arguments. The function
  17224. must check if the context is appropriate for it to act. If yes,
  17225. it should do its thing and then return a non-nil value. If the
  17226. context is wrong, just do nothing and return nil.")
  17227. (defvar org-ctrl-c-ctrl-c-final-hook nil
  17228. "Hook for functions attaching themselves to `C-c C-c'.
  17229. This can be used to add additional functionality to the C-c C-c
  17230. key which executes context-dependent commands. This hook is run
  17231. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  17232. before the first test.
  17233. Each function will be called with no arguments. The function
  17234. must check if the context is appropriate for it to act. If yes,
  17235. it should do its thing and then return a non-nil value. If the
  17236. context is wrong, just do nothing and return nil.")
  17237. (defvar org-tab-first-hook nil
  17238. "Hook for functions to attach themselves to TAB.
  17239. See `org-ctrl-c-ctrl-c-hook' for more information.
  17240. This hook runs as the first action when TAB is pressed, even before
  17241. `org-cycle' messes around with the `outline-regexp' to cater for
  17242. inline tasks and plain list item folding.
  17243. If any function in this hook returns t, any other actions that
  17244. would have been caused by TAB (such as table field motion or visibility
  17245. cycling) will not occur.")
  17246. (defvar org-tab-after-check-for-table-hook nil
  17247. "Hook for functions to attach themselves to TAB.
  17248. See `org-ctrl-c-ctrl-c-hook' for more information.
  17249. This hook runs after it has been established that the cursor is not in a
  17250. table, but before checking if the cursor is in a headline or if global cycling
  17251. should be done.
  17252. If any function in this hook returns t, not other actions like visibility
  17253. cycling will be done.")
  17254. (defvar org-tab-after-check-for-cycling-hook nil
  17255. "Hook for functions to attach themselves to TAB.
  17256. See `org-ctrl-c-ctrl-c-hook' for more information.
  17257. This hook runs after it has been established that not table field motion and
  17258. not visibility should be done because of current context. This is probably
  17259. the place where a package like yasnippets can hook in.")
  17260. (defvar org-tab-before-tab-emulation-hook nil
  17261. "Hook for functions to attach themselves to TAB.
  17262. See `org-ctrl-c-ctrl-c-hook' for more information.
  17263. This hook runs after every other options for TAB have been exhausted, but
  17264. before indentation and \t insertion takes place.")
  17265. (defvar org-metaleft-hook nil
  17266. "Hook for functions attaching themselves to `M-left'.
  17267. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17268. (defvar org-metaright-hook nil
  17269. "Hook for functions attaching themselves to `M-right'.
  17270. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17271. (defvar org-metaup-hook nil
  17272. "Hook for functions attaching themselves to `M-up'.
  17273. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17274. (defvar org-metadown-hook nil
  17275. "Hook for functions attaching themselves to `M-down'.
  17276. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17277. (defvar org-shiftmetaleft-hook nil
  17278. "Hook for functions attaching themselves to `M-S-left'.
  17279. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17280. (defvar org-shiftmetaright-hook nil
  17281. "Hook for functions attaching themselves to `M-S-right'.
  17282. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17283. (defvar org-shiftmetaup-hook nil
  17284. "Hook for functions attaching themselves to `M-S-up'.
  17285. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17286. (defvar org-shiftmetadown-hook nil
  17287. "Hook for functions attaching themselves to `M-S-down'.
  17288. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17289. (defvar org-metareturn-hook nil
  17290. "Hook for functions attaching themselves to `M-RET'.
  17291. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17292. (defvar org-shiftup-hook nil
  17293. "Hook for functions attaching themselves to `S-up'.
  17294. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17295. (defvar org-shiftup-final-hook nil
  17296. "Hook for functions attaching themselves to `S-up'.
  17297. This one runs after all other options except shift-select have been excluded.
  17298. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17299. (defvar org-shiftdown-hook nil
  17300. "Hook for functions attaching themselves to `S-down'.
  17301. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17302. (defvar org-shiftdown-final-hook nil
  17303. "Hook for functions attaching themselves to `S-down'.
  17304. This one runs after all other options except shift-select have been excluded.
  17305. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17306. (defvar org-shiftleft-hook nil
  17307. "Hook for functions attaching themselves to `S-left'.
  17308. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17309. (defvar org-shiftleft-final-hook nil
  17310. "Hook for functions attaching themselves to `S-left'.
  17311. This one runs after all other options except shift-select have been excluded.
  17312. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17313. (defvar org-shiftright-hook nil
  17314. "Hook for functions attaching themselves to `S-right'.
  17315. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17316. (defvar org-shiftright-final-hook nil
  17317. "Hook for functions attaching themselves to `S-right'.
  17318. This one runs after all other options except shift-select have been excluded.
  17319. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17320. (defun org-modifier-cursor-error ()
  17321. "Throw an error, a modified cursor command was applied in wrong context."
  17322. (user-error "This command is active in special context like tables, headlines or items"))
  17323. (defun org-shiftselect-error ()
  17324. "Throw an error because Shift-Cursor command was applied in wrong context."
  17325. (if (and (boundp 'shift-select-mode) shift-select-mode)
  17326. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  17327. (user-error "This command works only in special context like headlines or timestamps")))
  17328. (defun org-call-for-shift-select (cmd)
  17329. (let ((this-command-keys-shift-translated t))
  17330. (call-interactively cmd)))
  17331. (defun org-shifttab (&optional arg)
  17332. "Global visibility cycling or move to previous table field.
  17333. Call `org-table-previous-field' within a table.
  17334. When ARG is nil, cycle globally through visibility states.
  17335. When ARG is a numeric prefix, show contents of this level."
  17336. (interactive "P")
  17337. (cond
  17338. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  17339. ((integerp arg)
  17340. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  17341. (message "Content view to level: %d" arg)
  17342. (org-content (prefix-numeric-value arg2))
  17343. (org-cycle-show-empty-lines t)
  17344. (setq org-cycle-global-status 'overview)))
  17345. (t (call-interactively 'org-global-cycle))))
  17346. (defun org-shiftmetaleft ()
  17347. "Promote subtree or delete table column.
  17348. Calls `org-promote-subtree', `org-outdent-item-tree', or
  17349. `org-table-delete-column', depending on context. See the
  17350. individual commands for more information."
  17351. (interactive)
  17352. (cond
  17353. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  17354. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  17355. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  17356. ((if (not (org-region-active-p)) (org-at-item-p)
  17357. (save-excursion (goto-char (region-beginning))
  17358. (org-at-item-p)))
  17359. (call-interactively 'org-outdent-item-tree))
  17360. (t (org-modifier-cursor-error))))
  17361. (defun org-shiftmetaright ()
  17362. "Demote subtree or insert table column.
  17363. Calls `org-demote-subtree', `org-indent-item-tree', or
  17364. `org-table-insert-column', depending on context. See the
  17365. individual commands for more information."
  17366. (interactive)
  17367. (cond
  17368. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  17369. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  17370. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  17371. ((if (not (org-region-active-p)) (org-at-item-p)
  17372. (save-excursion (goto-char (region-beginning))
  17373. (org-at-item-p)))
  17374. (call-interactively 'org-indent-item-tree))
  17375. (t (org-modifier-cursor-error))))
  17376. (defun org-shiftmetaup (&optional _arg)
  17377. "Drag the line at point up.
  17378. In a table, kill the current row.
  17379. On a clock timestamp, update the value of the timestamp like `S-<up>'
  17380. but also adjust the previous clocked item in the clock history.
  17381. Everywhere else, drag the line at point up."
  17382. (interactive "P")
  17383. (cond
  17384. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  17385. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  17386. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17387. (call-interactively 'org-timestamp-up)))
  17388. (t (call-interactively 'org-drag-line-backward))))
  17389. (defun org-shiftmetadown (&optional _arg)
  17390. "Drag the line at point down.
  17391. In a table, insert an empty row at the current line.
  17392. On a clock timestamp, update the value of the timestamp like `S-<down>'
  17393. but also adjust the previous clocked item in the clock history.
  17394. Everywhere else, drag the line at point down."
  17395. (interactive "P")
  17396. (cond
  17397. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  17398. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  17399. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17400. (call-interactively 'org-timestamp-down)))
  17401. (t (call-interactively 'org-drag-line-forward))))
  17402. (defsubst org-hidden-tree-error ()
  17403. (user-error
  17404. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  17405. (defun org-metaleft (&optional _arg)
  17406. "Promote heading, list item at point or move table column left.
  17407. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  17408. depending on context. With no specific context, calls the Emacs
  17409. default `backward-word'. See the individual commands for more
  17410. information.
  17411. This function runs the hook `org-metaleft-hook' as a first step,
  17412. and returns at first non-nil value."
  17413. (interactive "P")
  17414. (cond
  17415. ((run-hook-with-args-until-success 'org-metaleft-hook))
  17416. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  17417. ((org-with-limited-levels
  17418. (or (org-at-heading-p)
  17419. (and (org-region-active-p)
  17420. (save-excursion
  17421. (goto-char (region-beginning))
  17422. (org-at-heading-p)))))
  17423. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  17424. (call-interactively 'org-do-promote))
  17425. ;; At an inline task.
  17426. ((org-at-heading-p)
  17427. (call-interactively 'org-inlinetask-promote))
  17428. ((or (org-at-item-p)
  17429. (and (org-region-active-p)
  17430. (save-excursion
  17431. (goto-char (region-beginning))
  17432. (org-at-item-p))))
  17433. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  17434. (call-interactively 'org-outdent-item))
  17435. (t (call-interactively 'backward-word))))
  17436. (defun org-metaright (&optional _arg)
  17437. "Demote heading, list item at point or move table column right.
  17438. In front of a drawer or a block keyword, indent it correctly.
  17439. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  17440. `org-indent-drawer' or `org-indent-block' depending on context.
  17441. With no specific context, calls the Emacs default `forward-word'.
  17442. See the individual commands for more information.
  17443. This function runs the hook `org-metaright-hook' as a first step,
  17444. and returns at first non-nil value."
  17445. (interactive "P")
  17446. (cond
  17447. ((run-hook-with-args-until-success 'org-metaright-hook))
  17448. ((org-at-table-p) (call-interactively 'org-table-move-column))
  17449. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  17450. ((org-at-block-p) (call-interactively 'org-indent-block))
  17451. ((org-with-limited-levels
  17452. (or (org-at-heading-p)
  17453. (and (org-region-active-p)
  17454. (save-excursion
  17455. (goto-char (region-beginning))
  17456. (org-at-heading-p)))))
  17457. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  17458. (call-interactively 'org-do-demote))
  17459. ;; At an inline task.
  17460. ((org-at-heading-p)
  17461. (call-interactively 'org-inlinetask-demote))
  17462. ((or (org-at-item-p)
  17463. (and (org-region-active-p)
  17464. (save-excursion
  17465. (goto-char (region-beginning))
  17466. (org-at-item-p))))
  17467. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  17468. (call-interactively 'org-indent-item))
  17469. (t (call-interactively 'forward-word))))
  17470. (defun org-check-for-hidden (what)
  17471. "Check if there are hidden headlines/items in the current visual line.
  17472. WHAT can be either `headlines' or `items'. If the current line is
  17473. an outline or item heading and it has a folded subtree below it,
  17474. this function returns t, nil otherwise."
  17475. (let ((re (cond
  17476. ((eq what 'headlines) org-outline-regexp-bol)
  17477. ((eq what 'items) (org-item-beginning-re))
  17478. (t (error "This should not happen"))))
  17479. beg end)
  17480. (save-excursion
  17481. (catch 'exit
  17482. (unless (org-region-active-p)
  17483. (setq beg (point-at-bol))
  17484. (beginning-of-line 2)
  17485. (while (and (not (eobp)) ;; this is like `next-line'
  17486. (get-char-property (1- (point)) 'invisible))
  17487. (beginning-of-line 2))
  17488. (setq end (point))
  17489. (goto-char beg)
  17490. (goto-char (point-at-eol))
  17491. (setq end (max end (point)))
  17492. (while (re-search-forward re end t)
  17493. (when (get-char-property (match-beginning 0) 'invisible)
  17494. (throw 'exit t))))
  17495. nil))))
  17496. (defun org-metaup (&optional _arg)
  17497. "Move subtree up or move table row up.
  17498. Calls `org-move-subtree-up' or `org-table-move-row' or
  17499. `org-move-item-up', depending on context. See the individual commands
  17500. for more information."
  17501. (interactive "P")
  17502. (cond
  17503. ((run-hook-with-args-until-success 'org-metaup-hook))
  17504. ((org-region-active-p)
  17505. (let* ((a (save-excursion
  17506. (goto-char (min (region-beginning) (region-end)))
  17507. (line-beginning-position)))
  17508. (b (save-excursion
  17509. (goto-char (max (region-beginning) (region-end)))
  17510. (if (bolp) (1- (point)) (line-end-position))))
  17511. (c (save-excursion
  17512. (goto-char a)
  17513. (move-beginning-of-line 0)
  17514. (point)))
  17515. (d (save-excursion
  17516. (goto-char a)
  17517. (move-end-of-line 0)
  17518. (point))))
  17519. (transpose-regions a b c d)
  17520. (goto-char c)))
  17521. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  17522. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  17523. ((org-at-item-p) (call-interactively 'org-move-item-up))
  17524. (t (org-drag-element-backward))))
  17525. (defun org-metadown (&optional _arg)
  17526. "Move subtree down or move table row down.
  17527. Calls `org-move-subtree-down' or `org-table-move-row' or
  17528. `org-move-item-down', depending on context. See the individual
  17529. commands for more information."
  17530. (interactive "P")
  17531. (cond
  17532. ((run-hook-with-args-until-success 'org-metadown-hook))
  17533. ((org-region-active-p)
  17534. (let* ((a (save-excursion
  17535. (goto-char (min (region-beginning) (region-end)))
  17536. (line-beginning-position)))
  17537. (b (save-excursion
  17538. (goto-char (max (region-beginning) (region-end)))
  17539. (if (bolp) (1- (point)) (line-end-position))))
  17540. (c (save-excursion
  17541. (goto-char b)
  17542. (move-beginning-of-line (if (bolp) 1 2))
  17543. (point)))
  17544. (d (save-excursion
  17545. (goto-char b)
  17546. (move-end-of-line (if (bolp) 1 2))
  17547. (point))))
  17548. (transpose-regions a b c d)
  17549. (goto-char d)))
  17550. ((org-at-table-p) (call-interactively 'org-table-move-row))
  17551. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  17552. ((org-at-item-p) (call-interactively 'org-move-item-down))
  17553. (t (org-drag-element-forward))))
  17554. (defun org-shiftup (&optional arg)
  17555. "Act on current element according to context.
  17556. Call `org-timestamp-up' or `org-priority-up', or
  17557. `org-previous-item', or `org-table-move-cell-up'. See the
  17558. individual commands for more information."
  17559. (interactive "P")
  17560. (cond
  17561. ((run-hook-with-args-until-success 'org-shiftup-hook))
  17562. ((and org-support-shift-select (org-region-active-p))
  17563. (org-call-for-shift-select 'previous-line))
  17564. ((org-at-timestamp-p 'lax)
  17565. (call-interactively (if org-edit-timestamp-down-means-later
  17566. 'org-timestamp-down 'org-timestamp-up)))
  17567. ((and (not (eq org-support-shift-select 'always))
  17568. org-enable-priority-commands
  17569. (org-at-heading-p))
  17570. (call-interactively 'org-priority-up))
  17571. ((and (not org-support-shift-select) (org-at-item-p))
  17572. (call-interactively 'org-previous-item))
  17573. ((org-clocktable-try-shift 'up arg))
  17574. ((org-at-table-p) (org-table-move-cell-up))
  17575. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  17576. (org-support-shift-select
  17577. (org-call-for-shift-select 'previous-line))
  17578. (t (org-shiftselect-error))))
  17579. (defun org-shiftdown (&optional arg)
  17580. "Act on current element according to context.
  17581. Call `org-timestamp-down' or `org-priority-down', or
  17582. `org-next-item', or `org-table-move-cell-down'. See the
  17583. individual commands for more information."
  17584. (interactive "P")
  17585. (cond
  17586. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  17587. ((and org-support-shift-select (org-region-active-p))
  17588. (org-call-for-shift-select 'next-line))
  17589. ((org-at-timestamp-p 'lax)
  17590. (call-interactively (if org-edit-timestamp-down-means-later
  17591. 'org-timestamp-up 'org-timestamp-down)))
  17592. ((and (not (eq org-support-shift-select 'always))
  17593. org-enable-priority-commands
  17594. (org-at-heading-p))
  17595. (call-interactively 'org-priority-down))
  17596. ((and (not org-support-shift-select) (org-at-item-p))
  17597. (call-interactively 'org-next-item))
  17598. ((org-clocktable-try-shift 'down arg))
  17599. ((org-at-table-p) (org-table-move-cell-down))
  17600. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  17601. (org-support-shift-select
  17602. (org-call-for-shift-select 'next-line))
  17603. (t (org-shiftselect-error))))
  17604. (defun org-shiftright (&optional arg)
  17605. "Act on the current element according to context.
  17606. This does one of the following:
  17607. - switch a timestamp at point one day into the future
  17608. - on a headline, switch to the next TODO keyword.
  17609. - on an item, switch entire list to the next bullet type
  17610. - on a property line, switch to the next allowed value
  17611. - on a clocktable definition line, move time block into the future
  17612. - in a table, move a single cell right"
  17613. (interactive "P")
  17614. (cond
  17615. ((run-hook-with-args-until-success 'org-shiftright-hook))
  17616. ((and org-support-shift-select (org-region-active-p))
  17617. (org-call-for-shift-select 'forward-char))
  17618. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  17619. ((and (not (eq org-support-shift-select 'always))
  17620. (org-at-heading-p))
  17621. (let ((org-inhibit-logging
  17622. (not org-treat-S-cursor-todo-selection-as-state-change))
  17623. (org-inhibit-blocking
  17624. (not org-treat-S-cursor-todo-selection-as-state-change)))
  17625. (org-call-with-arg 'org-todo 'right)))
  17626. ((or (and org-support-shift-select
  17627. (not (eq org-support-shift-select 'always))
  17628. (org-at-item-bullet-p))
  17629. (and (not org-support-shift-select) (org-at-item-p)))
  17630. (org-call-with-arg 'org-cycle-list-bullet nil))
  17631. ((and (not (eq org-support-shift-select 'always))
  17632. (org-at-property-p))
  17633. (call-interactively 'org-property-next-allowed-value))
  17634. ((org-clocktable-try-shift 'right arg))
  17635. ((org-at-table-p) (org-table-move-cell-right))
  17636. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  17637. (org-support-shift-select
  17638. (org-call-for-shift-select 'forward-char))
  17639. (t (org-shiftselect-error))))
  17640. (defun org-shiftleft (&optional arg)
  17641. "Act on current element according to context.
  17642. This does one of the following:
  17643. - switch a timestamp at point one day into the past
  17644. - on a headline, switch to the previous TODO keyword.
  17645. - on an item, switch entire list to the previous bullet type
  17646. - on a property line, switch to the previous allowed value
  17647. - on a clocktable definition line, move time block into the past
  17648. - in a table, move a single cell left"
  17649. (interactive "P")
  17650. (cond
  17651. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  17652. ((and org-support-shift-select (org-region-active-p))
  17653. (org-call-for-shift-select 'backward-char))
  17654. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  17655. ((and (not (eq org-support-shift-select 'always))
  17656. (org-at-heading-p))
  17657. (let ((org-inhibit-logging
  17658. (not org-treat-S-cursor-todo-selection-as-state-change))
  17659. (org-inhibit-blocking
  17660. (not org-treat-S-cursor-todo-selection-as-state-change)))
  17661. (org-call-with-arg 'org-todo 'left)))
  17662. ((or (and org-support-shift-select
  17663. (not (eq org-support-shift-select 'always))
  17664. (org-at-item-bullet-p))
  17665. (and (not org-support-shift-select) (org-at-item-p)))
  17666. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  17667. ((and (not (eq org-support-shift-select 'always))
  17668. (org-at-property-p))
  17669. (call-interactively 'org-property-previous-allowed-value))
  17670. ((org-clocktable-try-shift 'left arg))
  17671. ((org-at-table-p) (org-table-move-cell-left))
  17672. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  17673. (org-support-shift-select
  17674. (org-call-for-shift-select 'backward-char))
  17675. (t (org-shiftselect-error))))
  17676. (defun org-shiftcontrolright ()
  17677. "Switch to next TODO set."
  17678. (interactive)
  17679. (cond
  17680. ((and org-support-shift-select (org-region-active-p))
  17681. (org-call-for-shift-select 'forward-word))
  17682. ((and (not (eq org-support-shift-select 'always))
  17683. (org-at-heading-p))
  17684. (org-call-with-arg 'org-todo 'nextset))
  17685. (org-support-shift-select
  17686. (org-call-for-shift-select 'forward-word))
  17687. (t (org-shiftselect-error))))
  17688. (defun org-shiftcontrolleft ()
  17689. "Switch to previous TODO set."
  17690. (interactive)
  17691. (cond
  17692. ((and org-support-shift-select (org-region-active-p))
  17693. (org-call-for-shift-select 'backward-word))
  17694. ((and (not (eq org-support-shift-select 'always))
  17695. (org-at-heading-p))
  17696. (org-call-with-arg 'org-todo 'previousset))
  17697. (org-support-shift-select
  17698. (org-call-for-shift-select 'backward-word))
  17699. (t (org-shiftselect-error))))
  17700. (defun org-shiftcontrolup (&optional n)
  17701. "Change timestamps synchronously up in CLOCK log lines.
  17702. Optional argument N tells to change by that many units."
  17703. (interactive "P")
  17704. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  17705. (let (org-support-shift-select)
  17706. (org-clock-timestamps-up n))
  17707. (user-error "Not at a clock log")))
  17708. (defun org-shiftcontroldown (&optional n)
  17709. "Change timestamps synchronously down in CLOCK log lines.
  17710. Optional argument N tells to change by that many units."
  17711. (interactive "P")
  17712. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  17713. (let (org-support-shift-select)
  17714. (org-clock-timestamps-down n))
  17715. (user-error "Not at a clock log")))
  17716. (defun org-increase-number-at-point (&optional inc)
  17717. "Increment the number at point.
  17718. With an optional prefix numeric argument INC, increment using
  17719. this numeric value."
  17720. (interactive "p")
  17721. (if (not (number-at-point))
  17722. (user-error "Not on a number")
  17723. (unless inc (setq inc 1))
  17724. (let ((pos (point))
  17725. (beg (skip-chars-backward "-+^/*0-9eE."))
  17726. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  17727. (setq nap (buffer-substring-no-properties
  17728. (+ pos beg) (+ pos beg end)))
  17729. (delete-region (+ pos beg) (+ pos beg end))
  17730. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  17731. (when (org-at-table-p)
  17732. (org-table-align)
  17733. (org-table-end-of-field 1))))
  17734. (defun org-decrease-number-at-point (&optional inc)
  17735. "Decrement the number at point.
  17736. With an optional prefix numeric argument INC, decrement using
  17737. this numeric value."
  17738. (interactive "p")
  17739. (org-increase-number-at-point (- (or inc 1))))
  17740. (defun org-ctrl-c-ret ()
  17741. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  17742. (interactive)
  17743. (cond
  17744. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  17745. (t (call-interactively 'org-insert-heading))))
  17746. (defun org-find-visible ()
  17747. (let ((s (point)))
  17748. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  17749. (get-char-property s 'invisible)))
  17750. s))
  17751. (defun org-find-invisible ()
  17752. (let ((s (point)))
  17753. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  17754. (not (get-char-property s 'invisible))))
  17755. s))
  17756. (defun org-copy-visible (beg end)
  17757. "Copy the visible parts of the region."
  17758. (interactive "r")
  17759. (let ((result ""))
  17760. (while (/= beg end)
  17761. (when (get-char-property beg 'invisible)
  17762. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  17763. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  17764. (setq result (concat result (buffer-substring beg next)))
  17765. (setq beg next)))
  17766. (setq deactivate-mark t)
  17767. (kill-new result)
  17768. (message "Visible strings have been copied to the kill ring.")))
  17769. (defun org-copy-special ()
  17770. "Copy region in table or copy current subtree.
  17771. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  17772. context. See the individual commands for more information."
  17773. (interactive)
  17774. (call-interactively
  17775. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  17776. (defun org-cut-special ()
  17777. "Cut region in table or cut current subtree.
  17778. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  17779. context. See the individual commands for more information."
  17780. (interactive)
  17781. (call-interactively
  17782. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  17783. (defun org-paste-special (arg)
  17784. "Paste rectangular region into table, or past subtree relative to level.
  17785. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  17786. See the individual commands for more information."
  17787. (interactive "P")
  17788. (if (org-at-table-p)
  17789. (org-table-paste-rectangle)
  17790. (org-paste-subtree arg)))
  17791. (defun org-edit-special (&optional arg)
  17792. "Call a special editor for the element at point.
  17793. When at a table, call the formula editor with `org-table-edit-formulas'.
  17794. When in a source code block, call `org-edit-src-code'.
  17795. When in a fixed-width region, call `org-edit-fixed-width-region'.
  17796. When in an export block, call `org-edit-export-block'.
  17797. When in a LaTeX environment, call `org-edit-latex-environment'.
  17798. When at an #+INCLUDE keyword, visit the included file.
  17799. When at a footnote reference, call `org-edit-footnote-reference'.
  17800. When at a planning line call, `org-deadline' and/or `org-schedule'.
  17801. When at an active timestamp, call `org-time-stamp'.
  17802. When at an inactive timestamp, call `org-time-stamp-inactive'.
  17803. On a link, call `ffap' to visit the link at point.
  17804. Otherwise, return a user error."
  17805. (interactive "P")
  17806. (let ((element (org-element-at-point)))
  17807. (barf-if-buffer-read-only)
  17808. (pcase (org-element-type element)
  17809. (`src-block
  17810. (if (not arg) (org-edit-src-code)
  17811. (let* ((info (org-babel-get-src-block-info))
  17812. (lang (nth 0 info))
  17813. (params (nth 2 info))
  17814. (session (cdr (assq :session params))))
  17815. (if (not session) (org-edit-src-code)
  17816. ;; At a source block with a session and function called
  17817. ;; with an ARG: switch to the buffer related to the
  17818. ;; inferior process.
  17819. (switch-to-buffer
  17820. (funcall (intern (concat "org-babel-prep-session:" lang))
  17821. session params))))))
  17822. (`keyword
  17823. (unless (member (org-element-property :key element)
  17824. '("INCLUDE" "SETUPFILE"))
  17825. (user-error "No special environment to edit here"))
  17826. (org-open-link-from-string
  17827. (format "[[%s]]"
  17828. (expand-file-name
  17829. (let ((value (org-strip-quotes
  17830. (org-element-property :value element))))
  17831. (cond
  17832. ((not (org-string-nw-p value))
  17833. (user-error "No file to edit"))
  17834. ((org-file-url-p value)
  17835. (user-error "Files located with a URL cannot be edited"))
  17836. (t value)))))))
  17837. (`table
  17838. (if (eq (org-element-property :type element) 'table.el)
  17839. (org-edit-table.el)
  17840. (call-interactively 'org-table-edit-formulas)))
  17841. ;; Only Org tables contain `table-row' type elements.
  17842. (`table-row (call-interactively 'org-table-edit-formulas))
  17843. (`example-block (org-edit-src-code))
  17844. (`export-block (org-edit-export-block))
  17845. (`fixed-width (org-edit-fixed-width-region))
  17846. (`latex-environment (org-edit-latex-environment))
  17847. (`planning
  17848. (let ((proplist (cadr element)))
  17849. (mapc #'call-interactively
  17850. (remq nil
  17851. (list
  17852. (when (plist-get proplist :deadline) #'org-deadline)
  17853. (when (plist-get proplist :scheduled) #'org-schedule))))))
  17854. (_
  17855. ;; No notable element at point. Though, we may be at a link or
  17856. ;; a footnote reference, which are objects. Thus, scan deeper.
  17857. (let ((context (org-element-context element)))
  17858. (pcase (org-element-type context)
  17859. (`footnote-reference (org-edit-footnote-reference))
  17860. (`inline-src-block (org-edit-inline-src-code))
  17861. (`timestamp (if (eq 'inactive (org-element-property :type context))
  17862. (call-interactively #'org-time-stamp-inactive)
  17863. (call-interactively #'org-time-stamp)))
  17864. (`link (call-interactively #'ffap))
  17865. (_ (user-error "No special environment to edit here"))))))))
  17866. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  17867. (defun org-ctrl-c-ctrl-c (&optional arg)
  17868. "Set tags in headline, or update according to changed information at point.
  17869. This command does many different things, depending on context:
  17870. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  17871. this is what we do.
  17872. - If the cursor is on a statistics cookie, update it.
  17873. - If the cursor is in a headline, prompt for tags and insert them
  17874. into the current line, aligned to `org-tags-column'. When called
  17875. with prefix arg, realign all tags in the current buffer.
  17876. - If the cursor is in one of the special #+KEYWORD lines, this
  17877. triggers scanning the buffer for these lines and updating the
  17878. information.
  17879. - If the cursor is inside a table, realign the table. This command
  17880. works even if the automatic table editor has been turned off.
  17881. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  17882. the entire table.
  17883. - If the cursor is at a footnote reference or definition, jump to
  17884. the corresponding definition or references, respectively.
  17885. - If the cursor is a the beginning of a dynamic block, update it.
  17886. - If the current buffer is a capture buffer, close note and file it.
  17887. - If the cursor is on a <<<target>>>, update radio targets and
  17888. corresponding links in this buffer.
  17889. - If the cursor is on a numbered item in a plain list, renumber the
  17890. ordered list.
  17891. - If the cursor is on a checkbox, toggle it.
  17892. - If the cursor is on a code block, evaluate it. The variable
  17893. `org-confirm-babel-evaluate' can be used to control prompting
  17894. before code block evaluation, by default every code block
  17895. evaluation requires confirmation. Code block evaluation can be
  17896. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  17897. (interactive "P")
  17898. (cond
  17899. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  17900. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  17901. (org-remove-occur-highlights)
  17902. (message "Temporary highlights/overlays removed from current buffer"))
  17903. ((and (local-variable-p 'org-finish-function)
  17904. (fboundp org-finish-function))
  17905. (funcall org-finish-function))
  17906. ((org-babel-hash-at-point))
  17907. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  17908. (t
  17909. (let* ((context
  17910. (org-element-lineage
  17911. (org-element-context)
  17912. ;; Limit to supported contexts.
  17913. '(babel-call clock dynamic-block footnote-definition
  17914. footnote-reference inline-babel-call inline-src-block
  17915. inlinetask item keyword node-property paragraph
  17916. plain-list planning property-drawer radio-target
  17917. src-block statistics-cookie table table-cell table-row
  17918. timestamp)
  17919. t))
  17920. (type (org-element-type context)))
  17921. ;; For convenience: at the first line of a paragraph on the same
  17922. ;; line as an item, apply function on that item instead.
  17923. (when (eq type 'paragraph)
  17924. (let ((parent (org-element-property :parent context)))
  17925. (when (and (eq (org-element-type parent) 'item)
  17926. (= (line-beginning-position)
  17927. (org-element-property :begin parent)))
  17928. (setq context parent)
  17929. (setq type 'item))))
  17930. ;; Act according to type of element or object at point.
  17931. ;;
  17932. ;; Do nothing on a blank line, except if it is contained in
  17933. ;; a source block. Hence, we first check if point is in such
  17934. ;; a block and then if it is at a blank line.
  17935. (pcase type
  17936. ((or `inline-src-block `src-block)
  17937. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  17938. (org-babel-eval-wipe-error-buffer)
  17939. (org-babel-execute-src-block
  17940. current-prefix-arg (org-babel-get-src-block-info nil context))))
  17941. ((guard (org-match-line "[ \t]*$"))
  17942. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  17943. (user-error
  17944. (substitute-command-keys
  17945. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  17946. ((or `babel-call `inline-babel-call)
  17947. (let ((info (org-babel-lob-get-info context)))
  17948. (when info (org-babel-execute-src-block nil info))))
  17949. (`clock (org-clock-update-time-maybe))
  17950. (`dynamic-block
  17951. (save-excursion
  17952. (goto-char (org-element-property :post-affiliated context))
  17953. (org-update-dblock)))
  17954. (`footnote-definition
  17955. (goto-char (org-element-property :post-affiliated context))
  17956. (call-interactively 'org-footnote-action))
  17957. (`footnote-reference (call-interactively #'org-footnote-action))
  17958. ((or `headline `inlinetask)
  17959. (save-excursion (goto-char (org-element-property :begin context))
  17960. (call-interactively #'org-set-tags-command)))
  17961. (`item
  17962. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  17963. ;; unconditionally, whereas `C-u' will toggle its presence.
  17964. ;; Without a universal argument, if the item has a checkbox,
  17965. ;; toggle it. Otherwise repair the list.
  17966. (let* ((box (org-element-property :checkbox context))
  17967. (struct (org-element-property :structure context))
  17968. (old-struct (copy-tree struct))
  17969. (parents (org-list-parents-alist struct))
  17970. (prevs (org-list-prevs-alist struct))
  17971. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  17972. (org-list-set-checkbox
  17973. (org-element-property :begin context) struct
  17974. (cond ((equal arg '(16)) "[-]")
  17975. ((and (not box) (equal arg '(4))) "[ ]")
  17976. ((or (not box) (equal arg '(4))) nil)
  17977. ((eq box 'on) "[ ]")
  17978. (t "[X]")))
  17979. ;; Mimic `org-list-write-struct' but with grabbing a return
  17980. ;; value from `org-list-struct-fix-box'.
  17981. (org-list-struct-fix-ind struct parents 2)
  17982. (org-list-struct-fix-item-end struct)
  17983. (org-list-struct-fix-bul struct prevs)
  17984. (org-list-struct-fix-ind struct parents)
  17985. (let ((block-item
  17986. (org-list-struct-fix-box struct parents prevs orderedp)))
  17987. (if (and box (equal struct old-struct))
  17988. (if (equal arg '(16))
  17989. (message "Checkboxes already reset")
  17990. (user-error "Cannot toggle this checkbox: %s"
  17991. (if (eq box 'on)
  17992. "all subitems checked"
  17993. "unchecked subitems")))
  17994. (org-list-struct-apply-struct struct old-struct)
  17995. (org-update-checkbox-count-maybe))
  17996. (when block-item
  17997. (message "Checkboxes were removed due to empty box at line %d"
  17998. (org-current-line block-item))))))
  17999. (`keyword
  18000. (let ((org-inhibit-startup-visibility-stuff t)
  18001. (org-startup-align-all-tables nil))
  18002. (when (boundp 'org-table-coordinate-overlays)
  18003. (mapc #'delete-overlay org-table-coordinate-overlays)
  18004. (setq org-table-coordinate-overlays nil))
  18005. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  18006. (message "Local setup has been refreshed"))
  18007. (`plain-list
  18008. ;; At a plain list, with a double C-u argument, set
  18009. ;; checkboxes of each item to "[-]", whereas a single one
  18010. ;; will toggle their presence according to the state of the
  18011. ;; first item in the list. Without an argument, repair the
  18012. ;; list.
  18013. (let* ((begin (org-element-property :contents-begin context))
  18014. (struct (org-element-property :structure context))
  18015. (old-struct (copy-tree struct))
  18016. (first-box (save-excursion
  18017. (goto-char begin)
  18018. (looking-at org-list-full-item-re)
  18019. (match-string-no-properties 3)))
  18020. (new-box (cond ((equal arg '(16)) "[-]")
  18021. ((equal arg '(4)) (unless first-box "[ ]"))
  18022. ((equal first-box "[X]") "[ ]")
  18023. (t "[X]"))))
  18024. (cond
  18025. (arg
  18026. (dolist (pos
  18027. (org-list-get-all-items
  18028. begin struct (org-list-prevs-alist struct)))
  18029. (org-list-set-checkbox pos struct new-box)))
  18030. ((and first-box (eq (point) begin))
  18031. ;; For convenience, when point is at bol on the first
  18032. ;; item of the list and no argument is provided, simply
  18033. ;; toggle checkbox of that item, if any.
  18034. (org-list-set-checkbox begin struct new-box)))
  18035. (when (equal
  18036. (org-list-write-struct
  18037. struct (org-list-parents-alist struct) old-struct)
  18038. old-struct)
  18039. (message "Cannot update this checkbox"))
  18040. (org-update-checkbox-count-maybe)))
  18041. ((or `property-drawer `node-property)
  18042. (call-interactively #'org-property-action))
  18043. (`radio-target
  18044. (call-interactively #'org-update-radio-target-regexp))
  18045. (`statistics-cookie
  18046. (call-interactively #'org-update-statistics-cookies))
  18047. ((or `table `table-cell `table-row)
  18048. ;; At a table, recalculate every field and align it. Also
  18049. ;; send the table if necessary. If the table has
  18050. ;; a `table.el' type, just give up. At a table row or cell,
  18051. ;; maybe recalculate line but always align table.
  18052. (if (eq (org-element-property :type context) 'table.el)
  18053. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  18054. Use `\\[org-edit-special]' to edit table.el tables"))
  18055. (if (or (eq type 'table)
  18056. ;; Check if point is at a TBLFM line.
  18057. (and (eq type 'table-row)
  18058. (= (point) (org-element-property :end context))))
  18059. (save-excursion
  18060. (if (org-at-TBLFM-p)
  18061. (progn (require 'org-table)
  18062. (org-table-calc-current-TBLFM))
  18063. (goto-char (org-element-property :contents-begin context))
  18064. (org-call-with-arg 'org-table-recalculate (or arg t))
  18065. (orgtbl-send-table 'maybe)))
  18066. (org-table-maybe-eval-formula)
  18067. (cond (arg (call-interactively #'org-table-recalculate))
  18068. ((org-table-maybe-recalculate-line))
  18069. (t (org-table-align))))))
  18070. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  18071. (org-timestamp-change 0 'day))
  18072. ((and `nil (guard (org-at-heading-p)))
  18073. ;; When point is on an unsupported object type, we can miss
  18074. ;; the fact that it also is at a heading. Handle it here.
  18075. (call-interactively #'org-set-tags-command))
  18076. ((guard
  18077. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  18078. (_
  18079. (user-error
  18080. (substitute-command-keys
  18081. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  18082. (defun org-mode-restart ()
  18083. (interactive)
  18084. (let ((indent-status (bound-and-true-p org-indent-mode)))
  18085. (funcall major-mode)
  18086. (hack-local-variables)
  18087. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  18088. (org-indent-mode -1))
  18089. (org-reset-file-cache))
  18090. (message "%s restarted" major-mode))
  18091. (defun org-kill-note-or-show-branches ()
  18092. "Abort storing current note, or call `outline-show-branches'."
  18093. (interactive)
  18094. (if (not org-finish-function)
  18095. (save-excursion
  18096. (save-restriction
  18097. (org-narrow-to-subtree)
  18098. (org-flag-subtree t)
  18099. (call-interactively 'outline-show-branches)
  18100. (org-hide-archived-subtrees (point-min) (point-max))))
  18101. (let ((org-note-abort t))
  18102. (funcall org-finish-function))))
  18103. (defun org-delete-indentation (&optional arg)
  18104. "Join current line to previous and fix whitespace at join.
  18105. If previous line is a headline add to headline title. Otherwise
  18106. the function calls `delete-indentation'.
  18107. With a non-nil optional argument, join it to the following one."
  18108. (interactive "*P")
  18109. (if (save-excursion
  18110. (beginning-of-line (if arg 1 0))
  18111. (let ((case-fold-search nil))
  18112. (looking-at org-complex-heading-regexp)))
  18113. ;; At headline.
  18114. (let ((tags-column (when (match-beginning 5)
  18115. (save-excursion (goto-char (match-beginning 5))
  18116. (current-column))))
  18117. (string (concat " " (progn (when arg (forward-line 1))
  18118. (org-trim (delete-and-extract-region
  18119. (line-beginning-position)
  18120. (line-end-position)))))))
  18121. (unless (bobp) (delete-region (point) (1- (point))))
  18122. (goto-char (or (match-end 4)
  18123. (match-beginning 5)
  18124. (match-end 0)))
  18125. (skip-chars-backward " \t")
  18126. (save-excursion (insert string))
  18127. ;; Adjust alignment of tags.
  18128. (cond
  18129. ((not tags-column)) ;no tags
  18130. (org-auto-align-tags (org-align-tags))
  18131. (t (org--align-tags-here tags-column)))) ;preserve tags column
  18132. (delete-indentation arg)))
  18133. (defun org-open-line (n)
  18134. "Insert a new row in tables, call `open-line' elsewhere.
  18135. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  18136. As a special case, when a document starts with a table, allow to
  18137. call `open-line' on the very first character."
  18138. (interactive "*p")
  18139. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  18140. (org-table-insert-row)
  18141. (open-line n)))
  18142. (defun org-return (&optional indent)
  18143. "Goto next table row or insert a newline.
  18144. Calls `org-table-next-row' or `newline', depending on context.
  18145. When optional INDENT argument is non-nil, call
  18146. `newline-and-indent' instead of `newline'.
  18147. When `org-return-follows-link' is non-nil and point is on
  18148. a timestamp or a link, call `org-open-at-point'. However, it
  18149. will not happen if point is in a table or on a \"dead\"
  18150. object (e.g., within a comment). In these case, you need to use
  18151. `org-open-at-point' directly."
  18152. (interactive)
  18153. (let ((context (if org-return-follows-link (org-element-context)
  18154. (org-element-at-point))))
  18155. (cond
  18156. ;; In a table, call `org-table-next-row'. However, before first
  18157. ;; column or after last one, split the table.
  18158. ((or (and (eq 'table (org-element-type context))
  18159. (not (eq 'table.el (org-element-property :type context)))
  18160. (>= (point) (org-element-property :contents-begin context))
  18161. (< (point) (org-element-property :contents-end context)))
  18162. (org-element-lineage context '(table-row table-cell) t))
  18163. (if (or (looking-at-p "[ \t]*$")
  18164. (save-excursion (skip-chars-backward " \t") (bolp)))
  18165. (insert "\n")
  18166. (org-table-justify-field-maybe)
  18167. (call-interactively #'org-table-next-row)))
  18168. ;; On a link or a timestamp, call `org-open-at-point' if
  18169. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  18170. ;; locations, e.g., in a comment, as `org-open-at-point'.
  18171. ((and org-return-follows-link
  18172. (or (and (eq 'link (org-element-type context))
  18173. ;; Ensure point is not on the white spaces after
  18174. ;; the link.
  18175. (let ((origin (point)))
  18176. (org-with-point-at (org-element-property :end context)
  18177. (skip-chars-backward " \t")
  18178. (> (point) origin))))
  18179. (org-in-regexp org-ts-regexp-both nil t)
  18180. (org-in-regexp org-tsr-regexp-both nil t)
  18181. (org-in-regexp org-any-link-re nil t)))
  18182. (call-interactively #'org-open-at-point))
  18183. ;; Insert newline in heading, but preserve tags.
  18184. ((and (not (bolp))
  18185. (let ((case-fold-search nil))
  18186. (org-match-line org-complex-heading-regexp)))
  18187. ;; At headline. Split line. However, if point is on keyword,
  18188. ;; priority cookie or tags, do not break any of them: add
  18189. ;; a newline after the headline instead.
  18190. (let ((tags-column (and (match-beginning 5)
  18191. (save-excursion (goto-char (match-beginning 5))
  18192. (current-column))))
  18193. (string
  18194. (when (and (match-end 4) (org-point-in-group (point) 4))
  18195. (delete-and-extract-region (point) (match-end 4)))))
  18196. ;; Adjust tag alignment.
  18197. (cond
  18198. ((not (and tags-column string)))
  18199. (org-auto-align-tags (org-align-tags))
  18200. (t (org--align-tags-here tags-column))) ;preserve tags column
  18201. (end-of-line)
  18202. (org-show-entry)
  18203. (if indent (newline-and-indent) (newline))
  18204. (when string (save-excursion (insert (org-trim string))))))
  18205. ;; In a list, make sure indenting keeps trailing text within.
  18206. ((and indent
  18207. (not (eolp))
  18208. (org-element-lineage context '(item)))
  18209. (let ((trailing-data
  18210. (delete-and-extract-region (point) (line-end-position))))
  18211. (newline-and-indent)
  18212. (save-excursion (insert trailing-data))))
  18213. (t
  18214. ;; Do not auto-fill when point is in an Org property drawer.
  18215. (let ((auto-fill-function (and (not (org-at-property-p))
  18216. auto-fill-function)))
  18217. (if indent
  18218. (newline-and-indent)
  18219. (newline)))))))
  18220. (defun org-return-indent ()
  18221. "Goto next table row or insert a newline and indent.
  18222. Calls `org-table-next-row' or `newline-and-indent', depending on
  18223. context. See the individual commands for more information."
  18224. (interactive)
  18225. (org-return t))
  18226. (defun org-ctrl-c-tab (&optional _arg)
  18227. "Toggle columns width in a table, or show children.
  18228. Call `org-table-toggle-column-width' if point is in a table.
  18229. Otherwise, call `org-show-children'."
  18230. (interactive "p")
  18231. (call-interactively
  18232. (if (org-at-table-p) #'org-table-toggle-column-width
  18233. #'org-show-children)))
  18234. (defun org-ctrl-c-star ()
  18235. "Compute table, or change heading status of lines.
  18236. Calls `org-table-recalculate' or `org-toggle-heading',
  18237. depending on context."
  18238. (interactive)
  18239. (cond
  18240. ((org-at-table-p)
  18241. (call-interactively 'org-table-recalculate))
  18242. (t
  18243. ;; Convert all lines in region to list items
  18244. (call-interactively 'org-toggle-heading))))
  18245. (defun org-ctrl-c-minus ()
  18246. "Insert separator line in table or modify bullet status of line.
  18247. Also turns a plain line or a region of lines into list items.
  18248. Calls `org-table-insert-hline', `org-toggle-item', or
  18249. `org-cycle-list-bullet', depending on context."
  18250. (interactive)
  18251. (cond
  18252. ((org-at-table-p)
  18253. (call-interactively 'org-table-insert-hline))
  18254. ((org-region-active-p)
  18255. (call-interactively 'org-toggle-item))
  18256. ((org-in-item-p)
  18257. (call-interactively 'org-cycle-list-bullet))
  18258. (t
  18259. (call-interactively 'org-toggle-item))))
  18260. (defun org-toggle-heading (&optional nstars)
  18261. "Convert headings to normal text, or items or text to headings.
  18262. If there is no active region, only convert the current line.
  18263. With a `\\[universal-argument]' prefix, convert the whole list at
  18264. point into heading.
  18265. In a region:
  18266. - If the first non blank line is a headline, remove the stars
  18267. from all headlines in the region.
  18268. - If it is a normal line, turn each and every normal line (i.e.,
  18269. not an heading or an item) in the region into headings. If you
  18270. want to convert only the first line of this region, use one
  18271. universal prefix argument.
  18272. - If it is a plain list item, turn all plain list items into headings.
  18273. When converting a line into a heading, the number of stars is chosen
  18274. such that the lines become children of the current entry. However,
  18275. when a numeric prefix argument is given, its value determines the
  18276. number of stars to add."
  18277. (interactive "P")
  18278. (let ((skip-blanks
  18279. (function
  18280. ;; Return beginning of first non-blank line, starting from
  18281. ;; line at POS.
  18282. (lambda (pos)
  18283. (save-excursion
  18284. (goto-char pos)
  18285. (while (org-at-comment-p) (forward-line))
  18286. (skip-chars-forward " \r\t\n")
  18287. (point-at-bol)))))
  18288. beg end toggled)
  18289. ;; Determine boundaries of changes. If a universal prefix has
  18290. ;; been given, put the list in a region. If region ends at a bol,
  18291. ;; do not consider the last line to be in the region.
  18292. (when (and current-prefix-arg (org-at-item-p))
  18293. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  18294. (org-mark-element))
  18295. (if (org-region-active-p)
  18296. (setq beg (funcall skip-blanks (region-beginning))
  18297. end (copy-marker (save-excursion
  18298. (goto-char (region-end))
  18299. (if (bolp) (point) (point-at-eol)))))
  18300. (setq beg (funcall skip-blanks (point-at-bol))
  18301. end (copy-marker (point-at-eol))))
  18302. ;; Ensure inline tasks don't count as headings.
  18303. (org-with-limited-levels
  18304. (save-excursion
  18305. (goto-char beg)
  18306. (cond
  18307. ;; Case 1. Started at an heading: de-star headings.
  18308. ((org-at-heading-p)
  18309. (while (< (point) end)
  18310. (when (org-at-heading-p t)
  18311. (looking-at org-outline-regexp) (replace-match "")
  18312. (setq toggled t))
  18313. (forward-line)))
  18314. ;; Case 2. Started at an item: change items into headlines.
  18315. ;; One star will be added by `org-list-to-subtree'.
  18316. ((org-at-item-p)
  18317. (while (< (point) end)
  18318. (when (org-at-item-p)
  18319. ;; Pay attention to cases when region ends before list.
  18320. (let* ((struct (org-list-struct))
  18321. (list-end
  18322. (min (org-list-get-bottom-point struct) (1+ end))))
  18323. (save-restriction
  18324. (narrow-to-region (point) list-end)
  18325. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  18326. (setq toggled t))
  18327. (forward-line)))
  18328. ;; Case 3. Started at normal text: make every line an heading,
  18329. ;; skipping headlines and items.
  18330. (t (let* ((stars
  18331. (make-string
  18332. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  18333. (add-stars
  18334. (cond (nstars "") ; stars from prefix only
  18335. ((equal stars "") "*") ; before first heading
  18336. (org-odd-levels-only "**") ; inside heading, odd
  18337. (t "*"))) ; inside heading, oddeven
  18338. (rpl (concat stars add-stars " "))
  18339. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  18340. (while (< (point) (if (equal nstars '(4)) lend end))
  18341. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  18342. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  18343. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  18344. (forward-line)))))))
  18345. (unless toggled (message "Cannot toggle heading from here"))))
  18346. (defun org-meta-return (&optional arg)
  18347. "Insert a new heading or wrap a region in a table.
  18348. Calls `org-insert-heading', `org-insert-item' or
  18349. `org-table-wrap-region', depending on context. When called with
  18350. an argument, unconditionally call `org-insert-heading'."
  18351. (interactive "P")
  18352. (org-check-before-invisible-edit 'insert)
  18353. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  18354. (call-interactively (cond (arg #'org-insert-heading)
  18355. ((org-at-table-p) #'org-table-wrap-region)
  18356. ((org-in-item-p) #'org-insert-item)
  18357. (t #'org-insert-heading)))))
  18358. ;;; Menu entries
  18359. (defsubst org-in-subtree-not-table-p ()
  18360. "Are we in a subtree and not in a table?"
  18361. (and (not (org-before-first-heading-p))
  18362. (not (org-at-table-p))))
  18363. ;; Define the Org mode menus
  18364. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  18365. '("Tbl"
  18366. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  18367. ["Next Field" org-cycle (org-at-table-p)]
  18368. ["Previous Field" org-shifttab (org-at-table-p)]
  18369. ["Next Row" org-return (org-at-table-p)]
  18370. "--"
  18371. ["Blank Field" org-table-blank-field (org-at-table-p)]
  18372. ["Edit Field" org-table-edit-field (org-at-table-p)]
  18373. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  18374. "--"
  18375. ("Column"
  18376. ["Move Column Left" org-metaleft (org-at-table-p)]
  18377. ["Move Column Right" org-metaright (org-at-table-p)]
  18378. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  18379. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  18380. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  18381. ("Row"
  18382. ["Move Row Up" org-metaup (org-at-table-p)]
  18383. ["Move Row Down" org-metadown (org-at-table-p)]
  18384. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  18385. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  18386. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  18387. "--"
  18388. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  18389. ("Rectangle"
  18390. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  18391. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  18392. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  18393. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  18394. "--"
  18395. ("Calculate"
  18396. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  18397. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  18398. ["Edit Formulas" org-edit-special (org-at-table-p)]
  18399. "--"
  18400. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  18401. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  18402. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  18403. "--"
  18404. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  18405. "--"
  18406. ["Sum Column/Rectangle" org-table-sum
  18407. (or (org-at-table-p) (org-region-active-p))]
  18408. ["Which Column?" org-table-current-column (org-at-table-p)])
  18409. ["Debug Formulas"
  18410. org-table-toggle-formula-debugger
  18411. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  18412. ["Show Col/Row Numbers"
  18413. org-table-toggle-coordinate-overlays
  18414. :style toggle
  18415. :selected (bound-and-true-p org-table-overlay-coordinates)]
  18416. "--"
  18417. ["Create" org-table-create (not (org-at-table-p))]
  18418. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  18419. ["Import from File" org-table-import (not (org-at-table-p))]
  18420. ["Export to File" org-table-export (org-at-table-p)]
  18421. "--"
  18422. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  18423. "--"
  18424. ("Plot"
  18425. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  18426. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  18427. (easy-menu-define org-org-menu org-mode-map "Org menu"
  18428. '("Org"
  18429. ("Show/Hide"
  18430. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  18431. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  18432. ["Sparse Tree..." org-sparse-tree t]
  18433. ["Reveal Context" org-reveal t]
  18434. ["Show All" org-show-all t]
  18435. "--"
  18436. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  18437. "--"
  18438. ["New Heading" org-insert-heading t]
  18439. ("Navigate Headings"
  18440. ["Up" outline-up-heading t]
  18441. ["Next" outline-next-visible-heading t]
  18442. ["Previous" outline-previous-visible-heading t]
  18443. ["Next Same Level" outline-forward-same-level t]
  18444. ["Previous Same Level" outline-backward-same-level t]
  18445. "--"
  18446. ["Jump" org-goto t])
  18447. ("Edit Structure"
  18448. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  18449. "--"
  18450. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  18451. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  18452. "--"
  18453. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  18454. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  18455. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  18456. "--"
  18457. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  18458. "--"
  18459. ["Copy visible text" org-copy-visible t]
  18460. "--"
  18461. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  18462. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  18463. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  18464. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  18465. "--"
  18466. ["Sort Region/Children" org-sort t]
  18467. "--"
  18468. ["Convert to odd levels" org-convert-to-odd-levels t]
  18469. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  18470. ("Editing"
  18471. ["Emphasis..." org-emphasize t]
  18472. ["Edit Source Example" org-edit-special t]
  18473. "--"
  18474. ["Footnote new/jump" org-footnote-action t]
  18475. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  18476. ("Archive"
  18477. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  18478. "--"
  18479. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  18480. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  18481. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  18482. )
  18483. "--"
  18484. ("Hyperlinks"
  18485. ["Store Link (Global)" org-store-link t]
  18486. ["Find existing link to here" org-occur-link-in-agenda-files t]
  18487. ["Insert Link" org-insert-link t]
  18488. ["Follow Link" org-open-at-point t]
  18489. "--"
  18490. ["Next link" org-next-link t]
  18491. ["Previous link" org-previous-link t]
  18492. "--"
  18493. ["Descriptive Links"
  18494. org-toggle-link-display
  18495. :style radio
  18496. :selected org-descriptive-links
  18497. ]
  18498. ["Literal Links"
  18499. org-toggle-link-display
  18500. :style radio
  18501. :selected (not org-descriptive-links)])
  18502. "--"
  18503. ("TODO Lists"
  18504. ["TODO/DONE/-" org-todo t]
  18505. ("Select keyword"
  18506. ["Next keyword" org-shiftright (org-at-heading-p)]
  18507. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  18508. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  18509. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  18510. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  18511. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  18512. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  18513. "--"
  18514. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  18515. :selected org-enforce-todo-dependencies :style toggle :active t]
  18516. "Settings for tree at point"
  18517. ["Do Children sequentially" org-toggle-ordered-property :style radio
  18518. :selected (org-entry-get nil "ORDERED")
  18519. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  18520. ["Do Children parallel" org-toggle-ordered-property :style radio
  18521. :selected (not (org-entry-get nil "ORDERED"))
  18522. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  18523. "--"
  18524. ["Set Priority" org-priority t]
  18525. ["Priority Up" org-shiftup t]
  18526. ["Priority Down" org-shiftdown t]
  18527. "--"
  18528. ["Get news from all feeds" org-feed-update-all t]
  18529. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  18530. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  18531. ("TAGS and Properties"
  18532. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  18533. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  18534. "--"
  18535. ["Set property" org-set-property (not (org-before-first-heading-p))]
  18536. ["Column view of properties" org-columns t]
  18537. ["Insert Column View DBlock" org-columns-insert-dblock t])
  18538. ("Dates and Scheduling"
  18539. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  18540. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  18541. ("Change Date"
  18542. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  18543. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  18544. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  18545. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  18546. ["Compute Time Range" org-evaluate-time-range t]
  18547. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  18548. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  18549. "--"
  18550. ["Custom time format" org-toggle-time-stamp-overlays
  18551. :style radio :selected org-display-custom-times]
  18552. "--"
  18553. ["Goto Calendar" org-goto-calendar t]
  18554. ["Date from Calendar" org-date-from-calendar t]
  18555. "--"
  18556. ["Start/Restart Timer" org-timer-start t]
  18557. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  18558. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  18559. ["Insert Timer String" org-timer t]
  18560. ["Insert Timer Item" org-timer-item t])
  18561. ("Logging work"
  18562. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  18563. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  18564. ["Clock out" org-clock-out t]
  18565. ["Clock cancel" org-clock-cancel t]
  18566. "--"
  18567. ["Mark as default task" org-clock-mark-default-task t]
  18568. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  18569. ["Goto running clock" org-clock-goto t]
  18570. "--"
  18571. ["Display times" org-clock-display t]
  18572. ["Create clock table" org-clock-report t]
  18573. "--"
  18574. ["Record DONE time"
  18575. (progn (setq org-log-done (not org-log-done))
  18576. (message "Switching to %s will %s record a timestamp"
  18577. (car org-done-keywords)
  18578. (if org-log-done "automatically" "not")))
  18579. :style toggle :selected org-log-done])
  18580. "--"
  18581. ["Agenda Command..." org-agenda t]
  18582. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  18583. ("File List for Agenda")
  18584. ("Special views current file"
  18585. ["TODO Tree" org-show-todo-tree t]
  18586. ["Check Deadlines" org-check-deadlines t]
  18587. ["Tags/Property tree" org-match-sparse-tree t])
  18588. "--"
  18589. ["Export/Publish..." org-export-dispatch t]
  18590. ("LaTeX"
  18591. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  18592. :style toggle :selected org-cdlatex-mode]
  18593. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  18594. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  18595. ["Modify math symbol" org-cdlatex-math-modify
  18596. (org-inside-LaTeX-fragment-p)]
  18597. ["Insert citation" org-reftex-citation t])
  18598. "--"
  18599. ("MobileOrg"
  18600. ["Push Files and Views" org-mobile-push t]
  18601. ["Get Captured and Flagged" org-mobile-pull t]
  18602. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
  18603. "--"
  18604. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  18605. "--"
  18606. ("Documentation"
  18607. ["Show Version" org-version t]
  18608. ["Info Documentation" org-info t]
  18609. ["Browse Org News" org-browse-news t])
  18610. ("Customize"
  18611. ["Browse Org Group" org-customize t]
  18612. "--"
  18613. ["Expand This Menu" org-create-customize-menu
  18614. (fboundp 'customize-menu-create)])
  18615. ["Send bug report" org-submit-bug-report t]
  18616. "--"
  18617. ("Refresh/Reload"
  18618. ["Refresh setup current buffer" org-mode-restart t]
  18619. ["Reload Org (after update)" org-reload t]
  18620. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  18621. (defun org-info (&optional node)
  18622. "Read documentation for Org in the info system.
  18623. With optional NODE, go directly to that node."
  18624. (interactive)
  18625. (info (format "(org)%s" (or node ""))))
  18626. (defun org-browse-news ()
  18627. "Browse the news for the latest major release."
  18628. (interactive)
  18629. (browse-url "https://orgmode.org/Changes.html"))
  18630. ;;;###autoload
  18631. (defun org-submit-bug-report ()
  18632. "Submit a bug report on Org via mail.
  18633. Don't hesitate to report any problems or inaccurate documentation.
  18634. If you don't have setup sending mail from (X)Emacs, please copy the
  18635. output buffer into your mail program, as it gives us important
  18636. information about your Org version and configuration."
  18637. (interactive)
  18638. (require 'reporter)
  18639. (defvar reporter-prompt-for-summary-p)
  18640. (org-load-modules-maybe)
  18641. (org-require-autoloaded-modules)
  18642. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  18643. (reporter-submit-bug-report
  18644. "emacs-orgmode@gnu.org"
  18645. (org-version nil 'full)
  18646. (let (list)
  18647. (save-window-excursion
  18648. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  18649. (delete-other-windows)
  18650. (erase-buffer)
  18651. (insert "You are about to submit a bug report to the Org mailing list.
  18652. We would like to add your full Org and Outline configuration to the
  18653. bug report. This greatly simplifies the work of the maintainer and
  18654. other experts on the mailing list.
  18655. HOWEVER, some variables you have customized may contain private
  18656. information. The names of customers, colleagues, or friends, might
  18657. appear in the form of file names, tags, todo states, or search strings.
  18658. If you answer yes to the prompt, you might want to check and remove
  18659. such private information before sending the email.")
  18660. (add-text-properties (point-min) (point-max) '(face org-warning))
  18661. (when (yes-or-no-p "Include your Org configuration ")
  18662. (mapatoms
  18663. (lambda (v)
  18664. (and (boundp v)
  18665. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  18666. (or (and (symbol-value v)
  18667. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  18668. (and
  18669. (get v 'custom-type) (get v 'standard-value)
  18670. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  18671. (push v list)))))
  18672. (kill-buffer (get-buffer "*Warn about privacy*"))
  18673. list))
  18674. nil nil
  18675. "Remember to cover the basics, that is, what you expected to happen and
  18676. what in fact did happen. You don't know how to make a good report? See
  18677. https://orgmode.org/manual/Feedback.html#Feedback
  18678. Your bug report will be posted to the Org mailing list.
  18679. ------------------------------------------------------------------------")
  18680. (save-excursion
  18681. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  18682. (replace-match "\\1Bug: \\3 [\\2]")))))
  18683. (defun org-install-agenda-files-menu ()
  18684. (let ((bl (buffer-list)))
  18685. (save-excursion
  18686. (while bl
  18687. (set-buffer (pop bl))
  18688. (when (derived-mode-p 'org-mode) (setq bl nil)))
  18689. (when (derived-mode-p 'org-mode)
  18690. (easy-menu-change
  18691. '("Org") "File List for Agenda"
  18692. (append
  18693. (list
  18694. ["Edit File List" (org-edit-agenda-file-list) t]
  18695. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  18696. ["Remove Current File from List" org-remove-file t]
  18697. ["Cycle through agenda files" org-cycle-agenda-files t]
  18698. ["Occur in all agenda files" org-occur-in-agenda-files t]
  18699. "--")
  18700. (mapcar 'org-file-menu-entry
  18701. ;; Prevent initialization from failing.
  18702. (ignore-errors (org-agenda-files t)))))))))
  18703. ;;;; Documentation
  18704. (defun org-require-autoloaded-modules ()
  18705. (interactive)
  18706. (mapc #'require
  18707. '(org-agenda org-archive org-attach org-clock org-colview org-id
  18708. org-table org-timer)))
  18709. ;;;###autoload
  18710. (defun org-reload (&optional uncompiled)
  18711. "Reload all Org Lisp files.
  18712. With prefix arg UNCOMPILED, load the uncompiled versions."
  18713. (interactive "P")
  18714. (require 'loadhist)
  18715. (let* ((org-dir (org-find-library-dir "org"))
  18716. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  18717. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  18718. (remove-re (format "\\`%s\\'"
  18719. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  18720. (feats (delete-dups
  18721. (mapcar 'file-name-sans-extension
  18722. (mapcar 'file-name-nondirectory
  18723. (delq nil
  18724. (mapcar 'feature-file
  18725. features))))))
  18726. (lfeat (append
  18727. (sort
  18728. (setq feats
  18729. (delq nil (mapcar
  18730. (lambda (f)
  18731. (if (and (string-match feature-re f)
  18732. (not (string-match remove-re f)))
  18733. f nil))
  18734. feats)))
  18735. 'string-lessp)
  18736. (list "org-version" "org")))
  18737. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  18738. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  18739. load-uncore load-misses)
  18740. (setq load-misses
  18741. (delq 't
  18742. (mapcar (lambda (f)
  18743. (or (org-load-noerror-mustsuffix (concat org-dir f))
  18744. (and (string= org-dir contrib-dir)
  18745. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  18746. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  18747. (add-to-list 'load-uncore f 'append)
  18748. 't)
  18749. f))
  18750. lfeat)))
  18751. (when load-uncore
  18752. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  18753. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  18754. (if load-misses
  18755. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  18756. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  18757. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  18758. ;;;###autoload
  18759. (defun org-customize ()
  18760. "Call the customize function with org as argument."
  18761. (interactive)
  18762. (org-load-modules-maybe)
  18763. (org-require-autoloaded-modules)
  18764. (customize-browse 'org))
  18765. (defun org-create-customize-menu ()
  18766. "Create a full customization menu for Org mode, insert it into the menu."
  18767. (interactive)
  18768. (org-load-modules-maybe)
  18769. (org-require-autoloaded-modules)
  18770. (if (fboundp 'customize-menu-create)
  18771. (progn
  18772. (easy-menu-change
  18773. '("Org") "Customize"
  18774. `(["Browse Org group" org-customize t]
  18775. "--"
  18776. ,(customize-menu-create 'org)
  18777. ["Set" Custom-set t]
  18778. ["Save" Custom-save t]
  18779. ["Reset to Current" Custom-reset-current t]
  18780. ["Reset to Saved" Custom-reset-saved t]
  18781. ["Reset to Standard Settings" Custom-reset-standard t]))
  18782. (message "\"Org\"-menu now contains full customization menu"))
  18783. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  18784. ;;;; Miscellaneous stuff
  18785. ;;; Generally useful functions
  18786. (defun org-link-display-format (s)
  18787. "Replace links in string S with their description.
  18788. If there is no description, use the link target."
  18789. (save-match-data
  18790. (replace-regexp-in-string
  18791. org-bracket-link-analytic-regexp
  18792. (lambda (m)
  18793. (if (match-end 5) (match-string 5 m)
  18794. (concat (match-string 1 m) (match-string 3 m))))
  18795. s nil t)))
  18796. (defun org-toggle-link-display ()
  18797. "Toggle the literal or descriptive display of links."
  18798. (interactive)
  18799. (if org-descriptive-links
  18800. (remove-from-invisibility-spec '(org-link))
  18801. (add-to-invisibility-spec '(org-link)))
  18802. (org-restart-font-lock)
  18803. (setq org-descriptive-links (not org-descriptive-links)))
  18804. (defun org-in-clocktable-p ()
  18805. "Check if the cursor is in a clocktable."
  18806. (let ((pos (point)) start)
  18807. (save-excursion
  18808. (end-of-line 1)
  18809. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  18810. (setq start (match-beginning 0))
  18811. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  18812. (>= (match-end 0) pos)
  18813. start))))
  18814. (defun org-in-verbatim-emphasis ()
  18815. (save-match-data
  18816. (and (org-in-regexp org-verbatim-re 2)
  18817. (>= (point) (match-beginning 3))
  18818. (<= (point) (match-end 4)))))
  18819. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  18820. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  18821. (if (and marker (marker-buffer marker)
  18822. (buffer-live-p (marker-buffer marker)))
  18823. (progn
  18824. (pop-to-buffer-same-window (marker-buffer marker))
  18825. (when (or (> marker (point-max)) (< marker (point-min)))
  18826. (widen))
  18827. (goto-char marker)
  18828. (org-show-context 'org-goto))
  18829. (if bookmark
  18830. (bookmark-jump bookmark)
  18831. (error "Cannot find location"))))
  18832. (defun org-quote-csv-field (s)
  18833. "Quote field for inclusion in CSV material."
  18834. (if (string-match "[\",]" s)
  18835. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  18836. s))
  18837. (defun org-force-self-insert (N)
  18838. "Needed to enforce self-insert under remapping."
  18839. (interactive "p")
  18840. (self-insert-command N))
  18841. (defun org-fill-template (template alist)
  18842. "Find each %key of ALIST in TEMPLATE and replace it."
  18843. (let ((case-fold-search nil))
  18844. (dolist (entry (sort (copy-sequence alist)
  18845. (lambda (a b) (< (length (car a)) (length (car b))))))
  18846. (setq template
  18847. (replace-regexp-in-string
  18848. (concat "%" (regexp-quote (car entry)))
  18849. (or (cdr entry) "") template t t)))
  18850. template))
  18851. (defun org-quote-vert (s)
  18852. "Replace \"|\" with \"\\vert\"."
  18853. (while (string-match "|" s)
  18854. (setq s (replace-match "\\vert" t t s)))
  18855. s)
  18856. (defun org-uuidgen-p (s)
  18857. "Is S an ID created by UUIDGEN?"
  18858. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  18859. (defun org-in-src-block-p (&optional inside)
  18860. "Whether point is in a code source block.
  18861. When INSIDE is non-nil, don't consider we are within a source
  18862. block when point is at #+BEGIN_SRC or #+END_SRC."
  18863. (let ((case-fold-search t))
  18864. (or (and (eq (get-char-property (point) 'src-block) t))
  18865. (and (not inside)
  18866. (save-match-data
  18867. (save-excursion
  18868. (beginning-of-line)
  18869. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  18870. (defun org-context ()
  18871. "Return a list of contexts of the current cursor position.
  18872. If several contexts apply, all are returned.
  18873. Each context entry is a list with a symbol naming the context, and
  18874. two positions indicating start and end of the context. Possible
  18875. contexts are:
  18876. :headline anywhere in a headline
  18877. :headline-stars on the leading stars in a headline
  18878. :todo-keyword on a TODO keyword (including DONE) in a headline
  18879. :tags on the TAGS in a headline
  18880. :priority on the priority cookie in a headline
  18881. :item on the first line of a plain list item
  18882. :item-bullet on the bullet/number of a plain list item
  18883. :checkbox on the checkbox in a plain list item
  18884. :table in an Org table
  18885. :table-special on a special filed in a table
  18886. :table-table in a table.el table
  18887. :clocktable in a clocktable
  18888. :src-block in a source block
  18889. :link on a hyperlink
  18890. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  18891. :target on a <<target>>
  18892. :radio-target on a <<<radio-target>>>
  18893. :latex-fragment on a LaTeX fragment
  18894. :latex-preview on a LaTeX fragment with overlaid preview image
  18895. This function expects the position to be visible because it uses font-lock
  18896. faces as a help to recognize the following contexts: :table-special, :link,
  18897. and :keyword."
  18898. (let* ((f (get-text-property (point) 'face))
  18899. (faces (if (listp f) f (list f)))
  18900. (case-fold-search t)
  18901. (p (point)) clist o)
  18902. ;; First the large context
  18903. (cond
  18904. ((org-at-heading-p t)
  18905. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  18906. (when (progn
  18907. (beginning-of-line 1)
  18908. (looking-at org-todo-line-tags-regexp))
  18909. (push (org-point-in-group p 1 :headline-stars) clist)
  18910. (push (org-point-in-group p 2 :todo-keyword) clist)
  18911. (push (org-point-in-group p 4 :tags) clist))
  18912. (goto-char p)
  18913. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  18914. (when (looking-at "\\[#[A-Z0-9]\\]")
  18915. (push (org-point-in-group p 0 :priority) clist)))
  18916. ((org-at-item-p)
  18917. (push (org-point-in-group p 2 :item-bullet) clist)
  18918. (push (list :item (point-at-bol)
  18919. (save-excursion (org-end-of-item) (point)))
  18920. clist)
  18921. (and (org-at-item-checkbox-p)
  18922. (push (org-point-in-group p 0 :checkbox) clist)))
  18923. ((org-at-table-p)
  18924. (push (list :table (org-table-begin) (org-table-end)) clist)
  18925. (when (memq 'org-formula faces)
  18926. (push (list :table-special
  18927. (previous-single-property-change p 'face)
  18928. (next-single-property-change p 'face)) clist)))
  18929. ((org-at-table-p 'any)
  18930. (push (list :table-table) clist)))
  18931. (goto-char p)
  18932. (let ((case-fold-search t))
  18933. ;; New the "medium" contexts: clocktables, source blocks
  18934. (cond ((org-in-clocktable-p)
  18935. (push (list :clocktable
  18936. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  18937. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  18938. (match-beginning 1))
  18939. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  18940. (match-end 0))) clist))
  18941. ((org-in-src-block-p)
  18942. (push (list :src-block
  18943. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  18944. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  18945. (match-beginning 1))
  18946. (and (search-forward "#+END_SRC" nil t)
  18947. (match-beginning 0))) clist))))
  18948. (goto-char p)
  18949. ;; Now the small context
  18950. (cond
  18951. ((org-at-timestamp-p)
  18952. (push (org-point-in-group p 0 :timestamp) clist))
  18953. ((memq 'org-link faces)
  18954. (push (list :link
  18955. (previous-single-property-change p 'face)
  18956. (next-single-property-change p 'face)) clist))
  18957. ((memq 'org-special-keyword faces)
  18958. (push (list :keyword
  18959. (previous-single-property-change p 'face)
  18960. (next-single-property-change p 'face)) clist))
  18961. ((org-at-target-p)
  18962. (push (org-point-in-group p 0 :target) clist)
  18963. (goto-char (1- (match-beginning 0)))
  18964. (when (looking-at org-radio-target-regexp)
  18965. (push (org-point-in-group p 0 :radio-target) clist))
  18966. (goto-char p))
  18967. ((setq o (cl-some
  18968. (lambda (o)
  18969. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  18970. o))
  18971. (overlays-at (point))))
  18972. (push (list :latex-fragment
  18973. (overlay-start o) (overlay-end o)) clist)
  18974. (push (list :latex-preview
  18975. (overlay-start o) (overlay-end o)) clist))
  18976. ((org-inside-LaTeX-fragment-p)
  18977. ;; FIXME: positions wrong.
  18978. (push (list :latex-fragment (point) (point)) clist)))
  18979. (setq clist (nreverse (delq nil clist)))
  18980. clist))
  18981. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  18982. "Non-nil when point is between matches of START-RE and END-RE.
  18983. Also return a non-nil value when point is on one of the matches.
  18984. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  18985. buffer positions. Default values are the positions of headlines
  18986. surrounding the point.
  18987. The functions returns a cons cell whose car (resp. cdr) is the
  18988. position before START-RE (resp. after END-RE)."
  18989. (save-match-data
  18990. (let ((pos (point))
  18991. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  18992. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  18993. beg end)
  18994. (save-excursion
  18995. ;; Point is on a block when on START-RE or if START-RE can be
  18996. ;; found before it...
  18997. (and (or (org-in-regexp start-re)
  18998. (re-search-backward start-re limit-up t))
  18999. (setq beg (match-beginning 0))
  19000. ;; ... and END-RE after it...
  19001. (goto-char (match-end 0))
  19002. (re-search-forward end-re limit-down t)
  19003. (> (setq end (match-end 0)) pos)
  19004. ;; ... without another START-RE in-between.
  19005. (goto-char (match-beginning 0))
  19006. (not (re-search-backward start-re (1+ beg) t))
  19007. ;; Return value.
  19008. (cons beg end))))))
  19009. (defun org-in-block-p (names)
  19010. "Non-nil when point belongs to a block whose name belongs to NAMES.
  19011. NAMES is a list of strings containing names of blocks.
  19012. Return first block name matched, or nil. Beware that in case of
  19013. nested blocks, the returned name may not belong to the closest
  19014. block from point."
  19015. (save-match-data
  19016. (catch 'exit
  19017. (let ((case-fold-search t)
  19018. (lim-up (save-excursion (outline-previous-heading)))
  19019. (lim-down (save-excursion (outline-next-heading))))
  19020. (dolist (name names)
  19021. (let ((n (regexp-quote name)))
  19022. (when (org-between-regexps-p
  19023. (concat "^[ \t]*#\\+begin_" n)
  19024. (concat "^[ \t]*#\\+end_" n)
  19025. lim-up lim-down)
  19026. (throw 'exit n)))))
  19027. nil)))
  19028. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  19029. "Call `multi-occur' with buffers for all agenda files."
  19030. (interactive "sOrg-files matching: ")
  19031. (let* ((files (org-agenda-files))
  19032. (tnames (mapcar #'file-truename files))
  19033. (extra org-agenda-text-search-extra-files))
  19034. (when (eq (car extra) 'agenda-archives)
  19035. (setq extra (cdr extra))
  19036. (setq files (org-add-archive-files files)))
  19037. (dolist (f extra)
  19038. (unless (member (file-truename f) tnames)
  19039. (unless (member f files) (setq files (append files (list f))))
  19040. (setq tnames (append tnames (list (file-truename f))))))
  19041. (multi-occur
  19042. (mapcar (lambda (x)
  19043. (with-current-buffer
  19044. ;; FIXME: Why not just (find-file-noselect x)?
  19045. ;; Is it to avoid the "revert buffer" prompt?
  19046. (or (get-file-buffer x) (find-file-noselect x))
  19047. (widen)
  19048. (current-buffer)))
  19049. files)
  19050. regexp)))
  19051. (add-hook 'occur-mode-find-occurrence-hook
  19052. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  19053. (defun org-occur-link-in-agenda-files ()
  19054. "Create a link and search for it in the agendas.
  19055. The link is not stored in `org-stored-links', it is just created
  19056. for the search purpose."
  19057. (interactive)
  19058. (let ((link (condition-case nil
  19059. (org-store-link nil)
  19060. (error "Unable to create a link to here"))))
  19061. (org-occur-in-agenda-files (regexp-quote link))))
  19062. (defun org-back-over-empty-lines ()
  19063. "Move backwards over whitespace, to the beginning of the first empty line.
  19064. Returns the number of empty lines passed."
  19065. (let ((pos (point)))
  19066. (if (cdr (assq 'heading org-blank-before-new-entry))
  19067. (skip-chars-backward " \t\n\r")
  19068. (unless (eobp)
  19069. (forward-line -1)))
  19070. (beginning-of-line 2)
  19071. (goto-char (min (point) pos))
  19072. (count-lines (point) pos)))
  19073. (defun org-replace-escapes (string table)
  19074. "Replace %-escapes in STRING with values in TABLE.
  19075. TABLE is an association list with keys like \"%a\" and string values.
  19076. The sequences in STRING may contain normal field width and padding information,
  19077. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  19078. so values can contain further %-escapes if they are define later in TABLE."
  19079. (let ((tbl (copy-alist table))
  19080. (case-fold-search nil)
  19081. (pchg 0)
  19082. re rpl)
  19083. (dolist (e tbl)
  19084. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  19085. (when (and (cdr e) (string-match re (cdr e)))
  19086. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  19087. (safe "SREF"))
  19088. (add-text-properties 0 3 (list 'sref sref) safe)
  19089. (setcdr e (replace-match safe t t (cdr e)))))
  19090. (while (string-match re string)
  19091. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  19092. (cdr e)))
  19093. (setq string (replace-match rpl t t string))))
  19094. (while (setq pchg (next-property-change pchg string))
  19095. (let ((sref (get-text-property pchg 'sref string)))
  19096. (when (and sref (string-match "SREF" string pchg))
  19097. (setq string (replace-match sref t t string)))))
  19098. string))
  19099. ;;; TODO: Only called once, from ox-odt which should probably use
  19100. ;;; org-export-inline-image-p or something.
  19101. (defun org-file-image-p (file)
  19102. "Return non-nil if FILE is an image."
  19103. (save-match-data
  19104. (string-match (image-file-name-regexp) file)))
  19105. (defun org-get-cursor-date (&optional with-time)
  19106. "Return the date at cursor in as a time.
  19107. This works in the calendar and in the agenda, anywhere else it just
  19108. returns the current time.
  19109. If WITH-TIME is non-nil, returns the time of the event at point (in
  19110. the agenda) or the current time of the day."
  19111. (let (date day defd tp hod mod)
  19112. (when with-time
  19113. (setq tp (get-text-property (point) 'time))
  19114. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  19115. (setq hod (string-to-number (match-string 1 tp))
  19116. mod (string-to-number (match-string 2 tp))))
  19117. (or tp (let ((now (decode-time)))
  19118. (setq hod (nth 2 now)
  19119. mod (nth 1 now)))))
  19120. (cond
  19121. ((eq major-mode 'calendar-mode)
  19122. (setq date (calendar-cursor-to-date)
  19123. defd (encode-time 0 (or mod 0) (or hod 0)
  19124. (nth 1 date) (nth 0 date) (nth 2 date))))
  19125. ((eq major-mode 'org-agenda-mode)
  19126. (setq day (get-text-property (point) 'day))
  19127. (when day
  19128. (setq date (calendar-gregorian-from-absolute day)
  19129. defd (encode-time 0 (or mod 0) (or hod 0)
  19130. (nth 1 date) (nth 0 date) (nth 2 date))))))
  19131. (or defd (current-time))))
  19132. (defun org-mark-subtree (&optional up)
  19133. "Mark the current subtree.
  19134. This puts point at the start of the current subtree, and mark at
  19135. the end. If a numeric prefix UP is given, move up into the
  19136. hierarchy of headlines by UP levels before marking the subtree."
  19137. (interactive "P")
  19138. (org-with-limited-levels
  19139. (cond ((org-at-heading-p) (beginning-of-line))
  19140. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  19141. (t (outline-previous-visible-heading 1))))
  19142. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  19143. (if (called-interactively-p 'any)
  19144. (call-interactively 'org-mark-element)
  19145. (org-mark-element)))
  19146. ;;; Indentation
  19147. (defvar org-element-greater-elements)
  19148. (defun org--get-expected-indentation (element contentsp)
  19149. "Expected indentation column for current line, according to ELEMENT.
  19150. ELEMENT is an element containing point. CONTENTSP is non-nil
  19151. when indentation is to be computed according to contents of
  19152. ELEMENT."
  19153. (let ((type (org-element-type element))
  19154. (start (org-element-property :begin element))
  19155. (post-affiliated (org-element-property :post-affiliated element)))
  19156. (org-with-wide-buffer
  19157. (cond
  19158. (contentsp
  19159. (cl-case type
  19160. ((diary-sexp footnote-definition) 0)
  19161. ((headline inlinetask nil)
  19162. (if (not org-adapt-indentation) 0
  19163. (let ((level (org-current-level)))
  19164. (if level (1+ level) 0))))
  19165. ((item plain-list) (org-list-item-body-column post-affiliated))
  19166. (t
  19167. (goto-char start)
  19168. (current-indentation))))
  19169. ((memq type '(headline inlinetask nil))
  19170. (if (org-match-line "[ \t]*$")
  19171. (org--get-expected-indentation element t)
  19172. 0))
  19173. ((memq type '(diary-sexp footnote-definition)) 0)
  19174. ;; First paragraph of a footnote definition or an item.
  19175. ;; Indent like parent.
  19176. ((< (line-beginning-position) start)
  19177. (org--get-expected-indentation
  19178. (org-element-property :parent element) t))
  19179. ;; At first line: indent according to previous sibling, if any,
  19180. ;; ignoring footnote definitions and inline tasks, or parent's
  19181. ;; contents.
  19182. ((= (line-beginning-position) start)
  19183. (catch 'exit
  19184. (while t
  19185. (if (= (point-min) start) (throw 'exit 0)
  19186. (goto-char (1- start))
  19187. (let* ((previous (org-element-at-point))
  19188. (parent previous))
  19189. (while (and parent (<= (org-element-property :end parent) start))
  19190. (setq previous parent
  19191. parent (org-element-property :parent parent)))
  19192. (cond
  19193. ((not previous) (throw 'exit 0))
  19194. ((> (org-element-property :end previous) start)
  19195. (throw 'exit (org--get-expected-indentation previous t)))
  19196. ((memq (org-element-type previous)
  19197. '(footnote-definition inlinetask))
  19198. (setq start (org-element-property :begin previous)))
  19199. (t (goto-char (org-element-property :begin previous))
  19200. (throw 'exit
  19201. (if (bolp) (current-indentation)
  19202. ;; At first paragraph in an item or
  19203. ;; a footnote definition.
  19204. (org--get-expected-indentation
  19205. (org-element-property :parent previous) t))))))))))
  19206. ;; Otherwise, move to the first non-blank line above.
  19207. (t
  19208. (beginning-of-line)
  19209. (let ((pos (point)))
  19210. (skip-chars-backward " \r\t\n")
  19211. (cond
  19212. ;; Two blank lines end a footnote definition or a plain
  19213. ;; list. When we indent an empty line after them, the
  19214. ;; containing list or footnote definition is over, so it
  19215. ;; qualifies as a previous sibling. Therefore, we indent
  19216. ;; like its first line.
  19217. ((and (memq type '(footnote-definition plain-list))
  19218. (> (count-lines (point) pos) 2))
  19219. (goto-char start)
  19220. (current-indentation))
  19221. ;; Line above is the first one of a paragraph at the
  19222. ;; beginning of an item or a footnote definition. Indent
  19223. ;; like parent.
  19224. ((< (line-beginning-position) start)
  19225. (org--get-expected-indentation
  19226. (org-element-property :parent element) t))
  19227. ;; Line above is the beginning of an element, i.e., point
  19228. ;; was originally on the blank lines between element's start
  19229. ;; and contents.
  19230. ((= (line-beginning-position) post-affiliated)
  19231. (org--get-expected-indentation element t))
  19232. ;; POS is after contents in a greater element. Indent like
  19233. ;; the beginning of the element.
  19234. ((and (memq type org-element-greater-elements)
  19235. (let ((cend (org-element-property :contents-end element)))
  19236. (and cend (<= cend pos))))
  19237. ;; As a special case, if point is at the end of a footnote
  19238. ;; definition or an item, indent like the very last element
  19239. ;; within. If that last element is an item, indent like
  19240. ;; its contents.
  19241. (if (memq type '(footnote-definition item plain-list))
  19242. (let ((last (org-element-at-point)))
  19243. (goto-char pos)
  19244. (org--get-expected-indentation
  19245. last (eq (org-element-type last) 'item)))
  19246. (goto-char start)
  19247. (current-indentation)))
  19248. ;; In any other case, indent like the current line.
  19249. (t (current-indentation)))))))))
  19250. (defun org--align-node-property ()
  19251. "Align node property at point.
  19252. Alignment is done according to `org-property-format', which see."
  19253. (when (save-excursion
  19254. (beginning-of-line)
  19255. (looking-at org-property-re))
  19256. (replace-match
  19257. (concat (match-string 4)
  19258. (org-trim
  19259. (format org-property-format (match-string 1) (match-string 3))))
  19260. t t)))
  19261. (defun org-indent-line ()
  19262. "Indent line depending on context.
  19263. Indentation is done according to the following rules:
  19264. - Footnote definitions, diary sexps, headlines and inline tasks
  19265. have to start at column 0.
  19266. - On the very first line of an element, consider, in order, the
  19267. next rules until one matches:
  19268. 1. If there's a sibling element before, ignoring footnote
  19269. definitions and inline tasks, indent like its first line.
  19270. 2. If element has a parent, indent like its contents. More
  19271. precisely, if parent is an item, indent after the
  19272. description part, if any, or the bullet (see
  19273. `org-list-description-max-indent'). Else, indent like
  19274. parent's first line.
  19275. 3. Otherwise, indent relatively to current level, if
  19276. `org-adapt-indentation' is non-nil, or to left margin.
  19277. - On a blank line at the end of an element, indent according to
  19278. the type of the element. More precisely
  19279. 1. If element is a plain list, an item, or a footnote
  19280. definition, indent like the very last element within.
  19281. 2. If element is a paragraph, indent like its last non blank
  19282. line.
  19283. 3. Otherwise, indent like its very first line.
  19284. - In the code part of a source block, use language major mode
  19285. to indent current line if `org-src-tab-acts-natively' is
  19286. non-nil. If it is nil, do nothing.
  19287. - Otherwise, indent like the first non-blank line above.
  19288. The function doesn't indent an item as it could break the whole
  19289. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  19290. `\\[org-shiftmetaright]'.
  19291. Also align node properties according to `org-property-format'."
  19292. (interactive)
  19293. (cond
  19294. ((org-at-heading-p) 'noindent)
  19295. (t
  19296. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  19297. (type (org-element-type element)))
  19298. (cond ((and (memq type '(plain-list item))
  19299. (= (line-beginning-position)
  19300. (org-element-property :post-affiliated element)))
  19301. 'noindent)
  19302. ((and (eq type 'latex-environment)
  19303. (>= (point) (org-element-property :post-affiliated element))
  19304. (< (point) (org-with-wide-buffer
  19305. (goto-char (org-element-property :end element))
  19306. (skip-chars-backward " \r\t\n")
  19307. (line-beginning-position 2))))
  19308. 'noindent)
  19309. ((and (eq type 'src-block)
  19310. org-src-tab-acts-natively
  19311. (> (line-beginning-position)
  19312. (org-element-property :post-affiliated element))
  19313. (< (line-beginning-position)
  19314. (org-with-wide-buffer
  19315. (goto-char (org-element-property :end element))
  19316. (skip-chars-backward " \r\t\n")
  19317. (line-beginning-position))))
  19318. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  19319. (t
  19320. (let ((column (org--get-expected-indentation element nil)))
  19321. ;; Preserve current column.
  19322. (if (<= (current-column) (current-indentation))
  19323. (indent-line-to column)
  19324. (save-excursion (indent-line-to column))))
  19325. ;; Align node property. Also preserve current column.
  19326. (when (eq type 'node-property)
  19327. (let ((column (current-column)))
  19328. (org--align-node-property)
  19329. (org-move-to-column column)))))))))
  19330. (defun org-indent-region (start end)
  19331. "Indent each non-blank line in the region.
  19332. Called from a program, START and END specify the region to
  19333. indent. The function will not indent contents of example blocks,
  19334. verse blocks and export blocks as leading white spaces are
  19335. assumed to be significant there."
  19336. (interactive "r")
  19337. (save-excursion
  19338. (goto-char start)
  19339. (skip-chars-forward " \r\t\n")
  19340. (unless (eobp) (beginning-of-line))
  19341. (let ((indent-to
  19342. (lambda (ind pos)
  19343. ;; Set IND as indentation for all lines between point and
  19344. ;; POS. Blank lines are ignored. Leave point after POS
  19345. ;; once done.
  19346. (let ((limit (copy-marker pos)))
  19347. (while (< (point) limit)
  19348. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  19349. (forward-line))
  19350. (set-marker limit nil))))
  19351. (end (copy-marker end)))
  19352. (while (< (point) end)
  19353. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  19354. (let* ((element (org-element-at-point))
  19355. (type (org-element-type element))
  19356. (element-end (copy-marker (org-element-property :end element)))
  19357. (ind (org--get-expected-indentation element nil)))
  19358. (cond
  19359. ;; Element indented as a single block. Example blocks
  19360. ;; preserving indentation are a special case since the
  19361. ;; "contents" must not be indented whereas the block
  19362. ;; boundaries can.
  19363. ((or (memq type '(export-block latex-environment))
  19364. (and (eq type 'example-block)
  19365. (not
  19366. (or org-src-preserve-indentation
  19367. (org-element-property :preserve-indent element)))))
  19368. (let ((offset (- ind (current-indentation))))
  19369. (unless (zerop offset)
  19370. (indent-rigidly (org-element-property :begin element)
  19371. (org-element-property :end element)
  19372. offset)))
  19373. (goto-char element-end))
  19374. ;; Elements indented line wise. Be sure to exclude
  19375. ;; example blocks (preserving indentation) and source
  19376. ;; blocks from this category as they are treated
  19377. ;; specially later.
  19378. ((or (memq type '(paragraph table table-row))
  19379. (not (or (org-element-property :contents-begin element)
  19380. (memq type '(example-block src-block)))))
  19381. (when (eq type 'node-property)
  19382. (org--align-node-property)
  19383. (beginning-of-line))
  19384. (funcall indent-to ind (min element-end end)))
  19385. ;; Elements consisting of three parts: before the
  19386. ;; contents, the contents, and after the contents. The
  19387. ;; contents are treated specially, according to the
  19388. ;; element type, or not indented at all. Other parts are
  19389. ;; indented as a single block.
  19390. (t
  19391. (let* ((post (copy-marker
  19392. (org-element-property :post-affiliated element)))
  19393. (cbeg
  19394. (copy-marker
  19395. (cond
  19396. ((not (org-element-property :contents-begin element))
  19397. ;; Fake contents for source blocks.
  19398. (org-with-wide-buffer
  19399. (goto-char post)
  19400. (line-beginning-position 2)))
  19401. ((memq type '(footnote-definition item plain-list))
  19402. ;; Contents in these elements could start on
  19403. ;; the same line as the beginning of the
  19404. ;; element. Make sure we start indenting
  19405. ;; from the second line.
  19406. (org-with-wide-buffer
  19407. (goto-char post)
  19408. (end-of-line)
  19409. (skip-chars-forward " \r\t\n")
  19410. (if (eobp) (point) (line-beginning-position))))
  19411. (t (org-element-property :contents-begin element)))))
  19412. (cend (copy-marker
  19413. (or (org-element-property :contents-end element)
  19414. ;; Fake contents for source blocks.
  19415. (org-with-wide-buffer
  19416. (goto-char element-end)
  19417. (skip-chars-backward " \r\t\n")
  19418. (line-beginning-position)))
  19419. t)))
  19420. ;; Do not change items indentation individually as it
  19421. ;; might break the list as a whole. On the other
  19422. ;; hand, when at a plain list, indent it as a whole.
  19423. (cond ((eq type 'plain-list)
  19424. (let ((offset (- ind (current-indentation))))
  19425. (unless (zerop offset)
  19426. (indent-rigidly (org-element-property :begin element)
  19427. (org-element-property :end element)
  19428. offset))
  19429. (goto-char cbeg)))
  19430. ((eq type 'item) (goto-char cbeg))
  19431. (t (funcall indent-to ind (min cbeg end))))
  19432. (when (< (point) end)
  19433. (cl-case type
  19434. ((example-block verse-block))
  19435. (src-block
  19436. ;; In a source block, indent source code
  19437. ;; according to language major mode, but only if
  19438. ;; `org-src-tab-acts-natively' is non-nil.
  19439. (when (and (< (point) end) org-src-tab-acts-natively)
  19440. (ignore-errors
  19441. (org-babel-do-in-edit-buffer
  19442. (indent-region (point-min) (point-max))))))
  19443. (t (org-indent-region (point) (min cend end))))
  19444. (goto-char (min cend end))
  19445. (when (< (point) end)
  19446. (funcall indent-to ind (min element-end end))))
  19447. (set-marker post nil)
  19448. (set-marker cbeg nil)
  19449. (set-marker cend nil))))
  19450. (set-marker element-end nil))))
  19451. (set-marker end nil))))
  19452. (defun org-indent-drawer ()
  19453. "Indent the drawer at point."
  19454. (interactive)
  19455. (unless (save-excursion
  19456. (beginning-of-line)
  19457. (looking-at-p org-drawer-regexp))
  19458. (user-error "Not at a drawer"))
  19459. (let ((element (org-element-at-point)))
  19460. (unless (memq (org-element-type element) '(drawer property-drawer))
  19461. (user-error "Not at a drawer"))
  19462. (org-with-wide-buffer
  19463. (org-indent-region (org-element-property :begin element)
  19464. (org-element-property :end element))))
  19465. (message "Drawer at point indented"))
  19466. (defun org-indent-block ()
  19467. "Indent the block at point."
  19468. (interactive)
  19469. (unless (save-excursion
  19470. (beginning-of-line)
  19471. (let ((case-fold-search t))
  19472. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  19473. (user-error "Not at a block"))
  19474. (let ((element (org-element-at-point)))
  19475. (unless (memq (org-element-type element)
  19476. '(comment-block center-block dynamic-block example-block
  19477. export-block quote-block special-block
  19478. src-block verse-block))
  19479. (user-error "Not at a block"))
  19480. (org-with-wide-buffer
  19481. (org-indent-region (org-element-property :begin element)
  19482. (org-element-property :end element))))
  19483. (message "Block at point indented"))
  19484. ;;; Filling
  19485. ;; We use our own fill-paragraph and auto-fill functions.
  19486. ;; `org-fill-paragraph' relies on adaptive filling and context
  19487. ;; checking. Appropriate `fill-prefix' is computed with
  19488. ;; `org-adaptive-fill-function'.
  19489. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  19490. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  19491. ;; `org-adaptive-fill-function' value. Internally,
  19492. ;; `org-comment-line-break-function' breaks the line.
  19493. ;; `org-setup-filling' installs filling and auto-filling related
  19494. ;; variables during `org-mode' initialization.
  19495. (defun org-setup-filling ()
  19496. (require 'org-element)
  19497. ;; Prevent auto-fill from inserting unwanted new items.
  19498. (when (boundp 'fill-nobreak-predicate)
  19499. (setq-local
  19500. fill-nobreak-predicate
  19501. (org-uniquify
  19502. (append fill-nobreak-predicate
  19503. '(org-fill-line-break-nobreak-p
  19504. org-fill-n-macro-as-item-nobreak-p
  19505. org-fill-paragraph-with-timestamp-nobreak-p)))))
  19506. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  19507. (setq-local paragraph-start paragraph-ending)
  19508. (setq-local paragraph-separate paragraph-ending))
  19509. (setq-local fill-paragraph-function 'org-fill-paragraph)
  19510. (setq-local auto-fill-inhibit-regexp nil)
  19511. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  19512. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  19513. (setq-local comment-line-break-function 'org-comment-line-break-function))
  19514. (defun org-fill-line-break-nobreak-p ()
  19515. "Non-nil when a new line at point would create an Org line break."
  19516. (save-excursion
  19517. (skip-chars-backward "[ \t]")
  19518. (skip-chars-backward "\\\\")
  19519. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  19520. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  19521. "Non-nil when a new line at point would split a timestamp."
  19522. (and (org-at-timestamp-p 'lax)
  19523. (not (looking-at org-ts-regexp-both))))
  19524. (defun org-fill-n-macro-as-item-nobreak-p ()
  19525. "Non-nil when a new line at point would create a new list."
  19526. ;; During export, a "n" macro followed by a dot or a closing
  19527. ;; parenthesis can end up being parsed as a new list item.
  19528. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  19529. (defvar orgtbl-line-start-regexp) ; From org-table.el
  19530. (defun org-adaptive-fill-function ()
  19531. "Compute a fill prefix for the current line.
  19532. Return fill prefix, as a string, or nil if current line isn't
  19533. meant to be filled. For convenience, if `adaptive-fill-regexp'
  19534. matches in paragraphs or comments, use it."
  19535. (org-with-wide-buffer
  19536. (unless (org-at-heading-p)
  19537. (let* ((p (line-beginning-position))
  19538. (element (save-excursion
  19539. (beginning-of-line)
  19540. (org-element-at-point)))
  19541. (type (org-element-type element))
  19542. (post-affiliated (org-element-property :post-affiliated element)))
  19543. (unless (< p post-affiliated)
  19544. (cl-case type
  19545. (comment
  19546. (save-excursion
  19547. (beginning-of-line)
  19548. (looking-at "[ \t]*")
  19549. (concat (match-string 0) "# ")))
  19550. (footnote-definition "")
  19551. ((item plain-list)
  19552. (make-string (org-list-item-body-column post-affiliated) ?\s))
  19553. (paragraph
  19554. ;; Fill prefix is usually the same as the current line,
  19555. ;; unless the paragraph is at the beginning of an item.
  19556. (let ((parent (org-element-property :parent element)))
  19557. (save-excursion
  19558. (beginning-of-line)
  19559. (cond ((eq (org-element-type parent) 'item)
  19560. (make-string (org-list-item-body-column
  19561. (org-element-property :begin parent))
  19562. ?\s))
  19563. ((and adaptive-fill-regexp
  19564. ;; Locally disable
  19565. ;; `adaptive-fill-function' to let
  19566. ;; `fill-context-prefix' handle
  19567. ;; `adaptive-fill-regexp' variable.
  19568. (let (adaptive-fill-function)
  19569. (fill-context-prefix
  19570. post-affiliated
  19571. (org-element-property :end element)))))
  19572. ((looking-at "[ \t]+") (match-string 0))
  19573. (t "")))))
  19574. (comment-block
  19575. ;; Only fill contents if P is within block boundaries.
  19576. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  19577. (forward-line)
  19578. (point)))
  19579. (cend (save-excursion
  19580. (goto-char (org-element-property :end element))
  19581. (skip-chars-backward " \r\t\n")
  19582. (line-beginning-position))))
  19583. (when (and (>= p cbeg) (< p cend))
  19584. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  19585. (match-string 0)
  19586. ""))))))))))
  19587. (defun org-fill-element (&optional justify)
  19588. "Fill element at point, when applicable.
  19589. This function only applies to comment blocks, comments, example
  19590. blocks and paragraphs. Also, as a special case, re-align table
  19591. when point is at one.
  19592. If JUSTIFY is non-nil (interactively, with prefix argument),
  19593. justify as well. If `sentence-end-double-space' is non-nil, then
  19594. period followed by one space does not end a sentence, so don't
  19595. break a line there. The variable `fill-column' controls the
  19596. width for filling.
  19597. For convenience, when point is at a plain list, an item or
  19598. a footnote definition, try to fill the first paragraph within."
  19599. (with-syntax-table org-mode-transpose-word-syntax-table
  19600. ;; Move to end of line in order to get the first paragraph within
  19601. ;; a plain list or a footnote definition.
  19602. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  19603. ;; First check if point is in a blank line at the beginning of
  19604. ;; the buffer. In that case, ignore filling.
  19605. (cl-case (org-element-type element)
  19606. ;; Use major mode filling function is source blocks.
  19607. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  19608. ;; Align Org tables, leave table.el tables as-is.
  19609. (table-row (org-table-align) t)
  19610. (table
  19611. (when (eq (org-element-property :type element) 'org)
  19612. (save-excursion
  19613. (goto-char (org-element-property :post-affiliated element))
  19614. (org-table-align)))
  19615. t)
  19616. (paragraph
  19617. ;; Paragraphs may contain `line-break' type objects.
  19618. (let ((beg (max (point-min)
  19619. (org-element-property :contents-begin element)))
  19620. (end (min (point-max)
  19621. (org-element-property :contents-end element))))
  19622. ;; Do nothing if point is at an affiliated keyword.
  19623. (if (< (line-end-position) beg) t
  19624. ;; Fill paragraph, taking line breaks into account.
  19625. (save-excursion
  19626. (goto-char beg)
  19627. (let ((cuts (list beg)))
  19628. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  19629. (when (eq 'line-break
  19630. (org-element-type
  19631. (save-excursion (backward-char)
  19632. (org-element-context))))
  19633. (push (point) cuts)))
  19634. (dolist (c (delq end cuts))
  19635. (fill-region-as-paragraph c end justify)
  19636. (setq end c))))
  19637. t)))
  19638. ;; Contents of `comment-block' type elements should be
  19639. ;; filled as plain text, but only if point is within block
  19640. ;; markers.
  19641. (comment-block
  19642. (let* ((case-fold-search t)
  19643. (beg (save-excursion
  19644. (goto-char (org-element-property :begin element))
  19645. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  19646. (forward-line)
  19647. (point)))
  19648. (end (save-excursion
  19649. (goto-char (org-element-property :end element))
  19650. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  19651. (line-beginning-position))))
  19652. (if (or (< (point) beg) (> (point) end)) t
  19653. (fill-region-as-paragraph
  19654. (save-excursion (end-of-line)
  19655. (re-search-backward "^[ \t]*$" beg 'move)
  19656. (line-beginning-position))
  19657. (save-excursion (beginning-of-line)
  19658. (re-search-forward "^[ \t]*$" end 'move)
  19659. (line-beginning-position))
  19660. justify))))
  19661. ;; Fill comments.
  19662. (comment
  19663. (let ((begin (org-element-property :post-affiliated element))
  19664. (end (org-element-property :end element)))
  19665. (when (and (>= (point) begin) (<= (point) end))
  19666. (let ((begin (save-excursion
  19667. (end-of-line)
  19668. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  19669. (progn (forward-line) (point))
  19670. begin)))
  19671. (end (save-excursion
  19672. (end-of-line)
  19673. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  19674. (1- (line-beginning-position))
  19675. (skip-chars-backward " \r\t\n")
  19676. (line-end-position)))))
  19677. ;; Do not fill comments when at a blank line.
  19678. (when (> end begin)
  19679. (let ((fill-prefix
  19680. (save-excursion
  19681. (beginning-of-line)
  19682. (looking-at "[ \t]*#")
  19683. (let ((comment-prefix (match-string 0)))
  19684. (goto-char (match-end 0))
  19685. (if (looking-at adaptive-fill-regexp)
  19686. (concat comment-prefix (match-string 0))
  19687. (concat comment-prefix " "))))))
  19688. (save-excursion
  19689. (fill-region-as-paragraph begin end justify))))))
  19690. t))
  19691. ;; Ignore every other element.
  19692. (otherwise t)))))
  19693. (defun org-fill-paragraph (&optional justify region)
  19694. "Fill element at point, when applicable.
  19695. This function only applies to comment blocks, comments, example
  19696. blocks and paragraphs. Also, as a special case, re-align table
  19697. when point is at one.
  19698. For convenience, when point is at a plain list, an item or
  19699. a footnote definition, try to fill the first paragraph within.
  19700. If JUSTIFY is non-nil (interactively, with prefix argument),
  19701. justify as well. If `sentence-end-double-space' is non-nil, then
  19702. period followed by one space does not end a sentence, so don't
  19703. break a line there. The variable `fill-column' controls the
  19704. width for filling.
  19705. The REGION argument is non-nil if called interactively; in that
  19706. case, if Transient Mark mode is enabled and the mark is active,
  19707. fill each of the elements in the active region, instead of just
  19708. filling the current element."
  19709. (interactive (progn
  19710. (barf-if-buffer-read-only)
  19711. (list (when current-prefix-arg 'full) t)))
  19712. (let ((hash (and (not (buffer-modified-p))
  19713. (org-buffer-hash))))
  19714. (cond
  19715. ((and region transient-mark-mode mark-active
  19716. (not (eq (region-beginning) (region-end))))
  19717. (let ((origin (point-marker))
  19718. (start (region-beginning)))
  19719. (unwind-protect
  19720. (progn
  19721. (goto-char (region-end))
  19722. (while (> (point) start)
  19723. (org-backward-paragraph)
  19724. (org-fill-element justify)))
  19725. (goto-char origin)
  19726. (set-marker origin nil))))
  19727. (t (org-fill-element justify)))
  19728. ;; If we didn't change anything in the buffer (and the buffer was
  19729. ;; previously unmodified), then flip the modification status back
  19730. ;; to "unchanged".
  19731. (when (and hash (equal hash (org-buffer-hash)))
  19732. (set-buffer-modified-p nil))))
  19733. (defun org-auto-fill-function ()
  19734. "Auto-fill function."
  19735. ;; Check if auto-filling is meaningful.
  19736. (let ((fc (current-fill-column)))
  19737. (when (and fc (> (current-column) fc))
  19738. (let* ((fill-prefix (org-adaptive-fill-function))
  19739. ;; Enforce empty fill prefix, if required. Otherwise, it
  19740. ;; will be computed again.
  19741. (adaptive-fill-mode (not (equal fill-prefix ""))))
  19742. (when fill-prefix (do-auto-fill))))))
  19743. (defun org-comment-line-break-function (&optional soft)
  19744. "Break line at point and indent, continuing comment if within one.
  19745. The inserted newline is marked hard if variable
  19746. `use-hard-newlines' is true, unless optional argument SOFT is
  19747. non-nil."
  19748. (if soft (insert-and-inherit ?\n) (newline 1))
  19749. (save-excursion (forward-char -1) (delete-horizontal-space))
  19750. (delete-horizontal-space)
  19751. (indent-to-left-margin)
  19752. (insert-before-markers-and-inherit fill-prefix))
  19753. ;;; Fixed Width Areas
  19754. (defun org-toggle-fixed-width ()
  19755. "Toggle fixed-width markup.
  19756. Add or remove fixed-width markup on current line, whenever it
  19757. makes sense. Return an error otherwise.
  19758. If a region is active and if it contains only fixed-width areas
  19759. or blank lines, remove all fixed-width markup in it. If the
  19760. region contains anything else, convert all non-fixed-width lines
  19761. to fixed-width ones.
  19762. Blank lines at the end of the region are ignored unless the
  19763. region only contains such lines."
  19764. (interactive)
  19765. (if (not (org-region-active-p))
  19766. ;; No region:
  19767. ;;
  19768. ;; Remove fixed width marker only in a fixed-with element.
  19769. ;;
  19770. ;; Add fixed width maker in paragraphs, in blank lines after
  19771. ;; elements or at the beginning of a headline or an inlinetask,
  19772. ;; and before any one-line elements (e.g., a clock).
  19773. (progn
  19774. (beginning-of-line)
  19775. (let* ((element (org-element-at-point))
  19776. (type (org-element-type element)))
  19777. (cond
  19778. ((and (eq type 'fixed-width)
  19779. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  19780. (replace-match
  19781. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  19782. ((and (memq type '(babel-call clock comment diary-sexp headline
  19783. horizontal-rule keyword paragraph
  19784. planning))
  19785. (<= (org-element-property :post-affiliated element) (point)))
  19786. (skip-chars-forward " \t")
  19787. (insert ": "))
  19788. ((and (looking-at-p "[ \t]*$")
  19789. (or (eq type 'inlinetask)
  19790. (save-excursion
  19791. (skip-chars-forward " \r\t\n")
  19792. (<= (org-element-property :end element) (point)))))
  19793. (delete-region (point) (line-end-position))
  19794. (org-indent-line)
  19795. (insert ": "))
  19796. (t (user-error "Cannot insert a fixed-width line here")))))
  19797. ;; Region active.
  19798. (let* ((begin (save-excursion
  19799. (goto-char (region-beginning))
  19800. (line-beginning-position)))
  19801. (end (copy-marker
  19802. (save-excursion
  19803. (goto-char (region-end))
  19804. (unless (eolp) (beginning-of-line))
  19805. (if (save-excursion (re-search-backward "\\S-" begin t))
  19806. (progn (skip-chars-backward " \r\t\n") (point))
  19807. (point)))))
  19808. (all-fixed-width-p
  19809. (catch 'not-all-p
  19810. (save-excursion
  19811. (goto-char begin)
  19812. (skip-chars-forward " \r\t\n")
  19813. (when (eobp) (throw 'not-all-p nil))
  19814. (while (< (point) end)
  19815. (let ((element (org-element-at-point)))
  19816. (if (eq (org-element-type element) 'fixed-width)
  19817. (goto-char (org-element-property :end element))
  19818. (throw 'not-all-p nil))))
  19819. t))))
  19820. (if all-fixed-width-p
  19821. (save-excursion
  19822. (goto-char begin)
  19823. (while (< (point) end)
  19824. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  19825. (replace-match
  19826. "" nil nil nil
  19827. (if (= (line-end-position) (match-end 0)) 0 1)))
  19828. (forward-line)))
  19829. (let ((min-ind (point-max)))
  19830. ;; Find minimum indentation across all lines.
  19831. (save-excursion
  19832. (goto-char begin)
  19833. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  19834. (setq min-ind 0)
  19835. (catch 'zerop
  19836. (while (< (point) end)
  19837. (unless (looking-at-p "[ \t]*$")
  19838. (let ((ind (current-indentation)))
  19839. (setq min-ind (min min-ind ind))
  19840. (when (zerop ind) (throw 'zerop t))))
  19841. (forward-line)))))
  19842. ;; Loop over all lines and add fixed-width markup everywhere
  19843. ;; but in fixed-width lines.
  19844. (save-excursion
  19845. (goto-char begin)
  19846. (while (< (point) end)
  19847. (cond
  19848. ((org-at-heading-p)
  19849. (insert ": ")
  19850. (forward-line)
  19851. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  19852. (insert ":")
  19853. (forward-line)))
  19854. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  19855. (let* ((element (org-element-at-point))
  19856. (element-end (org-element-property :end element)))
  19857. (if (eq (org-element-type element) 'fixed-width)
  19858. (progn (goto-char element-end)
  19859. (skip-chars-backward " \r\t\n")
  19860. (forward-line))
  19861. (let ((limit (min end element-end)))
  19862. (while (< (point) limit)
  19863. (org-move-to-column min-ind t)
  19864. (insert ": ")
  19865. (forward-line))))))
  19866. (t
  19867. (org-move-to-column min-ind t)
  19868. (insert ": ")
  19869. (forward-line)))))))
  19870. (set-marker end nil))))
  19871. ;;; Blocks
  19872. (defun org-block-map (function &optional start end)
  19873. "Call FUNCTION at the head of all source blocks in the current buffer.
  19874. Optional arguments START and END can be used to limit the range."
  19875. (let ((start (or start (point-min)))
  19876. (end (or end (point-max))))
  19877. (save-excursion
  19878. (goto-char start)
  19879. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  19880. (save-excursion
  19881. (save-match-data
  19882. (goto-char (match-beginning 0))
  19883. (funcall function)))))))
  19884. (defun org-next-block (arg &optional backward block-regexp)
  19885. "Jump to the next block.
  19886. With a prefix argument ARG, jump forward ARG many blocks.
  19887. When BACKWARD is non-nil, jump to the previous block.
  19888. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  19889. Match data is set according to this regexp when the function
  19890. returns.
  19891. Return point at beginning of the opening line of found block.
  19892. Throw an error if no block is found."
  19893. (interactive "p")
  19894. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  19895. (case-fold-search t)
  19896. (search-fn (if backward #'re-search-backward #'re-search-forward))
  19897. (count (or arg 1))
  19898. (origin (point))
  19899. last-element)
  19900. (if backward (beginning-of-line) (end-of-line))
  19901. (while (and (> count 0) (funcall search-fn re nil t))
  19902. (let ((element (save-excursion
  19903. (goto-char (match-beginning 0))
  19904. (save-match-data (org-element-at-point)))))
  19905. (when (and (memq (org-element-type element)
  19906. '(center-block comment-block dynamic-block
  19907. example-block export-block quote-block
  19908. special-block src-block verse-block))
  19909. (<= (match-beginning 0)
  19910. (org-element-property :post-affiliated element)))
  19911. (setq last-element element)
  19912. (cl-decf count))))
  19913. (if (= count 0)
  19914. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  19915. (save-match-data (org-show-context)))
  19916. (goto-char origin)
  19917. (user-error "No %s code blocks" (if backward "previous" "further")))))
  19918. (defun org-previous-block (arg &optional block-regexp)
  19919. "Jump to the previous block.
  19920. With a prefix argument ARG, jump backward ARG many source blocks.
  19921. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  19922. (interactive "p")
  19923. (org-next-block arg t block-regexp))
  19924. ;;; Comments
  19925. ;; Org comments syntax is quite complex. It requires the entire line
  19926. ;; to be just a comment. Also, even with the right syntax at the
  19927. ;; beginning of line, some elements (e.g., verse-block or
  19928. ;; example-block) don't accept comments. Usual Emacs comment commands
  19929. ;; cannot cope with those requirements. Therefore, Org replaces them.
  19930. ;; Org still relies on `comment-dwim', but cannot trust
  19931. ;; `comment-only-p'. So, `comment-region-function' and
  19932. ;; `uncomment-region-function' both point
  19933. ;; to`org-comment-or-uncomment-region'. Eventually,
  19934. ;; `org-insert-comment' takes care of insertion of comments at the
  19935. ;; beginning of line.
  19936. ;; `org-setup-comments-handling' install comments related variables
  19937. ;; during `org-mode' initialization.
  19938. (defun org-setup-comments-handling ()
  19939. (interactive)
  19940. (setq-local comment-use-syntax nil)
  19941. (setq-local comment-start "# ")
  19942. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  19943. (setq-local comment-insert-comment-function 'org-insert-comment)
  19944. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  19945. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  19946. (defun org-insert-comment ()
  19947. "Insert an empty comment above current line.
  19948. If the line is empty, insert comment at its beginning. When
  19949. point is within a source block, comment according to the related
  19950. major mode."
  19951. (if (let ((element (org-element-at-point)))
  19952. (and (eq (org-element-type element) 'src-block)
  19953. (< (save-excursion
  19954. (goto-char (org-element-property :post-affiliated element))
  19955. (line-end-position))
  19956. (point))
  19957. (> (save-excursion
  19958. (goto-char (org-element-property :end element))
  19959. (skip-chars-backward " \r\t\n")
  19960. (line-beginning-position))
  19961. (point))))
  19962. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  19963. (beginning-of-line)
  19964. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  19965. (open-line 1))
  19966. (org-indent-line)
  19967. (insert "# ")))
  19968. (defvar comment-empty-lines) ; From newcomment.el.
  19969. (defun org-comment-or-uncomment-region (beg end &rest _)
  19970. "Comment or uncomment each non-blank line in the region.
  19971. Uncomment each non-blank line between BEG and END if it only
  19972. contains commented lines. Otherwise, comment them. If region is
  19973. strictly within a source block, use appropriate comment syntax."
  19974. (if (let ((element (org-element-at-point)))
  19975. (and (eq (org-element-type element) 'src-block)
  19976. (< (save-excursion
  19977. (goto-char (org-element-property :post-affiliated element))
  19978. (line-end-position))
  19979. beg)
  19980. (>= (save-excursion
  19981. (goto-char (org-element-property :end element))
  19982. (skip-chars-backward " \r\t\n")
  19983. (line-beginning-position))
  19984. end)))
  19985. ;; Translate region boundaries for the Org buffer to the source
  19986. ;; buffer.
  19987. (let ((offset (- end beg)))
  19988. (save-excursion
  19989. (goto-char beg)
  19990. (org-babel-do-in-edit-buffer
  19991. (comment-or-uncomment-region (point) (+ offset (point))))))
  19992. (save-restriction
  19993. ;; Restrict region
  19994. (narrow-to-region (save-excursion (goto-char beg)
  19995. (skip-chars-forward " \r\t\n" end)
  19996. (line-beginning-position))
  19997. (save-excursion (goto-char end)
  19998. (skip-chars-backward " \r\t\n" beg)
  19999. (line-end-position)))
  20000. (let ((uncommentp
  20001. ;; UNCOMMENTP is non-nil when every non blank line between
  20002. ;; BEG and END is a comment.
  20003. (save-excursion
  20004. (goto-char (point-min))
  20005. (while (and (not (eobp))
  20006. (let ((element (org-element-at-point)))
  20007. (and (eq (org-element-type element) 'comment)
  20008. (goto-char (min (point-max)
  20009. (org-element-property
  20010. :end element)))))))
  20011. (eobp))))
  20012. (if uncommentp
  20013. ;; Only blank lines and comments in region: uncomment it.
  20014. (save-excursion
  20015. (goto-char (point-min))
  20016. (while (not (eobp))
  20017. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  20018. (replace-match "" nil nil nil 1))
  20019. (forward-line)))
  20020. ;; Comment each line in region.
  20021. (let ((min-indent (point-max)))
  20022. ;; First find the minimum indentation across all lines.
  20023. (save-excursion
  20024. (goto-char (point-min))
  20025. (while (and (not (eobp)) (not (zerop min-indent)))
  20026. (unless (looking-at "[ \t]*$")
  20027. (setq min-indent (min min-indent (current-indentation))))
  20028. (forward-line)))
  20029. ;; Then loop over all lines.
  20030. (save-excursion
  20031. (goto-char (point-min))
  20032. (while (not (eobp))
  20033. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  20034. ;; Don't get fooled by invisible text (e.g. link path)
  20035. ;; when moving to column MIN-INDENT.
  20036. (let ((buffer-invisibility-spec nil))
  20037. (org-move-to-column min-indent t))
  20038. (insert comment-start))
  20039. (forward-line)))))))))
  20040. (defun org-comment-dwim (_arg)
  20041. "Call the comment command you mean.
  20042. Call `org-toggle-comment' if on a heading, otherwise call
  20043. `comment-dwim', within a source edit buffer if needed."
  20044. (interactive "*P")
  20045. (cond ((org-at-heading-p)
  20046. (call-interactively #'org-toggle-comment))
  20047. ((org-in-src-block-p)
  20048. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  20049. (t (call-interactively #'comment-dwim))))
  20050. ;;; Timestamps API
  20051. ;; This section contains tools to operate on, or create, timestamp
  20052. ;; objects, as returned by, e.g. `org-element-context'.
  20053. (defun org-timestamp-from-string (s)
  20054. "Convert Org timestamp S, as a string, into a timestamp object.
  20055. Return nil if S is not a valid timestamp string."
  20056. (when (org-string-nw-p s)
  20057. (with-temp-buffer
  20058. (save-excursion (insert s))
  20059. (org-element-timestamp-parser))))
  20060. (defun org-timestamp-from-time (time &optional with-time inactive)
  20061. "Convert a time value into a timestamp object.
  20062. TIME is an Emacs internal time representation, as returned, e.g.,
  20063. by `current-time'.
  20064. When optional argument WITH-TIME is non-nil, return a timestamp
  20065. object with a time part, i.e., with hours and minutes.
  20066. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  20067. return an active timestamp."
  20068. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  20069. (org-element-create 'timestamp
  20070. (list :type (if inactive 'inactive 'active)
  20071. :year-start year
  20072. :month-start month
  20073. :day-start day
  20074. :hour-start (and with-time hour)
  20075. :minute-start (and with-time minute)))))
  20076. (defun org-timestamp-to-time (timestamp &optional end)
  20077. "Convert TIMESTAMP object into an Emacs internal time value.
  20078. Use end of date range or time range when END is non-nil.
  20079. Otherwise, use its start."
  20080. (apply #'encode-time
  20081. (cons 0
  20082. (mapcar
  20083. (lambda (prop) (or (org-element-property prop timestamp) 0))
  20084. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  20085. '(:minute-start :hour-start :day-start :month-start
  20086. :year-start))))))
  20087. (defun org-timestamp-has-time-p (timestamp)
  20088. "Non-nil when TIMESTAMP has a time specified."
  20089. (org-element-property :hour-start timestamp))
  20090. (defun org-timestamp-format (timestamp format &optional end utc)
  20091. "Format a TIMESTAMP object into a string.
  20092. FORMAT is a format specifier to be passed to
  20093. `format-time-string'.
  20094. When optional argument END is non-nil, use end of date-range or
  20095. time-range, if possible.
  20096. When optional argument UTC is non-nil, time is be expressed as
  20097. Universal Time."
  20098. (format-time-string format (org-timestamp-to-time timestamp end)
  20099. (and utc t)))
  20100. (defun org-timestamp-split-range (timestamp &optional end)
  20101. "Extract a TIMESTAMP object from a date or time range.
  20102. END, when non-nil, means extract the end of the range.
  20103. Otherwise, extract its start.
  20104. Return a new timestamp object."
  20105. (let ((type (org-element-property :type timestamp)))
  20106. (if (memq type '(active inactive diary)) timestamp
  20107. (let ((split-ts (org-element-copy timestamp)))
  20108. ;; Set new type.
  20109. (org-element-put-property
  20110. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  20111. ;; Copy start properties over end properties if END is
  20112. ;; non-nil. Otherwise, copy end properties over `start' ones.
  20113. (let ((p-alist '((:minute-start . :minute-end)
  20114. (:hour-start . :hour-end)
  20115. (:day-start . :day-end)
  20116. (:month-start . :month-end)
  20117. (:year-start . :year-end))))
  20118. (dolist (p-cell p-alist)
  20119. (org-element-put-property
  20120. split-ts
  20121. (funcall (if end #'car #'cdr) p-cell)
  20122. (org-element-property
  20123. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  20124. ;; Eventually refresh `:raw-value'.
  20125. (org-element-put-property split-ts :raw-value nil)
  20126. (org-element-put-property
  20127. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  20128. (defun org-timestamp-translate (timestamp &optional boundary)
  20129. "Translate TIMESTAMP object to custom format.
  20130. Format string is defined in `org-time-stamp-custom-formats',
  20131. which see.
  20132. When optional argument BOUNDARY is non-nil, it is either the
  20133. symbol `start' or `end'. In this case, only translate the
  20134. starting or ending part of TIMESTAMP if it is a date or time
  20135. range. Otherwise, translate both parts.
  20136. Return timestamp as-is if `org-display-custom-times' is nil or if
  20137. it has a `diary' type."
  20138. (let ((type (org-element-property :type timestamp)))
  20139. (if (or (not org-display-custom-times) (eq type 'diary))
  20140. (org-element-interpret-data timestamp)
  20141. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  20142. org-time-stamp-custom-formats)))
  20143. (if (and (not boundary) (memq type '(active-range inactive-range)))
  20144. (concat (org-timestamp-format timestamp fmt)
  20145. "--"
  20146. (org-timestamp-format timestamp fmt t))
  20147. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  20148. ;;; Other stuff
  20149. (defvar reftex-docstruct-symbol)
  20150. (defvar org--rds)
  20151. (defun org-reftex-citation ()
  20152. "Use reftex-citation to insert a citation into the buffer.
  20153. This looks for a line like
  20154. #+BIBLIOGRAPHY: foo plain option:-d
  20155. and derives from it that foo.bib is the bibliography file relevant
  20156. for this document. It then installs the necessary environment for RefTeX
  20157. to work in this buffer and calls `reftex-citation' to insert a citation
  20158. into the buffer.
  20159. Export of such citations to both LaTeX and HTML is handled by the contributed
  20160. package ox-bibtex by Taru Karttunen."
  20161. (interactive)
  20162. (let ((reftex-docstruct-symbol 'org--rds)
  20163. org--rds bib)
  20164. (org-with-wide-buffer
  20165. (let ((case-fold-search t)
  20166. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  20167. (if (not (save-excursion
  20168. (or (re-search-forward re nil t)
  20169. (re-search-backward re nil t))))
  20170. (user-error "No bibliography defined in file")
  20171. (setq bib (concat (match-string 1) ".bib")
  20172. org--rds (list (list 'bib bib))))))
  20173. (call-interactively 'reftex-citation)))
  20174. ;;;; Functions extending outline functionality
  20175. (defun org-beginning-of-line (&optional n)
  20176. "Go to the beginning of the current visible line.
  20177. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  20178. symbol `reversed', on the first attempt move to where the
  20179. headline text starts, and only move to beginning of line when the
  20180. cursor is already before the start of the text of the headline.
  20181. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  20182. start of the text on the second attempt.
  20183. With argument N not nil or 1, move forward N - 1 lines first."
  20184. (interactive "^p")
  20185. (let ((origin (point))
  20186. (special (pcase org-special-ctrl-a/e
  20187. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  20188. deactivate-mark)
  20189. ;; First move to a visible line.
  20190. (if (bound-and-true-p visual-line-mode)
  20191. (beginning-of-visual-line n)
  20192. (move-beginning-of-line n)
  20193. ;; `move-beginning-of-line' may leave point after invisible
  20194. ;; characters if line starts with such of these (e.g., with
  20195. ;; a link at column 0). Really move to the beginning of the
  20196. ;; current visible line.
  20197. (beginning-of-line))
  20198. (cond
  20199. ;; No special behavior. Point is already at the beginning of
  20200. ;; a line, logical or visual.
  20201. ((not special))
  20202. ;; `beginning-of-visual-line' left point before logical beginning
  20203. ;; of line: point is at the beginning of a visual line. Bail
  20204. ;; out.
  20205. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  20206. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  20207. ;; At a headline, special position is before the title, but
  20208. ;; after any TODO keyword or priority cookie.
  20209. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  20210. (line-end-position)))
  20211. (bol (point)))
  20212. (if (eq special 'reversed)
  20213. (when (and (= origin bol) (eq last-command this-command))
  20214. (goto-char refpos))
  20215. (when (or (> origin refpos) (= origin bol))
  20216. (goto-char refpos)))))
  20217. ((and (looking-at org-list-full-item-re)
  20218. (memq (org-element-type (save-match-data (org-element-at-point)))
  20219. '(item plain-list)))
  20220. ;; Set special position at first white space character after
  20221. ;; bullet, and check-box, if any.
  20222. (let ((after-bullet
  20223. (let ((box (match-end 3)))
  20224. (cond ((not box) (match-end 1))
  20225. ((eq (char-after box) ?\s) (1+ box))
  20226. (t box)))))
  20227. (if (eq special 'reversed)
  20228. (when (and (= (point) origin) (eq last-command this-command))
  20229. (goto-char after-bullet))
  20230. (when (or (> origin after-bullet) (= (point) origin))
  20231. (goto-char after-bullet)))))
  20232. ;; No special context. Point is already at beginning of line.
  20233. (t nil))))
  20234. (defun org-end-of-line (&optional n)
  20235. "Go to the end of the line, but before ellipsis, if any.
  20236. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  20237. symbol `reversed', ignore tags on the first attempt, and only
  20238. move to after the tags when the cursor is already beyond the end
  20239. of the headline.
  20240. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  20241. on the second attempt.
  20242. With argument N not nil or 1, move forward N - 1 lines first."
  20243. (interactive "^p")
  20244. (let ((origin (point))
  20245. (special (pcase org-special-ctrl-a/e
  20246. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  20247. deactivate-mark)
  20248. ;; First move to a visible line.
  20249. (if (bound-and-true-p visual-line-mode)
  20250. (beginning-of-visual-line n)
  20251. (move-beginning-of-line n))
  20252. (cond
  20253. ;; At a headline, with tags.
  20254. ((and special
  20255. (save-excursion
  20256. (beginning-of-line)
  20257. (let ((case-fold-search nil))
  20258. (looking-at org-complex-heading-regexp)))
  20259. (match-end 5))
  20260. (let ((tags (save-excursion
  20261. (goto-char (match-beginning 5))
  20262. (skip-chars-backward " \t")
  20263. (point)))
  20264. (visual-end (and (bound-and-true-p visual-line-mode)
  20265. (save-excursion
  20266. (end-of-visual-line)
  20267. (point)))))
  20268. ;; If `end-of-visual-line' brings us before end of line or
  20269. ;; even tags, i.e., the headline spans over multiple visual
  20270. ;; lines, move there.
  20271. (cond ((and visual-end
  20272. (< visual-end tags)
  20273. (<= origin visual-end))
  20274. (goto-char visual-end))
  20275. ((eq special 'reversed)
  20276. (if (and (= origin (line-end-position))
  20277. (eq this-command last-command))
  20278. (goto-char tags)
  20279. (end-of-line)))
  20280. (t
  20281. (if (or (< origin tags) (= origin (line-end-position)))
  20282. (goto-char tags)
  20283. (end-of-line))))))
  20284. ((bound-and-true-p visual-line-mode)
  20285. (let ((bol (line-beginning-position)))
  20286. (end-of-visual-line)
  20287. ;; If `end-of-visual-line' gets us past the ellipsis at the
  20288. ;; end of a line, backtrack and use `end-of-line' instead.
  20289. (when (/= bol (line-beginning-position))
  20290. (goto-char bol)
  20291. (end-of-line))))
  20292. (t (end-of-line)))))
  20293. (defun org-backward-sentence (&optional _arg)
  20294. "Go to beginning of sentence, or beginning of table field.
  20295. This will call `backward-sentence' or `org-table-beginning-of-field',
  20296. depending on context."
  20297. (interactive)
  20298. (let* ((element (org-element-at-point))
  20299. (contents-begin (org-element-property :contents-begin element))
  20300. (table (org-element-lineage element '(table) t)))
  20301. (if (and table
  20302. (> (point) contents-begin)
  20303. (<= (point) (org-element-property :contents-end table)))
  20304. (call-interactively #'org-table-beginning-of-field)
  20305. (save-restriction
  20306. (when (and contents-begin
  20307. (< (point-min) contents-begin)
  20308. (> (point) contents-begin))
  20309. (narrow-to-region contents-begin
  20310. (org-element-property :contents-end element)))
  20311. (call-interactively #'backward-sentence)))))
  20312. (defun org-forward-sentence (&optional _arg)
  20313. "Go to end of sentence, or end of table field.
  20314. This will call `forward-sentence' or `org-table-end-of-field',
  20315. depending on context."
  20316. (interactive)
  20317. (if (and (org-at-heading-p)
  20318. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  20319. (save-restriction
  20320. (narrow-to-region (line-beginning-position) (line-end-position))
  20321. (call-interactively #'forward-sentence))
  20322. (let* ((element (org-element-at-point))
  20323. (contents-end (org-element-property :contents-end element))
  20324. (table (org-element-lineage element '(table) t)))
  20325. (if (and table
  20326. (>= (point) (org-element-property :contents-begin table))
  20327. (< (point) contents-end))
  20328. (call-interactively #'org-table-end-of-field)
  20329. (save-restriction
  20330. (when (and contents-end
  20331. (> (point-max) contents-end)
  20332. ;; Skip blank lines between elements.
  20333. (< (org-element-property :end element)
  20334. (save-excursion (goto-char contents-end)
  20335. (skip-chars-forward " \r\t\n"))))
  20336. (narrow-to-region (org-element-property :contents-begin element)
  20337. contents-end))
  20338. ;; End of heading is considered as the end of a sentence.
  20339. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  20340. (call-interactively #'forward-sentence)))))))
  20341. (defun org-kill-line (&optional _arg)
  20342. "Kill line, to tags or end of line."
  20343. (interactive)
  20344. (cond
  20345. ((or (not org-special-ctrl-k)
  20346. (bolp)
  20347. (not (org-at-heading-p)))
  20348. (when (and (get-char-property (line-end-position) 'invisible)
  20349. org-ctrl-k-protect-subtree
  20350. (or (eq org-ctrl-k-protect-subtree 'error)
  20351. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  20352. (user-error
  20353. (substitute-command-keys
  20354. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  20355. (call-interactively
  20356. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  20357. ((org-match-line org-tag-line-re)
  20358. (let ((end (save-excursion
  20359. (goto-char (match-beginning 1))
  20360. (skip-chars-backward " \t")
  20361. (point))))
  20362. (if (<= end (point)) ;on tags part
  20363. (kill-region (point) (line-end-position))
  20364. (kill-region (point) end)))
  20365. (org-align-tags))
  20366. (t (kill-region (point) (line-end-position)))))
  20367. (defun org-yank (&optional arg)
  20368. "Yank. If the kill is a subtree, treat it specially.
  20369. This command will look at the current kill and check if is a single
  20370. subtree, or a series of subtrees[1]. If it passes the test, and if the
  20371. cursor is at the beginning of a line or after the stars of a currently
  20372. empty headline, then the yank is handled specially. How exactly depends
  20373. on the value of the following variables.
  20374. `org-yank-folded-subtrees'
  20375. By default, this variable is non-nil, which results in
  20376. subtree(s) being folded after insertion, except if doing so
  20377. would swallow text after the yanked text.
  20378. `org-yank-adjusted-subtrees'
  20379. When non-nil (the default value is nil), the subtree will be
  20380. promoted or demoted in order to fit into the local outline tree
  20381. structure, which means that the level will be adjusted so that it
  20382. becomes the smaller one of the two *visible* surrounding headings.
  20383. Any prefix to this command will cause `yank' to be called directly with
  20384. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  20385. will just
  20386. plainly yank the text as it is.
  20387. \[1] The test checks if the first non-white line is a heading
  20388. and if there are no other headings with fewer stars."
  20389. (interactive "P")
  20390. (org-yank-generic 'yank arg))
  20391. (defun org-yank-generic (command arg)
  20392. "Perform some yank-like command.
  20393. This function implements the behavior described in the `org-yank'
  20394. documentation. However, it has been generalized to work for any
  20395. interactive command with similar behavior."
  20396. ;; pretend to be command COMMAND
  20397. (setq this-command command)
  20398. (if arg
  20399. (call-interactively command)
  20400. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  20401. (and (org-kill-is-subtree-p)
  20402. (or (bolp)
  20403. (and (looking-at "[ \t]*$")
  20404. (string-match
  20405. "\\`\\*+\\'"
  20406. (buffer-substring (point-at-bol) (point)))))))
  20407. swallowp)
  20408. (cond
  20409. ((and subtreep org-yank-folded-subtrees)
  20410. (let ((beg (point))
  20411. end)
  20412. (if (and subtreep org-yank-adjusted-subtrees)
  20413. (org-paste-subtree nil nil 'for-yank)
  20414. (call-interactively command))
  20415. (setq end (point))
  20416. (goto-char beg)
  20417. (when (and (bolp) subtreep
  20418. (not (setq swallowp
  20419. (org-yank-folding-would-swallow-text beg end))))
  20420. (org-with-limited-levels
  20421. (or (looking-at org-outline-regexp)
  20422. (re-search-forward org-outline-regexp-bol end t))
  20423. (while (and (< (point) end) (looking-at org-outline-regexp))
  20424. (outline-hide-subtree)
  20425. (org-cycle-show-empty-lines 'folded)
  20426. (condition-case nil
  20427. (outline-forward-same-level 1)
  20428. (error (goto-char end))))))
  20429. (when swallowp
  20430. (message
  20431. "Inserted text not folded because that would swallow text"))
  20432. (goto-char end)
  20433. (skip-chars-forward " \t\n\r")
  20434. (beginning-of-line 1)
  20435. (push-mark beg 'nomsg)))
  20436. ((and subtreep org-yank-adjusted-subtrees)
  20437. (let ((beg (point-at-bol)))
  20438. (org-paste-subtree nil nil 'for-yank)
  20439. (push-mark beg 'nomsg)))
  20440. (t
  20441. (call-interactively command))))))
  20442. (defun org-yank-folding-would-swallow-text (beg end)
  20443. "Would hide-subtree at BEG swallow any text after END?"
  20444. (let (level)
  20445. (org-with-limited-levels
  20446. (save-excursion
  20447. (goto-char beg)
  20448. (when (or (looking-at org-outline-regexp)
  20449. (re-search-forward org-outline-regexp-bol end t))
  20450. (setq level (org-outline-level)))
  20451. (goto-char end)
  20452. (skip-chars-forward " \t\r\n\v\f")
  20453. (not (or (eobp)
  20454. (and (bolp) (looking-at-p org-outline-regexp)
  20455. (<= (org-outline-level) level))))))))
  20456. (defun org-back-to-heading (&optional invisible-ok)
  20457. "Call `outline-back-to-heading', but provide a better error message."
  20458. (condition-case nil
  20459. (outline-back-to-heading invisible-ok)
  20460. (error (error "Before first headline at position %d in buffer %s"
  20461. (point) (current-buffer)))))
  20462. (defun org-before-first-heading-p ()
  20463. "Before first heading?"
  20464. (org-with-limited-levels
  20465. (save-excursion
  20466. (end-of-line)
  20467. (null (re-search-backward org-outline-regexp-bol nil t)))))
  20468. (defun org-at-heading-p (&optional _)
  20469. "Non-nil when on a headline."
  20470. (outline-on-heading-p t))
  20471. (defun org-in-commented-heading-p (&optional no-inheritance)
  20472. "Non-nil if point is under a commented heading.
  20473. This function also checks ancestors of the current headline,
  20474. unless optional argument NO-INHERITANCE is non-nil."
  20475. (cond
  20476. ((org-before-first-heading-p) nil)
  20477. ((let ((headline (nth 4 (org-heading-components))))
  20478. (and headline
  20479. (let ((case-fold-search nil))
  20480. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  20481. headline)))))
  20482. (no-inheritance nil)
  20483. (t
  20484. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  20485. (defun org-at-comment-p nil
  20486. "Is cursor in a commented line?"
  20487. (save-excursion
  20488. (save-match-data
  20489. (beginning-of-line)
  20490. (looking-at "^[ \t]*# "))))
  20491. (defun org-at-drawer-p nil
  20492. "Is cursor at a drawer keyword?"
  20493. (save-excursion
  20494. (move-beginning-of-line 1)
  20495. (looking-at org-drawer-regexp)))
  20496. (defun org-at-block-p nil
  20497. "Is cursor at a block keyword?"
  20498. (save-excursion
  20499. (move-beginning-of-line 1)
  20500. (looking-at org-block-regexp)))
  20501. (defun org-point-at-end-of-empty-headline ()
  20502. "If point is at the end of an empty headline, return t, else nil.
  20503. If the heading only contains a TODO keyword, it is still still considered
  20504. empty."
  20505. (let ((case-fold-search nil))
  20506. (and (looking-at "[ \t]*$")
  20507. org-todo-line-regexp
  20508. (save-excursion
  20509. (beginning-of-line)
  20510. (looking-at org-todo-line-regexp)
  20511. (string= (match-string 3) "")))))
  20512. (defun org-at-heading-or-item-p ()
  20513. (or (org-at-heading-p) (org-at-item-p)))
  20514. (defun org-at-target-p ()
  20515. (or (org-in-regexp org-radio-target-regexp)
  20516. (org-in-regexp org-target-regexp)))
  20517. (defun org-up-heading-all (arg)
  20518. "Move to the heading line of which the present line is a subheading.
  20519. This function considers both visible and invisible heading lines.
  20520. With argument, move up ARG levels."
  20521. (outline-up-heading arg t))
  20522. (defun org-up-heading-safe ()
  20523. "Move to the heading line of which the present line is a subheading.
  20524. This version will not throw an error. It will return the level of the
  20525. headline found, or nil if no higher level is found.
  20526. Also, this function will be a lot faster than `outline-up-heading',
  20527. because it relies on stars being the outline starters. This can really
  20528. make a significant difference in outlines with very many siblings."
  20529. (when (ignore-errors (org-back-to-heading t))
  20530. (let ((level-up (1- (funcall outline-level))))
  20531. (and (> level-up 0)
  20532. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  20533. (funcall outline-level)))))
  20534. (defun org-first-sibling-p ()
  20535. "Is this heading the first child of its parents?"
  20536. (interactive)
  20537. (let ((re org-outline-regexp-bol)
  20538. level l)
  20539. (unless (org-at-heading-p t)
  20540. (user-error "Not at a heading"))
  20541. (setq level (funcall outline-level))
  20542. (save-excursion
  20543. (if (not (re-search-backward re nil t))
  20544. t
  20545. (setq l (funcall outline-level))
  20546. (< l level)))))
  20547. (defun org-goto-sibling (&optional previous)
  20548. "Goto the next sibling, even if it is invisible.
  20549. When PREVIOUS is set, go to the previous sibling instead. Returns t
  20550. when a sibling was found. When none is found, return nil and don't
  20551. move point."
  20552. (let ((fun (if previous 're-search-backward 're-search-forward))
  20553. (pos (point))
  20554. (re org-outline-regexp-bol)
  20555. level l)
  20556. (when (ignore-errors (org-back-to-heading t))
  20557. (setq level (funcall outline-level))
  20558. (catch 'exit
  20559. (or previous (forward-char 1))
  20560. (while (funcall fun re nil t)
  20561. (setq l (funcall outline-level))
  20562. (when (< l level) (goto-char pos) (throw 'exit nil))
  20563. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  20564. (goto-char pos)
  20565. nil))))
  20566. (defun org-show-siblings ()
  20567. "Show all siblings of the current headline."
  20568. (save-excursion
  20569. (while (org-goto-sibling) (org-flag-heading nil)))
  20570. (save-excursion
  20571. (while (org-goto-sibling 'previous)
  20572. (org-flag-heading nil))))
  20573. (defun org-goto-first-child ()
  20574. "Goto the first child, even if it is invisible.
  20575. Return t when a child was found. Otherwise don't move point and
  20576. return nil."
  20577. (let (level (pos (point)) (re org-outline-regexp-bol))
  20578. (when (ignore-errors (org-back-to-heading t))
  20579. (setq level (outline-level))
  20580. (forward-char 1)
  20581. (if (and (re-search-forward re nil t) (> (outline-level) level))
  20582. (progn (goto-char (match-beginning 0)) t)
  20583. (goto-char pos) nil))))
  20584. (defun org-show-hidden-entry ()
  20585. "Show an entry where even the heading is hidden."
  20586. (save-excursion
  20587. (org-show-entry)))
  20588. (defun org-flag-heading (flag &optional entry)
  20589. "Flag the current heading. FLAG non-nil means make invisible.
  20590. When ENTRY is non-nil, show the entire entry."
  20591. (save-excursion
  20592. (org-back-to-heading t)
  20593. ;; Check if we should show the entire entry
  20594. (if (not entry)
  20595. (org-flag-region
  20596. (line-end-position 0) (line-end-position) flag 'outline)
  20597. (org-show-entry)
  20598. (save-excursion
  20599. (and (outline-next-heading)
  20600. (org-flag-heading nil))))))
  20601. (defun org-get-next-sibling ()
  20602. "Move to next heading of the same level, and return point.
  20603. If there is no such heading, return nil.
  20604. This is like outline-next-sibling, but invisible headings are ok."
  20605. (let ((level (funcall outline-level)))
  20606. (outline-next-heading)
  20607. (while (and (not (eobp)) (> (funcall outline-level) level))
  20608. (outline-next-heading))
  20609. (unless (or (eobp) (< (funcall outline-level) level))
  20610. (point))))
  20611. (defun org-get-last-sibling ()
  20612. "Move to previous heading of the same level, and return point.
  20613. If there is no such heading, return nil."
  20614. (let ((opoint (point))
  20615. (level (funcall outline-level)))
  20616. (outline-previous-heading)
  20617. (when (and (/= (point) opoint) (outline-on-heading-p t))
  20618. (while (and (> (funcall outline-level) level)
  20619. (not (bobp)))
  20620. (outline-previous-heading))
  20621. (unless (< (funcall outline-level) level)
  20622. (point)))))
  20623. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  20624. "Goto to the end of a subtree."
  20625. ;; This contains an exact copy of the original function, but it uses
  20626. ;; `org-back-to-heading', to make it work also in invisible
  20627. ;; trees. And is uses an invisible-ok argument.
  20628. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  20629. ;; Furthermore, when used inside Org, finding the end of a large subtree
  20630. ;; with many children and grandchildren etc, this can be much faster
  20631. ;; than the outline version.
  20632. (org-back-to-heading invisible-ok)
  20633. (let ((first t)
  20634. (level (funcall outline-level)))
  20635. (if (and (derived-mode-p 'org-mode) (< level 1000))
  20636. ;; A true heading (not a plain list item), in Org
  20637. ;; This means we can easily find the end by looking
  20638. ;; only for the right number of stars. Using a regexp to do
  20639. ;; this is so much faster than using a Lisp loop.
  20640. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  20641. (forward-char 1)
  20642. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  20643. ;; something else, do it the slow way
  20644. (while (and (not (eobp))
  20645. (or first (> (funcall outline-level) level)))
  20646. (setq first nil)
  20647. (outline-next-heading)))
  20648. (unless to-heading
  20649. (when (memq (preceding-char) '(?\n ?\^M))
  20650. ;; Go to end of line before heading
  20651. (forward-char -1)
  20652. (when (memq (preceding-char) '(?\n ?\^M))
  20653. ;; leave blank line before heading
  20654. (forward-char -1)))))
  20655. (point))
  20656. (defun org-end-of-meta-data (&optional full)
  20657. "Skip planning line and properties drawer in current entry.
  20658. When optional argument FULL is non-nil, also skip empty lines,
  20659. clocking lines and regular drawers at the beginning of the
  20660. entry."
  20661. (org-back-to-heading t)
  20662. (forward-line)
  20663. (when (looking-at-p org-planning-line-re) (forward-line))
  20664. (when (looking-at org-property-drawer-re)
  20665. (goto-char (match-end 0))
  20666. (forward-line))
  20667. (when (and full (not (org-at-heading-p)))
  20668. (catch 'exit
  20669. (let ((end (save-excursion (outline-next-heading) (point)))
  20670. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  20671. (while (not (eobp))
  20672. (cond ((looking-at-p org-drawer-regexp)
  20673. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  20674. (forward-line)
  20675. (throw 'exit t)))
  20676. ((looking-at-p re) (forward-line))
  20677. (t (throw 'exit t))))))))
  20678. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  20679. "Move forward to the ARG'th subheading at same level as this one.
  20680. Stop at the first and last subheadings of a superior heading.
  20681. Normally this only looks at visible headings, but when INVISIBLE-OK is
  20682. non-nil it will also look at invisible ones."
  20683. (interactive "p")
  20684. (let ((backward? (and arg (< arg 0))))
  20685. (if (org-before-first-heading-p)
  20686. (if backward? (goto-char (point-min)) (outline-next-heading))
  20687. (org-back-to-heading invisible-ok)
  20688. (unless backward? (end-of-line)) ;do not match current headline
  20689. (let ((level (- (match-end 0) (match-beginning 0) 1))
  20690. (f (if backward? #'re-search-backward #'re-search-forward))
  20691. (count (if arg (abs arg) 1))
  20692. (result (point)))
  20693. (while (and (> count 0)
  20694. (funcall f org-outline-regexp-bol nil 'move))
  20695. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  20696. (cond ((< l level) (setq count 0))
  20697. ((and (= l level)
  20698. (or invisible-ok
  20699. (not (org-invisible-p
  20700. (line-beginning-position)))))
  20701. (cl-decf count)
  20702. (when (= l level) (setq result (point)))))))
  20703. (goto-char result))
  20704. (beginning-of-line))))
  20705. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  20706. "Move backward to the ARG'th subheading at same level as this one.
  20707. Stop at the first and last subheadings of a superior heading."
  20708. (interactive "p")
  20709. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  20710. (defun org-next-visible-heading (arg)
  20711. "Move to the next visible heading.
  20712. This function wraps `outline-next-visible-heading' with
  20713. `org-with-limited-levels' in order to skip over inline tasks and
  20714. respect customization of `org-odd-levels-only'."
  20715. (interactive "p")
  20716. (org-with-limited-levels
  20717. (outline-next-visible-heading arg)))
  20718. (defun org-previous-visible-heading (arg)
  20719. "Move to the previous visible heading.
  20720. This function wraps `outline-previous-visible-heading' with
  20721. `org-with-limited-levels' in order to skip over inline tasks and
  20722. respect customization of `org-odd-levels-only'."
  20723. (interactive "p")
  20724. (org-with-limited-levels
  20725. (outline-previous-visible-heading arg)))
  20726. (defun org-forward-paragraph ()
  20727. "Move forward to beginning of next paragraph or equivalent.
  20728. The function moves point to the beginning of the next visible
  20729. structural element, which can be a paragraph, a table, a list
  20730. item, etc. It also provides some special moves for convenience:
  20731. - On an affiliated keyword, jump to the beginning of the
  20732. relative element.
  20733. - On an item or a footnote definition, move to the second
  20734. element inside, if any.
  20735. - On a table or a property drawer, jump after it.
  20736. - On a verse or source block, stop after blank lines."
  20737. (interactive)
  20738. (unless (eobp)
  20739. (let* ((deactivate-mark nil)
  20740. (element (org-element-at-point))
  20741. (type (org-element-type element))
  20742. (post-affiliated (org-element-property :post-affiliated element))
  20743. (contents-begin (org-element-property :contents-begin element))
  20744. (contents-end (org-element-property :contents-end element))
  20745. (end (let ((end (org-element-property :end element)) (parent element))
  20746. (while (and (setq parent (org-element-property :parent parent))
  20747. (= (org-element-property :contents-end parent) end))
  20748. (setq end (org-element-property :end parent)))
  20749. end)))
  20750. (cond ((not element)
  20751. (skip-chars-forward " \r\t\n")
  20752. (or (eobp) (beginning-of-line)))
  20753. ;; On affiliated keywords, move to element's beginning.
  20754. ((< (point) post-affiliated)
  20755. (goto-char post-affiliated))
  20756. ;; At a table row, move to the end of the table. Similarly,
  20757. ;; at a node property, move to the end of the property
  20758. ;; drawer.
  20759. ((memq type '(node-property table-row))
  20760. (goto-char (org-element-property
  20761. :end (org-element-property :parent element))))
  20762. ((memq type '(property-drawer table)) (goto-char end))
  20763. ;; Consider blank lines as separators in verse and source
  20764. ;; blocks to ease editing.
  20765. ((memq type '(src-block verse-block))
  20766. (when (eq type 'src-block)
  20767. (setq contents-end
  20768. (save-excursion (goto-char end)
  20769. (skip-chars-backward " \r\t\n")
  20770. (line-beginning-position))))
  20771. (beginning-of-line)
  20772. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  20773. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  20774. (goto-char end)
  20775. (skip-chars-forward " \r\t\n")
  20776. (if (= (point) contents-end) (goto-char end)
  20777. (beginning-of-line))))
  20778. ;; With no contents, just skip element.
  20779. ((not contents-begin) (goto-char end))
  20780. ;; If contents are invisible, skip the element altogether.
  20781. ((org-invisible-p (line-end-position))
  20782. (cl-case type
  20783. (headline
  20784. (org-with-limited-levels (outline-next-visible-heading 1)))
  20785. ;; At a plain list, make sure we move to the next item
  20786. ;; instead of skipping the whole list.
  20787. (plain-list (forward-char)
  20788. (org-forward-paragraph))
  20789. (otherwise (goto-char end))))
  20790. ((>= (point) contents-end) (goto-char end))
  20791. ((>= (point) contents-begin)
  20792. ;; This can only happen on paragraphs and plain lists.
  20793. (cl-case type
  20794. (paragraph (goto-char end))
  20795. ;; At a plain list, try to move to second element in
  20796. ;; first item, if possible.
  20797. (plain-list (end-of-line)
  20798. (org-forward-paragraph))))
  20799. ;; When contents start on the middle of a line (e.g. in
  20800. ;; items and footnote definitions), try to reach first
  20801. ;; element starting after current line.
  20802. ((> (line-end-position) contents-begin)
  20803. (end-of-line)
  20804. (org-forward-paragraph))
  20805. (t (goto-char contents-begin))))))
  20806. (defun org-backward-paragraph ()
  20807. "Move backward to start of previous paragraph or equivalent.
  20808. The function moves point to the beginning of the current
  20809. structural element, which can be a paragraph, a table, a list
  20810. item, etc., or to the beginning of the previous visible one if
  20811. point is already there. It also provides some special moves for
  20812. convenience:
  20813. - On an affiliated keyword, jump to the first one.
  20814. - On a table or a property drawer, move to its beginning.
  20815. - On comment, example, export, src and verse blocks, stop
  20816. before blank lines."
  20817. (interactive)
  20818. (unless (bobp)
  20819. (let* ((deactivate-mark nil)
  20820. (element (org-element-at-point))
  20821. (type (org-element-type element))
  20822. (contents-end (org-element-property :contents-end element))
  20823. (post-affiliated (org-element-property :post-affiliated element))
  20824. (begin (org-element-property :begin element))
  20825. (special? ;blocks handled specially
  20826. (memq type '(comment-block example-block export-block src-block
  20827. verse-block)))
  20828. (contents-begin
  20829. (if special?
  20830. ;; These types have no proper contents. Fake line
  20831. ;; below the block opening line as contents beginning.
  20832. (save-excursion (goto-char begin) (line-beginning-position 2))
  20833. (org-element-property :contents-begin element))))
  20834. (cond
  20835. ((not element) (goto-char (point-min)))
  20836. ((= (point) begin)
  20837. (backward-char)
  20838. (org-backward-paragraph))
  20839. ((<= (point) post-affiliated) (goto-char begin))
  20840. ;; Special behavior: on a table or a property drawer, move to
  20841. ;; its beginning.
  20842. ((memq type '(node-property table-row))
  20843. (goto-char (org-element-property
  20844. :post-affiliated (org-element-property :parent element))))
  20845. (special?
  20846. (if (<= (point) contents-begin) (goto-char post-affiliated)
  20847. ;; Inside a verse block, see blank lines as paragraph
  20848. ;; separators.
  20849. (let ((origin (point)))
  20850. (skip-chars-backward " \r\t\n" contents-begin)
  20851. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  20852. (skip-chars-forward " \r\t\n" origin)
  20853. (if (= (point) origin) (goto-char contents-begin)
  20854. (beginning-of-line))))))
  20855. ((eq type 'paragraph) (goto-char contents-begin)
  20856. ;; When at first paragraph in an item or a footnote definition,
  20857. ;; move directly to beginning of line.
  20858. (let ((parent-contents
  20859. (org-element-property
  20860. :contents-begin (org-element-property :parent element))))
  20861. (when (and parent-contents (= parent-contents contents-begin))
  20862. (beginning-of-line))))
  20863. ;; At the end of a greater element, move to the beginning of
  20864. ;; the last element within.
  20865. ((and contents-end (>= (point) contents-end))
  20866. (goto-char (1- contents-end))
  20867. (org-backward-paragraph))
  20868. (t (goto-char (or post-affiliated begin))))
  20869. ;; Ensure we never leave point invisible.
  20870. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  20871. (defun org-forward-element ()
  20872. "Move forward by one element.
  20873. Move to the next element at the same level, when possible."
  20874. (interactive)
  20875. (cond ((eobp) (user-error "Cannot move further down"))
  20876. ((org-with-limited-levels (org-at-heading-p))
  20877. (let ((origin (point)))
  20878. (goto-char (org-end-of-subtree nil t))
  20879. (unless (org-with-limited-levels (org-at-heading-p))
  20880. (goto-char origin)
  20881. (user-error "Cannot move further down"))))
  20882. (t
  20883. (let* ((elem (org-element-at-point))
  20884. (end (org-element-property :end elem))
  20885. (parent (org-element-property :parent elem)))
  20886. (cond ((and parent (= (org-element-property :contents-end parent) end))
  20887. (goto-char (org-element-property :end parent)))
  20888. ((integer-or-marker-p end) (goto-char end))
  20889. (t (message "No element at point")))))))
  20890. (defun org-backward-element ()
  20891. "Move backward by one element.
  20892. Move to the previous element at the same level, when possible."
  20893. (interactive)
  20894. (cond ((bobp) (user-error "Cannot move further up"))
  20895. ((org-with-limited-levels (org-at-heading-p))
  20896. ;; At a headline, move to the previous one, if any, or stay
  20897. ;; here.
  20898. (let ((origin (point)))
  20899. (org-with-limited-levels (org-backward-heading-same-level 1))
  20900. ;; When current headline has no sibling above, move to its
  20901. ;; parent.
  20902. (when (= (point) origin)
  20903. (or (org-with-limited-levels (org-up-heading-safe))
  20904. (progn (goto-char origin)
  20905. (user-error "Cannot move further up"))))))
  20906. (t
  20907. (let* ((elem (org-element-at-point))
  20908. (beg (org-element-property :begin elem)))
  20909. (cond
  20910. ;; Move to beginning of current element if point isn't
  20911. ;; there already.
  20912. ((null beg) (message "No element at point"))
  20913. ((/= (point) beg) (goto-char beg))
  20914. (t (goto-char beg)
  20915. (skip-chars-backward " \r\t\n")
  20916. (unless (bobp)
  20917. (let ((prev (org-element-at-point)))
  20918. (goto-char (org-element-property :begin prev))
  20919. (while (and (setq prev (org-element-property :parent prev))
  20920. (<= (org-element-property :end prev) beg))
  20921. (goto-char (org-element-property :begin prev)))))))))))
  20922. (defun org-up-element ()
  20923. "Move to upper element."
  20924. (interactive)
  20925. (if (org-with-limited-levels (org-at-heading-p))
  20926. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  20927. (let* ((elem (org-element-at-point))
  20928. (parent (org-element-property :parent elem)))
  20929. (if parent (goto-char (org-element-property :begin parent))
  20930. (if (org-with-limited-levels (org-before-first-heading-p))
  20931. (user-error "No surrounding element")
  20932. (org-with-limited-levels (org-back-to-heading)))))))
  20933. (defun org-down-element ()
  20934. "Move to inner element."
  20935. (interactive)
  20936. (let ((element (org-element-at-point)))
  20937. (cond
  20938. ((memq (org-element-type element) '(plain-list table))
  20939. (goto-char (org-element-property :contents-begin element))
  20940. (forward-char))
  20941. ((memq (org-element-type element) org-element-greater-elements)
  20942. ;; If contents are hidden, first disclose them.
  20943. (when (org-invisible-p (line-end-position)) (org-cycle))
  20944. (goto-char (or (org-element-property :contents-begin element)
  20945. (user-error "No content for this element"))))
  20946. (t (user-error "No inner element")))))
  20947. (defun org-drag-element-backward ()
  20948. "Move backward element at point."
  20949. (interactive)
  20950. (let ((elem (or (org-element-at-point)
  20951. (user-error "No element at point"))))
  20952. (if (eq (org-element-type elem) 'headline)
  20953. ;; Preserve point when moving a whole tree, even if point was
  20954. ;; on blank lines below the headline.
  20955. (let ((offset (skip-chars-backward " \t\n")))
  20956. (unwind-protect (org-move-subtree-up)
  20957. (forward-char (- offset))))
  20958. (let ((prev-elem
  20959. (save-excursion
  20960. (goto-char (org-element-property :begin elem))
  20961. (skip-chars-backward " \r\t\n")
  20962. (unless (bobp)
  20963. (let* ((beg (org-element-property :begin elem))
  20964. (prev (org-element-at-point))
  20965. (up prev))
  20966. (while (and (setq up (org-element-property :parent up))
  20967. (<= (org-element-property :end up) beg))
  20968. (setq prev up))
  20969. prev)))))
  20970. ;; Error out if no previous element or previous element is
  20971. ;; a parent of the current one.
  20972. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  20973. (user-error "Cannot drag element backward")
  20974. (let ((pos (point)))
  20975. (org-element-swap-A-B prev-elem elem)
  20976. (goto-char (+ (org-element-property :begin prev-elem)
  20977. (- pos (org-element-property :begin elem))))))))))
  20978. (defun org-drag-element-forward ()
  20979. "Move forward element at point."
  20980. (interactive)
  20981. (let* ((pos (point))
  20982. (elem (or (org-element-at-point)
  20983. (user-error "No element at point"))))
  20984. (when (= (point-max) (org-element-property :end elem))
  20985. (user-error "Cannot drag element forward"))
  20986. (goto-char (org-element-property :end elem))
  20987. (let ((next-elem (org-element-at-point)))
  20988. (when (or (org-element-nested-p elem next-elem)
  20989. (and (eq (org-element-type next-elem) 'headline)
  20990. (not (eq (org-element-type elem) 'headline))))
  20991. (goto-char pos)
  20992. (user-error "Cannot drag element forward"))
  20993. ;; Compute new position of point: it's shifted by NEXT-ELEM
  20994. ;; body's length (without final blanks) and by the length of
  20995. ;; blanks between ELEM and NEXT-ELEM.
  20996. (let ((size-next (- (save-excursion
  20997. (goto-char (org-element-property :end next-elem))
  20998. (skip-chars-backward " \r\t\n")
  20999. (forward-line)
  21000. ;; Small correction if buffer doesn't end
  21001. ;; with a newline character.
  21002. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  21003. (org-element-property :begin next-elem)))
  21004. (size-blank (- (org-element-property :end elem)
  21005. (save-excursion
  21006. (goto-char (org-element-property :end elem))
  21007. (skip-chars-backward " \r\t\n")
  21008. (forward-line)
  21009. (point)))))
  21010. (org-element-swap-A-B elem next-elem)
  21011. (goto-char (+ pos size-next size-blank))))))
  21012. (defun org-drag-line-forward (arg)
  21013. "Drag the line at point ARG lines forward."
  21014. (interactive "p")
  21015. (dotimes (_ (abs arg))
  21016. (let ((c (current-column)))
  21017. (if (< 0 arg)
  21018. (progn
  21019. (beginning-of-line 2)
  21020. (transpose-lines 1)
  21021. (beginning-of-line 0))
  21022. (transpose-lines 1)
  21023. (beginning-of-line -1))
  21024. (org-move-to-column c))))
  21025. (defun org-drag-line-backward (arg)
  21026. "Drag the line at point ARG lines backward."
  21027. (interactive "p")
  21028. (org-drag-line-forward (- arg)))
  21029. (defun org-mark-element ()
  21030. "Put point at beginning of this element, mark at end.
  21031. Interactively, if this command is repeated or (in Transient Mark
  21032. mode) if the mark is active, it marks the next element after the
  21033. ones already marked."
  21034. (interactive)
  21035. (let (deactivate-mark)
  21036. (if (and (called-interactively-p 'any)
  21037. (or (and (eq last-command this-command) (mark t))
  21038. (and transient-mark-mode mark-active)))
  21039. (set-mark
  21040. (save-excursion
  21041. (goto-char (mark))
  21042. (goto-char (org-element-property :end (org-element-at-point)))))
  21043. (let ((element (org-element-at-point)))
  21044. (end-of-line)
  21045. (push-mark (org-element-property :end element) t t)
  21046. (goto-char (org-element-property :begin element))))))
  21047. (defun org-narrow-to-element ()
  21048. "Narrow buffer to current element."
  21049. (interactive)
  21050. (let ((elem (org-element-at-point)))
  21051. (cond
  21052. ((eq (car elem) 'headline)
  21053. (narrow-to-region
  21054. (org-element-property :begin elem)
  21055. (org-element-property :end elem)))
  21056. ((memq (car elem) org-element-greater-elements)
  21057. (narrow-to-region
  21058. (org-element-property :contents-begin elem)
  21059. (org-element-property :contents-end elem)))
  21060. (t
  21061. (narrow-to-region
  21062. (org-element-property :begin elem)
  21063. (org-element-property :end elem))))))
  21064. (defun org-transpose-element ()
  21065. "Transpose current and previous elements, keeping blank lines between.
  21066. Point is moved after both elements."
  21067. (interactive)
  21068. (org-skip-whitespace)
  21069. (let ((end (org-element-property :end (org-element-at-point))))
  21070. (org-drag-element-backward)
  21071. (goto-char end)))
  21072. (defun org-unindent-buffer ()
  21073. "Un-indent the visible part of the buffer.
  21074. Relative indentation (between items, inside blocks, etc.) isn't
  21075. modified."
  21076. (interactive)
  21077. (unless (eq major-mode 'org-mode)
  21078. (user-error "Cannot un-indent a buffer not in Org mode"))
  21079. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  21080. (unindent-tree
  21081. (lambda (contents)
  21082. (dolist (element (reverse contents))
  21083. (if (memq (org-element-type element) '(headline section))
  21084. (funcall unindent-tree (org-element-contents element))
  21085. (save-excursion
  21086. (save-restriction
  21087. (narrow-to-region
  21088. (org-element-property :begin element)
  21089. (org-element-property :end element))
  21090. (org-do-remove-indentation))))))))
  21091. (funcall unindent-tree (org-element-contents parse-tree))))
  21092. (defun org-make-options-regexp (kwds &optional extra)
  21093. "Make a regular expression for keyword lines.
  21094. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  21095. when non-nil, is a regexp matching keywords names."
  21096. (concat "^[ \t]*#\\+\\("
  21097. (regexp-opt kwds)
  21098. (and extra (concat (and kwds "\\|") extra))
  21099. "\\):[ \t]*\\(.*\\)"))
  21100. ;;; Conveniently switch to Info nodes
  21101. (defun org-info-find-node (&optional nodename)
  21102. "Find Info documentation NODENAME or Org documentation according context.
  21103. Started from `gnus-info-find-node'."
  21104. (interactive)
  21105. (Info-goto-node
  21106. (or nodename
  21107. (let ((default-org-info-node "(org) Top"))
  21108. (cond
  21109. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  21110. ((eq 'org-mode major-mode)
  21111. (let* ((context (org-element-at-point))
  21112. (element-info-nodes ; compare to `org-element-all-elements'.
  21113. `((babel-call . "(org) Evaluating Code Blocks")
  21114. (center-block . "(org) Paragraphs")
  21115. (clock . ,default-org-info-node)
  21116. (comment . "(org) Comment Lines")
  21117. (comment-block . "(org) Comment Lines")
  21118. (diary-sexp . ,default-org-info-node)
  21119. (drawer . "(org) Drawers")
  21120. (dynamic-block . "(org) Dynamic Blocks")
  21121. (example-block . "(org) Literal Examples")
  21122. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  21123. (fixed-width . ,default-org-info-node)
  21124. (footnote-definition . "(org) Creating Footnotes")
  21125. (headline . "(org) Document Structure")
  21126. (horizontal-rule . "(org) Built-in Table Editor")
  21127. (inlinetask . ,default-org-info-node)
  21128. (item . "(org) Plain Lists")
  21129. (keyword . "(org) Per-file keywords")
  21130. (latex-environment . "(org) LaTeX Export")
  21131. (node-property . "(org) Properties and Columns")
  21132. (paragraph . "(org) Paragraphs")
  21133. (plain-list . "(org) Plain Lists")
  21134. (planning . "(org) Deadlines and Scheduling")
  21135. (property-drawer . "(org) Properties and Columns")
  21136. (quote-block . "(org) Paragraphs")
  21137. (section . ,default-org-info-node)
  21138. (special-block . ,default-org-info-node)
  21139. (src-block . "(org) Working with Source Code")
  21140. (table . "(org) Tables")
  21141. (table-row . "(org) Tables")
  21142. (verse-block . "(org) Paragraphs"))))
  21143. (or (cdr (assoc (car context) element-info-nodes))
  21144. default-org-info-node)))
  21145. (t default-org-info-node))))))
  21146. ;;; Finish up
  21147. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  21148. (lambda () (add-hook 'change-major-mode-hook
  21149. 'org-show-all 'append 'local)))
  21150. (provide 'org)
  21151. (run-hooks 'org-load-hook)
  21152. ;;; org.el ends here